Start bounded G1 copy calibration with fixed dimensionless route thresholds

This commit is contained in:
Frank14f committed 2026-11-14 21:28:47 +08:00
1 parent dbfb11ea42
commit 2ba7800d39
16 files changed
+876

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
"""Fixed-protocol geometric calibration; no simulation-field reads."""
from pathlib import Path
from zipfile import ZipFile
import argparse
import hashlib
import json
import os
import resource
import signal
import time
import numpy as np
from g1_registration_cost import geometry_only, register
from s2_e1_supervisor import save
ROOT = Path(os.environ.get('MELTMIND_G1_CALIBRATION_ROOT', 'artifacts/s2-g1-copy-calibration-2026-11-14'))
def transformed(g, kind, rotation, translation):
r = np.asarray(rotation, dtype=float)
t = np.asarray(translation, dtype=float)
if kind not in ('rigid', 'mirror', 'scale'):
raise ValueError('Unknown synthetic relation')
if not np.allclose(r.T @ r, np.eye(3), atol=1e-12, rtol=0) or abs(np.linalg.det(r)-1) > 1e-12:
raise ValueError('Base rotation must be proper')
a = r @ (np.diag([-1., 1., 1.]) if kind == 'mirror' else np.eye(3))
scale = 2. if kind == 'scale' else 1.
# Translation is expressed in multiples of the original volume Rg.
shift = t * float(g['rg'])
return {'points': scale * g['points'] @ a.T + shift,
'boundary': g['boundary'].copy(),
'center': scale * g['center'] @ a.T + shift,
'rg': np.asarray(scale * float(g['rg']))}
def check_contract(root):
c = json.loads((root/'contract.json').read_text())
for path, digest in c['code_sha256'].items():
if hashlib.sha256(Path(path).read_bytes()).hexdigest() != digest:
raise ValueError('Source changed after calibration freeze: '+path)
for path, digest in c['input_sha256'].items():
if hashlib.sha256(Path(path).read_bytes()).hexdigest() != digest:
raise ValueError('Calibration input changed: '+path)
return c
def load_geometry(case, contract, jobroot):
cache = Path(contract['existing_registration_cache'])/(case+'.npz')
if cache.exists():
with np.load(cache, allow_pickle=False) as z:
if set(z.files) != {'points','boundary','center','rg'}:
raise ValueError('Registration cache is not strictly geometry-only')
g = {k: z[k].copy() for k in z.files}
mode = 'existing_geometry_only_registration_cache'
else:
with ZipFile(contract['archive']) as z, z.open(case+'_sim.vtu') as stream:
g = geometry_only(stream)
mode = 'VTU_geometry_prefix_stop_before_field_associations'
if not all(np.isfinite(v).all() for v in g.values()) or float(g['rg']) <= 0:
raise ValueError('Nonfinite geometry or invalid Rg')
dest = jobroot/(case+'.npz')
if dest.exists():
raise FileExistsError('Never overwrite calibration geometry')
np.savez_compressed(dest, **g)
return g, mode
def expired(*_):
raise TimeoutError('Per-pair 1800 second wall-clock limit')
def main():
ap = argparse.ArgumentParser();ap.add_argument('index', type=int);args = ap.parse_args()
c = check_contract(ROOT)
verification = json.loads(Path(c['archive_verification']).read_text())
stat = Path(c['archive']).stat()
if (stat.st_size,stat.st_mtime_ns,stat.st_ino) != (verification['bytes'],verification['mtime_ns'],verification['inode']):
raise ValueError('Archive identity changed')
plan = json.loads((ROOT/'custodian/plan.json').read_text())
job = plan['jobs'][args.index]
work = ROOT/'custodian/results'/f'job-{args.index:02d}'
work.mkdir(parents=True, exist_ok=False)
start = time.monotonic();geometry = {};modes = {}
for case in sorted(set(job['cases'])):
geometry[case], modes[case] = load_geometry(case, c, work)
signal.signal(signal.SIGALRM, expired)
for pair in job['pairs']:
a = geometry[pair['a']]
b = geometry[pair['b']] if pair['kind']=='natural_visual_rigid' else transformed(a, pair['kind'], pair['rotation'], pair['unit_translation'])
begin = time.monotonic();signal.setitimer(signal.ITIMER_REAL, c['per_pair_wall_seconds'])
try:
routes = register(a, b, pair['source_sampling_prefix'], pair['target_sampling_prefix'])
finally:
signal.setitimer(signal.ITIMER_REAL, 0)
if not all(np.isfinite(r['residual_max_two_way_area_pps_p95']) for r in routes):
raise ValueError('Nonfinite registration residual')
rga, rgb = float(a['rg']), float(b['rg'])
save(work/(pair['id']+'.json'), {'pair':pair, 'routes':routes, 'wall_seconds':time.monotonic()-begin,
'source_rg':rga, 'target_rg':rgb, 'mean_rg':(rga+rgb)/2, 'rg_ratio':max(rga,rgb)/min(rga,rgb),
'simulation_labels_read':False, 'model_training':False,
'residual_definition':'Unchanged two-way area-PPS 2000 samples to full triangles P95, best start in each det branch'})
print(json.dumps({'pair_id':pair['id'],'kind':pair['kind'],'status':'RESIDUALS_COMPLETE'}),flush=True)
save(work/'complete.json', {'index':args.index,'pairs':len(job['pairs']),'source_modes':modes,
'cpu_seconds':sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),'wall_seconds':time.monotonic()-start,
'max_rss_bytes':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*1024,'all_pass':True})
if __name__=='__main__':main()
+75
View File
@@ -0,0 +1,75 @@
"""Freeze a new, reproducible calibration sample without consuming split RNGs."""
from pathlib import Path
import hashlib
import json
import numpy as np
from scipy.spatial.transform import Rotation
ROOT=Path('artifacts/s2-g1-copy-calibration-2026-11-14')
def save(path,value):
path.write_text(json.dumps(value,indent=2,ensure_ascii=False)+'\n')
def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def main():
ROOT.mkdir(exist_ok=False);private=ROOT/'custodian';private.mkdir(mode=0o700);(ROOT/'public').mkdir()
inventory=Path('artifacts/s2-g1-inventory-2026-11-14/custodian/parts.json')
rigid_path=Path('artifacts/s2-g1-custody-handoff-2026-11-14/custodian/rigid-calibration-inputs.json')
parts=json.loads(inventory.read_text());frame=sorted(p['case'] for p in parts)
assert len(frame)==len(set(frame))==624
children=np.random.SeedSequence([2026111414]).spawn(2)
sample=np.random.Generator(np.random.PCG64(children[0]));poses=np.random.Generator(np.random.PCG64(children[1]))
selected=sorted(sample.choice(frame,20,replace=False).tolist());jobs=[];pair_index=0
for case in selected:
pairs=[]
for kind in ['rigid','mirror','scale']:
pairs.append({'id':f'calib-{pair_index:03d}','a':case,'kind':kind,
'rotation':Rotation.random(random_state=poses).as_matrix().tolist(),
'unit_translation':poses.uniform(-3,3,3).tolist(),
'source_sampling_prefix':int(case.split('_')[0]),
'target_sampling_prefix':100000000+pair_index})
pair_index+=1
jobs.append({'cases':[case],'pairs':pairs})
rigid=json.loads(rigid_path.read_text())['pairs'];assert len(rigid)==2
for r in rigid:
pa,pb=int(r['a'].split('_')[0]),int(r['b'].split('_')[0]);assert pa!=pb
jobs.append({'cases':[r['a'],r['b']],'pairs':[{'id':f'calib-{pair_index:03d}',
'a':r['a'],'b':r['b'],'kind':'natural_visual_rigid','anonymous_pair_id':r['anonymous_pair_id'],
'source_sampling_prefix':pa,'target_sampling_prefix':pb}]});pair_index+=1
assert pair_index==62
save(private/'plan.json',{'seed_sequence':[2026111414],'sample_spawn_key':[0],'transform_spawn_key':[1],
'sampling':'uniform 20 without replacement over 624 lexicographically sorted cases; resulting cases sorted',
'selected_cases':selected,'jobs':jobs,'review_split_rng_consumed':False})
used={case for j in jobs for case in j['cases']}
save(private/'exposure-overlay.json',{'reason':'G1 calibration development exposure; does not rewrite sealed inventory',
'parts':[{'case':p['case'],'source_key':p['source_key'],'prior_exposure':p['exposure_state'],
'calibration_development_exposed':True} for p in parts if p['case'] in used]})
for p in private.iterdir():p.chmod(0o600)
code=['prepare_g1_copy_calibration','g1_copy_calibration','run_g1_copy_calibration','g1_registration_cost','s2_e1_supervisor','audit_samples','boundary_distance']
contract={'authorizing_rulings':['1794661944.308269','1794662380.787319'],
'code_sha256':{f'tools/{p}.py':sha(f'tools/{p}.py') for p in code},
'input_sha256':{str(p):sha(p) for p in [private/'plan.json',inventory,rigid_path]},
'archive':'data.zip','archive_verification':'artifacts/intake-2026-11-13/archive_verification.json',
'existing_registration_cache':'artifacts/s2-e1-2026-11-14/cost-geometry',
'sample_seed':[2026111414],'synthetic_parts':20,'synthetic_pairs':60,'natural_visual_rigid_pairs':2,
'synthetic_transform':'independent Haar proper R; mirror R diag(-1,1,1); scale 2; t=Rg*U[-3,3]^3; original face indices retained',
'sampling':'unchanged area-PPS 2000; source numeric prefix, unique synthetic target prefix 100000000+pair_index; natural original numeric prefixes',
'registration':'unchanged g1_registration_cost.register, both routes, det +/- starts, full-triangle two-way P95; no remeshing',
'threshold_policy':{'physical_residual':'raw P95 / mean(Rg_a,Rg_b)','physical_size_gate':'max(Rg_a,Rg_b)/min(Rg_a,Rg_b) <= 1.05',
'scale_free_residual':'unchanged individual Rg-normalized P95',
'positive_kinds_physical':['rigid','mirror','natural_visual_rigid'],'positive_kinds_scale_free':['rigid','mirror','scale','natural_visual_rigid'],
'per_pair_residual':'min of det+ and det- branch best P95 within route','threshold':'3 * largest positive-pair residual on each route',
'link':'either route meets own threshold; physical also requires Rg ratio gate',
'negative_control':'all 20 scale copies must fail physical size gate; any pass stops',
'mirror_check':'flag a mirror copy when det- does not strictly win; do not silently discard symmetric cases'},
'workers':4,'per_pair_wall_seconds':1800,'per_worker_rss_bytes':1342177280,
'aggregate_rss_bytes':20*1024**3,'worker_cpu_budget_seconds':100*3600,'wall_seconds':8*3600,'disk_bytes':20*1024**3,
'scope':'only calibration; formal candidate generation and registration queue follow calibration checkpoint',
'failed_jobs':'retained; no retry/replacement; final checkpoint after 22 jobs; any failure leaves calibration incomplete',
'no_simulation_fields_no_training_no_gpu':True}
save(ROOT/'contract.json',contract)
save(ROOT/'public/preparation.json',{'status':'CALIBRATION_FROZEN_NOT_STARTED','pairs':62,'synthetic_parts':20,'jobs':22,
'unique_source_parts':len(used),'plan_sha256':sha(private/'plan.json'),
'contract_sha256':sha(ROOT/'contract.json'),'exposure_overlay_sha256':sha(private/'exposure-overlay.json'),
'threshold_ruling':'1794662380.787319','previous_review_not_repeated':True,'split_stream_consumed':False})
print((ROOT/'public/preparation.json').read_text())
if __name__=='__main__':main()
+100
View File
@@ -0,0 +1,100 @@
"""Four guarded calibration workers; all CPU/failures retained, no retries."""
from pathlib import Path
import argparse
import fcntl
import json
import os
import resource
import signal
import subprocess
import sys
import time
import psutil
from g1_copy_calibration import ROOT, check_contract
from s2_e1_supervisor import supervise, save, disk_usage, stop_group
def guard(index):
c=check_contract(ROOT);plan=json.loads((ROOT/'custodian/plan.json').read_text());n=len(plan['jobs'][index]['pairs'])
job=ROOT/'jobs'/f'job-{index:02d}';job.mkdir(parents=True,exist_ok=True)
limit=n*c['per_pair_wall_seconds']
r=supervise([sys.executable,'tools/g1_copy_calibration.py',str(index)],job,'worker',
dict(total_cpu_seconds=limit+1,job_cpu_seconds=limit,job_wall_seconds=limit,
tree_rss_bytes=c['per_worker_rss_bytes'],disk_bytes=c['disk_bytes'],max_processes=2),poll=.25)
save(job/'guard-result.json',{'worker':r,'supervisor_cpu_seconds':sum(resource.getrusage(resource.RUSAGE_SELF)[:2])})
return 0 if r['status']=='PASS' else 1
def terminate_workers(active):
# Guards stay alive to reap killed workers and write failure receipts.
for p,_ in active.values():
try:
for child in psutil.Process(p.pid).children():stop_group(child.pid)
except psutil.NoSuchProcess:pass
def run():
c=check_contract(ROOT);plan=json.loads((ROOT/'custodian/plan.json').read_text())
lock=(ROOT/'batch.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
if (ROOT/'batch-started.json').exists():raise FileExistsError('Batch already attempted; no automatic restart')
env=dict(os.environ,OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1',NUMEXPR_NUM_THREADS='1',CUDA_VISIBLE_DEVICES='')
save(ROOT/'batch-started.json',{'pid':os.getpid(),'started_unix':time.time(),'jobs':len(plan['jobs']),'pairs':sum(len(j['pairs']) for j in plan['jobs']),'workers':c['workers'],'contract_sha256':__import__('hashlib').sha256((ROOT/'contract.json').read_bytes()).hexdigest()})
started=time.monotonic();active={};done=[];next_index=0;reason=None;peak_rss=0
def interrupted(*_):
nonlocal reason
reason='coordinator_interrupted'
signal.signal(signal.SIGTERM,interrupted);signal.signal(signal.SIGINT,interrupted)
try:
while active or (next_index<len(plan['jobs']) and reason is None):
while reason is None and len(active)<c['workers'] and next_index<len(plan['jobs']):
i=next_index;next_index+=1;path=ROOT/'jobs'/f'job-{i:02d}';path.mkdir(parents=True,exist_ok=True)
log=(path/'guard.log').open('x')
p=subprocess.Popen([sys.executable,__file__,'--guard',str(i)],env=env,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
active[i]=(p,log)
print(json.dumps({'event':'STARTED','job':i,'guard_pid':p.pid}),flush=True)
for i,(p,log) in list(active.items()):
code=p.poll()
if code is not None:
log.close();path=ROOT/'jobs'/f'job-{i:02d}'/'guard-result.json'
result=json.loads(path.read_text()) if path.exists() else {'worker':{'status':'GUARD_FAILED','cpu_seconds':0},'supervisor_cpu_seconds':0}
done.append({'index':i,'returncode':code,**result});del active[i]
print(json.dumps({'event':'FINISHED','job':i,'status':result['worker']['status'],'completed':len(done)}),flush=True)
# Calibration has 22 jobs: its scheduled failure-rate checkpoint is batch end.
if time.monotonic()-started>=c['wall_seconds']:reason='global_wall_limit'
if disk_usage(ROOT)>=c['disk_bytes']:reason='global_disk_limit'
live_cpu=live_rss=0
for p,_ in active.values():
try:
for q in [psutil.Process(p.pid)]+psutil.Process(p.pid).children(recursive=True):
try:
t=q.cpu_times();live_cpu+=t.user+t.system+t.children_user+t.children_system;live_rss+=q.memory_info().rss
except psutil.NoSuchProcess:pass
except psutil.NoSuchProcess:pass
peak_rss=max(peak_rss,live_rss)
completed_cpu=sum(r['worker']['cpu_seconds']+r['supervisor_cpu_seconds'] for r in done)
if completed_cpu+live_cpu>=c['worker_cpu_budget_seconds']:reason='global_cpu_limit'
if live_rss>=c['aggregate_rss_bytes']:reason='aggregate_rss_limit'
if reason:terminate_workers(active)
save(ROOT/'progress.json',{'completed_jobs':len(done),'active_jobs':list(active),'next_job':next_index,
'completed_worker_cpu_seconds':sum(r['worker']['cpu_seconds'] for r in done),
'live_tree_cpu_seconds':live_cpu,'active_tree_rss_bytes':live_rss,'stop_reason':reason,'elapsed_seconds':time.monotonic()-started})
if active:time.sleep(.5)
finally:
terminate_workers(active)
for p,log in active.values():
try:p.wait(timeout=10)
except subprocess.TimeoutExpired:stop_group(p.pid);p.wait()
log.close()
failures=sum(r['worker']['status']!='PASS' for r in done)
passed=reason is None and len(done)==len(plan['jobs']) and failures==0
summary={'status':'CALIBRATION_RESIDUALS_COMPLETE' if passed else 'CALIBRATION_INCOMPLETE',
'jobs':done,'failed_jobs':failures,'failure_rate_at_final_checkpoint':failures/len(done) if done else None,
'stop_reason':reason,'worker_cpu_seconds':sum(r['worker']['cpu_seconds'] for r in done),
'guard_cpu_seconds':sum(r['supervisor_cpu_seconds'] for r in done),
'coordinator_cpu_seconds':sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),
'wall_seconds':time.monotonic()-started,'peak_aggregate_tree_rss_bytes':peak_rss,
'disk_bytes':disk_usage(ROOT),'thresholds_frozen':False,'candidate_generation':False,'no_retries':True}
save(ROOT/'batch-complete.json' if passed else ROOT/'batch-incomplete.json',summary)
print(json.dumps({k:v for k,v in summary.items() if k!='jobs'}),flush=True)
return 0 if passed else 1
if __name__=='__main__':
ap=argparse.ArgumentParser();ap.add_argument('--guard',type=int);a=ap.parse_args()
sys.exit(guard(a.guard) if a.guard is not None else run())
+55
View File
@@ -0,0 +1,55 @@
"""Report fixed-route calibration residuals; freeze thresholds only after all jobs pass."""
from pathlib import Path
from collections import Counter
import argparse
import hashlib
import json
import math
from g1_copy_calibration import ROOT, check_contract
from s2_e1_supervisor import save
def main():
ap=argparse.ArgumentParser();ap.add_argument('--partial',action='store_true');args=ap.parse_args()
check_contract(ROOT)
if not args.partial:
batch=json.loads((ROOT/'batch-complete.json').read_text())
assert batch['status']=='CALIBRATION_RESIDUALS_COMPLETE' and batch['failed_jobs']==0
rows=[];mirror_flags=[];negative_controls=[]
for path in sorted((ROOT/'custodian/results').glob('job-*/calib-*.json')):
r=json.loads(path.read_text());pair=r['pair'];kind=pair['kind'];out={}
assert r['mean_rg']>0 and r['rg_ratio']>=1
for route in ['physical','scale_free']:
branches={str(v['parity']):v['residual_max_two_way_area_pps_p95']/(r['mean_rg'] if route=='physical' else 1.) for v in r['routes'] if v['route']==route}
assert set(branches)=={'1','-1'} and all(math.isfinite(v) and v>=0 for v in branches.values())
positive=route=='scale_free' or kind!='scale'
out[route]={'branch_residuals':branches,'best_residual':min(branches.values()),'positive':positive,
'size_gate_pass':r['rg_ratio']<=1.05 if route=='physical' else True}
if kind=='mirror' and branches['-1']>=branches['1']:
mirror_flags.append({'pair_id':pair['id'],'route':route,'det_minus':branches['-1'],'det_plus':branches['1'],
'note':'det- did not strictly win; retain result, including possible symmetry/local optimum'})
if kind=='scale':
negative_controls.append({'pair_id':pair['id'],'rg_ratio':r['rg_ratio'],'physical_size_gate_pass':out['physical']['size_gate_pass']})
rows.append({'pair_id':pair['id'],'kind':kind,'rg_ratio':r['rg_ratio'],'routes':out,
'source_result_sha256':hashlib.sha256(path.read_bytes()).hexdigest()})
if any(r['physical_size_gate_pass'] for r in negative_controls):
save(ROOT/'public/negative-control-stop.json',{'status':'STOP','controls':negative_controls})
raise ValueError('A scaled negative control passed the physical size gate; do not generate candidates')
thresholds=None
if not args.partial:
assert len(rows)==62 and Counter(r['kind'] for r in rows)=={'rigid':20,'mirror':20,'scale':20,'natural_visual_rigid':2}
thresholds={route:3*max(r['routes'][route]['best_residual'] for r in rows if r['routes'][route]['positive']) for route in ['physical','scale_free']}
assert sum(r['routes']['physical']['positive'] for r in rows)==42
assert len(negative_controls)==20
result={'status':'PARTIAL_RESIDUAL_CHECKPOINT' if args.partial else 'CALIBRATION_THRESHOLDS_FROZEN',
'completed_pairs':len(rows),'pair_kind_counts':dict(Counter(r['kind'] for r in rows)),
'thresholds':thresholds,'threshold_ruling':'1794662380.787319','residual_distributions':rows,
'physical_scale_negative_controls':negative_controls,'mirror_branch_flags':mirror_flags,
'physical_positive_size_gate_failures':[r['pair_id'] for r in rows if r['routes']['physical']['positive'] and not r['routes']['physical']['size_gate_pass']],
'claim':'Engineering calibration on development examples; not independent cross-key recall certification',
'candidate_generation_started':False,'source_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
dest=ROOT/'public'/('partial-residual-checkpoint.json' if args.partial else 'calibration-thresholds.json')
if dest.exists() and not args.partial:raise FileExistsError('Frozen thresholds already exist')
save(dest,result)
print(json.dumps({k:v for k,v in result.items() if k not in ['residual_distributions','physical_scale_negative_controls']},indent=2))
if __name__=='__main__':main()
+27
View File
@@ -0,0 +1,27 @@
import unittest
import numpy as np
from scipy.spatial.transform import Rotation
from g1_copy_calibration import transformed
from g1_registration_cost import sample_surface
class CopyChecks(unittest.TestCase):
def setUp(self):
self.g={'points':np.array([[0.,0,0],[3.,0,0],[0,2.,0],[0,0,1.]]),
'boundary':np.array([[0,1,2],[0,1,3],[0,2,3],[1,2,3]]),
'center':np.array([.75,.5,.25]),'rg':np.array(1.1)}
def test_lengths_rg_centroid_and_signed_volume(self):
r=Rotation.from_rotvec([.31,-.72,.2]).as_matrix();x=self.g['points'].copy()
for kind,s,parity in [('rigid',1,1),('mirror',1,-1),('scale',2,1)]:
out=transformed(self.g,kind,r,[2,-3,1]);y=out['points']
np.testing.assert_allclose(np.linalg.norm(y[:,None]-y[None,:],axis=2),s*np.linalg.norm(x[:,None]-x[None,:],axis=2),atol=1e-13)
self.assertAlmostEqual(float(out['rg']),s*float(self.g['rg']))
np.testing.assert_allclose(out['center'],y.mean(0),atol=1e-13)
self.assertAlmostEqual(np.linalg.det(y[1:]-y[0])/np.linalg.det(x[1:]-x[0]),parity*s**3)
np.testing.assert_array_equal(self.g['points'],x)
def test_sampling_streams_independent_and_reproducible(self):
x,_=sample_surface(self.g,42);y,_=sample_surface(self.g,100000000)
np.testing.assert_array_equal(x,sample_surface(self.g,42)[0]);self.assertFalse(np.array_equal(x,y))
def test_improper_base_rotation_rejected(self):
with self.assertRaises(ValueError):transformed(self.g,'rigid',np.diag([-1,1,1]),[0,0,0])
if __name__=='__main__':unittest.main(verbosity=2)