Evaluate matched half-size trajectory distillation updates
This commit is contained in:
@@ -0,0 +1,169 @@
|
||||
"""Test a single predeclared shrinkage of the two trained LiSA distillation updates."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from tokenizers import Tokenizer
|
||||
|
||||
from crossqkv.lisa_combination_screen import ADAPTER_SHA, SITES
|
||||
from crossqkv.lisa_full_answer import fingerprint
|
||||
from crossqkv.lisa_full_answer_train import checkpoint, load_locked
|
||||
from crossqkv.lisa_full_answer_verify import verify
|
||||
from crossqkv.lisa_rank_compare import make_adapters
|
||||
from crossqkv.lisa_trajectory_train import validate_checkpoint
|
||||
from functional.model import StreamingLM
|
||||
from functional.run import write_json
|
||||
|
||||
|
||||
PROTOCOL_SHA = '6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef'
|
||||
TRAINED_SHA = {
|
||||
'student': '7faacdffbc81d0c786ef0c7a5acaf1724d82af155fed7b834dabc73dcf91f3a4',
|
||||
'reference': '21ae007cb7343c1a0042655824bdc98ee2f03071d5f5dc43dbc8b441a262d84f',
|
||||
}
|
||||
VALIDATION_SHA = {
|
||||
'prior-lisa': '3a10cdd0a22e110b5468ba496c3440a8b510ab3595328df330e7ea02b0ccbb76',
|
||||
'trajectory-student': 'af213ef477e99780d48b995f8a1d07ada6409bd70011202fb73db56247199c5f',
|
||||
'trajectory-reference': '3b5557336570cbeb1f6a592013780dc3e00e7f29b4192d59c53c6b2493779b91',
|
||||
}
|
||||
|
||||
|
||||
def read(path):
|
||||
return json.loads(path.read_bytes())
|
||||
|
||||
|
||||
def midpoint(base, trained):
|
||||
if base.keys() != trained.keys():
|
||||
raise ValueError('Adapter parameter names differ')
|
||||
result = {}
|
||||
for name, old in base.items():
|
||||
new = trained[name]
|
||||
if new.shape != old.shape or new.dtype != old.dtype or not old.is_floating_point():
|
||||
raise ValueError(f'Incompatible parameters for {name}')
|
||||
value = ((old.double() + new.double()) * 0.5).to(old.dtype)
|
||||
if not torch.isfinite(value).all():
|
||||
raise ValueError(f'Nonfinite midpoint for {name}')
|
||||
result[name] = value
|
||||
return result
|
||||
|
||||
|
||||
def prepare(prior, out, directory):
|
||||
base_path = prior / 'final/lisa.pt'
|
||||
if fingerprint(base_path) != ADAPTER_SHA:
|
||||
raise ValueError('Wrong starting LiSA model')
|
||||
base = torch.load(base_path, weights_only=True, map_location='cpu')
|
||||
spec = {'protocol_sha256': PROTOCOL_SHA, 'base_sha256': ADAPTER_SHA, 'fraction': 0.5,
|
||||
'parameters': sum(t.numel() for t in base.values()), 'endpoints': {}}
|
||||
for prefix, digest in TRAINED_SHA.items():
|
||||
endpoint = out / ('trajectory-' + prefix) / 'adapter.pt'
|
||||
if fingerprint(endpoint) != digest:
|
||||
raise ValueError(f'Wrong {prefix} distillation checkpoint')
|
||||
value = midpoint(base, torch.load(endpoint, weights_only=True, map_location='cpu'))
|
||||
path = directory / (prefix + '.pt')
|
||||
if path.exists():
|
||||
saved = torch.load(path, weights_only=True, map_location='cpu')
|
||||
if saved.keys() != value.keys() or any(not torch.equal(t, saved[k]) for k, t in value.items()):
|
||||
raise ValueError(f'Stored {prefix} midpoint differs from its endpoints')
|
||||
else:
|
||||
checkpoint(path, value)
|
||||
spec['endpoints'][prefix] = {'trained_sha256': digest, 'midpoint_sha256': fingerprint(path)}
|
||||
path = directory / 'spec.json'
|
||||
if path.exists() and read(path) != spec:
|
||||
raise ValueError('Midpoint experiment specification changed')
|
||||
write_json(path, spec)
|
||||
return spec
|
||||
|
||||
|
||||
def summarize(questions, answers, *, intervals):
|
||||
ids = [q['id'] for q in questions]
|
||||
flags = {name: np.array([a['correct'] for a in rows], dtype=int).reshape(-1, 2)
|
||||
for name, rows in answers.items()}
|
||||
draws = np.random.default_rng(72505).integers(0, len(ids)//2, (10000, len(ids)//2)) if intervals else None
|
||||
comparisons = {}
|
||||
for prefix in TRAINED_SHA:
|
||||
name = 'half-' + prefix
|
||||
controls = ['prior-lisa', 'trajectory-' + prefix]
|
||||
if prefix == 'student':
|
||||
controls.append('half-reference')
|
||||
for control in controls:
|
||||
delta = flags[name] - flags[control]
|
||||
comparison = {'delta': float(delta.mean()),
|
||||
'corrected': [q for q, d in zip(ids, delta.flat) if d > 0],
|
||||
'lost': [q for q, d in zip(ids, delta.flat) if d < 0]}
|
||||
if intervals:
|
||||
comparison['interval_95'] = np.quantile(delta.mean(1)[draws].mean(1), [.025, .975]).tolist()
|
||||
comparisons[name + '-vs-' + control] = comparison
|
||||
return {'questions': len(ids), 'correct': {k: int(v.sum()) for k, v in flags.items()},
|
||||
'pairs_both_correct': {k: int(v.all(1).sum()) for k, v in flags.items()}, 'comparisons': comparisons}
|
||||
|
||||
|
||||
def score_split(args, directory, questions, split, protocol, model, tok, spec):
|
||||
folder = directory / split
|
||||
folder.mkdir(exist_ok=True)
|
||||
answers = {}
|
||||
for name, digest in VALIDATION_SHA.items():
|
||||
prefix = name.removeprefix('trajectory-')
|
||||
if split == 'validation':
|
||||
path = (args.out/'validation-prior-lisa.json' if name == 'prior-lisa'
|
||||
else args.out/name/('validation-' + prefix + '.json'))
|
||||
if fingerprint(path) != digest:
|
||||
raise ValueError(f'Validation control changed for {name}')
|
||||
else:
|
||||
path = args.out/'holdout'/(name + '.json')
|
||||
expected = ADAPTER_SHA if name == 'prior-lisa' else TRAINED_SHA[prefix]
|
||||
if read(path.with_name(name + '-source.json')) != expected:
|
||||
raise ValueError(f'Holdout control source changed for {name}')
|
||||
rows = read(path)
|
||||
verify(tok, protocol, questions, rows, (path.stem,))
|
||||
answers[name] = [r['arms'][path.stem] for r in rows]
|
||||
for prefix in TRAINED_SHA:
|
||||
name = 'half-' + prefix
|
||||
path = directory / (prefix + '.pt')
|
||||
if fingerprint(path) != spec['endpoints'][prefix]['midpoint_sha256']:
|
||||
raise ValueError(f'Midpoint changed for {prefix}')
|
||||
adapters = make_adapters(model.config, dict.fromkeys(SITES, 40), True)
|
||||
torch.nn.ModuleDict({str(i): v for i, v in adapters.items()}).load_state_dict(
|
||||
torch.load(path, weights_only=True, map_location='cpu'))
|
||||
answer_path = folder / (name + '.json')
|
||||
validate_checkpoint(model, tok, adapters, questions, protocol, answer_path, split_name=split)
|
||||
rows = read(answer_path)
|
||||
verify(tok, protocol, questions, rows, (name,))
|
||||
answers[name] = [r['arms'][name] for r in rows]
|
||||
summary = summarize(questions, answers, intervals=split == 'test')
|
||||
write_json(folder/'summary.json', summary)
|
||||
return summary
|
||||
|
||||
|
||||
def run(args):
|
||||
if fingerprint(args.out/'protocol.json') != PROTOCOL_SHA:
|
||||
raise ValueError('Wrong comparison protocol')
|
||||
directory = args.out/'trajectory-midpoint'
|
||||
directory.mkdir(exist_ok=True)
|
||||
with (directory/'.lock').open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
spec = prepare(args.prior, args.out, directory)
|
||||
if args.prepare_only:
|
||||
return
|
||||
_, prior = load_locked(args.source, args.prior)
|
||||
model = StreamingLM(args.source/'weights', read(args.source/'model_config.json'), seconds=172800,
|
||||
process_swap_limit_kib=None)
|
||||
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
|
||||
splits = read(args.out/'protocol.json')['splits']
|
||||
val = score_split(args, directory, splits['validation'], 'validation', prior['protocol'], model, tok, spec)
|
||||
counts = val['correct']
|
||||
qualified = [p for p in TRAINED_SHA if counts['half-' + p] > counts['prior-lisa']]
|
||||
if qualified:
|
||||
score_split(args, directory, splits['test'], 'test', prior['protocol'], model, tok, spec)
|
||||
write_json(directory/'decision.json', {'qualified_validation_prefixes': qualified,
|
||||
'test_evaluated': bool(qualified)})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for key in ('source', 'prior', 'out'):
|
||||
parser.add_argument('--' + key, required=True, type=Path)
|
||||
parser.add_argument('--prepare-only', action='store_true')
|
||||
torch.set_num_threads(1)
|
||||
run(parser.parse_args())
|
||||
@@ -61,7 +61,7 @@ def replay_teacher_inputs(tail, path, ids, start, lengths):
|
||||
return target, residual, donor
|
||||
|
||||
|
||||
def validate_checkpoint(model, tokenizer, adapters, questions, decode_spec, path):
|
||||
def validate_checkpoint(model, tokenizer, adapters, questions, decode_spec, path, *, split_name='validation'):
|
||||
label = path.stem
|
||||
rows = json.loads(path.read_text()) if path.exists() else []
|
||||
if rows:
|
||||
@@ -73,7 +73,7 @@ def validate_checkpoint(model, tokenizer, adapters, questions, decode_spec, path
|
||||
rows.extend(outputs)
|
||||
write_json(path, rows)
|
||||
correct = sum(row['arms'][label]['correct'] for row in rows)
|
||||
print(label, 'validation correct', correct, '/', len(rows), flush=True)
|
||||
print(label, split_name, 'correct', correct, '/', len(rows), flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -44,3 +44,13 @@
|
||||
标准答案前缀组运行期间,逐字节读取远程底座权重,核对 4,548,221,488 字节权重分片的 SHA-256 与冻结清单及上游摘要相同,并复核分词器和配置。[底座文件核验](../results/lisa-combinations/native-files.json)
|
||||
|
||||
已记录远程部署的 13 个实现与测试文件摘要。部署目录中的 `crossqkv/lisa_full_answer.py` 来自提交 `c53d78b`。它与本轮主线版本的差异限于该模块自身的筛选命令行入口,本轮调用的 `evaluate`、`prompt`、`grade` 等函数一致。 [远程代码摘要](../results/lisa-combinations/execution.sha256)
|
||||
|
||||
## 蒸馏权重更新幅度的补充实验
|
||||
|
||||
两个蒸馏终点在验证集分别答对 2/16 和 3/16,低于起始 LiSA 的 5/16。在主实验留出集开始生成前,为这两个终点各固定一个权重中点。对每个适配器张量,取起点和终点的算术平均,以 float64 计算后还原原精度。两个条件共享原底座,推理参数量与原 LiSA 相同,不增加训练步数。这个处理缩短了已训练的总权重位移,其效果可能与从头减半学习率不同。
|
||||
|
||||
在原定十组评估结束后,用相同的 16 道验证题、解码设置和完整答案判分比较起点、两个原终点、两个中点。单一插值系数固定为 0.5。任一中点在完整答案正确数上严格超过起点时,再对两个中点评估同一批 32 对留出题,与已生成的起点、相应终点和另一种前缀中点作配对比较。两者均未超过起点时,这项补充实验止于验证集。公布每组正确数、交换前后均正确的题对数以及各对照的救回和丢失题号。留出集差值以题对为单位、用固定种子 72505 做 10,000 次重采样。该补充分析因观察到验证退步而提出,结果单独记入 `trajectory-midpoint` 目录。
|
||||
|
||||
`python -m crossqkv.lisa_trajectory_midpoint` 接受与主实验一致的 `--source`、`--prior`、`--out`。附加 `--prepare-only` 时仅校验三个端点、生成两个中点及其摘要。正常运行会复核模型、已有答卷和已生成的中点,从每组已验证的完整答卷后续跑。
|
||||
|
||||
已在实验服务器用两个真实训练终点生成中点,并用独立实现逐元素复算。每个中点的 12 个张量、2,476,032 个参数均与按原精度取整的算术中点完全一致。[端点摘要及权重核验](../results/lisa-combinations/trajectory-midpoint/preparation.json)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"spec": {
|
||||
"protocol_sha256": "6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef",
|
||||
"base_sha256": "c82db5af7fa42cf58a349f3e53961da2360b211a7ed606f53a728860c64f6f29",
|
||||
"fraction": 0.5,
|
||||
"parameters": 2476032,
|
||||
"endpoints": {
|
||||
"student": {
|
||||
"trained_sha256": "7faacdffbc81d0c786ef0c7a5acaf1724d82af155fed7b834dabc73dcf91f3a4",
|
||||
"midpoint_sha256": "d0cf6b4ad1b4791dcaa4ebf50eb623f16260249996fe810ee8f0905dedb8a335"
|
||||
},
|
||||
"reference": {
|
||||
"trained_sha256": "21ae007cb7343c1a0042655824bdc98ee2f03071d5f5dc43dbc8b441a262d84f",
|
||||
"midpoint_sha256": "e0e2c61fcaecb591631a66889c838d351c1bf5a608638c05622a20487d8de324"
|
||||
}
|
||||
}
|
||||
},
|
||||
"independent_checks": {
|
||||
"student": {
|
||||
"tensors_checked": 12,
|
||||
"parameters_checked": 2476032,
|
||||
"update_l2_ratio": 0.49999999981533333
|
||||
},
|
||||
"reference": {
|
||||
"tensors_checked": 12,
|
||||
"parameters_checked": 2476032,
|
||||
"update_l2_ratio": 0.5000000004162759
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,37 @@ import torch
|
||||
from crossqkv.lisa_combination_eval import changed_answers, score_differences
|
||||
from crossqkv.lisa_combination_screen import SITES, paired_questions
|
||||
from crossqkv.lisa_rank_compare import assignments, make_adapters, score_gold_answers
|
||||
from crossqkv.lisa_trajectory_midpoint import midpoint, summarize
|
||||
from crossqkv.lisa_trajectory_train import replay_teacher_inputs, reverse_kl
|
||||
|
||||
|
||||
class CombinationTests(unittest.TestCase):
|
||||
def test_checkpoint_midpoint_preserves_shape_dtype_and_endpoints(self):
|
||||
base = {'a': torch.tensor([2., -4.]), 'b': torch.tensor([1.], dtype=torch.bfloat16)}
|
||||
trained = {'a': torch.tensor([0., 6.]), 'b': torch.tensor([3.], dtype=torch.bfloat16)}
|
||||
middle = midpoint(base, trained)
|
||||
torch.testing.assert_close(middle['a'], torch.tensor([1., 1.]))
|
||||
torch.testing.assert_close(middle['b'], torch.tensor([2.], dtype=torch.bfloat16))
|
||||
self.assertEqual(base['a'].tolist(), [2., -4.])
|
||||
self.assertEqual(trained['a'].tolist(), [0., 6.])
|
||||
with self.assertRaises(ValueError):
|
||||
midpoint(base, {'a': torch.ones(1), 'b': trained['b']})
|
||||
|
||||
def test_midpoint_comparisons_keep_gains_losses_and_pairs(self):
|
||||
qs = [{'id': f'q{i}'} for i in range(4)]
|
||||
flags = {'prior-lisa': [1, 0, 1, 0], 'trajectory-student': [0, 0, 1, 0],
|
||||
'trajectory-reference': [1, 0, 0, 0], 'half-reference': [1, 0, 0, 0],
|
||||
'half-student': [1, 1, 0, 1]}
|
||||
answers = {k: [{'correct': bool(x)} for x in v] for k, v in flags.items()}
|
||||
val = summarize(qs, answers, intervals=False)
|
||||
self.assertEqual(val['correct']['half-student'], 3)
|
||||
self.assertEqual(val['pairs_both_correct']['half-student'], 1)
|
||||
result = val['comparisons']['half-student-vs-prior-lisa']
|
||||
self.assertEqual(result, {'delta': .25, 'corrected': ['q1', 'q3'], 'lost': ['q2']})
|
||||
test = summarize(qs, answers, intervals=True)
|
||||
self.assertEqual(test['comparisons']['half-student-vs-prior-lisa']['interval_95'], [0., .5])
|
||||
self.assertEqual(test['comparisons']['half-student-vs-half-reference']['corrected'], ['q1', 'q3'])
|
||||
|
||||
def test_reference_replay_uses_native_tail_only_on_matching_gold_tokens(self):
|
||||
ids = torch.tensor([[13, 4, 7, 9]])
|
||||
lengths = torch.tensor([4])
|
||||
|
||||
Reference in New Issue
Block a user