File size: 7,255 Bytes
d2fc041
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
"""Data and metric contracts shared by the independently written experiment."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import random
import sys

import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
import yaml

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from model.FLARE import FLARE


def parser(description):
    result = argparse.ArgumentParser(description=description)
    result.add_argument('--config', type=Path, default=ROOT / 'config/config.yaml')
    result.add_argument('--data-dir', type=Path)
    result.add_argument('--output-dir', type=Path)
    result.add_argument('--device', choices=['cuda', 'cpu'])
    return result


def load_config(args):
    with args.config.open() as stream:
        cfg = yaml.safe_load(stream)
    if args.data_dir:
        cfg['data']['directory'] = str(args.data_dir.resolve())
    if args.output_dir:
        cfg['output']['directory'] = str(args.output_dir.resolve())
    if args.device:
        cfg['training']['device'] = args.device
    if cfg['data']['normalization'] != 'identity':
        raise ValueError('Only the documented identity preprocessing is implemented')
    if cfg['training']['precision'] != 'float32':
        raise ValueError('Paper Pipe protocol requires FP32')
    if cfg['training']['early_stopping']:
        raise ValueError('500 complete epochs required; early stopping must be false')
    return cfg


def config_digest(cfg):
    return hashlib.sha256(json.dumps(cfg, sort_keys=True).encode()).hexdigest()


def paths(cfg):
    output = Path(cfg['output']['directory'])
    results = output / cfg['output']['results']
    results.mkdir(parents=True, exist_ok=True)
    return output, results


def save_json(path, value):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temp = path.with_suffix(path.suffix + '.tmp')
    temp.write_text(json.dumps(value, indent=2, ensure_ascii=False, allow_nan=False) + '\n')
    os.replace(temp, path)


def seed_all(seed):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)
    torch.backends.cuda.matmul.allow_tf32 = False
    torch.backends.cudnn.allow_tf32 = False


def get_device(cfg):
    device = torch.device(cfg['training']['device'])
    if device.type == 'cuda' and not torch.cuda.is_available():
        raise RuntimeError('An allocated accelerator is required; CPU fallback is disabled')
    return device


class PipeDataset(Dataset):
    """Read exactly the specified original files; retain the entire curvilinear grid."""
    def __init__(self, cfg, split):
        data = cfg['data']
        folder = Path(data['directory'])
        arrays = [np.load(folder / data[name], mmap_mode='r', allow_pickle=False)
                  for name in ['x_file', 'y_file', 'q_file']]
        x, y, q = arrays
        if x.shape != (2310, 129, 129) or y.shape != x.shape or q.shape != (2310, 3, 129, 129):
            raise ValueError(f'Unexpected Pipe schema: {x.shape}, {y.shape}, {q.shape}')
        if data['grid'] != [129, 129] or data['target_channel'] != 0:
            raise ValueError('Pipe task requires full 129x129 grid and Q channel 0')
        start, count = data[f'{split}_start'], data[f'{split}_count']
        selection = slice(start, start + count)
        self.coordinates = torch.from_numpy(np.stack([x[selection], y[selection]], axis=-1).astype(np.float32)).reshape(count, -1, 2)
        self.targets = torch.from_numpy(np.array(q[selection, data['target_channel']], dtype=np.float32)).reshape(count, -1, 1)
        self.indices = torch.arange(start, start + count)
        if not torch.isfinite(self.coordinates).all() or not torch.isfinite(self.targets).all():
            raise ValueError('Nonfinite input or target')
        if (self.targets.flatten(1).norm(dim=1) == 0).any():
            raise ValueError('Relative L2 is undefined for a zero target')

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

    def __getitem__(self, index):
        return self.coordinates[index], self.targets[index], self.indices[index]


def make_loader(dataset, cfg, shuffle=False):
    return DataLoader(dataset, batch_size=cfg['training']['batch_size'], shuffle=shuffle,
                      num_workers=cfg['training']['num_workers'], pin_memory=True,
                      drop_last=False)


def relative_l2(prediction, target):
    difference = (prediction - target).flatten(1).norm(dim=1)
    denominator = target.flatten(1).norm(dim=1)
    return difference / denominator.clamp_min(torch.finfo(target.dtype).tiny)


def make_model(cfg, device):
    return FLARE(**cfg['model']).to(device=device, dtype=torch.float32)


def make_optimizer(model, cfg, steps_per_epoch):
    training = cfg['training']
    optimizer = torch.optim.AdamW(model.parameters(), lr=training['max_lr'],
                                 weight_decay=training['weight_decay'],
                                 betas=tuple(training['betas']), eps=training['adam_eps'])
    schedule = torch.optim.lr_scheduler.OneCycleLR(
        optimizer, max_lr=training['max_lr'], epochs=training['epochs'],
        steps_per_epoch=steps_per_epoch, pct_start=training['warmup_fraction'],
        anneal_strategy='cos', div_factor=training['div_factor'],
        final_div_factor=training['final_div_factor'], cycle_momentum=training['cycle_momentum'])
    return optimizer, schedule


@torch.no_grad()
def evaluate(model, loader, device, collect=False):
    model.eval()
    records, predictions, targets, coordinates = [], [], [], []
    for x, y, indices in loader:
        x, y = x.to(device, non_blocking=True), y.to(device, non_blocking=True)
        pred = model(x)
        if not torch.isfinite(pred).all():
            raise FloatingPointError('Nonfinite predictions')
        errors = pred - y
        rel = relative_l2(pred, y)
        mse = errors.square().flatten(1).mean(dim=1)
        mae = errors.abs().flatten(1).mean(dim=1)
        for sample_id, relative, square, absolute in zip(indices.tolist(), rel.tolist(), mse.tolist(), mae.tolist()):
            records.append({'sample_index': sample_id, 'relative_l2': relative,
                            'mse': square, 'mae': absolute})
        if collect:
            predictions.append(pred.cpu().numpy().reshape(-1, 129, 129))
            targets.append(y.cpu().numpy().reshape(-1, 129, 129))
            coordinates.append(x.cpu().numpy().reshape(-1, 129, 129, 2))
    mean_mse = float(np.mean([r['mse'] for r in records]))
    metrics = {'relative_l2': float(np.mean([r['relative_l2'] for r in records])),
               'mse': mean_mse, 'rmse': mean_mse ** 0.5,
               'mae': float(np.mean([r['mae'] for r in records])), 'samples': len(records)}
    arrays = {key: np.concatenate(value) for key, value in
              [('prediction', predictions), ('target', targets), ('coordinates', coordinates)]} if collect else None
    return metrics, records, arrays


def load_checkpoint(path, device='cpu'):
    # Checkpoints are generated locally by this package; RNG states require full loading.
    return torch.load(path, map_location=device, weights_only=False)