"""Local single-read Greif scoring and independently verified Drive safekeeping.""" from collections import defaultdict import hashlib import io import json import os from pathlib import Path import resource import time from zipfile import ZIP_STORED, ZipFile import numpy as np from phase2_h2_data import cached from s2_custody_common import prediction_inputs from s2_custody_statistics import part_metrics import track_b_gino_greif_entry as entry from track_b_gino_greif_drive_acl import prove as prove_drive_acl, prove_folder from track_b_gino_greif_prepare import PILOT, QUERY, PINS from track_b_gino_shapenet_entry import BASE, checked, read, save, sha METRICS=('relative_l2','last_location','kendall_tau_b') def frozen(c): root=entry.ROOT terminal=read(root/'complete.json') if (terminal['status'],terminal['contract_sha256'],terminal['test_targets_read']) != ( 'PREDICTIONS_FROZEN_NO_TARGETS',sha(root/'contract.json'),False) or not 00 else 'COMPARABLE' hard=[r for r in rows if r['case'] in compare['hard34']] return dict(field=primary,secondary={metric:bootstrap(rows,metric) for metric in METRICS[1:]}, hard_subset=dict(frozen_total=34,two_fold_cases=[r['case'] for r in hard], descriptive={metric:bootstrap(hard,metric) for metric in METRICS})) def target_array(pilot,case): item=pilot['parts'][case] file=BASE/item['output']/'seconds.npy' blob=file.read_bytes() if hashlib.sha256(blob).hexdigest()!=item['output_sha256']['seconds.npy']: raise ValueError('Pinned held-out bytes differ') return np.load(io.BytesIO(blob),allow_pickle=False) def one_case(pilot, meta, row, forecasts, reference, log): case=row['case'] fold=row['fold'] q=prediction_inputs(meta) raw=cached(pilot,case,'raw_ids') ix=np.searchsorted(raw,q['raw_ids']) if np.any(ix>=len(raw)) or not np.array_equal(raw[ix],q['raw_ids']): raise ValueError('Frozen PPS coordinates differ') new=[] for seed in (0,1): f=forecasts[fold,seed,case] if f['family']!=row['family']: raise ValueError('Predicted family differs') with np.load(checked(f['path'],f['sha256']),allow_pickle=False) as z: seconds=z['seconds'] if (seconds.dtype!=np.float64 or seconds.shape!=raw.shape or not np.isfinite(seconds).all() or not np.array_equal(raw,z['raw_ids']) or any(not np.array_equal(q[name],z['query_raw_ids' if name=='raw_ids' else name]) for name in ('counts','near_wall','coordinates_over_Rg','raw_ids'))): raise ValueError('Frozen full node or PPS support differs') new.append(seconds[ix]) old=reference[case] if (old['fold'],old['component_id'])!=(fold,row['family']): raise ValueError('H2 score pairing differs') log.write(json.dumps(dict(case=case,fold=fold,role='test',sha256=pilot['parts'][case]['output_sha256']['seconds.npy']))+'\n') log.flush() truth=target_array(pilot,case) if truth.shape!=raw.shape: raise ValueError('Original held-out node support differs') gino=[part_metrics(p,truth[ix],q['counts'],q['near_wall'],q['raw_ids'],q['coordinates_over_Rg'], int(case.split('_')[0])) for p in new] return dict(row,gino=gino,h2=[old['seed0'],old['seed1']]) def score(c): entry.authorize(c) if os.environ.get('CUDA_VISIBLE_DEVICES')!='': raise PermissionError('Custody scoring must run with CUDA hidden') ceiling=resource.getrlimit(resource.RLIMIT_CPU)[1] limit=c['budgets']['score_cpu_seconds'] if ceiling!=resource.RLIM_INFINITY: limit=min(limit,ceiling) resource.setrlimit(resource.RLIMIT_CPU,(limit,limit)) _,predictions=frozen(c) compare=read(checked(c['comparison_contract'],c['comparison_contract_sha256'])) rosters={(r['fold'],r['case']) for r in compare['roster']} new={(r['fold'],r['seed'],r['case']):r for r in predictions} if set(new)!={(fold,seed,case) for fold,case in rosters for seed in (0,1)}: raise ValueError('Frozen four-set test support differs') prior=read(checked(compare['h2_score']['path'],compare['h2_score']['sha256'])) reference={r['case']:r for r in prior['rows']} if prior['status']!='COMPLETE' or len(reference)!=552 or not {r['case'] for r in compare['roster']}<=set(reference): raise ValueError('H2 frozen score support differs') pilot=read(checked(PILOT,PINS[str(PILOT)])) query={r['case']:r for r in read(checked(QUERY,PINS[str(QUERY)]))['rows'] if r['included']} out=entry.ROOT/'score' out.mkdir(exist_ok=False) save(out/'custody-start.json',dict(unix=time.time(), model_manifest_sha256=sha(entry.ROOT/'models-frozen.json'), manifest_sha256=sha(entry.ROOT/'predictions-frozen.json'),before_test_target_reads=True)) results=[] with (out/'heldout-target-access.jsonl').open('x') as log: for row in compare['roster']: results.append(one_case(pilot,query[row['case']],row,new,reference,log)) save(out/'result.json',dict(status='COMPLETE',summary=summary(results,compare),rows=results, unique_test_target_reads=len(results),no_new_decode=True)) return 0