Compare isolated layer sharing against the native lookup model
This commit is contained in:
@@ -20,6 +20,12 @@ from functional.model import PREFIX, StreamingLM
|
|||||||
from functional.run import write_json
|
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):
|
class PathDecoder(GenerationDecoder):
|
||||||
def score_paths(self, h, layer, positions, scores):
|
def score_paths(self, h, layer, positions, scores):
|
||||||
if layer != self.site or self.mode == 'baseline':
|
if layer != self.site or self.mode == 'baseline':
|
||||||
@@ -66,6 +72,11 @@ def batch(model, tok, adapters, qs, site, mode):
|
|||||||
ids = [tok.encode(prompt(q['question']),add_special_tokens=False).ids for q in qs]
|
ids = [tok.encode(prompt(q['question']),add_special_tokens=False).ids for q in qs]
|
||||||
width = max(map(len,ids))
|
width = max(map(len,ids))
|
||||||
padding = [width-len(x) for x in 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 = PathDecoder(model,[SITES]*len(qs),padding,adapters)
|
||||||
dec.site, dec.mode = site, mode
|
dec.site, dec.mode = site, mode
|
||||||
h = dec.advance(torch.tensor([[0]*p+x for p,x in zip(padding,ids)]))[:,-1]
|
h = dec.advance(torch.tensor([[0]*p+x for p,x in zip(padding,ids)]))[:,-1]
|
||||||
@@ -147,6 +158,8 @@ def main():
|
|||||||
if not a.follow_through:
|
if not a.follow_through:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
evaluate('diagnostic', 'isolation', ISOLATION_SCHEDULES)
|
||||||
|
|
||||||
def diagnostic_score(mode):
|
def diagnostic_score(mode):
|
||||||
joint = total = 0
|
joint = total = 0
|
||||||
for kind, items in plan['diagnostic'].items():
|
for kind, items in plan['diagnostic'].items():
|
||||||
|
|||||||
@@ -61,7 +61,8 @@ def main():
|
|||||||
assert fingerprint(args.directory/'protocol.json') == 'c309f8721534b1f229a00ff556b48495c4e074be45c1905389aa57e9e3ddb048'
|
assert fingerprint(args.directory/'protocol.json') == 'c309f8721534b1f229a00ff556b48495c4e074be45c1905389aa57e9e3ddb048'
|
||||||
def read(name):
|
def read(name):
|
||||||
return json.loads((args.directory/name).read_text())
|
return json.loads((args.directory/name).read_text())
|
||||||
questions = read('protocol.json')['holdout']
|
plan = read('protocol.json')
|
||||||
|
questions = plan['holdout']
|
||||||
modes = read('selection.json')['holdout_modes']
|
modes = read('selection.json')['holdout_modes']
|
||||||
n = len(questions['swap']) // 2
|
n = len(questions['swap']) // 2
|
||||||
assert n >= 32 and len(questions['query']) == 2*n
|
assert n >= 32 and len(questions['query']) == 2*n
|
||||||
@@ -108,9 +109,28 @@ def main():
|
|||||||
sum(c*arms[m][i][k] for m, c in coefficients.items()) for i in range(n)
|
sum(c*arms[m][i][k] for m, c in coefficients.items()) for i in range(n)
|
||||||
], resamples) for k in fields}
|
], resamples) for k in fields}
|
||||||
summary[kind] = dict(means=estimates, paired_contrasts=comparisons)
|
summary[kind] = dict(means=estimates, paired_contrasts=comparisons)
|
||||||
|
isolation = {}
|
||||||
|
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] = {
|
||||||
|
'means': {m: {k: mean(row[k] for row in arm) for k in fields} for m, arm in arms.items()},
|
||||||
|
'contrasts': {name: {k: interval([
|
||||||
|
sum(c*arms[m][i][k] for m,c in coefficients.items()) for i in range(count)
|
||||||
|
], samples) for k in fields} for name, coefficients in combinations.items()}}
|
||||||
write_json(args.directory/'audit.json', dict(
|
write_json(args.directory/'audit.json', dict(
|
||||||
tables=n, bootstrap_seed=120204, bootstrap_replicates=len(resamples),
|
tables=n, bootstrap_seed=120204, bootstrap_replicates=len(resamples),
|
||||||
summary=summary, answers=detail, costs=costs))
|
summary=summary, answers=detail, costs=costs, diagnostic_isolation=isolation))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@@ -32,3 +32,7 @@ flock "$output/worker.lock" /opt/exp-model-parameter-similarity/venv/bin/python
|
|||||||
/opt/exp-model-parameter-similarity/venv/bin/python -B -m crossqkv.lisa_score_paths_audit \
|
/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"
|
"$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,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