Download rr2/integrate_gpu_evidence.py from nur-dev/pns-bind-25m: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/nur-dev/pns-bind-25m/resolve/main/rr2/integrate_gpu_evidence.py
- Command line
-
hf download hf://nur-dev/pns-bind-25m/rr2/integrate_gpu_evidence.py
-
curl -L -o integrate_gpu_evidence.py https://huggingface.co/nur-dev/pns-bind-25m/resolve/main/rr2/integrate_gpu_evidence.py
12.3 kB
| #!/usr/bin/env python3 | |
| """Verify the closed additional campaign and derive every new article number.""" | |
| from pathlib import Path | |
| import hashlib | |
| import json | |
| import re | |
| import sys | |
| import shutil | |
| import numpy as np | |
| import matplotlib | |
| matplotlib.use('Agg') | |
| import matplotlib.pyplot as plt | |
| HERE = Path(__file__).resolve().parent | |
| ARTICLE = HERE.parent | |
| ART = Path('/raid/nurgaly/datasets/pns/reviewer_rr2_20261004') | |
| sys.path.insert(0, str(HERE / 'gpu_campaign')) | |
| from runtime import freeze, sha, read, INVENTORIES, PUBLIC, ORIGINAL_ART | |
| def bootstrap(left, right, field): | |
| for key in ('seed', 'event', 'family'): | |
| assert np.array_equal(left[key], right[key]), key | |
| mask = left['family'] == 1 | |
| seeds, group = np.unique(left['seed'][mask], return_inverse=True) | |
| count = np.bincount(group) | |
| sums = np.bincount(group, weights=left[field][mask].astype(float) - right[field][mask].astype(float)) | |
| index = np.random.default_rng(20261004).integers(len(seeds), size=(2000, len(seeds))) | |
| estimates = sums[index].sum(1) / count[index].sum(1) | |
| return {'difference': float(sums.sum() / count.sum()), | |
| 'ci95': np.quantile(estimates, [.025, .975]).tolist(), | |
| 'questions': int(count.sum()), 'lifetimes': len(seeds), | |
| 'resamples': 2000, 'bootstrap_seed': 20261004} | |
| def load_rows(path): | |
| with np.load(path) as z: | |
| return dict(z) | |
| def table(name, rows): | |
| body = '\n'.join(' & '.join(r'\rev{' + str(c) + '}' for c in row) + r' \tabularnewline' for row in rows) | |
| body += '\n\\bottomrule\n' | |
| (ARTICLE / 'mdpi/tables' / name).write_text(body) | |
| source_path = ARTICLE / 'mdpi/main.tex' | |
| source = source_path.read_text() | |
| start, end = f'% Begin generated table body: {name}', f'% End generated table body: {name}' | |
| pattern = re.compile(re.escape(start) + '.*?' + re.escape(end), re.S) | |
| if len(pattern.findall(source)) != 1: | |
| raise ValueError(f'Table marker missing or repeated: {name}') | |
| source_path.write_text(pattern.sub(lambda _: start + '\n' + body + end, source)) | |
| def main(): | |
| frozen = freeze() | |
| hashes = {} | |
| def checked(path): | |
| hashes[str(path.relative_to(ART))] = sha(path) | |
| for path in ART.glob('*.json'): | |
| checked(path) | |
| gate = read(ART / 'CONFIRMATION_GATE.json') | |
| assert gate['all_passed'] and len(gate['checks']) == 144 | |
| assert read(ART / 'DEVELOPMENT_GATE.json')['all_passed'] | |
| opening = read(ART / 'CONFIRMATION_OPENED.json') | |
| assert opening['gate_sha256'] == sha(ART / 'DEVELOPMENT_GATE.json') | |
| assert opening['data_freeze_sha256'] == sha(ART / 'DATA_FREEZE_COMPOSE.json') | |
| for relative, expected in read(ART / 'DATA_FREEZE_COMPOSE.json')['files'].items(): | |
| assert sha(ART / relative) == expected, relative | |
| summary = {'models': {}, 'contrasts': {}, 'gru': {}, | |
| 'primary_development_passed': True, 'primary_confirmation_passed': True, | |
| 'primary_gate_count_each_split': 144, 'seeds_share_rows': True, | |
| 'sources': frozen['sources']} | |
| for suite, arms in (('compose', ('future', 'ordinary')), ('original', ('ordinary', 'reference'))): | |
| for arm in arms: | |
| for seed in (821, 822, 823): | |
| label = f'{suite}_{arm}_s{seed}' | |
| run = ART / 'runs' / label | |
| if arm != 'reference': | |
| done = read(run / 'DONE.json') | |
| assert done['updates'] == 6000 | |
| assert done['challenge_calls'] == (6000 if arm == 'future' else 0) | |
| assert sha(run / done['checkpoint']) == done['sha256'] | |
| for p in run.glob('*.json'): | |
| checked(p) | |
| checked(run / 'train.jsonl') | |
| entry = {} | |
| splits = ('known_development', 'development', 'confirmation') if suite == 'compose' else ('known_development',) | |
| for split in splits: | |
| result_path = run / f'{split}.json' | |
| result = read(result_path) | |
| checked(result_path) | |
| rows_path = run / f'{split}_ordinary_rows.npz' | |
| rows = load_rows(rows_path) | |
| checked(rows_path) | |
| for f in range(11): | |
| mask = rows['family'] == f | |
| assert mask.sum() == result['ordinary'][f'family_{f}_n'] | |
| assert abs(rows['correct'][mask].mean() - result['ordinary'][f'family_{f}_acc']) < 1e-12 | |
| mask = rows['family'] == 1 | |
| assert abs(rows['identity'][mask].mean() - result['ordinary']['twohop_identity']) < 1e-12 | |
| for n in (16, 32): | |
| cp = run / f'{split}_n{n}_challenge_rows.npz' | |
| cr = load_rows(cp) | |
| checked(cp) | |
| for key, value in cr.items(): | |
| if key in ('gold', 'world_seed', 'margin_at_write'): | |
| continue | |
| assert len(value) == 2000 | |
| assert abs(value.mean() - result['challenge'][str(n)][key]['accuracy']) < 1e-12 | |
| if arm != 'ordinary': | |
| for key in ('restore_agrees', 'replay_agrees', 'permutation_agrees'): | |
| assert cr[key].all() | |
| entry[split] = result | |
| summary['models'][label] = entry | |
| for suite, split in (('original', 'known_development'), ('compose', 'known_development'), | |
| ('compose', 'development'), ('compose', 'confirmation')): | |
| for seed in (821, 822, 823): | |
| primary_arm = 'reference' if suite == 'original' else 'future' | |
| left = load_rows(ART / 'runs' / f'{suite}_{primary_arm}_s{seed}' / f'{split}_ordinary_rows.npz') | |
| right = load_rows(ART / 'runs' / f'{suite}_ordinary_s{seed}' / f'{split}_ordinary_rows.npz') | |
| summary['contrasts'][f'{suite}_{split}_s{seed}'] = { | |
| 'answer': bootstrap(left, right, 'correct'), 'identity': bootstrap(left, right, 'identity')} | |
| # The registered >= .20 effect-size condition is a separate attribution gate, | |
| # not silently conflated with the primary confirmation conjunction. | |
| summary['large_added_supervision_effect_passed'] = all( | |
| summary['contrasts'][f'compose_confirmation_s{s}']['answer']['difference'] >= .20 and | |
| summary['contrasts'][f'compose_confirmation_s{s}']['answer']['ci95'][0] > 0 | |
| for s in (821, 822, 823)) | |
| assert not summary['large_added_supervision_effect_passed'] | |
| for seed in (821, 822, 823): | |
| run = ART / 'runs' / f'gru_semantic_s{seed}' | |
| done = read(run / 'DONE.json') | |
| assert done['updates'] == 12000 and done['parameters'] == 3390955 | |
| assert sha(run / done['checkpoint']) == done['sha256'] | |
| entry = {} | |
| for update in (6000, 12000): | |
| path = run / f'development_{update}.json' | |
| d = read(path) | |
| rows_path = run / f'development_{update}_rows.npz' | |
| rows = load_rows(rows_path) | |
| for key in ('correct', 'current_only', 'state_swap', 'reset128'): | |
| assert abs(rows[key].mean() - d[key]['accuracy']) < 1e-12 | |
| for p in (path, rows_path): | |
| checked(p) | |
| entry[str(update)] = d | |
| for p in (run / 'train.jsonl', run / 'START.json', run / 'DONE.json'): | |
| checked(p) | |
| summary['gru'][str(seed)] = entry | |
| summary['gru_registered_strong_memory_gate_passed'] = all( | |
| summary['gru'][str(s)]['12000']['correct']['accuracy'] >= .80 for s in (821, 822, 823)) | |
| assert not summary['gru_registered_strong_memory_gate_passed'] | |
| for directory in (ART / 'preflight',): | |
| for p in directory.rglob('*.json'): | |
| checked(p) | |
| (HERE / 'GPU_RESULTS.json').write_text(json.dumps(summary, indent=2, sort_keys=True, allow_nan=False) + '\n') | |
| (HERE / 'GPU_EVIDENCE_MANIFEST.json').write_text(json.dumps({'artifact_root': str(ART), 'files': hashes}, indent=2, sort_keys=True) + '\n') | |
| primary_rows, ordinary_rows, gru_rows = [], [], [] | |
| for seed in (821, 822, 823): | |
| result = summary['models'][f'compose_future_s{seed}']['confirmation'] | |
| for n in (16, 32): | |
| m = result['challenge'][str(n)] | |
| primary_rows.append([n, seed] + [f"{m[k]['accuracy']:.4f}" for k in | |
| ('identity_512', 'twohop_512', 'relation_zero', 'second_zero', 'relation_cf_identity', 'value_cf_answer')]) | |
| for suite, split, description in (('original', 'known_development', 'Original names'), | |
| ('compose', 'confirmation', 'Held-out names')): | |
| left_arm = 'reference' if suite == 'original' else 'future' | |
| left = summary['models'][f'{suite}_{left_arm}_s{seed}'][split]['ordinary'] | |
| right = summary['models'][f'{suite}_ordinary_s{seed}'][split]['ordinary'] | |
| contrast = summary['contrasts'][f'{suite}_{split}_s{seed}']['answer'] | |
| lo, hi = contrast['ci95'] | |
| ordinary_rows.append([description, seed, f"{left['family_1_acc']:.4f}", f"{right['family_1_acc']:.4f}", | |
| f"{contrast['difference']:.4f} [{lo:.4f}, {hi:.4f}]", | |
| f"{left['twohop_identity']:.4f}", f"{right['twohop_identity']:.4f}"]) | |
| g = summary['gru'][str(seed)]['12000'] | |
| gru_rows.append([seed, f"{g['correct']['accuracy']:.4f}", f"{g['current_only']['accuracy']:.4f}", | |
| f"{g['state_swap']['accuracy']:.4f}"] + | |
| [f"{g['delay_strata'][label]['accuracy']:.4f}" for label in ('le16', '17to128', 'gt128')]) | |
| table('rr2_heldout_rows.tex', primary_rows) | |
| table('rr2_ordinary_rows.tex', ordinary_rows) | |
| table('rr2_gru_rows.tex', gru_rows) | |
| plt.rcParams.update({'font.size': 8, 'pdf.fonttype': 42}) | |
| fig, axes = plt.subplots(1, 3, figsize=(10, 2.9)) | |
| colors = ('#0072B2', '#D55E00', '#009E73') | |
| for seed, color in zip((821, 822, 823), colors): | |
| run = ART / 'runs' / f'gru_semantic_s{seed}' | |
| logs = [json.loads(line) for line in (run / 'train.jsonl').read_text().splitlines()] | |
| updates = np.array([d['update'] for d in logs]) | |
| losses = np.array([d['loss'] for d in logs]) | |
| axes[0].plot(updates[10:], np.convolve(losses, np.ones(11)/11, mode='valid'), color=color, label=str(seed)) | |
| entry = summary['gru'][str(seed)] | |
| axes[1].plot([6000, 12000], [entry[str(u)]['correct']['accuracy'] for u in (6000, 12000)], 'o-', color=color) | |
| d = entry['12000'] | |
| axes[2].plot([0, 1, 2], [d['delay_strata'][l]['accuracy'] for l in ('le16', '17to128', 'gt128')], 'o-', color=color) | |
| rows = load_rows(ART / 'runs/gru_semantic_s821/development_12000_rows.npz') | |
| control = [] | |
| for lo, hi in ((0, 16), (17, 128), (129, 100000)): | |
| means = [] | |
| for seed in (821, 822, 823): | |
| r = load_rows(ART / 'runs' / f'gru_semantic_s{seed}' / 'development_12000_rows.npz') | |
| mask = (r['delay'] >= lo) & (r['delay'] <= hi) | |
| means.append(r['current_only'][mask].mean()) | |
| control.append(np.mean(means)) | |
| axes[2].plot([0, 1, 2], control, 'k--', label='Current-event mean') | |
| axes[0].set(title='(a) Semantic-only training loss', xlabel='Optimizer update', ylabel='Cross-entropy') | |
| axes[0].legend(title='Seed', fontsize=7) | |
| axes[1].set(title='(b) Fresh SEM-LATEST accuracy', xlabel='Fixed checkpoint update', ylabel='Accuracy', ylim=(0, 1)) | |
| axes[2].set(title='(c) Final accuracy by delay', ylabel='Accuracy', ylim=(0, 1)) | |
| axes[2].set_xticks([0, 1, 2], ['$\\leq$16', '17–128', '>128']) | |
| axes[2].set_xlabel('Intervening events') | |
| axes[2].legend(fontsize=7) | |
| for ax in axes: | |
| ax.spines[['top', 'right']].set_visible(False) | |
| ax.grid(alpha=.15) | |
| fig.tight_layout() | |
| fig.savefig(ARTICLE / 'mdpi/figures/rr2_gru_learning.pdf') | |
| plt.close(fig) | |
| print(json.dumps({'primary_confirmed': True, 'primary_gates': 144, | |
| 'large_added_supervision_effect_passed': False, | |
| 'gru_strong_memory_gate_passed': False, 'verified_evidence_files': len(hashes)})) | |
| if __name__ == '__main__': | |
| main() | |