File size: 9,438 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
150
151
152
153
154
155
156
157
158
159
"""Shared A/B single-teacher logit, feature or combined distillation."""
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.loss import logits_kd, feature_kd
from torch.utils.data import Dataset
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()

class Indexed(Dataset):

    def __init__(self, base):
        self.base = base

    def __len__(self):
        return len(self.base)

    def __getitem__(self, i):
        (x, y) = self.base[i]
        return (x, y, i)

def dataset(frame, j):
    return Indexed(SolarMultiSourceRAMDataset(eligible(frame), 'HMI', '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, indices) 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)
    cache_dir = CACHE_ROOT / j['cache_id']
    cache_record = json.loads((cache_dir / 'complete.json').read_text())
    assert cache_record['checkpoint_sha256'] == j['teacher_sha256'] and cache_record['manifest_id'] == plan['manifest_id']
    for (p, h) in cache_record['files'].items():
        cache_file = pathlib.Path(p)
        if not cache_file.is_absolute():
            cache_file = cache_dir / cache_file
        assert sha(cache_file) == h, str(cache_file)
    with np.load(cache_dir / 'train.npz') as source:
        cached = {k: source[k] for k in source.files}
    assert np.array_equal(cached['sample_ids'], endpoints[0].sample_id.astype(str).to_numpy()) and np.array_equal(cached['labels'], endpoints[0].target_binary.to_numpy())
    assert cached['features'].shape == (len(endpoints[0]), j['teacher_feature_dim'])
    with torch.random.fork_rng(devices=[]):
        projector = torch.nn.Linear(512, j['teacher_feature_dim'], bias=False) if j['feature_kd'] else None
    if projector is not None:
        projector = projector.cuda()
    opt = (torch.optim.AdamW if j['temporal'] else torch.optim.Adam)(list(model.parameters()) + (list(projector.parameters()) if projector is not None else []), 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)
    assert initial == j['baseline_initial_sha256'], 'Student initialization differs from matched baseline'
    for epoch in range(1, j['epochs'] + 1):
        model.train()
        total = 0.0
        batches = 0
        parts = np.zeros(3)
        for (x, y, indices) in tqdm(loaders[0], desc=f'Epoch {epoch}', dynamic_ncols=True):
            opt.zero_grad(set_to_none=True)
            features = model.extract_features(x.cuda())
            out = model.classifier(features)
            teacher_logits = torch.from_numpy(cached['logits'][indices.numpy()]).cuda()
            classification = criterion(out, y.cuda())
            kl = logits_kd(out, teacher_logits, j['temperature']) if j['lambda_logits'] > 0 else out.new_zeros(())
            alignment = feature_kd(features, torch.from_numpy(cached['features'][indices.numpy()]).cuda(), projector) if projector is not None else out.new_zeros(())
            loss = classification + j['lambda_logits'] * kl + j['lambda_feature'] * alignment
            assert torch.isfinite(loss)
            parts += np.array([classification.detach().item(), kl.detach().item(), alignment.detach().item()])
            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', 'logits_kd_loss', 'feature_kd_loss'), (parts / batches).tolist())))
        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(), 'projector_state_dict': projector.state_dict() if projector is not None else None, '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)