File size: 10,699 Bytes
2cf4a54 | 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | """Check joint targets, full-dataset evaluation and per-run artifacts without a GPU."""
from contextlib import redirect_stderr, redirect_stdout
import copy
import io
import json
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
import sadae_autoresearch_eval as evaluation
class AutoresearchEvaluationTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.output_root = Path(self.temporary.name)
self.dataset = self.output_root / 'dataset'
self.dataset.mkdir()
(self.dataset / 'mapping_file.json').write_text(json.dumps({str(index): {} for index in range(30)}))
self.summary = {
'count': 30,
'pie_bench_metrics': {'statistics': {
name: {'mean': value, 'count': 30}
for name, value in {
'clip_similarity_target_image': 25.5,
'clip_similarity_target_image_edit_part': 23.3,
'psnr_unedit_part': 25.0,
'mse_unedit_part': 0.06,
'lpips_unedit_part': 0.08,
}.items()
}},
}
self.child_commands = []
def run_child(self, command, **kwargs):
self.child_commands.append((command, kwargs))
directory = Path(command[command.index('--output-dir') + 1]) / 'alpha_1.5_beta_0_gamma_1.0'
directory.mkdir(parents=True)
(directory / 'summary.json').write_text(json.dumps(self.summary))
kwargs['stdout'].write(f'Finished {self.summary["count"]} images\n')
return subprocess.CompletedProcess(command, 0)
def invoke(self, command, runner=None, head='test-commit', extra_args=(), env=None):
stdout, stderr = io.StringIO(), io.StringIO()
arguments = [
'sadae_autoresearch_eval.py', command, '--output-root', str(self.output_root),
]
if command == 'verify':
arguments.extend(['--dataset', str(self.dataset)])
arguments.extend(extra_args)
with patch.object(sys, 'argv', arguments), patch.dict(evaluation.os.environ, env or {}, clear=True), \
patch.object(evaluation, 'git_head', return_value=head), patch.object(
evaluation.subprocess, 'run', side_effect=runner or self.run_child,
), redirect_stdout(stdout), redirect_stderr(stderr):
code = evaluation.main()
return code, json.loads(stdout.getvalue())
def test_verify_and_guard_contract_at_exact_thresholds(self):
code, result = self.invoke('verify')
self.assertEqual(code, 0)
self.assertEqual(result['violation'], 0.0)
self.assertTrue(result['targets_met'])
self.assertEqual(result['samples'], 30)
self.assertEqual(result['dataset'], str(self.dataset))
self.assertFalse(result['training_noise'])
self.assertTrue(Path(result['summary_path']).is_file())
self.assertEqual(Path(result['log_path']).read_text(), 'Finished 30 images\n')
command, kwargs = self.child_commands[0]
for option, expected in (('--max-samples', '0'), ('--start-index', '0'), ('--seed', '999'),
('--dataset', str(self.dataset))):
self.assertEqual(command[command.index(option) + 1], expected)
self.assertIn('--no-training-noise', command)
self.assertNotIn('--training-noise', command)
self.assertEqual(kwargs['env']['CUDA_VISIBLE_DEVICES'], '0,1,2,3')
self.assertEqual(kwargs['env']['NPROC_PER_NODE'], '4')
self.assertNotIn('PYTHON', kwargs['env'])
code, result = self.invoke('guard')
self.assertEqual(code, 0)
self.assertTrue(result['guard_passed'])
self.assertEqual(result['violations'], [])
self.assertEqual(len(self.child_commands), 1)
def test_each_unmet_target_contributes_to_violation_but_measurement_succeeds(self):
original = copy.deepcopy(self.summary)
for name, value in (
('psnr_unedit_part', 22.5), ('lpips_unedit_part', 0.088), ('mse_unedit_part', 0.066),
('clip_similarity_target_image', 22.95), ('clip_similarity_target_image_edit_part', 20.97),
):
with self.subTest(name=name):
self.summary = copy.deepcopy(original)
self.summary['pie_bench_metrics']['statistics'][name]['mean'] = value
code, result = self.invoke('verify')
self.assertEqual(code, 0)
self.assertAlmostEqual(result['violation'], 0.1)
self.assertFalse(result['targets_met'])
code, result = self.invoke('guard')
self.assertEqual(code, 1)
self.assertFalse(result['guard_passed'])
self.assertEqual(len(result['violations']), 1)
self.assertIn(name, result['violations'][0])
def test_surplus_on_one_target_cannot_cancel_other_deficits(self):
stats = self.summary['pie_bench_metrics']['statistics']
stats['psnr_unedit_part']['mean'] = 22.5
stats['lpips_unedit_part']['mean'] = 0.096
stats['clip_similarity_target_image']['mean'] = 100
stats['clip_similarity_target_image_edit_part']['mean'] = 100
_, result = self.invoke('verify')
self.assertAlmostEqual(result['violation'], 0.3)
self.assertFalse(result['targets_met'])
def test_sample_limit_and_seed_are_forwarded_and_counts_are_checked(self):
self.summary['count'] = 12
for stats in self.summary['pie_bench_metrics']['statistics'].values():
stats['count'] = 12
code, result = self.invoke('verify', extra_args=('--max-samples', '12', '--seed', '42'))
self.assertEqual(code, 0)
self.assertEqual(result['samples'], 12)
self.assertEqual(result['seed'], 42)
command = self.child_commands[0][0]
self.assertEqual(command[command.index('--max-samples') + 1], '12')
self.assertEqual(command[command.index('--seed') + 1], '42')
def test_limit_larger_than_dataset_still_requires_all_available_samples(self):
_, result = self.invoke('verify', extra_args=('--max-samples', '100'))
self.assertEqual(result['samples'], 30)
def test_gpu_selection_and_python_are_preserved_with_one_worker_per_gpu(self):
_, result = self.invoke('verify', env={
'CUDA_VISIBLE_DEVICES': '2,3', 'NPROC_PER_NODE': '1', 'PYTHON': '/chosen/python',
})
self.assertEqual(result['cuda_visible_devices'], '2,3')
env = self.child_commands[0][1]['env']
self.assertEqual(env['NPROC_PER_NODE'], '2')
self.assertEqual(env['PYTHON'], '/chosen/python')
def test_negative_sample_limit_is_rejected_before_launch(self):
with self.assertRaises(SystemExit):
self.invoke('verify', extra_args=('--max-samples', '-1'))
self.assertEqual(self.child_commands, [])
def test_empty_dataset_is_rejected_before_launch(self):
(self.dataset / 'mapping_file.json').write_text('{}')
with self.assertRaisesRegex(ValueError, 'dataset is empty'):
self.invoke('verify')
self.assertEqual(self.child_commands, [])
def test_each_measurement_has_a_new_output_directory(self):
_, first = self.invoke('verify')
_, second = self.invoke('verify')
self.assertNotEqual(first['summary_path'], second['summary_path'])
self.assertTrue(Path(first['summary_path']).is_file())
code, guarded = self.invoke('guard')
self.assertEqual(code, 0)
self.assertEqual(guarded['summary_path'], second['summary_path'])
def test_failed_child_clears_previous_result(self):
self.invoke('verify')
with self.assertRaisesRegex(RuntimeError, 'exited 7; log:'):
self.invoke('verify', runner=lambda command, **kwargs: subprocess.CompletedProcess(command, 7))
self.assertFalse((self.output_root / 'latest.json').exists())
with self.assertRaises(FileNotFoundError):
self.invoke('guard')
def test_guard_rejects_a_result_from_another_commit(self):
self.invoke('verify')
with self.assertRaisesRegex(ValueError, 'different Git commit'):
self.invoke('guard', head='another-commit')
def test_missing_samples_and_nonfinite_metrics_are_rejected(self):
original = copy.deepcopy(self.summary)
for change, message in (
('total', 'expected 30 samples'), ('valid', '29/30 valid samples'),
('nonfinite', 'non-finite'), ('missing', 'clip_similarity_target_image'),
):
with self.subTest(change=change):
self.summary = copy.deepcopy(original)
stats = self.summary['pie_bench_metrics']['statistics']
if change == 'total':
self.summary['count'] = 29
elif change == 'valid':
stats['clip_similarity_target_image']['count'] = 29
elif change == 'nonfinite':
stats['clip_similarity_target_image']['mean'] = float('nan')
else:
del stats['clip_similarity_target_image']
with self.assertRaisesRegex((ValueError, KeyError), message):
self.invoke('verify')
self.assertFalse((self.output_root / 'latest.json').exists())
def test_infinite_psnr_for_identical_background_is_valid_json(self):
stats = self.summary['pie_bench_metrics']['statistics']
stats['psnr_unedit_part']['mean'] = 'inf'
stats['mse_unedit_part']['mean'] = 0.0
_, result = self.invoke('verify')
self.assertEqual(result['psnr_unedit_part'], 'inf')
self.assertEqual(result['violation'], 0.0)
self.assertEqual(self.invoke('guard')[0], 0)
def test_missing_or_multiple_summaries_are_rejected(self):
def multiple(command, **kwargs):
completed = self.run_child(command, **kwargs)
directory = Path(command[command.index('--output-dir') + 1]) / 'second_pair'
directory.mkdir()
(directory / 'summary.json').write_text(json.dumps(self.summary))
return completed
for runner, count in (
(lambda command, **kwargs: subprocess.CompletedProcess(command, 0), 0),
(multiple, 2),
):
with self.subTest(count=count), self.assertRaisesRegex(ValueError, f'got {count}'):
self.invoke('verify', runner=runner)
if __name__ == '__main__':
unittest.main()
|