Cross-check LiSA held-out metrics across scoring paths

This commit is contained in:
2026-11-24 00:06:58 +08:00
parent 1c8943a2e8
commit 59072884ff
4 changed files with 119 additions and 12 deletions
+68 -9
View File
@@ -13,6 +13,12 @@ from functional.run import write_json
MODES = ('native', 'direct', 'linear', 'lisa', 'lisa_answer_weighted') MODES = ('native', 'direct', 'linear', 'lisa', 'lisa_answer_weighted')
def paired_interval(delta):
rng = np.random.default_rng(415006)
draw = rng.integers(0, len(delta), size=(10000, len(delta)))
return np.quantile(delta[draw].mean(1), [.025, .975]).tolist()
def paired(native, direct, candidate): def paired(native, direct, candidate):
damaged = native & ~direct damaged = native & ~direct
rescued = damaged & candidate rescued = damaged & candidate
@@ -20,9 +26,6 @@ def paired(native, direct, candidate):
candidate_only = ~direct & candidate candidate_only = ~direct & candidate
direct_only = direct & ~candidate direct_only = direct & ~candidate
delta = candidate.astype(int) - direct.astype(int) delta = candidate.astype(int) - direct.astype(int)
rng = np.random.default_rng(415006)
draw = rng.integers(0, len(delta), size=(10000, len(delta)))
ci = np.quantile(delta[draw].mean(1), [.025, .975])
a, b = int(candidate_only.sum()), int(direct_only.sum()) a, b = int(candidate_only.sum()), int(direct_only.sum())
k = a + b k = a + b
p = min(1., 2. * sum(math.comb(k, i) for i in range(min(a, b)+1)) / 2**k) p = min(1., 2. * sum(math.comb(k, i) for i in range(min(a, b)+1)) / 2**k)
@@ -30,10 +33,61 @@ def paired(native, direct, candidate):
'newly_lost_among_native_and_direct_correct': int(newly_lost.sum()), 'newly_lost_among_native_and_direct_correct': int(newly_lost.sum()),
'candidate_correct_direct_wrong': a, 'direct_correct_candidate_wrong': b, 'candidate_correct_direct_wrong': a, 'direct_correct_candidate_wrong': b,
'accuracy_delta_vs_direct': float(delta.mean()), 'accuracy_delta_vs_direct': float(delta.mean()),
'paired_prompt_bootstrap_95': ci.tolist(), 'mcnemar_exact_p': p} 'paired_prompt_bootstrap_95': paired_interval(delta), 'mcnemar_exact_p': p}
def audit(fixed, selection, items, perf=None, decode=None): def loss_delta(losses, baseline):
delta = losses - baseline
return {'mean_delta': float(delta.mean()), 'paired_prompt_bootstrap_95': paired_interval(delta)}
def full_vocab_metrics(path, expected, sites, choices):
report = json.loads(path.read_text())
chain = len(sites) > 1
if (report['candidate_sites'] != sites
or report['single_lisa_is_ablation_of_joint_checkpoint'] != chain):
raise ValueError('Full-vocabulary layers differ from the locked schedule')
arms = report['arms']
mapped = {'native': 'native', 'linear': 'linear', 'lisa_answer_weighted': 'lisa_answer_weighted',
'direct_chain' if chain else 'direct_23': 'direct',
'lisa_chain' if chain else 'lisa_23_ablation': 'lisa'}
if set(arms) != set(mapped) | {'direct_23', 'lisa_23_ablation'}:
raise ValueError('Unexpected full-vocabulary arms')
expected_ids = [name for name, _ in expected]
correct, nll = {}, {}
gold_ids = [row['gold_id'] for row in arms['native']['rows']]
for mode, summary in arms.items():
rows = summary['rows']
if (summary['n'] != len(expected_ids) or [row['id'] for row in rows] != expected_ids
or [row['gold_id'] for row in rows] != gold_ids):
raise ValueError(f'{mode} vocabulary result does not match the locked rows')
correct[mode] = np.array([row['greedy_id'] == row['gold_id'] for row in rows])
nll[mode] = np.array([row['nll'] for row in rows])
choice_correct = np.array([row['choice_id'] == row['gold_id'] for row in rows])
if (not np.isfinite(nll[mode]).all() or (nll[mode] < 0).any()
or int(correct[mode].sum()) != summary['full_vocab_correct']
or int(choice_correct.sum()) != summary['four_choice_correct']
or not np.isclose(nll[mode].mean(), summary['full_vocab_nll'])):
raise ValueError(f'Invalid vocabulary metrics for {mode}')
if mode in mapped and not np.array_equal(choice_correct, choices[mapped[mode]]):
raise ValueError(f'{mode} choices differ across the two evaluations')
matches = {'lisa_23_ablation': 'direct_23',
'native': 'direct_chain' if chain else 'direct_23',
'linear': 'direct_chain' if chain else 'direct_23',
'lisa_answer_weighted': 'direct_chain' if chain else 'direct_23'}
if chain:
matches['lisa_chain'] = 'direct_chain'
return {
'arms': {mode: {'correct': int(correct[mode].sum()), 'answer_nll': float(nll[mode].mean())}
for mode in arms},
'matched_direct_comparisons': {
mode: {'baseline': direct, 'answer_nll_delta': loss_delta(nll[mode], nll[direct]),
**paired(correct['native'], correct[direct], correct[mode])}
for mode, direct in matches.items()},
}
def audit(fixed, selection, items, perf=None, decode=None, full_vocab=None):
spec = json.loads(selection.read_text()) spec = json.loads(selection.read_text())
if hashlib.sha256(fixed.read_bytes()).hexdigest() != spec['fixed_problems_sha256']: if hashlib.sha256(fixed.read_bytes()).hexdigest() != spec['fixed_problems_sha256']:
raise ValueError('Fixed problems provenance mismatch') raise ValueError('Fixed problems provenance mismatch')
@@ -44,7 +98,7 @@ def audit(fixed, selection, items, perf=None, decode=None):
if set(data) != set(MODES) or not expected: if set(data) != set(MODES) or not expected:
raise ValueError('Unexpected test arms or empty selected split') raise ValueError('Unexpected test arms or empty selected split')
correct = {} correct = {}
mean_losses = {} losses = {}
for mode, rows in data.items(): for mode, rows in data.items():
if [(r['id'], r['gold']) for r in rows] != expected: if [(r['id'], r['gold']) for r in rows] != expected:
raise ValueError(f'{mode} result does not match the locked challenge') raise ValueError(f'{mode} result does not match the locked challenge')
@@ -56,9 +110,11 @@ def audit(fixed, selection, items, perf=None, decode=None):
or not np.array_equal(logits.argmax(1), pred)): or not np.array_equal(logits.argmax(1), pred)):
raise ValueError(f'Invalid choice scores for {mode}') raise ValueError(f'Invalid choice scores for {mode}')
np.testing.assert_allclose(nll, [row['answer_nll'] for row in rows], atol=3e-6, rtol=2e-6) np.testing.assert_allclose(nll, [row['answer_nll'] for row in rows], atol=3e-6, rtol=2e-6)
correct[mode], mean_losses[mode] = pred == gold, float(nll.mean()) correct[mode], losses[mode] = pred == gold, nll
metrics = {'selected_task': task, 'sites': spec['sites'], 'n': len(expected), metrics = {'selected_task': task, 'sites': spec['sites'], 'n': len(expected),
'arms': {mode: {'correct': int(correct[mode].sum()), 'answer_nll_4': mean_losses[mode], 'arms': {mode: {'correct': int(correct[mode].sum()),
'answer_nll_4': float(losses[mode].mean()),
'answer_nll_4_vs_direct': loss_delta(losses[mode], losses['direct']),
**paired(correct['native'], correct['direct'], correct[mode])} **paired(correct['native'], correct['direct'], correct[mode])}
for mode in MODES}} for mode in MODES}}
if perf: if perf:
@@ -80,6 +136,8 @@ def audit(fixed, selection, items, perf=None, decode=None):
'median_s_per_token': times, 'measured_kv_bytes': {'native': native, 'lisa': lisa}, 'median_s_per_token': times, 'measured_kv_bytes': {'native': native, 'lisa': lisa},
'lisa_upstream_score_row_bytes': nn, 'recipient_bytes_delta': lisa+nn-native, 'lisa_upstream_score_row_bytes': nn, 'recipient_bytes_delta': lisa+nn-native,
} }
if full_vocab:
metrics['full_vocab'] = full_vocab_metrics(full_vocab, expected, spec['sites'], correct)
return metrics return metrics
@@ -89,8 +147,9 @@ def main():
parser.add_argument('--'+name, type=Path, required=True) parser.add_argument('--'+name, type=Path, required=True)
parser.add_argument('--perf', type=Path) parser.add_argument('--perf', type=Path)
parser.add_argument('--decode', type=Path) parser.add_argument('--decode', type=Path)
parser.add_argument('--full-vocab', type=Path)
a = parser.parse_args() a = parser.parse_args()
report = audit(a.fixed, a.selection, a.items, a.perf, a.decode) report = audit(a.fixed, a.selection, a.items, a.perf, a.decode, a.full_vocab)
write_json(a.out, report) write_json(a.out, report)
+5 -2
View File
@@ -125,14 +125,17 @@ RESULT=runs/NEW_EFFECT_RESULT
--trained "$RESULT" --out "$RESULT/full-vocab-answers.json" --trained "$RESULT" --out "$RESULT/full-vocab-answers.json"
"$PYTHON" -B -m crossqkv.lisa_effect_audit --fixed "$SCREEN/fixed-problems.json" \ "$PYTHON" -B -m crossqkv.lisa_effect_audit --fixed "$SCREEN/fixed-problems.json" \
--selection "$CAPTURE/selection.json" --items "$RESULT/test-items.json" \ --selection "$CAPTURE/selection.json" --items "$RESULT/test-items.json" \
--perf "$RESULT/performance.json" --decode "$RESULT/decode.json" --out "$RESULT/paired-audit.json" --perf "$RESULT/performance.json" --decode "$RESULT/decode.json" \
--full-vocab "$RESULT/full-vocab-answers.json" --out "$RESULT/paired-audit.json"
``` ```
The paired audit defines a rescue as a native-correct item made wrong by The paired audit defines a rescue as a native-correct item made wrong by
direct sharing and made correct again by the tested adapter. It reports direct sharing and made correct again by the tested adapter. It reports
newly lost native-and-direct-correct items separately. An improvement in newly lost native-and-direct-correct items separately. An improvement in
mean four-option answer NLL, including among items already answered mean four-option answer NLL, including among items already answered
correctly, does not by itself establish a rescue. correctly, does not by itself establish a rescue. The audit computes paired
intervals for NLL differences and checks that common arms have identical
four-choice correctness in the primary test and the full-vocabulary pass.
Training scores *all* valid shifted tokens with exact full-vocabulary CE Training scores *all* valid shifted tokens with exact full-vocabulary CE
and uses the validation four-option answer loss to freeze checkpoints. The and uses the validation four-option answer loss to freeze checkpoints. The
@@ -35,6 +35,15 @@
"validated_remote_benchmark_sha256": "979e566a3391b9418b49beb10c200a48aac706ee95c145510850c929bcc2885a", "validated_remote_benchmark_sha256": "979e566a3391b9418b49beb10c200a48aac706ee95c145510850c929bcc2885a",
"reason": "Measure compute with resident projections separately from streamed execution", "reason": "Measure compute with resident projections separately from streamed execution",
"remote_numeric_tests": "4 passed; resident projection outputs compared with streamed output" "remote_numeric_tests": "4 passed; resident projection outputs compared with streamed output"
},
"lisa_effect_audit.py": {
"verified_audit_sha256": "2d7feb79c23bed05d4d961ead7cbdfcff61b5425f1c3ef88192c2c3cd5afecb4",
"reason": "Cross-check the four-choice arms against the full-vocabulary pass and quantify paired answer-loss changes",
"remote_numeric_tests": "4 passed in an isolated source directory",
"outputs": {
"paired-audit.json": "original audit hash in audit_code_sha256",
"verified-audit.json": "verified_audit_sha256"
}
} }
} }
} }
+37 -1
View File
@@ -1,4 +1,7 @@
"""Check answer-only metrics and isolate recovery from newly lost items.""" """Check answer-only metrics and isolate recovery from newly lost items."""
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest import unittest
import numpy as np import numpy as np
@@ -6,11 +9,44 @@ import torch
from torch.nn import functional as F from torch.nn import functional as F
from crossqkv.lisa_effect_answer_audit import vocabulary_scores from crossqkv.lisa_effect_answer_audit import vocabulary_scores
from crossqkv.lisa_effect_audit import paired from crossqkv.lisa_effect_audit import MODES, full_vocab_metrics, loss_delta, paired
from tests.test_lisa_tail import Tensor from tests.test_lisa_tail import Tensor
class EffectAuditTests(unittest.TestCase): class EffectAuditTests(unittest.TestCase):
def test_loss_interval_uses_paired_differences(self):
direct = np.array([0.5, 1.0, 4.0, 9.0])
result = loss_delta(direct - 0.25, direct)
self.assertEqual(result, {'mean_delta': -0.25,
'paired_prompt_bootstrap_95': [-0.25, -0.25]})
def test_full_vocab_compares_each_recipient_schedule_to_matched_direct(self):
mapped = ('native', 'linear', 'direct_chain', 'lisa_chain', 'lisa_answer_weighted',
'direct_23', 'lisa_23_ablation')
payload = {'candidate_sites': [19, 23], 'single_lisa_is_ablation_of_joint_checkpoint': True,
'arms': {}}
for name in mapped:
correct = name not in ('direct_chain', 'direct_23')
payload['arms'][name] = {
'n': 1, 'full_vocab_correct': int(correct), 'four_choice_correct': 1,
'full_vocab_nll': 0.25 if correct else 2.0,
'rows': [{'id': 'test-a', 'gold_id': 3, 'greedy_id': 3 if correct else 4,
'choice_id': 3, 'nll': 0.25 if correct else 2.0}],
}
choices = {name: np.array([True]) for name in MODES}
with TemporaryDirectory() as scratch:
path = Path(scratch) / 'answers.json'
path.write_text(json.dumps(payload))
measured = full_vocab_metrics(path, [('test-a', 0)], [19, 23], choices)
comparisons = measured['matched_direct_comparisons']
self.assertEqual(comparisons['lisa_chain']['baseline'], 'direct_chain')
self.assertEqual(comparisons['lisa_23_ablation']['baseline'], 'direct_23')
self.assertEqual(comparisons['lisa_chain']['rescued'], 1)
self.assertEqual(comparisons['lisa_chain']['answer_nll_delta']['mean_delta'], -1.75)
choices['lisa'] = np.array([False])
with self.assertRaisesRegex(ValueError, 'lisa_chain choices differ'):
full_vocab_metrics(path, [('test-a', 0)], [19, 23], choices)
def test_paired_rescue_excludes_natively_wrong_items(self): def test_paired_rescue_excludes_natively_wrong_items(self):
native, direct, candidate = (np.array(x, dtype=bool) for x in native, direct, candidate = (np.array(x, dtype=bool) for x in
[(1, 1, 1, 0), (0, 0, 1, 1), (1, 0, 0, 1)]) [(1, 1, 1, 0), (0, 0, 1, 1), (1, 0, 0, 1)])