diff --git a/.github/workflows/nor18r-runtime-memory.yml b/.github/workflows/nor18r-runtime-memory.yml new file mode 100644 index 000000000..eb336d535 --- /dev/null +++ b/.github/workflows/nor18r-runtime-memory.yml @@ -0,0 +1,124 @@ +name: NOR-18R source-locked CPU runtime bigint and memory benchmark + +on: + push: + paths: + - 'research/nor18r_runtime/**' + - '.github/workflows/nor18r-runtime-memory.yml' + pull_request: + paths: + - 'research/nor18r_runtime/**' + - '.github/workflows/nor18r-runtime-memory.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + arithmetic-parity-private-future-isolation: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Validate native exact mask, cached masks, integer inverse operand sizes and sealed target + run: python -m unittest research.nor18r_runtime.test_runtime -v + + frozen-original-public-receipt-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 reconstruct all original public sources and first-hosted CPU / bigint / RAM metrics + run: | + python research/nor18r_runtime/receipt_audit.py --check \ + --archive research/nor18r_runtime/results/nor18r_original_hosted.zip + + source-locked-64-case-cpu-bigint-memory: + needs: arithmetic-parity-private-future-isolation + runs-on: ubuntu-latest + timeout-minutes: 50 + 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: Rebuild only public fixture from original NOR-18 heldout 288-case receipts + run: | + python research/nor18r_runtime/benchmark.py --check \ + --make-fixture /tmp/nor18r_public_fixture.json + - name: Benchmark matched public CPU algorithms with seven trials and isolated RSS workers + run: | + python research/nor18r_runtime/benchmark.py --check \ + --fixture /tmp/nor18r_public_fixture.json \ + --repetitions 7 --warmups 2 --out /tmp/nor18r_full.json + - name: Audit public-only provenance, timed repeated measures, peak memory and bigint work + run: | + python - <<'PY' + from pathlib import Path + from hashlib import sha256 + from collections import Counter + import json,math + fixture=Path('/tmp/nor18r_public_fixture.json').read_bytes() + raw=Path('/tmp/nor18r_full.json').read_bytes() + public=json.loads(fixture) + z=json.loads(raw) + assert public['schema']=='nor18r.public_fixture_64_cases_from_original_288.v1' + assert public['no_hidden_query_outputs_or_planted_program_identities'] + assert public['NOR18_original_evidence_sha256']=='9905aa23466b98ba2068e6daf9206d35c453b8b3b75bd27c3ab7ff8f0db4041b' + assert len(public['cases'])==64 + assert z['schema']=='nor18r.executable_cpu_bigint_memory_source_locked.v1' + assert z['original_NOR18_full_JSON_SHA256']==public['NOR18_original_evidence_sha256'] + assert z['fixture_sha256']==sha256(fixture).hexdigest() + assert z['fixture_cases']==len(z['per_case'])==64 + assert z['timed_repetitions']==7 and z['untimed_warmups_per_case_per_algorithm']==2 + assert z['modes']==['independent16','cached16','prefix160','prefix176'] + assert z['source_families']=={'late_source':32,'signed':16,'rational':16} + assert len(set(x['full_public_input_sha256'] for x in z['per_case']))==64 + assert len({x['cohort'] for x in z['per_case']})==4 + assert z['primary_cohort_block_bootstrap']['draws']==4096 + assert z['scope']['future_outputs_and_private_generator_programs_not_in_fixture'] + assert z['scope']['exact_public_mask_and_certificate_match_original_for_every_mode'] + assert z['scope']['time_includes_python_bigint_implementation_effects'] + assert z['scope']['RSS_and_tracemalloc_measured_in_separate_untimed_passes'] + for r in z['per_case']: + assert r['algorithm_result_parity_all_modes'] + assert len(r['measured_ns'])==4 + for mode in z['modes']: + assert len(r['measured_ns'][mode])==7 + for timing in r['measured_ns'][mode]: + assert timing['total_ns']==timing['query_ns']+timing['verification_ns']+timing['certificate_ns'] + assert timing['total_ns']>0 + assert r['median_ns'][mode]['total_ns']>0 + assert r['untimed_tracemalloc'][mode]['mask']==r['reference_full_public_accept_mask'] + assert r['bigint_operand_width_ledger']['per_mode'][mode]['R_integer_multiplications_executed']>0 + assert r['bigint_operand_width_ledger']['per_mode'][mode]['R_operand_bitwidth_product_proxy']>0 + for mode,value in z['isolated_process_RSS_KiB'].items(): + assert mode in z['modes'] + assert value['cases']==64 + print('NOR18R HOST',z['host']) + print('NOR18R MEASURED COMPLETE CPU SPEEDUP',z['primary_median_paired_total_speedup']) + print('NOR18R PAIRED CACHED FASTER',z['primary_cached_faster_cases'],'/64') + print('NOR18R COHORT BLOCK BOOTSTRAP 95%',z['primary_cohort_block_bootstrap']) + print('NOR18R REGISTERED PRIMARY PASS',z['primary_preregistered_passed']) + print('NOR18R MODE FULL RESULTS',z['summary_all']) + print('NOR18R FAMILY RESULTS',z['summary_by_family']) + print('NOR18R ISOLATED RSS KiB',z['isolated_process_RSS_KiB']) + print('NOR18R FIXTURE SHA256',len(fixture),sha256(fixture).hexdigest()) + print('NOR18R FULL BENCHMARK SHA256',len(raw),sha256(raw).hexdigest()) + PY + - uses: actions/upload-artifact@v4 + with: + name: nor18r-original-public-only-64-case-fixture-and-timing-results + path: | + /tmp/nor18r_public_fixture.json + /tmp/nor18r_full.json diff --git a/research/nor18r_runtime/README.md b/research/nor18r_runtime/README.md new file mode 100644 index 000000000..b77b0fabd --- /dev/null +++ b/research/nor18r_runtime/README.md @@ -0,0 +1,101 @@ +# NOR-18R: executable CPU, bigint, and memory audit of cached exact verification + +**Preregistered 16 November 2026 before opening measured NOR-18R CPU timings.** Follows merged [NOR-18 #175](https://github.com/MoralityLabAI/Compactification-Theory/pull/175) and [MathCan cached-verifier work theorem #94](https://github.com/patrickdugan/MathCan/pull/94). + +NOR-18 measured **coefficient-operation work**, finding that one cached degree-192 sixteen-template public screen gave the entire certifiable 48/192 late-source subset at an eight-unit proxy cap. The mathematical work saving from sharing four unary public transforms is exact for that declared proxy. NOR-18R measures real Python 3.12 CPU execution, time per checked public case, Python-traced peak temporary allocation, isolated-process maximum resident memory and the actual integer operand sizes encountered by the reciprocal (\`R\`) recurrence. + +## Frozen test sources and execution + +Use the **original NOR-18 held-out 288-case record**, preserved at \`research/nor18_costed_prefix/results/nor18_full.zip\`. Require the original uncompressed 12,896,423-byte JSON SHA-256: + +\`9905aa23466b98ba2068e6daf9206d35c453b8b3b75bd27c3ab7ff8f0db4041b\`. + +Regenerate the exact public source cases from NOR-18's frozen generator and seeds. Verify **every** reconstructed public source hash against its corresponding archived first-run record before selecting the benchmark subset. In each of four cohorts, take the first eight late_source, first four signed and first four rational entries in the original cohort order. This fixes **64 public-distinct benchmark sources**, with 32 late_source, 16 signed and 16 rational cases. Store only degree-192 public input/output demonstrations, degree-256 *public query input*, the publicly derived header, source family and archival source digest. The planted program and withheld future query output remain excluded from every benchmark fixture and timed path. + +All measured algorithms use the *identical* two degree-192 public demonstrations and query input and must produce the **same 16-bit exact acceptance mask and the same unanimous-future-output certificate**. Recovered masks must also match the original frozen NOR-18 full-mask receipts; each public simulated future must agree with the reference RRC25 exact interpreter in standalone parity tests. + +## Preregistered executable comparisons + +1. **\`independent16\`:** Call the original \`compound25.verify_template\` sixteen times, using native \`execute\` and recalculating its base, U and V unary transformations for each candidate. +2. **\`cached16\`:** Call the existing \`nor17.candidate_outputs\` once per demonstration at degree 192, reusing the four unary transforms across all sixteen templates, then compare each candidate output with the observed public demonstration. +3. **\`prefix160\`:** Construct the two cached degree-160 source-prefix screens, intersect the survivors, and call the *same native* full exact \`verify_template\` on each surviving candidate. +4. **\`prefix176\`:** Repeat with a degree-176 screen and exactly the same downstream native full checks. + +Every algorithm also independently computes all sixteen hypothetical degree-256 outputs from the known **public query input**. The benchmark reports **query simulation time and public verification time separately**, as well as combined execution time, so comparisons of complete certificates include shared query computation costs. It reads neither future query outputs nor private program identities. Query simulations for every mode are recomputed and metered within that mode, with no cross-mode cache credit. + +For each of the 64 cases, run two warmups and **seven measured repetitions per mode**. Randomize the order of the four modes deterministically inside each repetition, so CPython allocator warming and CPU frequency drift do not always favor a particular algorithm. Before each sample, perform \`gc.collect()\`; temporarily disable garbage collection during the timed segment. Report per-case median query, verification and combined \`perf_counter_ns\` times; paired speedup \`median(independent16)/median(cached16)\` and a 95% **four-cohort block bootstrap** confidence interval with 4096 deterministic seeded draws. Give per-family medians and the fraction of source cases where cached execution is faster. CPU architecture, Python/compiler version and host information must accompany every source receipt. + +Measure peak Python-traced temporary allocation **in an untimed separate run per case and algorithm** using \`tracemalloc\` starting before the algorithm and stopping afterward. Also launch isolated subprocesses per mode, reading their process maximum resident set size via \`resource.getrusage(RUSAGE_SELF).ru_maxrss\` on Linux; report pre-run baseline RSS, peak RSS, and peak-minus-baseline, with clear caveats that allocator reservations and process startup can make the RSS increments zero. These memory metrics are separate from timings, and neither is a hardware-independent proof. + +## Integer costs and safety interpretation + +Replay one exact reciprocal formal-series inversion for each degree-192 demonstration input and the degree-256 public query input. Verify the replay against the exact original \`graph11.inv\` result. Record the **actual number of Python big-integer multiplications and the sum of the products of the operands' positive bit lengths** in that inverse recurrence. Scale this observed per-source integer workload by the *exact* reciprocal invocation counts implied by each algorithm's public base, U and V calls (and cache reuse) to provide a per-method bigint operand-width ledger. Record maximum intermediate and output coefficient bit lengths and maximum Python integer storage size. This bit-length product sum is an **operand-size proxy**, distinct from native CPU instructions, Python multiplications per second and asymptotic multiplication bit complexity. + +The prior NOR-18 coefficients-only prediction is that cached sixteen-template verification does fewer repeated reciprocal-series operations and may be faster in real CPU time. **Primary registered performance criterion:** cached16 has the same exact masks/certificates for every source, a paired median complete-public-certificate speedup of **at least 1.5×**, and is faster on **at least 48 of 64 cases**. Report those components independently. All other comparisons, including prefix160/prefix176, memory, process RSS and family-specific effects, are exploratory. This is measured performance on a pinned GitHub Actions CPU runner, not a claim about 5080/3050 GPUs, other machines or mathematical generalization. + +## Reproduce + +\`\`\`sh +python -m unittest research.nor18r_runtime.test_runtime -v +python research/nor18r_runtime/benchmark.py --check \ + --make-fixture /tmp/nor18r_fixture.json +python research/nor18r_runtime/benchmark.py --check \ + --fixture /tmp/nor18r_fixture.json \ + --repetitions 7 --warmups 2 --out /tmp/nor18r_full.json +\`\`\` + +The hosted workflow separately verifies the source manifest, original public-mask parity, all 64×4×7 timing samples, memory ledgers and test-source integrity. Full original benchmark evidence is frozen by SHA-256 after the first successful run. Unexpected errors, parity failures or insufficient measurements block merge. + + +## First executed CPU result (original source locked) + +[Original green hosted CPU and memory benchmark](https://github.com/MoralityLabAI/Compactification-Theory/actions/runs/43797844269), artifact ID 14195445905, completed on 16 November 2026. Its public-only 64-source fixture and complete 7×4×64 timing records are **preserved byte-for-byte** in [results/nor18r_original_hosted.zip](results/nor18r_original_hosted.zip) and fingerprinted in [results/nor18r_first_frozen_receipt.json](results/nor18r_first_frozen_receipt.json). + +The original JSON fingerprints are: + +- Public-only NOR-18 source fixture: 1,306,733 bytes, SHA-256 \`5d75f2971d8b94daa9b65caae68e65921f2a90cd267481c7bb80a881e937d186\`. +- Complete first measured CPU benchmark: 580,813 bytes, SHA-256 \`59d48c8c9fe1bdf80ee2662d0c18f069f8414a92d48ad7980e3bb19b2a10ad98\`. +- Original NOR-18 288-case source record: SHA-256 \`9905aa23466b98ba2068e6daf9206d35c453b8b3b75bd27c3ab7ff8f0db4041b\`. + +The [independent archived-receipt auditor](receipt_audit.py) regenerates exact acceptance masks and candidate query predictions from the fixture's public data using the original corpus interpreter, checks 1,792 original nanosecond timing samples, all 256 separately measured peak allocation records, per-case inverse-operand bit sizes, and the deterministic 4,096-draw cohort-block bootstrap. It imports no benchmarking implementation. The separate native-parity test verifies the four original public algorithms and future-label isolation, while the full hosted benchmark is reproducible without changing frozen source selection. + +### Hosted platform and CPU measurements + +Measured on GitHub Actions Linux \`7.0.0-1019-azure\`, x86-64, CPython 3.12.16 compiled with GCC 15.2.0, reporting four logical CPUs. Garbage collection was collected immediately before each timed run and disabled during the measured segment. Each case/mode was warmed twice, timed seven times, and mode order was deterministically shuffled. Source generation and JSON loading were excluded from timings. + +| Public checker, including identical public query simulations | Median per-case complete CPU time | Median public-verification time | Median separately traced peak temporary allocation | +| --- | ---: | ---: | ---: | +| Native 16 independent checks | 23.913 ms | 21.291 ms | 74.1 KiB | +| **Four-unary cached sixteen-candidate batch** | **4.327 ms** | **2.266 ms** | 128.2 KiB | +| Degree-160 prefix cache + independent survivor checks | 12.331 ms | 9.706 ms | 112.8 KiB | +| Degree-176 prefix cache + independent survivor checks | 8.836 ms | 5.744 ms | 120.6 KiB | + +The **median of the 64 paired complete-time speed ratios** was **4.32878×**, with cached full-batch execution faster in **64/64** cases. The preregistered speed criterion (median paired speedup at least 1.5× and cached faster on at least 48 of 64 public inputs) **passed**. The four-cohort block-bootstrap 95% interval was **4.280× to 4.396×**. This interval resamples the same four fixed generator cohorts and is conditional on this first hosted execution. It is not a cross-machine confidence interval or an independent-replication result. + +Per-family median paired speedups were 4.396× for late_source (32 cases), 4.323× for signed (16) and 4.204× for rational (16). Every mode exactly reproduced every publicly accepted template and every logical output-unanimity certificate on all sixty-four benchmark sources. + +### Exact integer operand workload and memory qualification + +The independent RRC25 reciprocal algorithm executes a quadratic number of Python bigint products per inversion. The observed multiplication counts and operand-bitwidth products, including the once-per-mode public query simulation, were: + +| Method | Observed R integer products across 64 cases | Sum of positive operand bitwidth products | +| --- | ---: | ---: | +| Native sixteen checks | 31,750,144 | 845,306,615 | +| Cached sixteen-candidate batch | **4,476,928** | **163,683,594** | +| Prefix160 plus native survivors | 18,724,608 | 227,918,645 | +| Prefix176 plus native survivors | 16,549,888 | 215,773,495 | + +The second column is an **observed operand-size proxy**, computed from the exact integers passed into the original reciprocal recurrence. It measures multiplication count and operand bit widths, not the actual dynamic native integer multiplication instruction count or wall-clock cost of each operation. The call-multiplicity identity is kernel-proved in [MathCan NOR-18R PR #98](https://github.com/patrickdugan/MathCan/pull/98): eight native R inversions per public demonstration from U/V, plus sixteen more when the fixed base is R, versus one cached R inversion. + +Caching uses **more temporary Python allocation** in these source-locked tests, with median independently measured \`tracemalloc\` peaks of 128.2 KiB versus 74.1 KiB for the native repeated checker. Isolated-worker maximum RSS was 29,364 KiB for every mode, with no measurable rise over that worker's fixture-loaded baseline. That process-level peak does not resolve the temporary Python allocation difference; it also excludes the cost of loading source files on a fresh machine. + +NOR-18's arithmetic proxy predicted a cached-work benefit. NOR-18R establishes that the specifically tested CPython implementation also runs faster on this original held-out source subset, while revealing an allocation tradeoff. Generalization to a fresh source generator, other Python versions, different CPU microarchitectures, GPU implementations or production proof tasks remains to be tested. + +### Independently reproduce the frozen evidence + +\`\`\`sh +python research/nor18r_runtime/receipt_audit.py --check \ + --archive research/nor18r_runtime/results/nor18r_original_hosted.zip +\`\`\` + +The complete archived fixture deliberately excludes all withheld query-output labels and planted program identities. It is suitable for independent public-only verifier microbenchmarks without unsealing NOR-18's future truth. diff --git a/research/nor18r_runtime/benchmark.py b/research/nor18r_runtime/benchmark.py new file mode 100644 index 000000000..8cc563f82 --- /dev/null +++ b/research/nor18r_runtime/benchmark.py @@ -0,0 +1,649 @@ +"""NOR-18R: executable source-locked CPU, Python memory and bigint audit. + +Run under CPython 3.12 on a dedicated hosted Actions CPU runner. Four +public algorithms must return the same full sixteen-class accepted mask +and output-unanimity certificate on 64 public heldout NOR18 sources. + +Measured timings include fresh public degree256 query output simulation +for every algorithm, separately reported from degree192 public +verification. No private query future output or planted source program +is present in the generated fixture or read by any benchmark method. + +The prior NOR18 full JSON is used exclusively to verify original source +hashes and reference public mask / identifiability; it is never read by a +policy while executing. Bigint bit widths are observed from exact inverse +recurrences outside the timed phases. Memory allocations are measured in +separate untimed passes. +""" +from __future__ import annotations + +import argparse +from collections import Counter,defaultdict +from dataclasses import replace +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 +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 +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 + +SCHEMA="nor18r.executable_cpu_bigint_memory_source_locked.v1" +FIXTURE_SCHEMA="nor18r.public_fixture_64_cases_from_original_288.v1" +NOR18_ZIP=ROOT/"research/nor18_costed_prefix/results/nor18_full.zip" +NOR18_SHA="9905aa23466b98ba2068e6daf9206d35c453b8b3b75bd27c3ab7ff8f0db4041b" +CHECKPOINT_SHA="54f225f2a61c52fee5a740576eaab3bcbc5280a595fc1ac1ac115ec8ac26c41b" +MODES=("independent16","cached16","prefix160","prefix176") +SAMPLES_PER_REP={"late_source":8,"signed":4,"rational":4} +COHORTS=4 +SOURCES=64 +TIMED_REPS=7 +WARMUPS=2 +BOOTSTRAPS=4096 +SEED=202611181816 +QUERY_DEGREE=256 +PUBLIC_DEGREE=192 + + +def serialized(obj): + return json.dumps(obj,sort_keys=True,separators=(",",":")) + + +def read_nor18(): + with ZipFile(NOR18_ZIP) as z: + assert z.namelist()==["nor18_full.json"] + assert z.testzip() is None + source=z.read("nor18_full.json") + assert len(source)==12896423 + assert sha256(source).hexdigest()==NOR18_SHA + d=json.loads(source) + assert d["source_checkpoint_sha256"]==CHECKPOINT_SHA + assert d["all_cases"]==288 + assert len(d["records"])==288 + assert d["primary_late_distinct_complete_public_inputs"]==192 + return d + + +def fixture_from_locked_source(): + d=read_nor18() + original=nor11.sample_cohorts(nor12.SPLIT_COUNTS) + batches=nor18.fresh_cohorts(original) + assert len(batches)==4 and len(d["cohorts"])==4 + selected=[] + for rep,batch in enumerate(batches): + assert len(batch)==72 + manifest=sha256("\n".join( + nor16.full_public_digest(case) for case,h,public_digest in batch + ).encode()).hexdigest() + assert manifest==d["cohorts"][rep]["public_manifest_sha256"] + for ix,(case,header,model_hash) in enumerate(batch): + published=d["records"][rep*72+ix] + assert case.family==published["family"] + assert nor16.full_public_digest(case)==published["full_public_input_sha256"] + assert nor11.public_digest(case,header)==model_hash==published["model_visible_sha256"] + # Original cohort order: 48 late_source, 12 signed, 12 rational. + chosen_indexes=list(range(8))+list(range(48,52))+list(range(60,64)) + assert Counter(batch[i][0].family for i in chosen_indexes)==SAMPLES_PER_REP + for ix in chosen_indexes: + case,head,model_hash=batch[ix] + published=d["records"][rep*72+ix] + demos=[[list(source[:PUBLIC_DEGREE+1]), + list(output[:PUBLIC_DEGREE+1])] + for source,output in case.demos] + selected.append({ + "cohort":rep, + "original_index":rep*72+ix, + "family":case.family, + "original_full_public_sha256":published["full_public_input_sha256"], + "original_model_input_sha256":model_hash, + "public_header":{"base":head.base, + "delay":head.delay, + "spacing":head.spacing, + "amplitude":head.amplitude}, + "demos":demos, + "public_query_input":list(case.query), + "original_exact_full_accept_mask":published["retro_full_accepted_mask"], + "original_public_future_output_identifiable": + published["certificate_possible_from_complete_public_mask"], + }) + assert len(selected)==SOURCES + assert len({s["original_full_public_sha256"] for s in selected})==64 + assert Counter(s["family"] for s in selected)=={ + "late_source":32,"signed":16,"rational":16} + return { + "schema":FIXTURE_SCHEMA, + "NOR18_original_evidence_sha256":NOR18_SHA, + "frozen_checkpoint_sha256":CHECKPOINT_SHA, + "source_selection":"four cohorts, 8 late + 4 signed + 4 rational each", + "cases":selected, + "public_only":True, + "no_hidden_query_outputs_or_planted_program_identities":True, + } + + +def load_fixture(path): + raw=Path(path).read_bytes() + obj=json.loads(raw) + assert obj["schema"]==FIXTURE_SCHEMA + assert obj["NOR18_original_evidence_sha256"]==NOR18_SHA + assert obj["frozen_checkpoint_sha256"]==CHECKPOINT_SHA + assert obj["public_only"] + assert obj["no_hidden_query_outputs_or_planted_program_identities"] + assert len(obj["cases"])==SOURCES + assert Counter(z["family"] for z in obj["cases"])=={ + "late_source":32,"signed":16,"rational":16} + assert len({z["original_full_public_sha256"] for z in obj["cases"]})==64 + return obj + + +def unpack_case(row): + h=row["public_header"] + header=corpus.Header(h["base"],h["delay"],h["spacing"],h["amplitude"]) + demos=tuple((tuple(x),tuple(y)) for x,y in row["demos"]) + query=tuple(row["public_query_input"]) + assert len(demos)==2 and all(len(x)==len(y)==193 for x,y in demos) + assert len(query)==257 + # Private source program and future query truth deliberately absent. + c=corpus.Case(f"nor18r-{row['original_index']}",row["family"], + demos,query,(),None) + assert nor16.full_public_digest(c)==row["original_full_public_sha256"] + assert nor11.public_digest(c,header)==row["original_model_input_sha256"] + return c,header + + +def mask_independent(c,h): + """Unmodified native exact full verification of 16 templates.""" + return sum(1<=0 for t in times.values()) + return {"mask":mask,"unanimous":unanimous, + "chosen_class":chosen,"times":times} + return {"mask":mask,"unanimous":unanimous,"chosen_class":chosen} + + +def exact_inverse_operand_ledger(f): + """Replay the actual degree-n R formal-series recurrence, counting + executed Python integer products and their observed operand bit widths. + + This is an operand-size PROXY. It measures real integer bit_length() + values but does not estimate native GMP cost or CPython clock ticks. + """ + assert f[0]==1 and len(f)>1 + inverse=[1] + products=0 + width_products=0 + peak_operand_bits=0 + peak_output_bits=1 + max_int_bytes=sys.getsizeof(1) + zero_operand_products=0 + for n in range(1,len(f)): + value=0 + for k in range(1,n+1): + a=f[k] + b=inverse[n-k] + products+=1 + if a==0 or b==0: + zero_operand_products+=1 + abit=max(1,abs(a).bit_length()) + bbit=max(1,abs(b).bit_length()) + width_products+=abit*bbit + peak_operand_bits=max(peak_operand_bits,abit,bbit) + value+=a*b + inverse.append(-value) + peak_output_bits=max(peak_output_bits,abs(value).bit_length()) + max_int_bytes=max(max_int_bytes,sys.getsizeof(inverse[-1])) + exact=corpus.d.operate(f,"R") + assert tuple(inverse)==exact + assert products==(len(f)-1)*len(f)//2 + return { + "multiplications":products, + "operand_bitwidth_products":width_products, + "zero_operand_multiplications":zero_operand_products, + "max_operand_bits":peak_operand_bits, + "max_inverse_coefficient_bits":peak_output_bits, + "max_inverse_coefficient_python_int_bytes":max_int_bytes, + } + + +def reciprocal_invocation_count(header,mode,source_masks): + """Number of R transforms in the actual public-demo verification.""" + per_check=lambda j:( + int(header.base=="R")+ + int(corpus.OPS[j//4]=="R")+ + int(corpus.OPS[j%4]=="R") + ) + if mode=="independent16": + return 16*int(header.base=="R")+8 + if mode=="cached16": + return 1 + degree=160 if mode=="prefix160" else 176 + prefix=source_masks[str(degree)] + return 1+sum(per_check(j) for j in range(16) if prefix&(1<=warmups: + per_mode[mode].append(measured["times"]) + assert all(len(v)==TIMED_REPS for v in per_mode.values()) + medians={mode:{ + "query_ns":median_ns(per_mode[mode],"query_ns"), + "verification_ns":median_ns(per_mode[mode],"verification_ns"), + "certificate_ns":median_ns(per_mode[mode],"certificate_ns"), + "total_ns":median_ns(per_mode[mode],"total_ns")} + for mode in MODES} + temporary={mode:ephemeral_memory_profile(c,h,mode) for mode in MODES} + assert all(z["mask"]==expected[0] for z in temporary.values()) + short={str(degree):nor17.prefix_mask(c,h,degree) + for degree in (160,176)} + bigint=integer_cost_ledger(c,h,short) + speed=medians["independent16"]["total_ns"]/max( + 1.,medians["cached16"]["total_ns"]) + output.append({ + "cohort":row["cohort"], + "family":row["family"], + "original_index":row["original_index"], + "full_public_input_sha256":row["original_full_public_sha256"], + "public_header":row["public_header"], + "reference_full_public_accept_mask":expected[0], + "reference_unanimous_future_output":expected[1], + "full_accepted_template_count":expected[0].bit_count(), + "prefix_public_survivor_masks":short, + "algorithm_result_parity_all_modes":True, + "measured_ns":per_mode, + "median_ns":medians, + "untimed_tracemalloc":temporary, + "bigint_operand_width_ledger":bigint, + "speedup_independent_over_cached_total":speed, + }) + assert families=={"late_source":32,"signed":16,"rational":16} + ratios=[x["speedup_independent_over_cached_total"] for x in output] + median_ratio=statistics.median(ratios) + primary_pass=( + median_ratio>=1.5 and + sum(x>1 for x in ratios)>=48 and + all(x["algorithm_result_parity_all_modes"] for x in output) + ) + def family_summary(rows): + selected=[x for x in output if x["family"] in rows] + if not selected:return None + return { + "cases":len(selected), + "median_paired_total_speedup":statistics.median( + x["speedup_independent_over_cached_total"] for x in selected), + "cached_faster_cases":sum( + x["speedup_independent_over_cached_total"]>1 for x in selected), + "per_mode_median_total_ms":{mode:statistics.median( + x["median_ns"][mode]["total_ns"] for x in selected)/1e6 + for mode in MODES}, + "per_mode_median_verification_ms":{mode:statistics.median( + x["median_ns"][mode]["verification_ns"] for x in selected)/1e6 + for mode in MODES}, + "per_mode_median_temporary_tracemalloc_KiB":{mode:statistics.median( + x["untimed_tracemalloc"][mode][ + "python_tracemalloc_peak_bytes"] for x in selected)/1024 + for mode in MODES}, + "per_mode_total_R_integer_multiplications":{mode:sum( + x["bigint_operand_width_ledger"]["per_mode"][mode][ + "R_integer_multiplications_executed"] for x in selected) + for mode in MODES}, + "per_mode_total_R_operand_width_product_proxy":{mode:sum( + x["bigint_operand_width_ledger"]["per_mode"][mode][ + "R_operand_bitwidth_product_proxy"] for x in selected) + for mode in MODES}, + } + return { + "schema":SCHEMA, + "original_NOR18_full_JSON_SHA256":NOR18_SHA, + "fixture_schema":FIXTURE_SCHEMA, + "fixture_sha256":sha256(Path(fixture_path).read_bytes()).hexdigest(), + "fixture_cases":SOURCES, + "source_families":dict(families), + "timed_repetitions":TIMED_REPS, + "untimed_warmups_per_case_per_algorithm":WARMUPS, + "modes":list(MODES), + "host":host_info(), + "elapsed_setup_excluded_from_timing":True, + "query_input_degree":QUERY_DEGREE, + "public_demo_degree":PUBLIC_DEGREE, + "per_case":output, + "summary_all":family_summary(set(families)), + "summary_by_family":{family:family_summary({family}) for family in families}, + "primary_median_paired_total_speedup":median_ratio, + "primary_cached_faster_cases":sum(v>1 for v in ratios), + "primary_fraction_cached_faster":sum(v>1 for v in ratios)/SOURCES, + "primary_cohort_block_bootstrap":block_bootstrap(output), + "primary_preregistered_speedup_threshold":1.5, + "primary_preregistered_faster_case_threshold":48, + "primary_preregistered_passed":primary_pass, + "isolated_process_RSS_KiB":isolated_rss(fixture_path), + "scope":{ + "all_source_inputs_from_original_NOR18_288_case_test":True, + "exact_public_mask_and_certificate_match_original_for_every_mode":True, + "future_outputs_and_private_generator_programs_not_in_fixture":True, + "native_independent_full_verifier_is_unmodified":True, + "cached_public_verifier_uses_existing_NOR17_compound_series":True, + "fixed_public_query_recomputed_for_each_mode":True, + "time_includes_python_bigint_implementation_effects":True, + "input_serialization_and_cohort_generation_excluded_from_timing":True, + "cohort_bootstrap_not_independent_research_replication":True, + "reciprocal_integer_operand_width_products_are_cost_proxy":True, + "RSS_and_tracemalloc_measured_in_separate_untimed_passes":True, + "no_general_theorem_proving_or_GPU_speedup_claim":True, + }, + } + + +def main(): + p=argparse.ArgumentParser() + p.add_argument("--make-fixture",type=Path) + p.add_argument("--fixture",type=Path) + p.add_argument("--out",type=Path) + p.add_argument("--repetitions",type=int,default=TIMED_REPS) + p.add_argument("--warmups",type=int,default=WARMUPS) + p.add_argument("--rss-worker",choices=MODES) + p.add_argument("--check",action="store_true") + args=p.parse_args() + if args.make_fixture: + fixture=fixture_from_locked_source() + args.make_fixture.parent.mkdir(parents=True,exist_ok=True) + args.make_fixture.write_text(json.dumps( + fixture,indent=2,sort_keys=True)+"\n") + assert len(fixture["cases"])==SOURCES + print("NOR18R ORIGINAL SOURCE INTEGRITY AND PUBLIC-ONLY FIXTURE PASSED", + {"cases":64,"sha256":sha256( + args.make_fixture.read_bytes()).hexdigest()}) + return + if not args.fixture: + p.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["fixture_cases"]==64 + assert result["timed_repetitions"]==7 + assert result["primary_cached_faster_cases"]<=64 + assert result["primary_cohort_block_bootstrap"]["draws"]==4096 + assert len(result["per_case"])==64 + assert all(x["algorithm_result_parity_all_modes"] for x in result["per_case"]) + doc=json.dumps(result,indent=2,sort_keys=True)+"\n" + if args.out: + args.out.parent.mkdir(parents=True,exist_ok=True) + args.out.write_text(doc) + else: + print(doc,end="") + + +if __name__=="__main__": + main() diff --git a/research/nor18r_runtime/receipt_audit.py b/research/nor18r_runtime/receipt_audit.py new file mode 100644 index 000000000..8ec6cb30c --- /dev/null +++ b/research/nor18r_runtime/receipt_audit.py @@ -0,0 +1,413 @@ +"""Independent NOR-18R source-only artifact and measured arithmetic auditor. + +Uses no benchmark module or benchmark trained model. Reads archived original +public fixture and first-hosted timing JSON, verifies their immutable byte +SHA-256 hashes, reconstructs all public masks with the ORIGINAL native +corpus checker, replays candidate query outputs, inverse operand widths, +per-case sample medians, and all registered aggregate speed/memory claims. + +Measured wall-clock times are observed data. This audit checks the samples +and arithmetic but cannot reproduce identical nanosecond timings on a +different CPU run. It does not consult a planted program or withheld future. +""" +from __future__ import annotations + +from collections import Counter,defaultdict +from hashlib import sha256 +import argparse +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 + +RECEIPT=HERE/"results"/"nor18r_first_frozen_receipt.json" +ORIGINAL_RUN_SHA="59d48c8c9fe1bdf80ee2662d0c18f069f8414a92d48ad7980e3bb19b2a10ad98" +ORIGINAL_FIXTURE_SHA="5d75f2971d8b94daa9b65caae68e65921f2a90cd267481c7bb80a881e937d186" +ORIGINAL_NOR18_SHA="9905aa23466b98ba2068e6daf9206d35c453b8b3b75bd27c3ab7ff8f0db4041b" +MODES=("independent16","cached16","prefix160","prefix176") +SEED=202611181816 + + +def ref_receipt(): + r=json.loads(RECEIPT.read_text()) + assert r["schema"]=="nor18r.first_hosted_source_locked_cpu_and_bigint_receipt.v1" + assert r["original_benchmark_json_sha256"]==ORIGINAL_RUN_SHA + assert r["original_benchmark_bytes"]==580813 + assert r["public_fixture_json_sha256"]==ORIGINAL_FIXTURE_SHA + assert r["public_fixture_bytes"]==1306733 + assert r["source_nor18_original_json_sha256"]==ORIGINAL_NOR18_SHA + assert r["source_cases"]==64 and r["source_cohorts"]==4 + assert r["primary_preregistered_passed"] is True + assert r["primary_source_cases_cached_faster"]==64 + assert r["primary_median_paired_end_to_end_speedup_cached_vs_independent"]==4.328780845629943 + assert r["modes"]==list(MODES) + return r + + +def fixture_public_case(item): + assert set(item)=={ + "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 item["cohort"] in (0,1,2,3) + index=item["original_index"] + assert index//72==item["cohort"] + off=index%72 + assert (item["family"]=="late_source" and off in range(8) + or item["family"]=="signed" and off in range(48,52) + or item["family"]=="rational" and off in range(60,64)) + assert len(item["demos"])==2 + assert all(len(f)==len(y)==193 and f[0]==1 + for f,y in item["demos"]) + assert len(item["public_query_input"])==257 + assert item["public_query_input"][0]==1 + assert set(item["public_header"])=={"base","delay","spacing","amplitude"} + h=item["public_header"] + assert h["base"] in corpus.OPS + assert h["delay"] in corpus.DELAYS + assert h["spacing"] in corpus.SPACINGS + assert h["amplitude"] in corpus.AMPLITUDES + digest=sha256(json.dumps( + [item["demos"],item["public_query_input"]], + separators=(",",":")).encode()).hexdigest() + assert digest==item["original_full_public_sha256"] + assert len(item["original_model_input_sha256"])==64 + demos=tuple((tuple(f),tuple(y)) for f,y in item["demos"]) + c=corpus.Case(str(index),item["family"],demos, + tuple(item["public_query_input"]),(),None) + header=corpus.Header(h["base"],h["delay"],h["spacing"],h["amplitude"]) + return c,header + + +def original_native_accept_mask(c,header): + return sum(1<=0 for value in x.values()) + assert x["total_ns"]==x["query_ns"]+x["verification_ns"]+x["certificate_ns"] + assert x["total_ns"]>0 + for key in ("query_ns","verification_ns","certificate_ns","total_ns"): + assert approximately(statistics.median(x[key] for x in records), + obs["median_ns"][mode][key]) + mem=obs["untimed_tracemalloc"][mode] + assert mem["mask"]==mask + assert 0<=mem["python_tracemalloc_current_bytes"]<=mem[ + "python_tracemalloc_peak_bytes"] + speed=obs["median_ns"]["independent16"]["total_ns"]/obs[ + "median_ns"]["cached16"]["total_ns"] + assert approximately(speed,obs["speedup_independent_over_cached_total"]) + independent_bigint_check(c,header,obs) + assert counts=={"late_source":32,"signed":16,"rational":16} + ratios=[r["speedup_independent_over_cached_total"] for r in z["per_case"]] + assert approximately(statistics.median(ratios),z[ + "primary_median_paired_total_speedup"]) + assert approximately(statistics.median(ratios),receipt[ + "primary_median_paired_end_to_end_speedup_cached_vs_independent"]) + assert sum(x>1 for x in ratios)==z["primary_cached_faster_cases"]==64 + lo,hi=independent_bootstrap(z["per_case"]) + ci=z["primary_cohort_block_bootstrap"] + assert approximately(ci["percentile_2_5"],lo) + assert approximately(ci["percentile_97_5"],hi) + assert approximately(lo,receipt["cohort_block_bootstrap_95"][0]) + assert approximately(hi,receipt["cohort_block_bootstrap_95"][1]) + summary=z["summary_all"] + for mode in MODES: + median_total=statistics.median(r["median_ns"][mode]["total_ns"] + for r in z["per_case"])/1e6 + median_verification=statistics.median( + r["median_ns"][mode]["verification_ns"] for r in z["per_case"])/1e6 + median_peak=statistics.median( + r["untimed_tracemalloc"][mode]["python_tracemalloc_peak_bytes"] + for r in z["per_case"])/1024 + assert approximately(median_total,summary["per_mode_median_total_ms"][mode]) + assert approximately(median_total,receipt["per_mode_median_total_ms"][mode]) + assert approximately(median_verification,summary[ + "per_mode_median_verification_ms"][mode]) + assert approximately(median_peak,summary[ + "per_mode_median_temporary_tracemalloc_KiB"][mode]) + assert approximately(median_peak,receipt[ + "per_mode_median_python_tracemalloc_peak_KiB"][mode]) + for output_key,source_key,receipt_key in ( + ("per_mode_total_R_integer_multiplications", + "R_integer_multiplications_executed", + "per_mode_total_native_R_integer_products"), + ("per_mode_total_R_operand_width_product_proxy", + "R_operand_bitwidth_product_proxy", + "per_mode_total_R_operand_bitwidth_product_proxy")): + expected=sum(r["bigint_operand_width_ledger"]["per_mode"][mode][ + source_key] for r in z["per_case"]) + assert summary[output_key][mode]==expected==receipt[receipt_key][mode] + rss=z["isolated_process_RSS_KiB"][mode] + assert rss["mode"]==mode and rss["cases"]==64 + assert rss["process_exit_separate"] + assert rss["baseline_peak_rss_KiB_before_algorithm"]==receipt[ + "memory_isolated_process_baseline_RSS_KiB"][mode] + assert rss["process_peak_rss_KiB_after_algorithm"]==receipt[ + "memory_isolated_process_peak_RSS_KiB"][mode] + assert rss["max_rss_increase_KiB"]==0 + + for fam,source_summary in z["summary_by_family"].items(): + selected=[x for x in z["per_case"] if x["family"]==fam] + assert source_summary["cases"]==len(selected) + assert approximately(statistics.median( + x["speedup_independent_over_cached_total"] for x in selected), + source_summary["median_paired_total_speedup"]) + assert approximately(source_summary["median_paired_total_speedup"], + receipt["family_median_paired_speedup"][fam]) + + for flag in ( + "all_source_inputs_from_original_NOR18_288_case_test", + "exact_public_mask_and_certificate_match_original_for_every_mode", + "future_outputs_and_private_generator_programs_not_in_fixture", + "native_independent_full_verifier_is_unmodified", + "cached_public_verifier_uses_existing_NOR17_compound_series", + "fixed_public_query_recomputed_for_each_mode", + "time_includes_python_bigint_implementation_effects", + "input_serialization_and_cohort_generation_excluded_from_timing", + "cohort_bootstrap_not_independent_research_replication", + "reciprocal_integer_operand_width_products_are_cost_proxy", + "RSS_and_tracemalloc_measured_in_separate_untimed_passes", + "no_general_theorem_proving_or_GPU_speedup_claim", + ): + assert z["scope"][flag],flag + return { + "public_only_source_cases":64, + "distinct_source_hashes_verified":64, + "source_cohorts":4, + "exact_native_masks_and_certificates_recomputed":64, + "timed_samples_checked":64*4*7, + "untimed_memory_records_checked":64*4, + "bigint_operand_width_ledgers_replayed":64, + "four_cohort_bootstrap_recomputed":4096, + "registered_performance_criterion_passed":True, + "paired_complete_CPU_speedup":statistics.median(ratios), + } + + +def main(): + p=argparse.ArgumentParser() + p.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() + pinned=ref_receipt() + if args.archive: + assert args.fixture is None and args.full is None + with ZipFile(args.archive) as z: + assert sorted(z.namelist())==[ + "nor18r_full.json","nor18r_public_fixture.json"] + assert z.testzip() is None + original_fixture=z.read("nor18r_public_fixture.json") + original_run=z.read("nor18r_full.json") + elif args.fixture and args.full: + original_fixture=args.fixture.read_bytes() + original_run=args.full.read_bytes() + else: + print("NOR18R FIRST ORIGINAL PUBLIC FIXTURE / BENCHMARK HASH RECEIPT VALID") + return + assert len(original_fixture)==pinned["public_fixture_bytes"] + assert len(original_run)==pinned["original_benchmark_bytes"] + assert sha256(original_fixture).hexdigest()==ORIGINAL_FIXTURE_SHA + assert sha256(original_run).hexdigest()==ORIGINAL_RUN_SHA + report=audit(original_fixture,original_run,pinned) + print("NOR18R INDEPENDENT CPU BIGINT MEMORY AUDIT PASSED",report) + if args.check: + assert report["source_cohorts"]==4 + assert report["timed_samples_checked"]==1792 + + +if __name__=="__main__": + main() diff --git a/research/nor18r_runtime/results/nor18r_first_frozen_receipt.json b/research/nor18r_runtime/results/nor18r_first_frozen_receipt.json new file mode 100644 index 000000000..4d88cc2f1 --- /dev/null +++ b/research/nor18r_runtime/results/nor18r_first_frozen_receipt.json @@ -0,0 +1,96 @@ +{ + "schema": "nor18r.first_hosted_source_locked_cpu_and_bigint_receipt.v1", + "executed_utc_date": "2026-11-16", + "original_hosted_run": "https://github.com/MoralityLabAI/Compactification-Theory/actions/runs/43797844269", + "original_artifact_id": 14195445905, + "original_artifact_name": "nor18r-original-public-only-64-case-fixture-and-timing-results", + "public_fixture_json_sha256": "5d75f2971d8b94daa9b65caae68e65921f2a90cd267481c7bb80a881e937d186", + "public_fixture_bytes": 1306733, + "original_benchmark_json_sha256": "59d48c8c9fe1bdf80ee2662d0c18f069f8414a92d48ad7980e3bb19b2a10ad98", + "original_benchmark_bytes": 580813, + "source_nor18_original_json_sha256": "9905aa23466b98ba2068e6daf9206d35c453b8b3b75bd27c3ab7ff8f0db4041b", + "source_original_checkpoint_sha256": "54f225f2a61c52fee5a740576eaab3bcbc5280a595fc1ac1ac115ec8ac26c41b", + "host": { + "python": "CPython 3.12.16", + "compiler": "GCC 15.2.0", + "cpu_arch": "x86_64", + "os": "Linux 7.0.0-1019-azure x86_64 glibc 2.43", + "logical_cpu_count": 4 + }, + "source_cases": 64, + "source_family_counts": { + "late_source": 32, + "signed": 16, + "rational": 16 + }, + "source_cohorts": 4, + "source_selection": "8 late, 4 signed, 4 rational from original NOR18 per cohort", + "timed_samples_per_case_per_algorithm": 7, + "warmups_per_case_per_algorithm": 2, + "modes": [ + "independent16", + "cached16", + "prefix160", + "prefix176" + ], + "primary_median_paired_end_to_end_speedup_cached_vs_independent": 4.328780845629943, + "primary_source_cases_cached_faster": 64, + "primary_registered_speedup_threshold": 1.5, + "primary_registered_faster_case_threshold": 48, + "cohort_block_bootstrap_95": [ + 4.280324127583885, + 4.395943169762888 + ], + "bootstrap_draws": 4096, + "primary_preregistered_passed": true, + "per_mode_median_total_ms": { + "independent16": 23.9128035, + "cached16": 4.327269, + "prefix160": 12.330759, + "prefix176": 8.8359965 + }, + "per_mode_median_verification_ms": { + "independent16": 21.2912325, + "cached16": 2.265918, + "prefix160": 9.706176, + "prefix176": 5.7443145 + }, + "per_mode_median_python_tracemalloc_peak_KiB": { + "independent16": 74.1171875, + "cached16": 128.244140625, + "prefix160": 112.771484375, + "prefix176": 120.646484375 + }, + "per_mode_total_native_R_integer_products": { + "independent16": 31750144, + "cached16": 4476928, + "prefix160": 18724608, + "prefix176": 16549888 + }, + "per_mode_total_R_operand_bitwidth_product_proxy": { + "independent16": 845306615, + "cached16": 163683594, + "prefix160": 227918645, + "prefix176": 215773495 + }, + "family_median_paired_speedup": { + "late_source": 4.395943169762888, + "signed": 4.3228197397623855, + "rational": 4.2036264314713865 + }, + "memory_isolated_process_peak_RSS_KiB": { + "independent16": 29364, + "cached16": 29364, + "prefix160": 29364, + "prefix176": 29364 + }, + "memory_isolated_process_baseline_RSS_KiB": { + "independent16": 29364, + "cached16": 29364, + "prefix160": 29364, + "prefix176": 29364 + }, + "all_64_source_public_masks_identical_across_four_algorithms": true, + "all_64_source_unanimity_certificates_identical_across_four_algorithms": true, + "scientific_scope": "First hosted execution under one GitHub Actions CPU runner. Exact public mask parity, seven paired measured time repetitions per mode on 64 fixed sources. Four-cohort bootstrap is conditional on this source set and run. Bigint operand-bitwidth products are separately measured size proxy. Memory Python tracemalloc separate untimed measurements; Linux isolated process RSS showed no change above startup/fixture baseline. No general CPU/hardware performance guarantee." +} diff --git a/research/nor18r_runtime/results/nor18r_original_hosted.zip b/research/nor18r_runtime/results/nor18r_original_hosted.zip new file mode 100644 index 000000000..366b6f04f Binary files /dev/null and b/research/nor18r_runtime/results/nor18r_original_hosted.zip differ diff --git a/research/nor18r_runtime/test_runtime.py b/research/nor18r_runtime/test_runtime.py new file mode 100644 index 000000000..1d89879ae --- /dev/null +++ b/research/nor18r_runtime/test_runtime.py @@ -0,0 +1,117 @@ +"""NOR-18R tests: public-source parity, reciprocal operands and CPU accounting.""" +from __future__ import annotations +from dataclasses import replace +from collections import Counter +import json +import math +import random +import statistics +import unittest + +from research.nor18r_runtime import benchmark as r +from research.rrc_compactification import compound25 as corpus + + +class NOR18RuntimeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + rng=random.Random(202611181816) + cases=[] + for family in ("late_source","signed","rational"): + for t in range(100): + case=corpus.make_case(rng,family,f"nor18r-parity-{family}-{t}") + heads=corpus.possible_headers(case) + if len(heads)==1: + cases.append((case,heads[0])) + break + else: + raise AssertionError("could not generate positive unique public header") + cls.cases=cases + + def test_exact_public_full_masks_and_prediction_certificates_equal(self): + for case,header in self.cases: + expected=r.mask_independent(case,header) + self.assertGreater(expected,0) + for mode in r.MODES: + self.assertEqual(r.evaluated_full_mask(case,header,mode),expected) + out=r.outcome(case,header,mode) + self.assertEqual(out["mask"],expected) + self.assertEqual(out["unanimous"],r.outcome( + case,header,"independent16")["unanimous"]) + + def test_sealed_future_and_program_identity_do_not_change_algorithms(self): + for c,h in self.cases: + contaminated=replace(c,program=None, + future=tuple(123456789 for _ in c.future)) + for mode in r.MODES: + self.assertEqual(r.outcome(c,h,mode), + r.outcome(contaminated,h,mode)) + + def test_public_exact_inverse_recursion_product_counts(self): + for c,h in self.cases: + for f,y in c.demos: + inv=r.exact_inverse_operand_ledger(f[:193]) + self.assertEqual(inv["multiplications"],192*193//2) + self.assertGreater(inv["operand_bitwidth_products"],0) + self.assertGreaterEqual(inv["max_operand_bits"],1) + self.assertGreaterEqual(inv["max_inverse_coefficient_bits"],1) + self.assertGreater(inv["max_inverse_coefficient_python_int_bytes"],0) + query=r.exact_inverse_operand_ledger(c.query) + self.assertEqual(query["multiplications"],256*257//2) + assert query["operand_bitwidth_products"]>0 + + def test_per_mode_reciprocal_count_and_width_ledger(self): + for c,h in self.cases: + short={str(d):r.nor17.prefix_mask(c,h,d) for d in (160,176)} + x=r.integer_cost_ledger(c,h,short) + self.assertEqual(set(x["per_mode"]),set(r.MODES)) + self.assertEqual(x["per_mode"]["cached16"]["R_invocations_full_public_demos"],2) + self.assertEqual(x["per_mode"]["independent16"]["R_invocations_full_public_demos"], + 2*(16*int(h.base=="R")+8)) + self.assertEqual(x["per_mode"]["cached16"]["R_invocations_query"],1) + self.assertGreater( + x["per_mode"]["independent16"]["R_operand_bitwidth_product_proxy"], + x["per_mode"]["cached16"]["R_operand_bitwidth_product_proxy"]) + self.assertEqual( + x["per_mode"]["independent16"]["R_integer_multiplications_executed"]- + x["per_mode"]["cached16"]["R_integer_multiplications_executed"], + 2*((16*int(h.base=="R")+8)-1)*192*193//2) + + def test_peak_memory_is_untimed_and_matches_public_mask(self): + c,h=self.cases[0] + for mode in r.MODES: + z=r.ephemeral_memory_profile(c,h,mode) + self.assertEqual(z["mask"],r.mask_independent(c,h)) + self.assertGreaterEqual(z["python_tracemalloc_peak_bytes"], + z["python_tracemalloc_current_bytes"]) + self.assertGreater(z["python_tracemalloc_peak_bytes"],0) + + def test_full_benchmark_schema_and_bootstrap(self): + cases=[] + for cohort in range(4): + for i in range(16): + cases.append({ + "cohort":cohort, + "speedup_independent_over_cached_total":2.0+cohort*.1, + }) + b=r.block_bootstrap(cases,draws=128) + self.assertEqual(b["draws"],128) + self.assertLessEqual(b["percentile_2_5"],b["percentile_97_5"]) + self.assertTrue(2<=b["percentile_2_5"]<=b["percentile_97_5"]<=2.3) + self.assertEqual(len(r.MODES),4) + self.assertEqual(r.SOURCES,64) + self.assertEqual(r.TIMED_REPS,7) + self.assertEqual(r.WARMUPS,2) + self.assertEqual(r.BOOTSTRAPS,4096) + + def test_ledger_has_zero_unpaid_future_access(self): + c,h=self.cases[0] + masked=corpus.Case(c.identifier,c.family,c.demos,c.query,(),None) + for mode in r.MODES: + self.assertEqual(r.outcome(c,h,mode),r.outcome(masked,h,mode)) + self.assertEqual(r.QUERY_DEGREE,256) + self.assertEqual(r.PUBLIC_DEGREE,192) + + +if __name__=="__main__": + unittest.main()