Replay verified frozen prefix inputs for reference trajectory distillation
This commit is contained in:
@@ -44,6 +44,22 @@ def load_locked(source, screen):
|
||||
return chosen, manifest
|
||||
|
||||
|
||||
def verified_fit_captures(source, fit):
|
||||
"""Verify the frozen fit inputs and return their archives by question ID."""
|
||||
captures = source/'fit-capture'
|
||||
receipt = source/'verified-fit-capture.json'
|
||||
if fingerprint(receipt) != '682bc035a5bed9f9245f589cacf3e9616300e8bf5e85d3743b1264a56360fa55':
|
||||
raise ValueError('Capture receipt mismatch')
|
||||
records = json.loads(receipt.read_text())['records']
|
||||
if ([r['id'] for r in records] != [r['id'] for r in fit] or
|
||||
sorted(x.name for x in captures.glob('*.npz')) != [r['file'] for r in records]):
|
||||
raise ValueError('Unexpected capture set')
|
||||
for row in records:
|
||||
if fingerprint(captures/row['file']) != row['sha256']:
|
||||
raise ValueError('Fit capture mismatch')
|
||||
return {r['id']: captures/r['file'] for r in records}
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def capture(model, tokenizer, fit_examples, directory):
|
||||
directory.mkdir(exist_ok=True)
|
||||
|
||||
@@ -9,7 +9,7 @@ from tokenizers import Tokenizer
|
||||
from crossqkv.lisa_combination_screen import ADAPTER_SHA, SITES
|
||||
from crossqkv.lisa_effect_answer_audit import vocabulary_scores
|
||||
from crossqkv.lisa_full_answer import STOP_TEXT, fingerprint, prompt
|
||||
from crossqkv.lisa_full_answer_train import FitCapture, load_locked, train
|
||||
from crossqkv.lisa_full_answer_train import FitCapture, load_locked, train, verified_fit_captures
|
||||
from crossqkv.lisa_tail import TorchTail
|
||||
from crossqkv.lisa_train import LearnableSharingAttention
|
||||
from functional.model import PREFIX, StreamingLM
|
||||
@@ -119,17 +119,8 @@ def main():
|
||||
_, prior = load_locked(args.source,args.prior)
|
||||
source = args.prior/'final'
|
||||
captures = source/'fit-capture'
|
||||
receipt = source/'verified-fit-capture.json'
|
||||
if fingerprint(receipt) != '682bc035a5bed9f9245f589cacf3e9616300e8bf5e85d3743b1264a56360fa55':
|
||||
raise ValueError('Capture receipt mismatch')
|
||||
records = json.loads(receipt.read_text())['records']
|
||||
fit = [r for r in prior['problems']['fit'] if r['task']=='lookup']
|
||||
if ([r['id'] for r in records] != [r['id'] for r in fit] or
|
||||
sorted(x.name for x in captures.glob('*.npz')) != [r['file'] for r in records]):
|
||||
raise ValueError('Unexpected capture set')
|
||||
for row in records:
|
||||
if fingerprint(captures/row['file']) != row['sha256']:
|
||||
raise ValueError('Fit capture mismatch')
|
||||
verified_fit_captures(source, fit)
|
||||
config = json.loads((args.source/'model_config.json').read_text())
|
||||
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
|
||||
diagnostic_model = StreamingLM(args.source/'weights', config, seconds=172800, process_swap_limit_kib=None)
|
||||
|
||||
@@ -3,12 +3,13 @@ import argparse
|
||||
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 STOP_TEXT, evaluate, fingerprint, prompt
|
||||
from crossqkv.lisa_full_answer_train import FitCapture, checkpoint, load_locked
|
||||
from crossqkv.lisa_full_answer_train import FitCapture, checkpoint, load_locked, verified_fit_captures
|
||||
from crossqkv.lisa_full_answer_verify import verify
|
||||
from crossqkv.lisa_tail import TorchTail, weight_chunks
|
||||
from crossqkv.lisa_train import LearnableSharingAttention
|
||||
@@ -42,6 +43,24 @@ def reverse_kl(student, teacher, chunks):
|
||||
return kl.mean() + ((student - student.detach()) * grad).sum()
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def full_teacher_inputs(model, teacher, ids, lengths):
|
||||
hidden = torch.from_numpy(model.embedding(ids.numpy()))
|
||||
target, maps = teacher(hidden, None, lengths, 'native', ())
|
||||
return target, teacher.residual, maps[SITES[0]-4][0]
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def replay_teacher_inputs(tail, path, ids, start, lengths):
|
||||
with np.load(path, allow_pickle=False) as saved:
|
||||
if int(saved['start'].item()) != start or not np.array_equal(saved['ids'], ids.numpy()):
|
||||
raise ValueError('Cached sequence does not match this gold answer and prompt')
|
||||
residual = torch.from_numpy(saved['residual'])
|
||||
donor = torch.from_numpy(saved['donor'])
|
||||
target, _ = tail(residual, donor, lengths, 'native', ())
|
||||
return target, residual, donor
|
||||
|
||||
|
||||
def validate_checkpoint(model, tokenizer, adapters, questions, decode_spec, path):
|
||||
label = path.stem
|
||||
rows = json.loads(path.read_text()) if path.exists() else []
|
||||
@@ -106,7 +125,15 @@ def main():
|
||||
def chunks():
|
||||
yield from weight_chunks(embedding, 0, embedding.shape[0], rows=1024)
|
||||
|
||||
for item in tasks[len(rows):]:
|
||||
captures = {}
|
||||
final = args.prior/'final'
|
||||
if args.prefix == 'reference' and (final/'verified-fit-capture.json').is_file():
|
||||
try:
|
||||
captures = verified_fit_captures(final, tasks)
|
||||
except (OSError, ValueError, KeyError) as exc:
|
||||
print('Using full native forward for reference prefixes:', exc, flush=True)
|
||||
|
||||
for offset, item in enumerate(tasks[len(rows):]):
|
||||
text = prompt(item['question'])
|
||||
base = tok.encode(text, add_special_tokens=False).ids
|
||||
if args.prefix == 'student':
|
||||
@@ -118,12 +145,25 @@ def main():
|
||||
sampled = complete[len(base):]
|
||||
ids = torch.tensor([base+sampled])
|
||||
lengths = torch.tensor([ids.shape[1]])
|
||||
with torch.no_grad():
|
||||
h = torch.from_numpy(model.embedding(ids.numpy()))
|
||||
target, maps = teacher(h, None, lengths, 'native', ())
|
||||
donor = maps[SITES[0]-4][0]
|
||||
if captures:
|
||||
try:
|
||||
cached = replay_teacher_inputs(tail, captures[item['id']], ids, len(base), lengths)
|
||||
except (OSError, ValueError, KeyError) as exc:
|
||||
print('Using full native forward for reference prefixes:', exc, flush=True)
|
||||
captures = {}
|
||||
if not captures or offset == 0:
|
||||
inputs = full_teacher_inputs(model, teacher, ids, lengths)
|
||||
if captures:
|
||||
if all(torch.equal(a, b) for a, b in zip(inputs, cached)):
|
||||
print('Reference cache matches full native target, residual and donor', flush=True)
|
||||
else:
|
||||
print('Reference cache differs. Using full native forward', flush=True)
|
||||
captures = {}
|
||||
else:
|
||||
inputs = cached
|
||||
target, residual, donor = inputs
|
||||
opt.zero_grad(set_to_none=True)
|
||||
student, _ = tail(teacher.residual, donor, lengths, 'lisa', SITES)
|
||||
student, _ = tail(residual, donor, lengths, 'lisa', SITES)
|
||||
span = slice(len(base)-1, -1)
|
||||
loss = reverse_kl(student[0, span], target[0, span], chunks)
|
||||
loss.backward()
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
|
||||
两组均从上一轮 LiSA 权重开始,依次在相同 24 道训练题上各更新一次。学生轨迹组每步先用更新前的学生生成完整的贪心回答,在这些前缀上最小化学生对原模型的全词表逆 KL。参考轨迹组使用标准答案前缀,学习率、优化器和题序相同。两组均使用最后一步权重。生成路径固定时反向传播下一 token 分布的梯度。这是借鉴 MiniLLM 的简化方法。两组的训练步数相等,生成与训练 token 数和实际训练开销可不同。
|
||||
|
||||
学生前缀随更新变化,当前学生组以提交 `2338679` 的蒸馏代码逐题运行原生教师。标准答案前缀固定,参考组可以复用上一轮保存的第 15 层输入及第 11 层供给分数。先核验缓存回执、24 个文件的摘要、题序,再逐题核对完整 token 序列与答案起点。每次启动或续跑时,首道待训题同时走完整前向和缓存路径,逐元素核对教师最终隐状态、接收层输入和供给分数。三者完全相等后,后续题才使用缓存。缓存缺失或核对不符时,以完整教师前向继续。分秩组使用同一份缓存回执。参考组实际采用的路径由训练日志记录,解释训练耗时需考虑这项缓存复用。
|
||||
|
||||
## 复跑顺序
|
||||
|
||||
使用上一轮远程 CPU Python 环境和完整仓库依赖。所有命令共用 `--source`(冻结模型目录)、`--prior`(上一轮包含 frozen.json 和 final 子目录的作业目录)、`--out`(本轮独立目录)。按顺序运行以下 Python 模块。
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
024720e9eae7556e4d5ca2ca1d71dd544815c79ed2c51b113564d5a6fb4ad004 crossqkv/lisa_combination_screen.py
|
||||
7c2156139d3447a9e69e903bc80821ea55b4e01df63a1b6137e4de589748efba crossqkv/lisa_rank_compare.py
|
||||
1aab837faee43bbdf1b4fe8f92ce28647a4f1377d962d538a57d32ab65215678 crossqkv/lisa_trajectory_train.py
|
||||
663d4dad556f08b69521543e73d67362d46dc694c747e72b6cb786da7484e090 crossqkv/lisa_rank_compare.py
|
||||
f212bd1b17b38d995060fc04b20a77b4e572cffc9b3776dc16ef7cf012ee89a3 crossqkv/lisa_trajectory_train.py
|
||||
0a91cc8b446165dfd33cd3e30e9fdeb5082202c4183eba9918404e01e30cb4b7 crossqkv/lisa_combination_eval.py
|
||||
519e0a031efcfb69c9b86fca1cb649fe8bb93d799401c8023ff7b6549cded448 crossqkv/lisa_full_answer.py
|
||||
6369a674600812d06fc6d667e4a67ae97b63b4be3ba02ad28520eb9a748d272b crossqkv/lisa_full_answer_train.py
|
||||
1a1a4cbc8e3c5b97accfe2d0ba18a21c9e2ebfa25d66561d7ef9c59668049efa crossqkv/lisa_full_answer_train.py
|
||||
57e73f1e30c8db8daec7b13d6455af2822b2db3e600531f8a60e2381d093ad91 crossqkv/lisa_full_answer_verify.py
|
||||
98927a1ccd935b2f7a438bad31bbd973e210a54deceac911c61551092e52c96c crossqkv/lisa_generate.py
|
||||
d47b4c9cc34082e9b356e745821298a43981e4cd18ed55a3f59b4b6fe7cc46e3 crossqkv/lisa_tail.py
|
||||
9f0b6a53f107950661e91c16f03b49440708b3936120e2f84ef1d66f185257b6 crossqkv/lisa_train.py
|
||||
94437e0138c54ec34b1beaaa0e08a334ce0822f60af598a5a896459b778a3a1c functional/model.py
|
||||
8df6854024042d5cc7962b3b0c9f0591cedb364787fcae27d58ecc2cd3ba0c61 tests/test_lisa_combinations.py
|
||||
a2585456d6e6093c8af7976ac26c37033d7352c4753991218ad64305827a7c23 tests/test_lisa_combinations.py
|
||||
e1d70b10863dab1e13dfa9573c0d87fc6ca017039c3cf9b90f7628f3e7fe5664 crossqkv/lisa_effect_answer_audit.py
|
||||
|
||||
@@ -10,10 +10,32 @@ import torch
|
||||
from crossqkv.lisa_combination_eval import changed_answers
|
||||
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_train import reverse_kl
|
||||
from crossqkv.lisa_trajectory_train import replay_teacher_inputs, reverse_kl
|
||||
|
||||
|
||||
class CombinationTests(unittest.TestCase):
|
||||
def test_reference_replay_uses_native_tail_only_on_matching_gold_tokens(self):
|
||||
ids = torch.tensor([[13, 4, 7, 9]])
|
||||
lengths = torch.tensor([4])
|
||||
residual = torch.arange(12).reshape(1, 4, 3).float()
|
||||
donor = torch.arange(16).reshape(1, 1, 4, 4).float()
|
||||
|
||||
def native_tail(h, scores, sizes, mode, recipients):
|
||||
self.assertTrue(torch.equal(sizes, lengths))
|
||||
self.assertEqual((mode, recipients), ('native', ()))
|
||||
return h * 2, {}
|
||||
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder)/'capture.npz'
|
||||
np.savez(path, ids=ids.numpy(), start=[2], residual=residual.numpy(), donor=donor.numpy())
|
||||
target, h, scores = replay_teacher_inputs(native_tail, path, ids, 2, lengths)
|
||||
self.assertTrue(torch.equal(target, 2 * residual))
|
||||
self.assertTrue(torch.equal(h, residual))
|
||||
self.assertTrue(torch.equal(scores, donor))
|
||||
for wrong_ids, start in [(ids + 1, 2), (ids, 1)]:
|
||||
with self.assertRaises(ValueError):
|
||||
replay_teacher_inputs(native_tail, path, wrong_ids, start, lengths)
|
||||
|
||||
def test_joint_recoveries_require_beating_both_single_methods_on_one_item(self):
|
||||
items = [{'id': name} for name in ['a', 'b', 'c', 'd']]
|
||||
diffs = {'rank-vs-uniform': np.array([[1, -1], [1, 0]]),
|
||||
|
||||
Reference in New Issue
Block a user