Download src/binaryforecast/training/baseline/supervised.py from SPARK-LAB/ST-DTKD: direct link, hf CLI and curl.
- Browser
- Download file 7.1 kB
-
https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/src/binaryforecast/training/baseline/supervised.py
- Command line
-
hf download hf://SPARK-LAB/ST-DTKD/src/binaryforecast/training/baseline/supervised.py
-
curl -L -o supervised.py https://huggingface.co/SPARK-LAB/ST-DTKD/resolve/main/src/binaryforecast/training/baseline/supervised.py
7.1 kB
| """Shared A/B supervised CNN training; architecture is selected by configuration.""" | |
| 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_model | |
| 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 dataset(frame, j): | |
| return SolarTemporalMultiSourceRAMDataset(frame, 5, 1, j['modality'], 'target_binary') if j['temporal'] else SolarMultiSourceRAMDataset(eligible(frame), j['modality'], 'target_binary') | |
| def logits(model, x, j): | |
| return model(x, return_features=False) if j['temporal'] else model(x) | |
| def predict(model, loader, device, j): | |
| model.eval() | |
| ys = [] | |
| ps = [] | |
| with torch.no_grad(): | |
| for (x, y) in tqdm(loader, desc='Evaluate', dynamic_ncols=True): | |
| p = torch.softmax(logits(model, x.to(device), j), 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_model(j['modality'], j['temporal']).cuda() | |
| counts = np.bincount(endpoints[0].target_binary, minlength=2) | |
| weights = build_class_weights(counts, 'sqrt_inv').cuda() | |
| criterion = 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': 'random', '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 | |
| for (x, y) in tqdm(loaders[0], desc=f'Epoch {epoch}', dynamic_ncols=True): | |
| opt.zero_grad(set_to_none=True) | |
| loss = criterion(logits(model, x.cuda(), j), y.cuda()) | |
| assert torch.isfinite(loss) | |
| 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()}}) | |
| 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) | |