File size: 8,819 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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | """Shared A/B MDT2D/MDT3D training with corrected squared orthogonality."""
import pathlib, sys, json, hashlib, datetime
import numpy as np, pandas as pd, torch
from binaryforecast.core.utils.data_api import load_manifest, require_training_release
from binaryforecast.core.utils.vendor.protocol import eligible
from binaryforecast.core.model import build_mdt
from binaryforecast.core.loss import SquaredMDTLoss
def build_model(modality, temporal=False):
return build_mdt(temporal)
from binaryforecast.core.utils.datasets import SolarMultiSourceRAMDataset, SolarTemporalMultiSourceRAMDataset, set_seed
from binaryforecast.core.utils.experiment import make_loader, load_state_dict_file
from binaryforecast.core.loss import FocalLoss, build_class_weights
from binaryforecast.core.utils.binary_metrics import binary, calibrated_threshold
from tqdm import tqdm
def sha(p):
return hashlib.sha256(pathlib.Path(p).read_bytes()).hexdigest()
def initialize(model, j):
audit = []
for modality in ('AIA', 'HMI'):
entry = j['initialization'][modality]
path = pathlib.Path(entry['path'])
assert sha(path) == entry['sha256']
record = json.loads(pathlib.Path(entry['training_record']).read_text())
a = record['args']
assert a['seed'] == j['seed'] and a['manifest_id'] == PLAN['manifest_id'] and (a['label_col'] == 'target_binary') and (a['modality'] == modality)
state = load_state_dict_file(str(path), torch.device('cpu'))
features = {k.removeprefix('features.'): v for (k, v) in state.items() if k.startswith('features.')}
target = getattr(model, 'extractor_' + modality.lower()).features
target.load_state_dict(features, strict=True)
assert all((torch.equal(v.cpu(), features[k].cpu()) for (k, v) in target.state_dict().items()))
audit.append({'modality': modality, **entry, 'feature_tensors_exactly_matched': True, 'trainable': True})
return audit
def dataset(frame, j):
return SolarTemporalMultiSourceRAMDataset(frame, 5, 1, 'BOTH', 'target_binary') if j['temporal'] else SolarMultiSourceRAMDataset(eligible(frame), 'BOTH', 'target_binary')
def logits(model, x, j):
return model(*x)[0]
def predict(model, loader, device, j):
model.eval()
ys = []
ps = []
with torch.no_grad():
for (aia, hmi, y) in tqdm(loader, desc='Evaluate', dynamic_ncols=True):
p = torch.softmax(model(aia.to(device), hmi.to(device))[0], 1).cpu().numpy()
assert p.shape[1] == 2
ys.append(y.numpy())
ps.append(p)
return (np.concatenate(ys), np.concatenate(ps))
def write_predictions(path, frame, y, probs):
assert np.array_equal(frame.target_binary.to_numpy(), y)
out = frame[['sample_id', 'timestamp', 'target_binary']].rename(columns={'target_binary': 'true_label'}).reset_index(drop=True)
out['pred_label'] = (probs[:, 1] >= 0.5).astype(int)
out['prob_0'] = probs[:, 0]
out['prob_1'] = probs[:, 1]
out.to_csv(path, index=False)
def train(plan, j):
for folder in ('logs', 'checkpoints'):
assert not (HERE / folder / j['run_name']).exists(), 'Existing run; no automatic retry'
set_seed(j['seed'])
(meta, frames) = load_manifest(plan['manifest_dir'])
log = HERE / 'logs' / j['run_name']
ckpt = HERE / 'checkpoints' / j['run_name']
log.mkdir()
ckpt.mkdir()
ds = [dataset(frames[n], j) for n in ('train', 'validation')]
endpoints = [eligible(frames[n]) for n in ('train', 'validation')]
loaders = [make_loader(d, j['batch_size'], i == 0, 0, j['seed'], drop_last=False) for (i, d) in enumerate(ds)]
model = build_mdt(j['temporal'])
initialization_audit = initialize(model, j)
model = model.cuda()
counts = np.bincount(endpoints[0].target_binary, minlength=2)
weights = build_class_weights(counts, 'sqrt_inv').cuda()
criterion = SquaredMDTLoss(1.0, 0.5, 1.0, FocalLoss(weights, 2.0))
opt = (torch.optim.AdamW if j['temporal'] else torch.optim.Adam)(model.parameters(), lr=j['lr'], weight_decay=j['weight_decay'])
args = {**j, 'manifest_id': meta['manifest_id'], 'manifest_dir': plan['manifest_dir'], 'label_col': 'target_binary', 'horizon_hours': 24, 'tail_buffer_hours': 96, 'selection': 'validation TSS fixed0.5; earliest tie', 'initialization': 'same_seed_corrected_binary_baseline_backbones', 'initialization_audit': initialization_audit, 'alpha_sim': 1.0, 'alpha_diff': 0.5, 'alpha_recon': 1.0, 'class_weight_mode': 'sqrt_inv', 'gamma': 2.0, 'amp': False, 'num_workers': 0, 'class_counts': counts.tolist(), 'class_weights': weights.cpu().tolist(), 'dropout': 0.5}
(log / 'config.json').write_text(json.dumps(args, indent=2))
best = -float('inf')
best_epoch = -1
history = []
initial = hashlib.sha256(b''.join((t.cpu().numpy().tobytes() for t in model.state_dict().values()))).hexdigest()
(log / 'initial_state_sha256.txt').write_text(initial)
for epoch in range(1, j['epochs'] + 1):
model.train()
total = 0.0
batches = 0
criterion.reset_epoch()
components = np.zeros(4)
for (aia, hmi, y) in tqdm(loaders[0], desc=f'Epoch {epoch}', dynamic_ncols=True):
opt.zero_grad(set_to_none=True)
(out, ht, zt) = model(aia.cuda(), hmi.cuda())
losses = criterion(out, y.cuda(), ht, zt)
loss = losses[0]
assert all((torch.isfinite(v) for v in losses))
components += np.array([v.detach().item() for v in losses[1:]])
loss.backward()
opt.step()
total += float(loss.item())
batches += 1
(y, p) = predict(model, loaders[1], 'cuda', j)
m = binary(y, p[:, 1], 0.5)
history.append({'epoch': epoch, 'train_loss': total / batches, **{'val_' + k: v for (k, v) in m.items()}})
history[-1].update(dict(zip(('class_loss', 'shared_loss', 'orth_loss', 'recon_loss'), (components / batches).tolist())))
criterion.write_diagnostics(log, epoch)
pd.DataFrame(history).to_csv(log / 'history.csv', index=False)
print('VAL', epoch, json.dumps({k: m[k] for k in ('tss', 'hss', 'f1', 'accuracy', 'roc_auc')}), flush=True)
if m['tss'] > best:
best = m['tss']
best_epoch = epoch
best_metrics = m
torch.save(model.state_dict(), ckpt / 'best_model_state.pth')
torch.save({'epoch': epoch, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': opt.state_dict(), 'args': args, 'validation_fixed05': m}, ckpt / 'best_checkpoint.pth')
model.load_state_dict(load_state_dict_file(str(ckpt / 'best_model_state.pth'), torch.device('cuda')), strict=True)
(y, p) = predict(model, loaders[1], 'cuda', j)
write_predictions(log / 'validation_predictions.csv', endpoints[1], y, p)
threshold = calibrated_threshold(y, p[:, 1])
report = {'fixed_0.5': {'threshold': 0.5, 'validation': binary(y, p[:, 1], 0.5)}, 'validation_max_tss': {'threshold': threshold, 'validation': binary(y, p[:, 1], threshold), 'note': 'Threshold fitted on validation; in-sample estimate'}}
assert best_epoch == int(max(history, key=lambda row: row['val_tss'])['epoch'])
(log / 'training_complete.json').write_text(json.dumps({'args': args, 'epochs': j['epochs'], 'best_epoch': best_epoch, 'best_val_metrics': best_metrics, 'operating_points': report, 'test_evaluated': False}, indent=2))
print('TRAINING_COMPLETE_NO_TEST', j['id'], flush=True)
def evaluate(plan, j):
frozen = json.loads((HERE / 'frozen_training_results.json').read_text())
for (p, h) in frozen['files'].items():
assert sha(p) == h, p
assert all(((HERE / 'logs' / x['run_name'] / 'training_complete.json').exists() for x in plan['jobs']))
(meta, frames) = load_manifest(plan['manifest_dir'])
log = HERE / 'logs' / j['run_name']
assert not (log / 'result.json').exists(), 'No repeated test inference'
record = json.loads((log / 'training_complete.json').read_text())
ds = dataset(frames['test'], j)
loader = make_loader(ds, j['batch_size'], False, 0, j['seed'])
model = build_model(j['modality'], j['temporal'])
model.load_state_dict(load_state_dict_file(str(HERE / 'checkpoints' / j['run_name'] / 'best_model_state.pth'), torch.device('cpu')), strict=True)
model = model.cuda()
(y, p) = predict(model, loader, 'cuda', j)
write_predictions(log / 'test_predictions.csv', eligible(frames['test']), y, p)
for (key, value) in record['operating_points'].items():
value['test'] = binary(y, p[:, 1], value['threshold'])
record.update(test_evaluated=True, test_metrics=record['operating_points']['fixed_0.5']['test'])
(log / 'result.json').write_text(json.dumps(record, indent=2))
print('TEST_COMPLETE', j['id'], flush=True)
|