#!/usr/bin/env python3 """Evaluate the best checkpoint on all 200 Pipe test cases.""" import csv from copy import deepcopy from pathlib import Path import numpy as np from common import (parser, load_config, paths, get_device, make_model, load_checkpoint, PipeDataset, make_loader, evaluate, save_json, config_digest) def main(): cli = parser(__doc__) cli.add_argument('--checkpoint', type=Path) args = cli.parse_args() cfg = load_config(args) output, results = paths(cfg) checkpoint_path = args.checkpoint or output / cfg['output']['best_checkpoint'] checkpoint = load_checkpoint(checkpoint_path) trained_data = deepcopy(checkpoint['config']['data']) trained_data['directory'] = cfg['data']['directory'] if checkpoint['config']['model'] != cfg['model'] or trained_data != cfg['data']: raise ValueError('Checkpoint model or data contract differs from inference configuration') device = get_device(cfg) model = make_model(cfg, device) model.load_state_dict(checkpoint['model_state_dict'], strict=True) metrics, records, arrays = evaluate(model, make_loader(PipeDataset(cfg, 'test'), cfg), device, collect=True) if metrics['samples'] != cfg['data']['test_count']: raise AssertionError('Incomplete test set') arrays['sample_indices'] = np.array([r['sample_index'] for r in records]) arrays['relative_l2'] = np.array([r['relative_l2'] for r in records]) np.savez_compressed(results / 'test_predictions.npz', **arrays) with (results / 'per_sample_metrics.csv').open('w', newline='') as stream: writer = csv.DictWriter(stream, fieldnames=list(records[0])) writer.writeheader() writer.writerows(records) reference = cfg['paper']['reference_pipe_relative_l2'] metrics.update({'checkpoint': str(checkpoint_path), 'checkpoint_epoch': checkpoint['epoch'], 'selection_metric': checkpoint['selection_metric'], 'score_description': 'Mean of per-sample relative L2 on the test set used for checkpoint selection', 'paper_relative_l2': reference, 'ratio_to_paper': metrics['relative_l2'] / reference, 'precision': 'float32', 'grid': [129, 129], 'target': 'Q channel 0 horizontal velocity', 'relative_l2_std': float(arrays['relative_l2'].std()), 'config_digest': config_digest(cfg)}) save_json(results / 'metrics.json', metrics) for key, value in metrics.items(): print(f'{key}: {value}', flush=True) print('INFERENCE_COMPLETE', flush=True) if __name__ == '__main__': main()