Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 04a58682de | |||
| 80f79f7d15 | |||
| 41895ae357 |
@@ -56,9 +56,13 @@ class GenerationDecoder(TorchTail):
|
||||
scores = adapter.fuse(both).permute(0, 3, 1, 2)
|
||||
elif layer in self.share:
|
||||
scores = torch.where(self.share[layer], donor, scores)
|
||||
scores, outgoing = self.score_paths(h, layer, positions, scores)
|
||||
weights = scores.masked_fill(~allowed, -torch.inf).softmax(dim=-1)
|
||||
context = torch.einsum('bhts,bshd->bthd', weights, v.repeat_interleave(repeats, 2))
|
||||
return self.linear((context * gate.sigmoid()).flatten(-2), p+'o_proj'), scores
|
||||
return self.linear((context * gate.sigmoid()).flatten(-2), p+'o_proj'), outgoing
|
||||
|
||||
def score_paths(self, h, layer, positions, scores):
|
||||
return scores, scores
|
||||
|
||||
@torch.no_grad()
|
||||
def advance(self, ids):
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Replay and separate the local and outgoing attention scores at one LiSA site."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from tokenizers import Tokenizer
|
||||
|
||||
from crossqkv.lisa_combination_screen import ADAPTER_SHA, SITES, paired_questions
|
||||
from crossqkv.lisa_effect_answer_audit import vocabulary_scores
|
||||
from crossqkv.lisa_full_answer import MAX_NEW_TOKENS, STOP_TEXT, fingerprint, grade, prompt
|
||||
from crossqkv.lisa_full_answer_train import load_locked
|
||||
from crossqkv.lisa_full_answer_verify import verify
|
||||
from crossqkv.lisa_generate import GenerationDecoder, greedy_tokens
|
||||
from crossqkv.lisa_rank_compare import make_adapters
|
||||
from crossqkv.lisa_tail import rotate
|
||||
from functional.model import PREFIX, StreamingLM
|
||||
from functional.run import write_json
|
||||
|
||||
|
||||
# Vary only layers 15 and 19 with native attention at layer 23 in all four arms.
|
||||
ISOLATION_SCHEDULES = {
|
||||
'native': (), 'only-15': (15,), 'only-19': (19,), 'both-15-19': (15, 19)
|
||||
}
|
||||
|
||||
|
||||
class PathDecoder(GenerationDecoder):
|
||||
def score_paths(self, h, layer, positions, scores):
|
||||
if layer != self.site or self.mode == 'baseline':
|
||||
return scores, scores
|
||||
c = self.c
|
||||
heads, kv, dim = (c[k] for k in ('num_attention_heads', 'num_key_value_heads', 'head_dim'))
|
||||
p = f'layers.{layer}.self_attn.'
|
||||
q = self.linear(h, p+'q_proj').unflatten(-1, (heads, 2*dim)).chunk(2, -1)[0]
|
||||
k = self.linear(h, p+'k_proj').unflatten(-1, (kv, dim))
|
||||
rope = c['rope_parameters']
|
||||
def rotated(x, name):
|
||||
return rotate(self.norm(x, p+name), rope['rope_theta'], rope['partial_rotary_factor'], positions)
|
||||
q = rotated(q, 'q_norm')
|
||||
k = rotated(k, 'k_norm')
|
||||
if self.position:
|
||||
k = torch.cat((self.native_keys, k), dim=1)
|
||||
self.native_keys = k
|
||||
native = torch.einsum('bthd,bshd->bhts', q, k.repeat_interleave(heads//kv, 2)) / math.sqrt(dim)
|
||||
if self.mode.startswith('read-group-'):
|
||||
group = int(self.mode.rsplit('-', 1)[1])
|
||||
chosen = torch.arange(heads) // (heads // kv) == group
|
||||
return torch.where(chosen[None, :, None, None], native, scores), scores
|
||||
if self.mode == 'send-permuted':
|
||||
# Exchange the two GQA groups while retaining the same score entries.
|
||||
return scores, native.roll(heads // kv, dims=1)
|
||||
return (native if self.mode in ('read','both') else scores,
|
||||
native if self.mode in ('send','both') else scores)
|
||||
|
||||
|
||||
def questions(name, count, seed):
|
||||
swap = paired_questions(name, count, seed)
|
||||
query = []
|
||||
for first, second in zip(swap[::2], swap[1::2]):
|
||||
records, ask = first['question'].split('.\n')
|
||||
table = dict(x.split('=') for x in records.removeprefix('Records in time order: ').split(', '))
|
||||
key = next(k for k,v in table.items() if int(v)==second['answer'])
|
||||
query.extend([dict(first,id=first['id']+'-query'),
|
||||
dict(second,id=second['id']+'-query',question=records+'.\n'+ask.rsplit(' ',1)[0]+' '+key+'?')])
|
||||
return {'swap':swap, 'query':query}
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def batch(model, tok, adapters, qs, site, mode):
|
||||
ids = [tok.encode(prompt(q['question']),add_special_tokens=False).ids for q in qs]
|
||||
width = max(map(len,ids))
|
||||
padding = [width-len(x) for x in ids]
|
||||
if mode in ISOLATION_SCHEDULES:
|
||||
schedule = ISOLATION_SCHEDULES[mode]
|
||||
dec = GenerationDecoder(model, [schedule]*len(qs), padding,
|
||||
{layer: adapters[layer] for layer in schedule})
|
||||
else:
|
||||
dec = PathDecoder(model,[SITES]*len(qs),padding,adapters)
|
||||
dec.site, dec.mode = site, mode
|
||||
h = dec.advance(torch.tensor([[0]*p+x for p,x in zip(padding,ids)]))[:,-1]
|
||||
head = model.tensors[PREFIX+'embed_tokens.weight']
|
||||
gold = torch.tensor([tok.encode(str(q['answer']),add_special_tokens=False).ids[0] for q in qs])
|
||||
nxt,nll = vocabulary_scores(h,gold,head)
|
||||
stops = {tok.token_to_id(t) for t in STOP_TEXT}
|
||||
seq = [[] for _ in qs]
|
||||
for step in range(MAX_NEW_TOKENS):
|
||||
for s,t in zip(seq,nxt.tolist()):
|
||||
if not s or s[-1] not in stops:
|
||||
s.append(t)
|
||||
if all(s[-1] in stops for s in seq) or step+1==MAX_NEW_TOKENS:
|
||||
break
|
||||
nxt = greedy_tokens(dec.advance(nxt[:,None])[:,-1],head)
|
||||
return [dict(id=q['id'],task=q['task'],gold=q['answer'],first_digit_probability=float((-v).exp()),
|
||||
arms={mode:grade(tok,s,'eos' if s[-1] in stops else 'max_new_tokens',q['answer'])})
|
||||
for q,s,v in zip(qs,seq,nll)]
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
for k in ('source','prior','previous','out'):
|
||||
p.add_argument('--'+k,type=Path,required=True)
|
||||
p.add_argument('--follow-through', action='store_true')
|
||||
a=p.parse_args()
|
||||
torch.set_num_threads(1)
|
||||
_,old=load_locked(a.source,a.prior)
|
||||
assert fingerprint(a.previous/'protocol.json')=='6858dbc64db0b989e8112e9dbea70662a2a05f66f11b180e8f2c668c74c43aef'
|
||||
prev=json.loads((a.previous/'protocol.json').read_text())['splits']
|
||||
plan={'replay':prev['diagnostic'],'diagnostic':questions('paths-dev',8,120201),
|
||||
'holdout':questions('paths-test',32,120202)}
|
||||
used={q['question'] for split in old['problems'].values() for q in split}
|
||||
used.update(q['question'] for split in prev.values() for q in split)
|
||||
for key in ('diagnostic','holdout'):
|
||||
fresh={q['question'] for group in plan[key].values() for q in group}
|
||||
assert not fresh & used
|
||||
used.update(fresh)
|
||||
a.out.mkdir(exist_ok=True,parents=True)
|
||||
path=a.out/'protocol.json'
|
||||
assert not path.exists() or json.loads(path.read_text())==plan
|
||||
write_json(path,plan)
|
||||
model=StreamingLM(a.source/'weights',json.loads((a.source/'model_config.json').read_text()),seconds=172800,process_swap_limit_kib=None)
|
||||
tok=Tokenizer.from_file(str(a.source/'tokenizer.json'))
|
||||
weights=a.prior/'final/lisa.pt'
|
||||
assert fingerprint(weights)==ADAPTER_SHA
|
||||
adapters=make_adapters(model.config,dict.fromkeys(SITES,40),True)
|
||||
torch.nn.ModuleDict({str(k):v for k,v in adapters.items()}).load_state_dict(torch.load(weights,weights_only=True))
|
||||
def evaluate(split, site, modes):
|
||||
for mode in modes:
|
||||
groups={'old':plan['replay']} if split=='replay' else plan[split]
|
||||
for kind,qs in groups.items():
|
||||
path=a.out/f'{split}-{site}-{mode}-{kind}.json'
|
||||
rows=json.loads(path.read_text()) if path.exists() else []
|
||||
expected=None
|
||||
if split=='replay':
|
||||
label='baseline' if mode=='baseline' else 'restore-19'
|
||||
expected=json.loads((a.previous/(label+'.json')).read_text())
|
||||
def check(items, saved):
|
||||
verify(tok,old['protocol'],items,saved,(mode,))
|
||||
if expected is not None:
|
||||
oracle={r['id']:r['arms'][label] for r in expected}
|
||||
assert all(r['arms'][mode]==oracle[r['id']] for r in saved)
|
||||
if rows:
|
||||
check(qs[:len(rows)],rows)
|
||||
for start in range(len(rows),len(qs),2):
|
||||
items=qs[start:start+2]
|
||||
generated=batch(model,tok,adapters,items,site,mode)
|
||||
check(items,generated)
|
||||
rows.extend(generated)
|
||||
write_json(path,rows)
|
||||
print(path.name,len(rows),flush=True)
|
||||
|
||||
for split, site, modes in [
|
||||
('replay', 19, ('baseline', 'both')),
|
||||
('diagnostic', 19, ('baseline', 'both', 'read', 'send')),
|
||||
('diagnostic', 15, ('both', 'read', 'send'))]:
|
||||
evaluate(split, site, modes)
|
||||
if not a.follow_through:
|
||||
return
|
||||
|
||||
evaluate('diagnostic', 'isolation', ISOLATION_SCHEDULES)
|
||||
|
||||
def diagnostic_score(mode):
|
||||
joint = total = 0
|
||||
for kind, items in plan['diagnostic'].items():
|
||||
rows = json.loads((a.out/f'diagnostic-19-{mode}-{kind}.json').read_text())
|
||||
verify(tok, old['protocol'], items, rows, (mode,))
|
||||
correct = [row['arms'][mode]['correct'] for row in rows]
|
||||
joint += sum(x and y for x, y in zip(correct[::2], correct[1::2]))
|
||||
total += sum(correct)
|
||||
return joint, total
|
||||
|
||||
ranking = {mode: diagnostic_score(mode) for mode in ('baseline', 'read', 'send', 'both')}
|
||||
single = max(('read', 'send'), key=ranking.get)
|
||||
modes = ['baseline', 'read', 'send', 'both']
|
||||
decision = {'ranking': ranking, 'site': 19}
|
||||
if ranking[single] > ranking['baseline']:
|
||||
if single == 'read':
|
||||
groups = ['read-group-0', 'read-group-1']
|
||||
evaluate('diagnostic', 19, groups)
|
||||
scores = {group: diagnostic_score(group) for group in groups}
|
||||
decision.update(group_scores=scores, selected=max(groups, key=scores.get),
|
||||
random_group=random.Random(120203).choice(groups))
|
||||
modes.extend(groups)
|
||||
else:
|
||||
modes.append('send-permuted')
|
||||
decision['holdout_modes'] = modes
|
||||
selection = a.out/'selection.json'
|
||||
if selection.exists():
|
||||
assert json.loads(selection.read_text()) == json.loads(json.dumps(decision))
|
||||
else:
|
||||
write_json(selection, decision)
|
||||
evaluate('holdout', 19, modes)
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Summarize paired score interventions, resampling entire tables."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
from pathlib import Path
|
||||
from statistics import mean
|
||||
|
||||
|
||||
def classify(question, row, mode):
|
||||
records, query = question['question'].split('.\n')
|
||||
table = dict(field.split('=') for field in records.removeprefix(
|
||||
'Records in time order: ').split(', '))
|
||||
target = query.removesuffix('?').split()[-1]
|
||||
assert len(table) == len(set(table.values())) == 12
|
||||
assert int(table[target]) == question['answer'] == row['gold']
|
||||
assert question['id'] == row['id']
|
||||
answer = row['arms'][mode]['answer']
|
||||
correct = answer == row['gold']
|
||||
assert correct == row['arms'][mode]['correct']
|
||||
other_key = next((k for k, v in table.items() if int(v) == answer and k != target), None)
|
||||
return dict(id=row['id'], answer=answer, correct=correct, target=target,
|
||||
wrong_key=other_key, outside_table=answer is not None and not correct and other_key is None,
|
||||
unparsable=answer is None)
|
||||
|
||||
|
||||
def table_metrics(items, rows, mode):
|
||||
assert len(items) == len(rows) and len(items) % 2 == 0
|
||||
classified = [classify(item, row, mode) for item, row in zip(items, rows)]
|
||||
metrics = []
|
||||
for i in range(0, len(rows), 2):
|
||||
pair = classified[i:i+2]
|
||||
probabilities = [row['first_digit_probability'] for row in rows[i:i+2]]
|
||||
assert all(math.isfinite(p) and 0 <= p <= 1 for p in probabilities)
|
||||
metrics.append(dict(correct=mean(r['correct'] for r in pair),
|
||||
both_correct=int(all(r['correct'] for r in pair)),
|
||||
wrong_key=mean(r['wrong_key'] is not None for r in pair),
|
||||
first_digit_probability=mean(probabilities)))
|
||||
return metrics, classified
|
||||
|
||||
|
||||
def interval(values, resamples):
|
||||
estimates = sorted(sum(values[i] for i in indices)/len(values) for indices in resamples)
|
||||
return dict(delta=mean(values), lower95=estimates[int(len(estimates)*.025)],
|
||||
upper95=estimates[math.ceil(len(estimates)*.975)-1])
|
||||
|
||||
|
||||
def summarize_arms(arms, contrasts, samples):
|
||||
first = next(iter(arms.values()))
|
||||
fields = first[0].keys()
|
||||
count = len(first)
|
||||
assert all(len(arm) == count for arm in arms.values())
|
||||
means = {m: {k: mean(row[k] for row in arm) for k in fields}
|
||||
for m, arm in arms.items()}
|
||||
comparisons = {}
|
||||
for name, coefficients in contrasts.items():
|
||||
comparisons[name] = {}
|
||||
for field in fields:
|
||||
differences = [sum(c * arms[m][i][field] for m, c in coefficients.items())
|
||||
for i in range(count)]
|
||||
comparisons[name][field] = interval(differences, samples)
|
||||
return dict(means=means, paired_contrasts=comparisons)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('directory', type=Path)
|
||||
parser.add_argument('--tokenizer', required=True, type=Path)
|
||||
parser.add_argument('--frozen', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
from tokenizers import Tokenizer
|
||||
from crossqkv.lisa_full_answer import fingerprint, prompt
|
||||
from crossqkv.lisa_full_answer_verify import verify
|
||||
from functional.run import write_json
|
||||
protocol = json.loads(args.frozen.read_text())['protocol']
|
||||
assert fingerprint(args.tokenizer) == protocol['weights']['tokenizer.json']
|
||||
tokenizer = Tokenizer.from_file(str(args.tokenizer))
|
||||
assert fingerprint(args.directory/'protocol.json') == 'c309f8721534b1f229a00ff556b48495c4e074be45c1905389aa57e9e3ddb048'
|
||||
def read(name):
|
||||
return json.loads((args.directory/name).read_text())
|
||||
plan = read('protocol.json')
|
||||
questions = plan['holdout']
|
||||
modes = read('selection.json')['holdout_modes']
|
||||
n = len(questions['swap']) // 2
|
||||
assert n >= 32 and len(questions['query']) == 2*n
|
||||
rng = random.Random(120204)
|
||||
resamples = [rng.choices(range(n), k=n) for _ in range(10000)]
|
||||
tables, detail, summary = {}, {}, {}
|
||||
costs = {}
|
||||
for kind, prompts in questions.items():
|
||||
lengths = [len(tokenizer.encode(prompt(item['question']), add_special_tokens=False).ids)
|
||||
for item in prompts]
|
||||
costs[kind] = {}
|
||||
tables[kind], detail[kind] = {}, {}
|
||||
for mode in modes:
|
||||
rows = read(f'holdout-19-{mode}-{kind}.json')
|
||||
verify(tokenizer, protocol, prompts, rows, (mode,))
|
||||
positions = edges = 0
|
||||
for i in range(0, len(rows), 2):
|
||||
width = max(lengths[i:i+2])
|
||||
steps = max(len(r['arms'][mode]['tokens']) for r in rows[i:i+2]) - 1
|
||||
positions += 2 * (width + steps)
|
||||
edges += 2 * (width**2 + steps*width + steps*(steps+1)//2)
|
||||
costs[kind][mode] = dict(processed_positions=positions, computed_score_positions=edges,
|
||||
extra_native_projection_macs=0 if mode == 'baseline' else 9437184*positions,
|
||||
extra_native_score_macs=0 if mode == 'baseline' else 2048*edges)
|
||||
tables[kind][mode], detail[kind][mode] = table_metrics(prompts, rows, mode)
|
||||
fields = tables['swap']['baseline'][0].keys()
|
||||
tables['both_kinds'] = {
|
||||
mode: [{k: (s[k]+q[k])/2 for k in fields}
|
||||
for s, q in zip(tables['swap'][mode], tables['query'][mode])] for mode in modes}
|
||||
for kind, arms in tables.items():
|
||||
contrasts = {mode+'-baseline': {mode: 1, 'baseline': -1} for mode in modes if mode != 'baseline'}
|
||||
contrasts['interaction'] = {'both': 1, 'baseline': 1, 'read': -1, 'send': -1}
|
||||
if 'send-permuted' in modes:
|
||||
contrasts['send-permuted-control'] = {'send': 1, 'send-permuted': -1}
|
||||
if 'read-group-0' in modes:
|
||||
selected = read('selection.json')['selected']
|
||||
other = next(m for m in modes if m.startswith('read-group-') and m != selected)
|
||||
contrasts['selected-other'] = {selected: 1, other: -1}
|
||||
contrasts['selected-full-read'] = {selected: 1, 'read': -1}
|
||||
summary[kind] = summarize_arms(arms, contrasts, resamples)
|
||||
isolation = {}
|
||||
layer_comparison = {}
|
||||
for kind, prompts in plan['diagnostic'].items():
|
||||
arms = {}
|
||||
for mode in ('native', 'only-15', 'only-19', 'both-15-19'):
|
||||
rows = read(f'diagnostic-isolation-{mode}-{kind}.json')
|
||||
verify(tokenizer, protocol, prompts, rows, (mode,))
|
||||
arms[mode], _ = table_metrics(prompts, rows, mode)
|
||||
count = len(prompts)//2
|
||||
diagnostic_rng = random.Random(120205)
|
||||
samples = [diagnostic_rng.choices(range(count), k=count) for _ in range(10000)]
|
||||
combinations = {
|
||||
'only-15-minus-native': {'only-15': 1, 'native': -1},
|
||||
'only-19-minus-native': {'only-19': 1, 'native': -1},
|
||||
'joint-interaction': {'both-15-19': 1, 'only-19': -1, 'only-15': -1, 'native': 1}}
|
||||
isolation[kind] = summarize_arms(arms, combinations, samples)
|
||||
arms = {}
|
||||
for site, mode in [(19, 'baseline')] + [(s, m) for s in (15, 19)
|
||||
for m in ('both', 'read', 'send')]:
|
||||
rows = read(f'diagnostic-{site}-{mode}-{kind}.json')
|
||||
verify(tokenizer, protocol, prompts, rows, (mode,))
|
||||
label = 'baseline' if mode == 'baseline' else f'{site}-{mode}'
|
||||
arms[label], _ = table_metrics(prompts, rows, mode)
|
||||
comparisons = {f'19-minus-15-{m}': {f'19-{m}': 1, f'15-{m}': -1}
|
||||
for m in ('read', 'send', 'both')}
|
||||
for site in (15, 19):
|
||||
comparisons[f'{site}-interaction'] = {
|
||||
f'{site}-both': 1, 'baseline': 1, f'{site}-read': -1, f'{site}-send': -1}
|
||||
layer_comparison[kind] = summarize_arms(arms, comparisons, samples)
|
||||
write_json(args.directory/'audit.json', dict(
|
||||
tables=n, bootstrap_seed=120204, bootstrap_replicates=len(resamples),
|
||||
summary=summary, answers=detail, costs=costs, diagnostic_isolation=isolation,
|
||||
diagnostic_site_comparison=layer_comparison))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,38 @@
|
||||
# 查表任务的分数路径干预
|
||||
|
||||
使用冻结的三层 LiSA 与原底座,先在原 16 道诊断题逐 token 重放基线和第 19 层整层恢复。两组均须与既有生成完全相同。之后在新诊断题上分别干预第 19、15 层。读取和输出给下一全注意力层的分数可独立取原生或 LiSA 值;两套分数均在当前隐藏状态上计算。局部读取的改变仍会通过残差流影响下游。
|
||||
|
||||
冻结题集 SHA-256 为 c309f8721534b1f229a00ff556b48495c4e074be45c1905389aa57e9e3ddb048。诊断使用 8 张独立表,最终评估使用另外 32 张。每张表测两种反事实:保持查询键、交换两项数值,以及保持原表、切换查询键。两种测法共用第一个提示词,分别统计,合并推断以整张表为重采样单位。每次生成从头解码完整整数;首位正确数字概率在生成前使用完整词表计算。
|
||||
|
||||
诊断分支判据以第 19 层的逐表双正确为先,完整答案数为同分判据。在两个任务类型上合计(双正确分别计数),单路径超过基线时检验得分较高的单路径,同分优先读取;若只有联合条件超过基线,保留四组分析联合效应。第 15 层用于独立层位对照。诊断排序只选择下一步干预,不构成显著性检验。留出集开启前固定所选组、同预算对照及成本口径。最终报告逐题得失、表内错键、首位概率与按表配对的区间,区分模拟恢复开销与部署成本。
|
||||
|
||||
第 19 层有 8 个查询头、2 个 KV 组。若读取分支入选,分别恢复对应同一 KV 头的 4 个查询头,按上述诊断顺序选择,平局取第 0 组。用固定种子 120203 在两组中等概率抽取随机对照,并公布两个组的成绩。若抽中的恰好是所选组,随机组不提供独立对照,另一个组仍提供相同预算比较。若传递分支入选,把相同的原生分数交换两个 GQA 组再向下传,保持分数计算次数与数值集合相同。所有局部恢复均同时计算完整原生与 LiSA 分数后再选取;此实现用于诊断,不将选择半数头计为实际节省了一半算力。
|
||||
|
||||
### 原生计算成本与统计口径
|
||||
|
||||
每个干预条件都保留完整 LiSA 前向。额外的原生投影按本实现的真实形状计算:输入宽度 2048,打包的 Q/gate 输出宽度 4096,K 输出宽度 512,每个处理位置多用 9,437,184 次乘加。打包投影中的 gate 部分也实际执行,随后丢弃。每个 query-key 位置对的原生点积另需 8 × 256 = 2048 次乘加;预填充实际形成完整方阵,包含随后才被掩蔽的位置。原生 K 缓存增加每位置 512 个 float32 数。若将来只计算一个 GQA 组且复用已有 gate,每位置额外投影可降为 2048 × (1024 + 256) 次乘加,点积降为每位置对 1024 次乘加。这是理想裁剪后的算术量,运行中的诊断实现仍使用完整组。此处只计投影与点积,排除归一化、旋转、掩蔽、数据搬运和机器延时。
|
||||
|
||||
最终区间以整张表为单位固定种子重采样 10,000 次。对所有条件用相同的重采样索引,并分别列出两种题型。汇总指标给两种题型等权,同一张表的共用原题始终在同一重采样单元内。交互量为“两路同时恢复 − 只恢复读取 − 只恢复传递 + 基线”。逐题给出实际输出、目标键、错读键或表外数字,便于重新判分。
|
||||
|
||||
### 复跑与断点续算
|
||||
|
||||
在实验机的仓库根目录使用已有的 CPU 环境。下列命令可从空输出目录完整复跑。已有答卷时,评估程序核对题号、金标、生成 token 和判分,再从下一对题继续。应在同一输出目录使用同一把锁。最终核验要求所选各组的全部留出答卷均已生成。
|
||||
|
||||
```sh
|
||||
runs=/opt/exp-model-parameter-similarity/runs
|
||||
source_dir=$runs/cpu-qwen35-2b
|
||||
prior=$runs/lisa-full-answer-20261124-run
|
||||
previous=$runs/lisa-combinations-72501
|
||||
output=$runs/lisa-score-paths-120201
|
||||
mkdir -p "$output"
|
||||
export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
|
||||
flock "$output/worker.lock" /opt/exp-model-parameter-similarity/venv/bin/python -Bu \
|
||||
-m crossqkv.lisa_score_paths --source "$source_dir" --prior "$prior" \
|
||||
--previous "$previous" --out "$output" --follow-through
|
||||
/opt/exp-model-parameter-similarity/venv/bin/python -B -m crossqkv.lisa_score_paths_audit \
|
||||
"$output" --tokenizer "$source_dir/tokenizer.json" --frozen "$prior/frozen.json"
|
||||
```
|
||||
|
||||
### 链上恢复与单层共享的反向对照
|
||||
|
||||
在任何新诊断答案产生之前,增加四个诊断条件,逐一开启第 15、19 层的已训练 LiSA,第 23 层均使用原生注意力。按两层开关依次得到全原生、只共享 15、只共享 19、共享 15 和 19。均使用同一批 8 张诊断表和完整生成。只共享 19 时,适配器读取第 15 层的原生分数;同时共享 15 和 19 时,第 19 层也收到共享后的供给分数以及上游改变的隐藏状态。比较只共享 19 与全原生,可检验当前权重下单层共享是否足以损害查表;比较双层条件与两个单层条件,可估计两处共享的交互。诊断结果需限定在当前适配器及任务分布,四个补充条件均不参与留出组的选择。
|
||||
@@ -0,0 +1,7 @@
|
||||
# LiSA 查表分数路径实验结果
|
||||
|
||||
## 旧诊断题端点重放
|
||||
|
||||
同一份 Qwen3.5-2B 和同一份冻结 LiSA 在旧诊断集上重放 8 对题。原 LiSA 的 16 份答卷逐 token 与归档相同,完整答案全错。只在第 19 层同时恢复本层读取与向第 23 层传递的原生分数,另 16 份答卷也逐 token 与旧恢复组相同,完整答案全对。两组正确首位数字的概率相对既有全词表评分,最大绝对差分别为 0.00000136 和 0.00000241。核验还比较了题号、金标、终止原因及整数解析。[基线答卷](../results/lisa-score-paths/replay-19-baseline-old.json) · [恢复组答卷](../results/lisa-score-paths/replay-19-both-old.json) · [哈希与核验结果](../results/lisa-score-paths/replay-verified.json)
|
||||
|
||||
这批题曾用于选层,重放检验的是实现一致性。区分本层读取、分数传递和单层共享损伤的实验采用另外生成的表。[实验协议](LISA_SCORE_PATHS.md)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,306 @@
|
||||
[
|
||||
{
|
||||
"id": "diagnostic-000-0",
|
||||
"task": "lookup",
|
||||
"gold": 76,
|
||||
"first_digit_probability": 0.043660085648298264,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
24,
|
||||
19,
|
||||
248046
|
||||
],
|
||||
"response": "94<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 94,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-000-1",
|
||||
"task": "lookup",
|
||||
"gold": 75,
|
||||
"first_digit_probability": 0.049357522279024124,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
24,
|
||||
19,
|
||||
248046
|
||||
],
|
||||
"response": "94<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 94,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-001-0",
|
||||
"task": "lookup",
|
||||
"gold": 39,
|
||||
"first_digit_probability": 0.1423700600862503,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
22,
|
||||
18,
|
||||
248046
|
||||
],
|
||||
"response": "73<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 73,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-001-1",
|
||||
"task": "lookup",
|
||||
"gold": 76,
|
||||
"first_digit_probability": 0.7241368293762207,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
22,
|
||||
18,
|
||||
248046
|
||||
],
|
||||
"response": "73<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 73,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-002-0",
|
||||
"task": "lookup",
|
||||
"gold": 49,
|
||||
"first_digit_probability": 0.1303817480802536,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
20,
|
||||
17,
|
||||
248046
|
||||
],
|
||||
"response": "52<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 52,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-002-1",
|
||||
"task": "lookup",
|
||||
"gold": 22,
|
||||
"first_digit_probability": 0.019029637798666954,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
20,
|
||||
17,
|
||||
248046
|
||||
],
|
||||
"response": "52<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 52,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-003-0",
|
||||
"task": "lookup",
|
||||
"gold": 63,
|
||||
"first_digit_probability": 0.03255172818899155,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
24,
|
||||
15,
|
||||
248046
|
||||
],
|
||||
"response": "90<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 90,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-003-1",
|
||||
"task": "lookup",
|
||||
"gold": 21,
|
||||
"first_digit_probability": 0.005789129063487053,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
24,
|
||||
15,
|
||||
248046
|
||||
],
|
||||
"response": "90<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 90,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-004-0",
|
||||
"task": "lookup",
|
||||
"gold": 74,
|
||||
"first_digit_probability": 0.058539994060993195,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
24,
|
||||
24,
|
||||
248046
|
||||
],
|
||||
"response": "99<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 99,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-004-1",
|
||||
"task": "lookup",
|
||||
"gold": 29,
|
||||
"first_digit_probability": 0.006509687285870314,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
24,
|
||||
24,
|
||||
248046
|
||||
],
|
||||
"response": "99<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 99,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-005-0",
|
||||
"task": "lookup",
|
||||
"gold": 39,
|
||||
"first_digit_probability": 0.0035035305190831423,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
21,
|
||||
16,
|
||||
248046
|
||||
],
|
||||
"response": "61<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 61,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-005-1",
|
||||
"task": "lookup",
|
||||
"gold": 77,
|
||||
"first_digit_probability": 0.1008690670132637,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
21,
|
||||
16,
|
||||
248046
|
||||
],
|
||||
"response": "61<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 61,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-006-0",
|
||||
"task": "lookup",
|
||||
"gold": 40,
|
||||
"first_digit_probability": 0.22315144538879395,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
20,
|
||||
15,
|
||||
248046
|
||||
],
|
||||
"response": "50<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 50,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-006-1",
|
||||
"task": "lookup",
|
||||
"gold": 67,
|
||||
"first_digit_probability": 0.06879249960184097,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
20,
|
||||
15,
|
||||
248046
|
||||
],
|
||||
"response": "50<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 50,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-007-0",
|
||||
"task": "lookup",
|
||||
"gold": 89,
|
||||
"first_digit_probability": 0.015698770061135292,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
19,
|
||||
18,
|
||||
248046
|
||||
],
|
||||
"response": "43<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 43,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-007-1",
|
||||
"task": "lookup",
|
||||
"gold": 61,
|
||||
"first_digit_probability": 0.011921032331883907,
|
||||
"arms": {
|
||||
"baseline": {
|
||||
"tokens": [
|
||||
19,
|
||||
18,
|
||||
248046
|
||||
],
|
||||
"response": "43<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 43,
|
||||
"correct": false
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,306 @@
|
||||
[
|
||||
{
|
||||
"id": "diagnostic-000-0",
|
||||
"task": "lookup",
|
||||
"gold": 76,
|
||||
"first_digit_probability": 0.49160245060920715,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
22,
|
||||
21,
|
||||
248046
|
||||
],
|
||||
"response": "76<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 76,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-000-1",
|
||||
"task": "lookup",
|
||||
"gold": 75,
|
||||
"first_digit_probability": 0.533911406993866,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
22,
|
||||
20,
|
||||
248046
|
||||
],
|
||||
"response": "75<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 75,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-001-0",
|
||||
"task": "lookup",
|
||||
"gold": 39,
|
||||
"first_digit_probability": 0.9007320404052734,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
18,
|
||||
24,
|
||||
248046
|
||||
],
|
||||
"response": "39<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 39,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-001-1",
|
||||
"task": "lookup",
|
||||
"gold": 76,
|
||||
"first_digit_probability": 0.9933711290359497,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
22,
|
||||
21,
|
||||
248046
|
||||
],
|
||||
"response": "76<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 76,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-002-0",
|
||||
"task": "lookup",
|
||||
"gold": 49,
|
||||
"first_digit_probability": 0.784931480884552,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
19,
|
||||
24,
|
||||
248046
|
||||
],
|
||||
"response": "49<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 49,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-002-1",
|
||||
"task": "lookup",
|
||||
"gold": 22,
|
||||
"first_digit_probability": 0.6501032710075378,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
17,
|
||||
17,
|
||||
248046
|
||||
],
|
||||
"response": "22<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 22,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-003-0",
|
||||
"task": "lookup",
|
||||
"gold": 63,
|
||||
"first_digit_probability": 0.9689449071884155,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
21,
|
||||
18,
|
||||
248046
|
||||
],
|
||||
"response": "63<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 63,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-003-1",
|
||||
"task": "lookup",
|
||||
"gold": 21,
|
||||
"first_digit_probability": 0.9367953538894653,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
17,
|
||||
16,
|
||||
248046
|
||||
],
|
||||
"response": "21<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 21,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-004-0",
|
||||
"task": "lookup",
|
||||
"gold": 74,
|
||||
"first_digit_probability": 0.9645876288414001,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
22,
|
||||
19,
|
||||
248046
|
||||
],
|
||||
"response": "74<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 74,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-004-1",
|
||||
"task": "lookup",
|
||||
"gold": 29,
|
||||
"first_digit_probability": 0.788325309753418,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
17,
|
||||
24,
|
||||
248046
|
||||
],
|
||||
"response": "29<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 29,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-005-0",
|
||||
"task": "lookup",
|
||||
"gold": 39,
|
||||
"first_digit_probability": 0.6246046423912048,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
18,
|
||||
24,
|
||||
248046
|
||||
],
|
||||
"response": "39<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 39,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-005-1",
|
||||
"task": "lookup",
|
||||
"gold": 77,
|
||||
"first_digit_probability": 0.7460411787033081,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
22,
|
||||
22,
|
||||
248046
|
||||
],
|
||||
"response": "77<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 77,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-006-0",
|
||||
"task": "lookup",
|
||||
"gold": 40,
|
||||
"first_digit_probability": 0.9425035715103149,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
19,
|
||||
15,
|
||||
248046
|
||||
],
|
||||
"response": "40<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 40,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-006-1",
|
||||
"task": "lookup",
|
||||
"gold": 67,
|
||||
"first_digit_probability": 0.8656787872314453,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
21,
|
||||
22,
|
||||
248046
|
||||
],
|
||||
"response": "67<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 67,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-007-0",
|
||||
"task": "lookup",
|
||||
"gold": 89,
|
||||
"first_digit_probability": 0.8434507846832275,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
23,
|
||||
24,
|
||||
248046
|
||||
],
|
||||
"response": "89<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 89,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "diagnostic-007-1",
|
||||
"task": "lookup",
|
||||
"gold": 61,
|
||||
"first_digit_probability": 0.49588829278945923,
|
||||
"arms": {
|
||||
"both": {
|
||||
"tokens": [
|
||||
21,
|
||||
16,
|
||||
248046
|
||||
],
|
||||
"response": "61<|im_end|>",
|
||||
"stop": "eos",
|
||||
"answer": 61,
|
||||
"correct": true
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"baseline": {
|
||||
"replay_sha256": "b69bdd1aa5bc91447a6b8f600b597f5a2d61c9ecd16aa1f29815b3dc0414afba",
|
||||
"reference_sha256": "8f3fb8773fa790de01604db9a313365bab25a55c86b363eaf0269f94df020e8f",
|
||||
"token_identical": 16,
|
||||
"correct": 0,
|
||||
"maximum_first_digit_probability_difference": 1.361978284930565e-06
|
||||
},
|
||||
"both": {
|
||||
"replay_sha256": "f74d4d4ab6af9c92188f5a4d9e34195c67d187f6a72586f2d60710f5ea456152",
|
||||
"reference_sha256": "c1b158e61eaa98b1c24ead81363ef3193b392d36947f3199e7930fe199e5163a",
|
||||
"token_identical": 16,
|
||||
"correct": 16,
|
||||
"maximum_first_digit_probability_difference": 2.4037814841948446e-06
|
||||
},
|
||||
"reference_probabilities_sha256": "7fb33eca323ab3ec45ceae8be77609e388fe88b2b77eb59c43726cc0c39b69e3"
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Check score routing against separate native and shared attention computations."""
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from crossqkv.lisa_generate import GenerationDecoder
|
||||
from crossqkv.lisa_score_paths import PathDecoder
|
||||
from crossqkv.lisa_train import LearnableSharingAttention
|
||||
from functional.model import PREFIX
|
||||
from functional.reference_check import ArrayLM
|
||||
from tests.test_lisa_tail import Tensor
|
||||
|
||||
|
||||
class ScorePathTests(unittest.TestCase):
|
||||
def test_route_native_and_shared_scores_independently_across_decode_steps(self):
|
||||
rng = np.random.default_rng(129)
|
||||
torch.manual_seed(129)
|
||||
heads, kv, dim, width = 4, 2, 8, 16
|
||||
config = dict(rms_norm_eps=1e-6, layer_types=['full_attention'] * 2,
|
||||
num_attention_heads=heads, num_key_value_heads=kv, head_dim=dim,
|
||||
rope_parameters=dict(rope_theta=10000., partial_rotary_factor=.5))
|
||||
shapes = dict(q_proj=(2*heads*dim, width), k_proj=(kv*dim, width),
|
||||
v_proj=(kv*dim, width), o_proj=(width, heads*dim),
|
||||
q_norm=(dim,), k_norm=(dim,))
|
||||
weights = {'layers.1.self_attn.'+k+'.weight': rng.normal(0, .2, shape).astype('f4')
|
||||
for k, shape in shapes.items()}
|
||||
source = ArrayLM(weights, config)
|
||||
source.tensors = {PREFIX+k: Tensor(v) for k, v in weights.items()}
|
||||
adapter = {1: LearnableSharingAttention(width, heads, kv, 4, 10000., .5, 12)}
|
||||
native = GenerationDecoder(source, [()], [0])
|
||||
shared = GenerationDecoder(source, [(1,)], [0], adapter)
|
||||
routed = {}
|
||||
for mode in ('read', 'send', 'both', 'send-permuted', 'read-group-0', 'read-group-1'):
|
||||
decoder = PathDecoder(source, [(1,)], [0], adapter)
|
||||
decoder.site, decoder.mode = 1, mode
|
||||
routed[mode] = decoder
|
||||
|
||||
for start, stop in ((0, 3), (3, 4)):
|
||||
positions = torch.arange(start, stop)[None, :]
|
||||
causal = (torch.arange(stop) <= positions.T)[None, None]
|
||||
hidden = torch.randn(1, stop-start, width)
|
||||
donor = torch.randn(1, heads, stop-start, stop)
|
||||
args = (hidden, 1, positions, causal, donor)
|
||||
native_out, native_scores = native.attention_chunk(*args)
|
||||
shared_out, shared_scores = shared.attention_chunk(*args)
|
||||
self.assertFalse(torch.allclose(native_scores, shared_scores))
|
||||
self.assertFalse(torch.allclose(native_out, shared_out))
|
||||
outputs = {}
|
||||
for mode, decoder in routed.items():
|
||||
decoder.position = start
|
||||
outputs[mode], outgoing = decoder.attention_chunk(*args)
|
||||
expected = native_scores if mode in ('both', 'send') else shared_scores
|
||||
if mode == 'send-permuted':
|
||||
expected = native_scores.roll(heads//kv, dims=1)
|
||||
torch.testing.assert_close(outgoing, expected)
|
||||
for mode in ('read', 'both'):
|
||||
torch.testing.assert_close(outputs[mode], native_out)
|
||||
for mode in ('send', 'send-permuted'):
|
||||
torch.testing.assert_close(outputs[mode], shared_out)
|
||||
# Head contexts are concatenated before the common linear output projection.
|
||||
# Restoring complementary groups must reconstruct the full output difference.
|
||||
torch.testing.assert_close(outputs['read-group-0'] + outputs['read-group-1'],
|
||||
native_out + shared_out)
|
||||
for group in ('read-group-0', 'read-group-1'):
|
||||
self.assertFalse(torch.allclose(outputs[group], shared_out))
|
||||
self.assertFalse(torch.allclose(outputs[group], native_out))
|
||||
Reference in New Issue
Block a user