FLARE / scripts /common.py
yushuang88's picture
Upload folder using huggingface_hub
d2fc041 verified
Raw History Blame Contribute Delete
7.26 kB
"""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)