Download reference/strict_reference_v1/replay.py from STRICT-APT/strict-score-record: direct link, hf CLI and curl.
- Browser
- Download file 12.8 kB
-
https://huggingface.co/datasets/STRICT-APT/strict-score-record/resolve/main/reference/strict_reference_v1/replay.py
- Command line
-
hf download hf://datasets/STRICT-APT/strict-score-record/reference/strict_reference_v1/replay.py
-
curl -L -o replay.py https://huggingface.co/datasets/STRICT-APT/strict-score-record/resolve/main/reference/strict_reference_v1/replay.py
12.8 kB
| #!/usr/bin/env python3 | |
| """Verify the self-contained chronological reference from public numeric inputs.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import numpy as np | |
| import metrics as m | |
| def sha256(path): | |
| value = hashlib.sha256() | |
| with path.open('rb') as handle: | |
| for chunk in iter(lambda: handle.read(1 << 20), b''): | |
| value.update(chunk) | |
| return value.hexdigest() | |
| def verify_manifest(root): | |
| expected = {} | |
| for line in (root / 'MANIFEST.sha256').read_text().splitlines(): | |
| sha, name = line.split(' ', 1) | |
| path = Path(name) | |
| if path.is_absolute() or '..' in path.parts or name in expected or len(sha) != 64: | |
| raise ValueError('Invalid or duplicated manifest entry') | |
| expected[name] = sha | |
| # Only the root manifest is excluded, not same-named extra files in subdirectories. | |
| actual = {str(p.relative_to(root)) for p in root.rglob('*') if p.is_file() and p != root / 'MANIFEST.sha256'} | |
| if actual != set(expected) or any(p.is_symlink() for p in root.rglob('*')): | |
| raise ValueError('Missing, extra or symbolic-link release entries') | |
| for name, sha in expected.items(): | |
| if sha256(root / name) != sha: | |
| raise ValueError('Hash mismatch: ' + name) | |
| return len(expected) | |
| def compare(actual, expected, location='result'): | |
| actual = m.finite_json(actual) | |
| if isinstance(expected, dict): | |
| assert isinstance(actual, dict) and set(actual) == set(expected), location | |
| for key in expected: | |
| compare(actual[key], expected[key], location + '/' + key) | |
| elif isinstance(expected, list): | |
| assert isinstance(actual, list) and len(actual) == len(expected), location | |
| for index, (left, right) in enumerate(zip(actual, expected)): | |
| compare(left, right, location + '/' + str(index)) | |
| elif isinstance(expected, (float, int)) and not isinstance(expected, bool): | |
| assert actual is not None and np.isclose(actual, expected, rtol=1e-12, atol=1e-12), (location, actual, expected) | |
| else: | |
| assert actual == expected, (location, actual, expected) | |
| def arrays(path): | |
| with np.load(path, allow_pickle=False) as data: | |
| out = {k: data[k] for k in data.files} | |
| assert all(a.dtype.kind in 'biuf' and a.ndim == 1 and np.isfinite(a).all() for a in out.values()) | |
| return out | |
| def score_arrays(path): | |
| data = arrays(path) | |
| assert set(data) == {'nodes', 'y_truth', 'pred_scores', 'y_preds', 'attack_nodes', 'attacks'} | |
| nodes = data['nodes'] | |
| assert len(np.unique(nodes)) == len(nodes) | |
| assert all(len(data[k]) == len(nodes) for k in ('y_truth', 'pred_scores', 'y_preds')) | |
| assert np.isin(data['y_truth'], [0, 1]).all() and np.isin(data['y_preds'], [0, 1]).all() | |
| assert len(data['attack_nodes']) == len(data['attacks']) | |
| labels = defaultdict(list) | |
| for node, attack in zip(data['attack_nodes'].tolist(), data['attacks'].tolist()): | |
| labels[node].append(attack) | |
| assert all(len(v) == len(set(v)) for v in labels.values()) | |
| return data, dict(labels) | |
| def budgets(scores, nodes, labels, attacks): | |
| order = np.lexsort((nodes, -scores)) | |
| result = {} | |
| for budget in (10, 100, 1000): | |
| assert len(nodes) >= budget | |
| chosen = np.zeros(len(nodes), bool) | |
| chosen[order[:budget]] = True | |
| value = m.metrics(chosen, labels, nodes, attacks) | |
| cutoff = scores[order[budget - 1]] | |
| above, tied = scores > cutoff, scores == cutoff | |
| slots = budget - int(above.sum()) | |
| tp_above, tp_tied = int((above & (labels == 1)).sum()), int((tied & (labels == 1)).sum()) | |
| value.update(tie_size=int(tied.sum()), precision_best=(tp_above + min(slots, tp_tied)) / budget, | |
| precision_worst=(tp_above + max(0, slots - int((tied & (labels == 0)).sum()))) / budget) | |
| result[str(budget)] = value | |
| return result | |
| def temporal(policy, blocks, nodes, dataset, attacks, onsets): | |
| value = m.temporal_metrics(policy, blocks, nodes, dataset, attacks, onsets, 120) | |
| value['campaign_delays'] = {str(i): value['attack_delays'].get(i) for i in range(value['campaigns'])} | |
| return value | |
| def replay_host(root): | |
| record = json.loads((root / 'record.json').read_text()) | |
| dataset, dates = record['dataset'], record['dates'] | |
| assert max(dates['train']) < min(dates['val']) and max(dates['val']) < min(dates['test']) | |
| assert record['final_epoch'] == 11 | |
| m.DATASET_DEFAULT_CONFIG[dataset] = {'attack_to_time_window': dates['attack_windows']} | |
| windows = m.attack_windows(dataset) | |
| onset_arrays = arrays(root / 'onsets.npz') | |
| onsets = dict(zip(zip(onset_arrays['attacks'].tolist(), onset_arrays['nodes'].tolist()), onset_arrays['times'].tolist())) | |
| assert len(onsets) == len(onset_arrays['times']) | |
| assert all(0 <= a < len(windows) and windows[a][0] <= t < windows[a][1] for (a, _), t in onsets.items()) | |
| settings, test_means = defaultdict(list), {} | |
| for candidate in record['tuning']: | |
| setting = candidate['setting'] | |
| assert [v['training_seed'] for v in candidate['members']] == [1, 2, 3] | |
| losses, test_values = [], [] | |
| for member in candidate['members']: | |
| validation = arrays(root / member['validation_file'])['losses'] | |
| mean = sum(float(x) for x in validation) / len(validation) | |
| assert mean == member['validation']['mean'] | |
| assert len(validation) == member['validation']['count'] | |
| losses.append(mean) | |
| data, attacks = score_arrays(root / member['scores_file']) | |
| value = m.adp(data['pred_scores'], data['nodes'], attacks, data['y_truth']) | |
| compare(value, member['expected_adp'], setting['name']) | |
| test_values.append(value) | |
| assert losses == setting['losses'] and sum(losses) / 3 == setting['mean'] | |
| key = setting['system'] + '|' + dataset | |
| settings[key].append(setting) | |
| test_means[setting['name']] = float(np.mean(test_values)) | |
| assert sum(len(v) for v in settings.values()) == (16 if dataset.startswith('CLEARSCOPE') else 24) | |
| assert len(settings) == 2 | |
| gaps = [] | |
| for key, candidates in sorted(settings.items()): | |
| selected = min(candidates, key=lambda r: (r['mean'], int(r['width']), int(r['emb']), float(r['lr']))) | |
| assert selected == record['selected'][key] | |
| chosen_adp = test_means[selected['name']] | |
| best_adp = max(test_means[r['name']] for r in candidates) | |
| gaps.append(dict(configuration=key, settings=len(candidates), selected=selected['name'], | |
| validation_selected_adp=chosen_adp, test_best_adp=best_adp, gap=best_adp-chosen_adp)) | |
| compare(gaps, record['expected_selection_gaps']) | |
| summaries, member_results = [], [] | |
| common_population = None | |
| for key in sorted(settings): | |
| members = sorted((r for r in record['reference'] if r['expected']['configuration'] == key), | |
| key=lambda r: r['expected']['training_seed']) | |
| assert [r['expected']['training_seed'] for r in members] == list(range(101, 111)) | |
| rows, vote, base_blocks, base_nodes = [], None, None, None | |
| for member in members: | |
| expected = member['expected'] | |
| data, attacks = score_arrays(root / member['scores_file']) | |
| nodes, labels, scores = (data[k] for k in ('nodes', 'y_truth', 'pred_scores')) | |
| assert {(a, n) for n, aa in attacks.items() for a in aa} == set(onsets) | |
| pop = sorted(zip(nodes.tolist(), labels.tolist())) | |
| if common_population is None: | |
| common_population = pop | |
| else: | |
| assert pop == common_population | |
| validation = arrays(root / member['validation_file'])['losses'] | |
| threshold = float(validation.max()) | |
| assert threshold == expected['threshold'] == member['validation']['maximum'] | |
| assert len(validation) == member['validation']['count'] | |
| predictions = scores > threshold | |
| assert np.array_equal(predictions, data['y_preds'].astype(bool)) | |
| raw = arrays(root / member['blocks_file']) | |
| assert len(raw['blocks']) == len(raw['nodes']) == len(raw['scores']) | |
| unique, inverse = np.unique(raw['nodes'], return_inverse=True) | |
| maxima = np.full(len(unique), -np.inf) | |
| np.maximum.at(maxima, inverse, raw['scores']) | |
| positions = np.searchsorted(unique, nodes) | |
| assert len(unique) == len(nodes) and np.array_equal(unique[positions], nodes) | |
| assert np.allclose(maxima[positions], scores, rtol=1e-7, atol=1e-8) | |
| keep = np.isin(raw['blocks'], record['timeline']) | |
| blocks, stream_nodes, block_scores = (raw[k][keep] for k in ('blocks', 'nodes', 'scores')) | |
| assert np.array_equal(np.lexsort((stream_nodes, blocks)), np.arange(len(blocks))) | |
| if vote is None: | |
| base_blocks, base_nodes = blocks, stream_nodes | |
| vote = np.zeros(len(blocks), dtype=np.int16) | |
| else: | |
| assert np.array_equal(blocks, base_blocks) and np.array_equal(stream_nodes, base_nodes) | |
| vote += block_scores > threshold | |
| policy = m.cooldown_mask(block_scores > threshold, blocks, stream_nodes, 120, 24) | |
| stream_value = temporal(policy, blocks, stream_nodes, dataset, attacks, onsets) | |
| delays = stream_value.pop('campaign_delays') | |
| result = dict(threshold=threshold, adp=m.adp(scores, nodes, attacks, labels), | |
| bstar=m.coverage_cost(scores, nodes, attacks), budgets=budgets(scores, nodes, labels, attacks), | |
| whole_test=m.metrics(predictions, labels, nodes, attacks), stream=stream_value, | |
| campaign_delays=delays, nodes=len(nodes), positives=int(labels.sum()), | |
| days=m.exposure_days(record['timeline'], 120)) | |
| compare(result, {k: expected[k] for k in result}, key + '/' + str(expected['training_seed'])) | |
| rows.append(result) | |
| member_results.append(dict(configuration=key, training_seed=expected['training_seed'], **result)) | |
| voted = m.cooldown_mask(vote >= 4, base_blocks, base_nodes, 120, 24) | |
| capped = m.rolling_cap_mask(voted, base_blocks, base_nodes, vote, 120, 10) | |
| companion = {name: temporal(policy, base_blocks, base_nodes, dataset, attacks, onsets) | |
| for name, policy in (('vote', voted), ('capped', capped))} | |
| campaigns = {} | |
| for attack in range(len(windows)): | |
| found = [r['campaign_delays'][str(attack)] for r in rows if r['campaign_delays'][str(attack)] is not None] | |
| campaigns[str(attack)] = dict(detected=len(found), members=10, | |
| conditional_median=float(np.median(found)) if found else None) | |
| summary = dict(configuration=key, dataset=dataset, n=10, adp=m.interval([r['adp'] for r in rows]), | |
| campaigns=campaigns, companion=companion, | |
| budgets={str(b): dict(precision=m.interval([r['budgets'][str(b)]['precision'] for r in rows]), | |
| coverage=m.interval([r['budgets'][str(b)]['attacks'] for r in rows])) | |
| for b in (10, 100, 1000)}) | |
| expected, = [s for s in record['expected_summary'] if s['configuration'] == key] | |
| compare(summary, expected, key) | |
| summaries.append(summary) | |
| print('PASS:', dataset, len(settings[key]), 'settings in last system;', len(member_results), 'reference members', flush=True) | |
| return dict(dataset=dataset, summary=summaries, members=member_results, selection_gaps=gaps, | |
| tuning_members=sum(len(s['members']) for s in record['tuning'])) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('root', type=Path) | |
| parser.add_argument('--out', type=Path) | |
| args = parser.parse_args() | |
| assert not args.out or not args.out.exists() | |
| checked = verify_manifest(args.root) | |
| hosts = [args.root / h for h in ('CADETS_E3_CHRONO', 'CLEARSCOPE_E3_CHRONO', 'THEIA_E3')] | |
| result = dict(status='PASS', verified_files=checked, manifest_sha256=sha256(args.root / 'MANIFEST.sha256'), | |
| hosts=[replay_host(h) for h in hosts]) | |
| assert sum(h['tuning_members'] for h in result['hosts']) == 192 | |
| assert sum(len(h['members']) for h in result['hosts']) == 60 | |
| if args.out: | |
| args.out.write_text(json.dumps(m.finite_json(result), indent=2, allow_nan=False) + '\n') | |
| print('PASS: all 192 tuning and 60 reference members, six choices, ranking, tie bounds, alerts, delays and votes.') | |
| if __name__ == '__main__': | |
| main() | |