File size: 7,402 Bytes
21419ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import pathlib,json,hashlib,shutil
ROOT=pathlib.Path(__file__).resolve().parents[2]

def sha(path):
    h=hashlib.sha256()
    with pathlib.Path(path).open('rb')as f:
        for block in iter(lambda:f.read(1024*1024),b''):h.update(block)
    return h.hexdigest()

def registry():return json.loads((ROOT/'registry.json').read_text())
def experiments():
    common=_read(ROOT/'configs/training.json');published={a['id']:a for a in registry()};items=[]
    for setting in ['A','B']:
        specific=_read(ROOT/'configs'/('setting'+setting+'.json'))
        for method,spec in common['methods'].items():
            params={**common['defaults'],**spec['parameters'],**specific.get('method_overrides',{}).get(method,{})}
            for seed in common['seeds']:
                ident=f'{setting}/{method}/seed{seed}'
                a={'id':ident,'setting':setting,'family':method,'seed':seed,'manifest_id':specific['manifest_id'],'modality':params['modality'],'temporal':params['temporal'],**spec['model'],'weight':None,'weight_available':False}
                a.update(published.get(ident,{}));items.append(a)
    return items
def artifact(ident):
    for a in experiments():
        if a['id']==ident:return a
    raise ValueError('Unknown experiment: '+ident)

def output_path(name):
    p=(ROOT/'runs'/name).resolve()
    if not p.is_relative_to((ROOT/'runs').resolve()):raise ValueError('Output must stay inside runs/')
    p.parent.mkdir(parents=True,exist_ok=True);return p

def run_directory(ident,run_tag='reproduction'):
    p=(ROOT/'runs'/run_tag/ident).resolve()
    if not p.is_relative_to((ROOT/'runs').resolve()):raise ValueError('Invalid run tag')
    return p

def _read(path):return json.loads(pathlib.Path(path).read_text())
def resolve_checkpoint(ident,checkpoint_root=None,run_tag=None):
    """Prefer explicitly supplied/retrained models; then use published seed42 weights."""
    a=artifact(ident);setting,method,seed=ident.split('/');name=method+'_'+seed;candidates=[]
    if checkpoint_root:
        folder=pathlib.Path(checkpoint_root).expanduser().resolve()/setting;candidates.append((folder/(name+'.pth'),folder/(name+'.json'),False))
    if run_tag:
        folder=ROOT/'runs'/run_tag/'weights'/setting;candidates.append((folder/(name+'.pth'),folder/(name+'.json'),False))
    if a.get('weight'):candidates.append((ROOT/a['weight'],ROOT/a['metadata'],True))
    for weight,record,published in candidates:
        if not weight.exists():continue
        if not record.exists():raise FileNotFoundError('Checkpoint training record missing: '+str(record))
        meta=_read(record);args=meta['args']
        if args['seed']!=a['seed']or args['manifest_id']!=a['manifest_id']or args['label_col']!='target_binary' or args['modality']!=a['modality']or args['temporal']!=a['temporal']:raise ValueError('Checkpoint/configuration mismatch: '+ident)
        common=_read(ROOT/'configs/training.json');specific=_read(ROOT/'configs'/('setting'+setting+'.json'))
        expected={**common['defaults'],**common['methods'][method]['parameters'],**specific.get('method_overrides',{}).get(method,{})}
        for key,value in expected.items():
            if args.get(key)!=value:raise ValueError('Checkpoint hyperparameter mismatch: '+ident+' / '+key)
        if a['kind']=='baseline' and (args.get('lambda_con',0)>0 or args.get('lambda_kd',0)>0 or args.get('lambda_logits',0)>0 or args.get('lambda_feature',0)>0):raise ValueError('A distilled/CTL checkpoint cannot be used as a supervised baseline: '+ident)
        digest=sha(weight)
        if meta.get('weight_sha256',digest)!=digest:raise ValueError('Checkpoint metadata hash differs: '+ident)
        if published and digest!=a['weight_sha256']:raise ValueError('Published checkpoint hash differs: '+ident)
        return {'id':ident,'path':str(weight),'training_record':str(record),'sha256':digest,'published':published}
    raise FileNotFoundError('Missing prerequisite '+ident+'. Train it first using the same --run-tag, or supply --checkpoint-root with '+setting+'/'+name+'.pth and matching .json training record.')

def load_model(a,device='cpu',checkpoint_root=None,run_tag=None):
    from binaryforecast.core.model import build_model
    from binaryforecast.core.model import build_mdt
    from binaryforecast.core.utils.experiment import load_state_dict_file
    entry=resolve_checkpoint(a['id'],checkpoint_root,run_tag)
    m=build_mdt(a['temporal'])if a['architecture']=='mdt'else build_model(a['modality'],a['temporal'])
    m.load_state_dict(load_state_dict_file(entry['path'],__import__('torch').device('cpu')),strict=True)
    return m.to(device).eval().requires_grad_(False)

def build_plan(setting,method,seed=42,run_tag='reproduction',checkpoint_root=None,resolve=True):
    common=_read(ROOT/'configs/training.json');specific=_read(ROOT/'configs'/('setting'+setting+'.json'))
    if seed not in common['seeds']:raise ValueError('Unsupported seed')
    spec=common['methods'][method];job={**common['defaults'],**spec['parameters'],**specific.get('method_overrides',{}).get(method,{})};job.update(id=f'{method}_{seed}',family=method,seed=seed,run_name=f'{method}_seed{seed}_setting{setting}')
    if not isinstance(job['epochs'],int)or isinstance(job['epochs'],bool)or job['epochs']<1:raise ValueError('epochs must be a positive integer')
    ident=f'{setting}/{method}/seed{seed}';a=artifact(ident);dep_ids=[f'{setting}/{name}/seed{seed}'for name in spec.get('dependencies',[])]
    plan={'setting':setting,'manifest_id':specific['manifest_id'],'manifest_dir':str(ROOT/specific['manifest_dir']),'sample_counts':specific['sample_counts'],'jobs':[job],'dependencies':dep_ids}
    initial=spec.get('initial_state_model')
    if initial:job['baseline_initial_sha256']=specific['initial_state_sha256'][initial][str(seed)]
    if a['kind']in ['single','dual']:job['cache_id']=f'{setting}_'+('_'.join(spec['dependencies']))+f'_{seed}'
    if resolve:
        deps={name:resolve_checkpoint(f'{setting}/{name}/seed{seed}',checkpoint_root,run_tag)for name in spec.get('dependencies',[])}
        if a['kind']=='mdt':job['initialization']={modality:{k:v for k,v in deps[modality+('3D'if a['temporal']else'2D')].items()if k in ['path','training_record','sha256']}for modality in ['AIA','HMI']}
        elif a['kind']=='single':
            teacher=deps[spec['dependencies'][0]];job.update(teacher_checkpoint=teacher['path'],teacher_record=teacher['training_record'],teacher_sha256=teacher['sha256'])
        elif a['kind']=='dual':job['teacher_shas']={'mdt':deps['MDT2D']['sha256'],'ctl':deps['HMI3D_CTL']['sha256']}
    return plan

def export_checkpoint(ident,checkpoint,training_record,run_tag='reproduction'):
    a=artifact(ident);setting,method,seed=ident.split('/');folder=ROOT/'runs'/run_tag/'weights'/setting
    if not folder.resolve().is_relative_to((ROOT/'runs').resolve()):raise ValueError('Invalid run tag')
    folder.mkdir(parents=True,exist_ok=True);weight=folder/(method+'_'+seed+'.pth');record=weight.with_suffix('.json')
    if weight.exists()or record.exists():raise FileExistsError('Export already exists: '+str(weight))
    meta=_read(training_record);meta.update(id=ident,weight_sha256=sha(checkpoint))
    shutil.copyfile(checkpoint,weight);record.write_text(json.dumps(meta,indent=2));return str(weight)

def metrics():
    from binaryforecast.core.utils.binary_metrics import binary
    return binary