"""Bounded exact-source CUDA plumbing gate; never a flow-accuracy certificate. Run this driver externally against exact dev with --mode baseline first, then against the experimental source with --mode candidate --baseline . Only scalar receipts/hashes and actual compiler sidecars are retained. Whole-step mass/momentum are diagnostics: no verified FP32 conservation bound is claimed. """ import argparse from contextlib import contextmanager from dataclasses import replace import hashlib import json import os import shutil from pathlib import Path import subprocess import sys import numpy as np BASE = 'ed9d8c937d446b854d6963bd92d718bb4fb98b96' PRODUCTION = 'a135252ae78b47b57d7e77d19001700b3bedac8b' STOPS = (0, 1, 2, 8) OPERATOR_ATOL, OPERATOR_RTOL = 6e-8, 2e-7 REST_ATOL, REST_RTOL = 3e-7, 1e-6 REPLAY_ATOL = 3e-6 E = np.array([(0,0),(1,0),(-1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)]) W = np.array([4/9]+[1/9]*4+[1/36]*4) def digest(array): """All finite bits (including signed zero) and exact NaN mask; no NaN payloads.""" array = np.asarray(array) if np.isinf(array).any(): raise AssertionError('infinite population') finite = np.isfinite(array) h = hashlib.sha256() h.update(str((array.shape, array.dtype.str)).encode()) h.update(np.ascontiguousarray(finite).tobytes()) h.update(np.ascontiguousarray(array[finite]).tobytes()) return h.hexdigest() def independent_explosion(coarse, pair, layout, kind): """Coordinate oracle; never reads the production neighbor/offset tables.""" ny, nx = pair.coarse_shape legal = np.zeros((ny,nx), bool) legal.ravel()[pair.ghost_coarse] = True legal &= layout.owned & ~pair.covered & (kind == 0) if not legal.ravel()[pair.ghost_coarse].all(): raise AssertionError('illegal center donor') out = np.empty((9,len(pair.ghost_fine))) flat = np.asarray(coarse, np.float64).reshape(9,-1) for row, (target, donor) in enumerate(zip(pair.ghost_fine,pair.ghost_coarse)): y,x = divmod(int(donor),nx) gradient = np.zeros((9,2)) for axis, (dx,dy) in enumerate(((1,0),(0,1))): ends = [(x-dx,y-dy),(x+dx,y+dy)] if not layout.periodic[axis] and any(not (0<=xx 8*1024*1024: raise RuntimeError('receipt exceeds 8 MiB cap') temporary = args.output.with_suffix(args.output.suffix+'.tmp') temporary.write_text(text); os.replace(temporary,args.output) save() if args.dry_run: print('Source preflight only; no CUDA imports or execution.'); return try: from CelerisLab.cuda.context import CudaContext from test_refinement_blocked_base import raw with CudaContext(0) as ctx, capture_builds(report,save,baseline): import pycuda.driver as cuda report['device'] = dict(name=ctx.device.name(),pci_bus_id=ctx.device.pci_bus_id(), capability=list(ctx.device.compute_capability()), driver=cuda.get_driver_version(),runtime=list(cuda.get_version())) nvcc = shutil.which('nvcc') or '/usr/local/cuda/bin/nvcc' report['nvcc_version'] = subprocess.check_output([nvcc,'--version'],text=True).strip() if baseline and (report['device'] != baseline.get('device') or report['nvcc_version'] != baseline.get('nvcc_version') or selected != baseline.get('device_selection')): raise ValueError('baseline GPU/device selection or toolchain differs') for name,case in cases().items(): for shifted in (False,True): key = f'{name}:shifted={shifted}' report['active_case'] = f'default:{key}' result = run_case(ctx,case,shifted,'omitted',raw) report['default_snapshots'][key] = result['snapshots'] if baseline: compare_snapshots(result['snapshots'],baseline['default_snapshots'][key]) explicit = run_case(ctx,case,shifted,'constant',raw) compare_snapshots(explicit['snapshots'],result['snapshots']) report['default_equivalence'].append(dict(case=key,passed=True)) save() if baseline: for name,case in cases().items(): for shifted in (False,True): report['active_case'] = f'projected:{name}:shifted={shifted}' result = run_case(ctx,case,shifted,'projected_linear',raw,True,name=='concave') cfg,refs,blocks = case if name == 'four': variant_refs = [list(reversed(rects)) for rects in refs] elif name == 'concave': variant_refs = [[(4,5,7,7),(4,4,5,5)]] # same union, disjoint decomposition else: variant_refs = refs variant = (cfg,variant_refs,[(2,2)]*len(blocks)) alternate = run_case(ctx,variant,shifted,'projected_linear',raw,True) compare_snapshots(alternate['snapshots'],result['snapshots']) report['projected_operator'].append(dict(case=name,shifted=shifted,rows=result['operator'])) report['union_multilevel_smoke'].append(dict(case=name,shifted=shifted,result=result, alternate_bits_identical=True)) save() for shifted in (False,True): report['active_case'] = f'changed-remap:shifted={shifted}' report['changed_remap'].append(remap_case(ctx,shifted,raw)); save() expected_builds = {(s['arch'],tuple(s['flags'])) for s in baseline['actual_build_sidecars']} actual_builds = {(s['arch'],tuple(s['flags'])) for s in report['actual_build_sidecars']} if actual_builds != expected_builds: raise AssertionError('baseline build architecture or compiler flags differ') report['completed'] = True save() except Exception as error: report['error'] = f'{type(error).__name__}: {error}' save(); raise print(json.dumps(dict(completed=True,mode=args.mode,receipt=str(args.output)))) if __name__ == '__main__': main()