File size: 8,395 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
"""Shared A/B HMI3D supervised contrastive teacher training."""
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.loss import SupConLoss, anchor_diagnostics
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)
    supcon = SupConLoss(j['con_temperature'])
    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, 'CTL_feature': 'raw pooled512 L2-normalized inside original single-view SupCon', 'CTL_source': 'multiclass_aaai_unified/loss/loss.py', 'no_projection_head': True}
    (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)
    assert initial == j['baseline_initial_sha256'], 'Initial student differs from matched baseline'
    for epoch in range(1, j['epochs'] + 1):
        model.train()
        total = 0.0
        batches = 0
        parts = np.zeros(6)
        for (x, y) in tqdm(loaders[0], desc=f'Epoch {epoch}', dynamic_ncols=True):
            opt.zero_grad(set_to_none=True)
            yb = y.cuda()
            (out, features) = model(x.cuda(), return_features=True)
            classification = criterion(out, yb)
            contrast = supcon(features, yb) if j['lambda_con'] > 0 else features.sum() * 0.0
            loss = classification + j['lambda_con'] * contrast
            assert torch.isfinite(loss)
            diag = anchor_diagnostics(yb)
            parts += np.array([classification.detach().item(), contrast.detach().item(), diag['valid_anchor_ratio'], diag['positive_class_anchor_ratio'], diag['negative_class_anchor_ratio'], diag['single_class_batch']])
            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(['classification_loss', 'contrastive_loss', 'valid_anchor_ratio', 'positive_class_anchor_ratio', 'negative_class_anchor_ratio', 'single_class_batch_fraction'], (parts / batches).tolist())))
        history[-1]['weighted_contrastive_loss'] = j['lambda_con'] * parts[1] / batches
        history[-1]['contrast_to_classification_ratio'] = j['lambda_con'] * parts[1] / max(parts[0], 1e-12)
        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)