Add controlled two-layer LiSA reproduction on Qwen

This commit is contained in:
2026-11-24 00:00:42 +08:00
parent 115e440455
commit 1c8943a2e8
21 changed files with 4444 additions and 7 deletions
+101
View File
@@ -0,0 +1,101 @@
"""Incremental full-attention sites for measuring LiSA's real K/V allocation.
The scheduler supplies the earlier full-attention site's raw score row for
the same query. This file measures an attention site, excluding GDN, MLP,
embedding, and scheduler overhead.
"""
import math
import torch
from crossqkv.lisa_tail import TorchTail, rotate
class AttentionSiteCache:
def __init__(self, tail: TorchTail, layer, batch_size, capacity, adapter=None,
dtype=torch.float32):
self.tail, self.adapter = tail, adapter
self.name = f'layers.{layer}.self_attn.'
self.heads = tail.c['num_attention_heads']
self.kv_heads = tail.c['num_key_value_heads']
self.head_dim = tail.c['head_dim']
self.key_dim = adapter.rank if adapter is not None else self.head_dim
self.capacity = capacity
self.next_position = 0
self.k = torch.empty(batch_size, capacity, self.kv_heads, self.key_dim, dtype=dtype)
self.v = torch.empty(batch_size, capacity, self.kv_heads, self.head_dim, dtype=dtype)
rp = tail.c['rope_parameters']
n = int(self.head_dim * rp['partial_rotary_factor'])
self.rotary_frequency = rp['rope_theta'] ** (-torch.arange(0, n, 2, dtype=dtype) / n)
def reset(self):
self.next_position = 0
@property
def allocated_bytes(self):
return {'k': self.k.numel()*self.k.element_size(),
'v': self.v.numel()*self.v.element_size()}
def native_rotate(self, x, position):
angle = self.rotary_frequency * position
a, b = x[..., :2*len(angle)].chunk(2, -1)
angle = torch.cat((angle, angle))
return torch.cat((torch.cat((a, b), -1)*angle.cos()
+ torch.cat((-b, a), -1)*angle.sin(),
x[..., 2*len(self.rotary_frequency):]), -1)
@torch.no_grad()
def prefill(self, h):
"""Populate K/V from a fresh prefix without scoring its queries."""
n = h.shape[1]
if h.shape[0] != self.k.shape[0] or n > self.capacity:
raise ValueError('Prefix does not fit the attention cache')
base, name = self.tail, self.name
if self.adapter is None:
rp = base.c['rope_parameters']
k = base.linear(h, name+'k_proj').unflatten(-1, (self.kv_heads, self.head_dim))
k = rotate(base.norm(k, name+'k_norm'), rp['rope_theta'], rp['partial_rotary_factor'])
else:
a = self.adapter
k = a.k_proj(h).unflatten(-1, (self.kv_heads, self.key_dim))
k = a.rotate(k, torch.arange(n, device=h.device)[None, :])
self.k[:, :n].copy_(k)
self.v[:, :n].copy_(base.linear(h, name+'v_proj').unflatten(-1, (self.kv_heads, self.head_dim)))
self.next_position = n
@torch.no_grad()
def step(self, h, donor=None):
"""h has shape (batch, 1, hidden). Return output and unmasked score row."""
pos = self.next_position
if h.shape[:2] != (self.k.shape[0], 1) or pos >= self.capacity:
raise ValueError('Wrong input shape or full attention cache')
if self.adapter is not None and (donor is None or
donor.shape != (len(h), self.heads, 1, pos+1)):
raise ValueError('LiSA requires the upstream score row for its full prefix')
base = self.tail
name = self.name
if self.adapter is None:
packed = base.linear(h, name+'q_proj').unflatten(-1, (self.heads, 2*self.head_dim))
q, gate = packed.chunk(2, -1)
k = base.linear(h, name+'k_proj').unflatten(-1, (self.kv_heads, self.head_dim))
q = self.native_rotate(base.norm(q, name+'q_norm'), pos)
k = self.native_rotate(base.norm(k, name+'k_norm'), pos)
else:
a = self.adapter
position = torch.tensor([[pos]], device=h.device)
q = a.rotate(a.q_proj(h).unflatten(-1, (self.heads, self.key_dim)), position)
k = a.rotate(a.k_proj(h).unflatten(-1, (self.kv_heads, self.key_dim)), position)
gate = base.gate_only(h, name)
v = base.linear(h, name+'v_proj').unflatten(-1, (self.kv_heads, self.head_dim))
self.k[:, pos:pos+1].copy_(k)
self.v[:, pos:pos+1].copy_(v)
self.next_position += 1
groups = self.heads // self.kv_heads
keys = self.k[:, :pos+1].repeat_interleave(groups, 2)
values = self.v[:, :pos+1].repeat_interleave(groups, 2)
scores = torch.einsum('bthd,bshd->bhts', q, keys) / math.sqrt(self.key_dim)
if self.adapter is not None:
both = torch.cat((scores, donor), dim=1).permute(0, 2, 3, 1)
scores = self.adapter.fuse(both).permute(0, 3, 1, 2)
context = torch.einsum('bhts,bshd->bthd', scores.softmax(-1), values)
return base.linear((context * gate.sigmoid()).flatten(-2), name+'o_proj'), scores
+130
View File
@@ -0,0 +1,130 @@
"""Measure real K/V allocation and isolated incremental attention on Qwen."""
import argparse
import json
import time
from statistics import median
from pathlib import Path
import numpy as np
import torch
from torch.nn import functional as F
from crossqkv.lisa_decode import AttentionSiteCache
from crossqkv.lisa_tail import TorchTail, weight_chunks
from crossqkv.lisa_train import LearnableSharingAttention
from functional.model import PREFIX, StreamingLM
from functional.run import write_json
class TracedTail(TorchTail):
def full(self, h, layer, donor, lengths, mode, recipients, keep_teacher):
self.inputs[layer] = (h, donor)
return super().full(h, layer, donor, lengths, mode, recipients, keep_teacher)
class ResidentSite:
"""Keep one site's frozen projections resident to isolate compute latency."""
def __init__(self, tail, layer):
self.tail, self.c = tail, tail.c
self.name = f'layers.{layer}.self_attn.'
self.weights = {}
for k in ('q_proj', 'k_proj', 'v_proj', 'o_proj'):
t = tail.source.tensors[PREFIX + self.name + k + '.weight']
self.weights[self.name+k] = torch.cat(list(weight_chunks(t, 0, t.shape[0])))
w = self.weights[self.name+'q_proj']
heads, dim = self.c['num_attention_heads'], self.c['head_dim']
self.gate_weight = w.reshape(heads, 2*dim, -1)[:, dim:].reshape(heads*dim, -1).contiguous()
def linear(self, h, name, start=0, end=None):
return F.linear(h, self.weights[name][start:end])
def gate_only(self, h, name):
if name != self.name:
raise ValueError('Resident gate called for the wrong site')
return F.linear(h, self.gate_weight).unflatten(-1,
(self.c['num_attention_heads'], self.c['head_dim']))
def norm(self, *args):
return self.tail.norm(*args)
def timed_site(groups, h, donor, n, samples=3, rounds=4):
timings = {k: [] for k in groups}
states = {}
for i in range(rounds):
order = tuple(groups) if i % 2 == 0 else tuple(reversed(groups))
for mode in order:
cache = groups[mode]
cache.reset()
cache.prefill(h[:, :n-samples])
for pos in range(n-samples, n):
row = donor[:, :, pos:pos+1, :pos+1].contiguous() if mode == 'lisa' else None
start = time.perf_counter()
result, attention = cache.step(h[:, pos:pos+1], row)
elapsed = time.perf_counter() - start
if i:
timings[mode].append(elapsed)
if not torch.isfinite(result).all():
raise FloatingPointError('Invalid cached decode')
states[mode] = result, attention
return timings, states
def run(source, capture, checkpoint, out):
torch.set_num_threads(1)
spec = json.loads((capture/'selection.json').read_text())
sites = spec['sites']
source = StreamingLM(source/'weights', json.loads((source/'model_config.json').read_text()))
cfg = source.config
rope = cfg['rope_parameters']
adap = {i: LearnableSharingAttention(cfg['hidden_size'], cfg['num_attention_heads'],
cfg['num_key_value_heads'], 40, rope['rope_theta'], rope['partial_rotary_factor'],
bias=cfg.get('attention_bias', False)) for i in sites}
tail = TracedTail(source, sites[0], adap)
tail.adapters.load_state_dict(torch.load(checkpoint, map_location='cpu', weights_only=True))
with np.load(sorted(capture.glob('validation-*.npz'))[0], allow_pickle=False) as f:
n = int(f['lengths'][0])
data = {k: torch.from_numpy(f[k][:1]) for k in ('residual', 'donor', 'lengths')}
data['residual'] = data['residual'][:, :n]
data['donor'] = data['donor'][:, :, :n, :n]
tail.inputs = {}
measurements = {}
with torch.no_grad():
tail(data['residual'], data['donor'], data['lengths'], 'native', ())
for layer in sites:
h, donor = tail.inputs[layer]
groups = {'native': AttentionSiteCache(tail, layer, 1, n),
'lisa': AttentionSiteCache(tail, layer, 1, n, adap[layer])}
timings, reference = timed_site(groups, h, donor, n)
resident = ResidentSite(tail, layer)
resident_groups = {mode: AttentionSiteCache(resident, layer, 1, n,
adap[layer] if mode == 'lisa' else None) for mode in groups}
warm, checked = timed_site(resident_groups, h, donor, n)
for mode in groups:
for actual, expected in zip(checked[mode], reference[mode]):
torch.testing.assert_close(actual, expected, rtol=5e-5, atol=5e-5)
measurements[layer] = {'seconds_per_token': timings,
'resident_seconds_per_token': warm,
'resident_median_s_per_token': {k: median(v) for k,v in warm.items()},
'resident_matches_streamed': True,
'allocated_bytes': {k: v.allocated_bytes for k, v in groups.items()},
'lisa_input_score_row_bytes': (
cfg['num_attention_heads'] * n * h.element_size()),
'sequence_length': n}
write_json(out, {'scope': 'isolated full-attention recipient, FP32, frozen true activations; '
'excludes donor generation and full-model decode', 'sites': measurements,
'streamed_timings_include_weight_reads': True,
'resident_timings_exclude_projection_load': True})
def main():
p = argparse.ArgumentParser(description=__doc__)
for name in ('source', 'capture', 'checkpoint', 'out'):
p.add_argument('--'+name, type=Path, required=True)
a = p.parse_args()
run(a.source, a.capture, a.checkpoint, a.out)
if __name__ == '__main__':
main()
+296
View File
@@ -0,0 +1,296 @@
"""Train matched multi-recipient sharing adapters and evaluate the frozen test set."""
import argparse
import hashlib
import json
import time
from pathlib import Path
import numpy as np
from crossqkv.core import QKVModel
from crossqkv.lisa_effect_screen import TASKS
from crossqkv.lisa_pilot import batch, scores
from functional.model import PREFIX
from functional.run import write_json
CANDIDATES = ('linear', 'lisa', 'lisa_answer_weighted')
def selection(screen):
eligible = []
for task, modes in screen.items():
base = modes['native']
if base['correct'] < 5:
continue
for name, sites in [('direct_23', [23]), ('direct_19_23', [19, 23])]:
row = modes[name]
if row['native_wins_lost']:
eligible.append((row['native_wins_lost'], len(sites),
base['correct']-row['correct'], task, sites))
if not eligible:
raise ValueError('No task/schedule met the prespecified development eligibility rule')
_, _, _, task, sites = max(eligible)
return {'task': task, 'sites': sites}
class Capture(QKVModel):
def normalization(self, x, name):
if name == f'layers.{self.first}.input_layernorm':
self.residual = x
return super().normalization(x, name)
def full_attention(self, h, layer, shared_p=None):
if layer != self.first - 4:
return super().full_attention(h, layer, shared_p)
part = self.parts(h, layer, heads=False)
self.donor = scores(part['q'], part['k'])
return part['output'], part['p']
def capture(source, screen_dir, out, schedule):
from tokenizers import Tokenizer
fixed_path = screen_dir/'fixed-problems.json'
fixed = json.loads(fixed_path.read_text())
chosen = selection(json.loads((screen_dir/'screen-summary.json').read_text()))
if schedule == 'chain':
modes = json.loads((screen_dir/'screen-summary.json').read_text())[chosen['task']]
if not modes['direct_19_23']['native_wins_lost']:
raise ValueError('The development-selected task has no recorded losses under the chain')
chosen['sites'] = [19, 23]
model = Capture(source/'weights', json.loads((source/'model_config.json').read_text()),
seconds=7200)
model.first = chosen['sites'][0]
tok = Tokenizer.from_file(str(source/'tokenizer.json'))
sha = lambda path: hashlib.sha256(path.read_bytes()).hexdigest()
write_json(out/'selection.json', {**chosen, 'fixed_problems_sha256': sha(fixed_path),
'source_sha256': {n: sha(source/n) for n in
('manifest.json', 'model_config.json', 'tokenizer.json')}})
for split in ('fit', 'validation', 'test'):
selected = [ex for ex in fixed[split] if ex['task'] == chosen['task']]
for start in range(0, len(selected), 4):
group = selected[start:start+4]
ids, lengths, labels = batch(tok, group)
gold = np.array([r['answer_index'] for r in group])
ids = np.pad(ids, ((0, 0), (0, 1)))
ids[np.arange(len(group)), lengths] = np.asarray(labels)[gold]
h, _ = model.forward(ids)
pending = out/f'{split}-{start:03}.tmp.npz'
np.savez(pending, ids=ids, lengths=np.asarray(lengths)+1, labels=labels, gold=gold,
residual=model.residual, donor=model.donor, expected=h,
names=[x['id'] for x in group])
pending.replace(out/f'{split}-{start:03}.npz')
print('capture', split, start+len(group), '/', len(selected), flush=True)
def train(source, cache, out, epochs, resume=False):
import torch
from torch import nn
from crossqkv.lisa_tail import TorchTail
from crossqkv.lisa_train import LearnableSharingAttention, huber_distillation, language_model_loss
from functional.model import StreamingLM
torch.set_num_threads(1)
torch.manual_seed(415005)
spec = json.loads((cache/'selection.json').read_text())
if any(hashlib.sha256((source/n).read_bytes()).hexdigest() != s
for n, s in spec['source_sha256'].items()):
raise ValueError('Checkpoint provenance mismatch')
expected_batches = {'fit':12, 'validation':12, 'test':32}
for split, count in expected_batches.items():
actual = 0
for p in cache.glob(f'{split}-*.npz'):
with np.load(p, allow_pickle=False) as b:
actual += len(b['names'])
if actual != count:
raise ValueError(f'Expected {count} {split} examples, found {actual}')
run_config = {'epochs': epochs, 'selection': spec, 'optimizer': 'AdamW',
'lr': .0003, 'weight_decay': .1, 'answer_weight': 16., 'seed': 415005}
config_path = out/'train-protocol.json'
if resume:
if json.loads(config_path.read_text()) != run_config:
raise ValueError('Training configuration differs from the original run')
else:
write_json(config_path, run_config)
model = StreamingLM(source/'weights', json.loads((source/'model_config.json').read_text()))
sites = tuple(spec['sites'])
cfg = model.config
heads = cfg['num_attention_heads']
rope = cfg['rope_parameters']
t = model.tensors[PREFIX+'embed_tokens.weight']
def vocab():
for start in range(0, t.shape[0], 1024):
end = min(start+1024, t.shape[0])
yield start, torch.from_numpy(t.read(slice(start*t.shape[1], end*t.shape[1]))
.reshape(end-start, t.shape[1]))
t.evict()
def batches(split, micro=False):
for path in sorted(cache.glob(f'{split}-*.npz')):
with np.load(path, allow_pickle=False) as f:
b = {k: torch.from_numpy(f[k]) for k in f.files if k != 'names'}
names = f['names'].tolist()
if not micro:
yield b, names
else:
for j, name in enumerate(names):
yield {k: v if k == 'labels' else v[j:j+1] for k, v in b.items()}, [name]
def make(candidate):
torch.manual_seed(415005)
if candidate == 'linear':
blocks = {i: nn.Linear(heads, heads, bias=False) for i in sites}
for value in blocks.values():
with torch.no_grad():
value.weight.copy_(torch.eye(heads))
else:
blocks = {i: LearnableSharingAttention(cfg['hidden_size'], heads,
cfg['num_key_value_heads'], 40, rope['rope_theta'],
rope['partial_rotary_factor'], bias=cfg.get('attention_bias', False))
for i in sites}
return TorchTail(model, sites[0], blocks)
def run(tail, b, mode, teacher=False):
return tail(b['residual'], b['donor'], b['lengths'], mode, sites, teacher)
def score(h, b):
index = b['lengths'] - 2
f = h[torch.arange(len(index)), index]
labels = b['labels'].tolist()
weights = np.stack([t.read(slice(i*t.shape[1], (i+1)*t.shape[1])) for i in labels])
t.evict()
logits = f @ torch.from_numpy(weights).T
nll = torch.logsumexp(logits, -1) - logits[torch.arange(len(index)), b['gold']]
return logits, nll
def evaluate(tail, split, mode):
rows = []
with torch.no_grad():
for b, names in batches(split):
h, _ = run(tail, b, mode)
if mode == 'native':
valid = torch.arange(h.shape[1])[None] < b['lengths'][:, None]
torch.testing.assert_close(h[valid], b['expected'][valid], rtol=7e-5, atol=8e-5)
logits, nll = score(h, b)
rows.extend({'id': name, 'gold': int(g), 'logits': x.tolist(),
'pred': int(x.argmax()), 'answer_nll': float(v)}
for name, g, x, v in zip(names, b['gold'], logits, nll))
if not rows:
raise ValueError(f'No cached rows for {split}')
return rows
def mean_nll(rows):
return sum(r['answer_nll'] for r in rows) / len(rows)
trace = {}
for candidate in CANDIDATES:
tail = make(candidate)
mode = 'linear' if candidate == 'linear' else 'lisa'
optim = torch.optim.AdamW(tail.parameters(), lr=.0003, weight_decay=.1)
ans_weight = 16.0 if candidate == 'lisa_answer_weighted' else 1.0
best = float('inf')
best_weights = None
trace[candidate] = []
last = out/f'{candidate}-resume.pt'
if resume and last.exists():
state = torch.load(last, weights_only=True, map_location='cpu')
tail.adapters.load_state_dict(state['parameters'])
optim.load_state_dict(state['optimizer'])
trace[candidate] = state['trace']
best = state['best']
best_weights = state['best_parameters']
for epoch in range(len(trace[candidate]), epochs):
loss_total = 0.
count = 0
for b, _ in batches('fit', micro=True):
optim.zero_grad(set_to_none=True)
h, layer = run(tail, b, mode, teacher=True)
kd = torch.stack([huber_distillation(*layer[i], b['lengths']) for i in sites]).mean()
ce = None if mode == 'linear' else language_model_loss(
h, b['ids'], b['lengths'], vocab, answer_weight=ans_weight)
loss = kd if ce is None else .25 * kd + .75 * ce
loss.backward()
if any(p.grad is None or not torch.isfinite(p.grad).all() for p in tail.parameters()):
raise FloatingPointError('Invalid adapter gradients')
optim.step()
loss_total += float(loss.detach())
count += 1
rows = evaluate(tail, 'validation', mode)
val = mean_nll(rows)
trace[candidate].append({'epoch': epoch+1, 'fit_loss': loss_total/count,
'validation_answer_nll': val})
if val < best:
best = val
best_weights = {k: v.detach().clone() for k, v in tail.adapters.state_dict().items()}
pending = last.with_suffix('.tmp')
torch.save({'parameters': tail.adapters.state_dict(), 'optimizer': optim.state_dict(),
'trace': trace[candidate], 'best': best, 'best_parameters': best_weights},
pending)
pending.replace(last)
write_json(out/'trace.json', trace)
print(candidate, epoch+1, 'validation answer NLL', val, flush=True)
selected = out/f'{candidate}.pt'
pending = selected.with_suffix('.tmp')
torch.save(best_weights, pending)
pending.replace(selected)
# All checkpoints are frozen before evaluating holdout. Native and direct
# go through the same path, including numerical parity with NumPy.
results = {}
empty = TorchTail(model, sites[0])
for mode in ('native', 'direct'):
results[mode] = evaluate(empty, 'test', mode)
for name in CANDIDATES:
tail = make(name)
tail.adapters.load_state_dict(torch.load(out/f'{name}.pt', map_location='cpu', weights_only=True))
results[name] = evaluate(tail, 'test', 'linear' if name == 'linear' else 'lisa')
write_json(out/'test-items.json', results)
b, _ = next(batches('validation'))
b = {k: v if k == 'labels' else v[:1] for k, v in b.items()}
trained = make('lisa')
trained.adapters.load_state_dict(torch.load(out/'lisa.pt', weights_only=True))
timing = {'native': [], 'direct': [], 'lisa': []}
with torch.no_grad():
for turn in range(4):
modes = list(timing)
for mode in modes[turn % 3:] + modes[:turn % 3]:
t0 = time.perf_counter()
_, _ = run(trained if mode == 'lisa' else empty, b, mode)
if turn:
timing[mode].append(time.perf_counter()-t0)
tokens = int(b['lengths'][0])
kv, d = cfg['num_key_value_heads'], cfg['head_dim']
cache_bytes = {'scope': 'formula for one sequence, BF16 keys and score buffers',
'native_recipient_key_bytes': len(sites)*tokens*kv*d*2,
'lisa_recipient_key_bytes': len(sites)*tokens*kv*40*2,
'one_shared_decode_score_row_bytes': heads*tokens*2,
'one_full_prefill_score_matrix_bytes': heads*tokens*tokens*2}
write_json(out/'performance.json', {'scope': 'cached-prefix last layers, prefill',
'seconds': timing, 'real_tokens': tokens, 'cache_estimate': cache_bytes})
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('phase', choices=('capture', 'train'))
p.add_argument('--source', required=True, type=Path)
p.add_argument('--input', required=True, type=Path)
p.add_argument('--out', required=True, type=Path)
p.add_argument('--schedule', choices=('best','chain'), default='best')
p.add_argument('--epochs', type=int, default=2)
p.add_argument('--resume', action='store_true')
a = p.parse_args()
if a.epochs < 1:
p.error('--epochs must be positive')
if a.resume and a.phase != 'train':
p.error('--resume is for training with saved epoch checkpoints')
a.out.mkdir(exist_ok=a.resume)
if a.phase == 'capture':
capture(a.source, a.input, a.out, a.schedule)
else:
train(a.source, a.input, a.out, a.epochs, a.resume)
if __name__ == '__main__':
main()
+115
View File
@@ -0,0 +1,115 @@
"""Compare one vs two recipients on the same task using full-vocabulary answers."""
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from torch.nn import functional as F
from crossqkv.lisa_tail import TorchTail, weight_chunks
from crossqkv.lisa_train import LearnableSharingAttention
from functional.model import PREFIX, StreamingLM
from functional.run import write_json
def vocabulary_scores(hidden, targets, embedding):
n = len(hidden)
peak = hidden.new_full((n,), -torch.inf)
total = peak.clone()
top = torch.zeros(n, dtype=torch.int64)
true = torch.zeros_like(peak)
start = 0
for w in weight_chunks(embedding, 0, embedding.shape[0], rows=1024):
logits = F.linear(hidden, w)
total = torch.logaddexp(total, logits.logsumexp(dim=-1))
values, indices = logits.max(dim=-1)
top = torch.where(values > peak, indices + start, top)
peak = torch.maximum(values, peak)
local = (targets >= start) & (targets < start + len(w))
true[local] = logits[local, targets[local]-start]
start += len(w)
return top, total-true
def run(source, cache, trained, out):
torch.set_num_threads(1)
spec = json.loads((cache/'selection.json').read_text())
sites = tuple(spec['sites'])
stream = StreamingLM(source/'weights', json.loads((source/'model_config.json').read_text()))
cfg = stream.config
rp = cfg['rope_parameters']
heads, kv = cfg['num_attention_heads'], cfg['num_key_value_heads']
def loaded(mode):
if mode == 'linear':
from torch import nn
modules = {site: nn.Linear(heads, heads, bias=False) for site in sites}
else:
modules = {site: LearnableSharingAttention(cfg['hidden_size'], heads, kv, 40,
rp['rope_theta'], rp['partial_rotary_factor'],
bias=cfg.get('attention_bias', False)) for site in sites}
tail = TorchTail(stream, sites[0], modules)
tail.adapters.load_state_dict(torch.load(trained/f'{mode}.pt', weights_only=True,
map_location='cpu'))
return tail
empty = TorchTail(stream, sites[0])
fitted = loaded('lisa')
arms = [('native', empty, 'native', ()),
('direct_23', empty, 'direct', (sites[-1],)),
('lisa_23_ablation', fitted, 'lisa', (sites[-1],))]
if len(sites) > 1:
arms.extend([('direct_chain', empty, 'direct', sites),
('lisa_chain', fitted, 'lisa', sites)])
arms.extend([('linear', loaded('linear'), 'linear', sites),
('lisa_answer_weighted', loaded('lisa_answer_weighted'), 'lisa', sites)])
answers = {name: [] for name, *_ in arms}
ids, labels, options = [], [], []
with torch.no_grad():
for path in sorted(cache.glob('test-*.npz')):
with np.load(path, allow_pickle=False) as f:
b = {k: torch.from_numpy(f[k]) for k in f.files if k != 'names'}
ids.extend(f['names'].tolist())
labels.append(b['labels'][b['gold']])
options.append(b['labels'].expand(len(b['gold']), -1))
for name, tail, mode, chosen in arms:
h, _ = tail(b['residual'], b['donor'], b['lengths'], mode, chosen)
answers[name].append(h[torch.arange(len(h)), b['lengths']-2])
print('matched full-vocabulary audit', len(ids), flush=True)
if not ids:
raise ValueError('No captured holdout batches')
y = torch.cat(labels)
t = stream.tensors[PREFIX+'embed_tokens.weight']
hidden = torch.cat([torch.cat(answers[k]) for k in answers])
pred, nll = vocabulary_scores(hidden, y.repeat(len(answers)), t)
result = {}
opts = torch.cat(options)
for (name, h), p, v in zip(answers.items(), pred.split(len(y)), nll.split(len(y))):
option_w = torch.stack([torch.from_numpy(t.read(slice(i*t.shape[1], (i+1)*t.shape[1])))
for i in opts[0].tolist()])
if not torch.equal(opts, opts[0].expand_as(opts)):
raise ValueError('Option token IDs unexpectedly vary across items')
t.evict()
choice = opts[torch.arange(len(y)), F.linear(torch.cat(h), option_w).argmax(-1)]
result[name] = {'n': len(y), 'full_vocab_correct': int((p==y).sum()),
'four_choice_correct': int((choice==y).sum()),
'full_vocab_nll': float(v.mean()),
'rows': [{'id': key, 'gold_id': int(g), 'greedy_id': int(j),
'choice_id': int(c), 'nll': float(s)}
for key, g, j, c, s in zip(ids, y, p, choice, v)]}
write_json(out, {'single_lisa_is_ablation_of_joint_checkpoint': len(sites) > 1,
'candidate_sites': list(sites), 'arms': result})
def main():
p = argparse.ArgumentParser(description=__doc__)
for name in ('source', 'cache', 'trained', 'out'):
p.add_argument('--'+name, type=Path, required=True)
a = p.parse_args()
run(a.source, a.cache, a.trained, a.out)
if __name__ == '__main__':
main()
+98
View File
@@ -0,0 +1,98 @@
"""Independently validate frozen test outputs and report paired capability recovery."""
import argparse
import hashlib
import json
import math
from pathlib import Path
from statistics import median
import numpy as np
from functional.run import write_json
MODES = ('native', 'direct', 'linear', 'lisa', 'lisa_answer_weighted')
def paired(native, direct, candidate):
damaged = native & ~direct
rescued = damaged & candidate
newly_lost = native & direct & ~candidate
candidate_only = ~direct & candidate
direct_only = direct & ~candidate
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())
k = a + b
p = min(1., 2. * sum(math.comb(k, i) for i in range(min(a, b)+1)) / 2**k)
return {'native_correct_lost_by_direct': int(damaged.sum()), 'rescued': int(rescued.sum()),
'newly_lost_among_native_and_direct_correct': int(newly_lost.sum()),
'candidate_correct_direct_wrong': a, 'direct_correct_candidate_wrong': b,
'accuracy_delta_vs_direct': float(delta.mean()),
'paired_prompt_bootstrap_95': ci.tolist(), 'mcnemar_exact_p': p}
def audit(fixed, selection, items, perf=None, decode=None):
spec = json.loads(selection.read_text())
if hashlib.sha256(fixed.read_bytes()).hexdigest() != spec['fixed_problems_sha256']:
raise ValueError('Fixed problems provenance mismatch')
problem = json.loads(fixed.read_text())
task = spec['task']
expected = [(r['id'], r['answer_index']) for r in problem['test'] if r['task'] == task]
data = json.loads(items.read_text())
if set(data) != set(MODES) or not expected:
raise ValueError('Unexpected test arms or empty selected split')
correct = {}
mean_losses = {}
for mode, rows in data.items():
if [(r['id'], r['gold']) for r in rows] != expected:
raise ValueError(f'{mode} result does not match the locked challenge')
logits = np.array([r['logits'] for r in rows])
gold = np.array([r['gold'] for r in rows])
pred = np.array([r['pred'] for r in rows])
nll = np.logaddexp.reduce(logits, 1) - logits[np.arange(len(rows)), gold]
if (logits.shape != (len(rows), 4) or not np.isfinite(logits).all()
or not np.array_equal(logits.argmax(1), pred)):
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)
correct[mode], mean_losses[mode] = pred == gold, float(nll.mean())
metrics = {'selected_task': task, 'sites': spec['sites'], 'n': len(expected),
'arms': {mode: {'correct': int(correct[mode].sum()), 'answer_nll_4': mean_losses[mode],
**paired(correct['native'], correct['direct'], correct[mode])}
for mode in MODES}}
if perf:
measured = json.loads(perf.read_text())
med = {k: median(v) for k,v in measured['seconds'].items()}
metrics['prefill'] = {'scope': measured['scope'], 'median_s': med,
'lisa_median_ratio_to_native': med['lisa']/med['native']}
if decode:
measured = json.loads(decode.read_text())
metrics['decode'] = {'scope': measured['scope'], 'sites': {}}
for layer, raw in measured['sites'].items():
times = {k: median(v) for k,v in raw['seconds_per_token'].items()}
mem = raw['allocated_bytes']
native = mem['native']['k'] + mem['native']['v']
lisa = mem['lisa']['k'] + mem['lisa']['v']
nn = raw['lisa_input_score_row_bytes']
assert mem['lisa']['v'] == mem['native']['v'] and mem['lisa']['k'] < mem['native']['k']
metrics['decode']['sites'][layer] = {
'median_s_per_token': times, 'measured_kv_bytes': {'native': native, 'lisa': lisa},
'lisa_upstream_score_row_bytes': nn, 'recipient_bytes_delta': lisa+nn-native,
}
return metrics
def main():
parser = argparse.ArgumentParser(description=__doc__)
for name in ('fixed', 'selection', 'items', 'out'):
parser.add_argument('--'+name, type=Path, required=True)
parser.add_argument('--perf', type=Path)
parser.add_argument('--decode', type=Path)
a = parser.parse_args()
report = audit(a.fixed, a.selection, a.items, a.perf, a.decode)
write_json(a.out, report)
if __name__ == '__main__':
main()
+183
View File
@@ -0,0 +1,183 @@
"""Screen task difficulty and joint sharing schedules without opening test results."""
import argparse
import json
import random
from pathlib import Path
import numpy as np
from tokenizers import Tokenizer
from crossqkv.core import QKVModel
from crossqkv.lisa_pilot import batch
from functional.model import PREFIX
from functional.run import write_json
from pilot.tensors import decode
MODES = ('native', 'direct_23', 'direct_19_23')
SITES = (15, 19, 23)
TASKS = ('lookup8', 'lookup16', 'latest8', 'arithmetic')
SPLIT_SEEDS = {'screen': 415001, 'fit': 415002, 'validation': 415003, 'test': 415004}
WORDS = ('amber birch cedar dune elm fern grove heath iris jade kelp larch '
'maple nettle olive pine quartz reed slate thyme umber vine willow yew').split()
def problems(split, per_task):
rng = random.Random(SPLIT_SEEDS[split])
rows = []
for task in TASKS:
answers = [i % 4 for i in range(per_task)]
rng.shuffle(answers)
for i, answer in enumerate(answers):
if task == 'arithmetic':
a, b = rng.sample(range(12, 99), 2)
target = a + b
distractors = [target - 10, target + 10, target + rng.choice((-1, 1))]
question = f'What is {a} + {b}?'
else:
size = 16 if task == 'lookup16' else 8
keys, vals = rng.sample(WORDS, size), rng.sample(range(10, 100), size)
if task == 'latest8':
first = rng.randrange(size - 1)
last = rng.randrange(first + 1, size)
keys[last] = keys[first]
target = vals[last]
remaining = [v for j, v in enumerate(vals) if j not in (first, last)]
distractors = [vals[first], *rng.sample(remaining, 2)]
key = keys[first]
else:
match = rng.randrange(size)
target, key = vals[match], keys[match]
distractors = rng.sample([v for v in vals if v != target], 3)
table = '\n'.join(f'{k}: {v}' for k, v in zip(keys, vals))
request = 'latest value' if task == 'latest8' else 'value'
order = ' (oldest first)' if task == 'latest8' else ''
question = f'Use the lookup table{order}.\n{table}\nWhich option is the {request} for {key}?'
rng.shuffle(distractors)
distractors.insert(answer, target)
options = '\n'.join(f'{j+1}. {v}' for j, v in enumerate(distractors))
prompt = f'{question}\n{options}\nAnswer with only the option number.\nAnswer:'
rows.append({'id': f'{split}-{task}-{i:03}', 'task': task,
'prompt': prompt, 'answer_index': answer})
return rows
class ScreeningModel(QKVModel):
def normalization(self, h, name):
if getattr(self, 'capture_prefix', False) and name == 'layers.19.input_layernorm':
self.residual_19 = h
return super().normalization(h, name)
def full_attention(self, h, layer, shared_p=None):
if layer not in SITES:
return super().full_attention(h, layer, shared_p)
own = self.parts(h, layer, heads=False)
p = own['p'].copy()
if getattr(self, 'capture_prefix', False):
if layer == 15:
self.donor_15 = p
return own['output'], p
if layer == 19:
p[self.chain] = self.prior[self.chain]
elif layer == 23:
p[self.shared] = self.prior[self.shared]
self.prior = p
repeats = self.config['num_attention_heads'] // self.config['num_key_value_heads']
v = np.repeat(own['v'], repeats, axis=2)
out = self.project(np.einsum('bhts,bshd->bthd', p, v), own['gate'], layer)
return out, p
def evaluate(model, tokenizer, examples):
ids, lengths, labels = batch(tokenizer, examples)
n = len(examples)
model.chain = slice(2*n, 3*n)
model.shared = slice(n, 3*n)
if not getattr(model, 'reuse_prefix', False):
h, _ = model.forward(np.tile(ids, (len(MODES), 1)))
else:
model.capture_prefix = True
native, _ = model.forward(ids)
model.capture_prefix = False
h = np.concatenate([model.residual_19] * len(MODES))
model.prior = np.concatenate([model.donor_15] * len(MODES))
for layer, kind in enumerate(model.config['layer_types'][19:], 19):
model.guard()
p = f'layers.{layer}.'
n_h = model.normalization(h, p+'input_layernorm')
out = (model.full_attention(n_h, layer)[0] if kind == 'full_attention'
else model.linear_attention(n_h, layer))
h = h + out
h = h + model.mlp(model.normalization(h, p+'post_attention_layernorm'), layer)
h = model.normalization(h, 'norm')
np.testing.assert_allclose(h[:n], native, atol=4e-5, rtol=3e-5)
t = model.tensors[PREFIX + 'embed_tokens.weight']
digit_weights = decode(t.raw.reshape(t.shape)[labels], t.dtype)
t.evict()
scores = [x[np.arange(n), np.asarray(lengths) - 1] @ digit_weights.T
for x in np.split(h, len(MODES))]
rows = []
for i, ex in enumerate(examples):
gold = ex['answer_index']
item = {'id': ex['id'], 'task': ex['task'], 'gold': gold, 'scores': {}}
for mode, logits in zip(MODES, scores):
values = logits[i].astype(float)
item['scores'][mode] = {'pred': int(values.argmax()), 'logits': values.tolist(),
'nll': float(np.logaddexp.reduce(values) - values[gold])}
rows.append(item)
return rows
def summarize(rows):
table = {}
for task in TASKS:
group = [r for r in rows if r['task'] == task]
if not group:
continue
table[task] = {}
for mode in MODES:
table[task][mode] = {
'n': len(group),
'correct': sum(r['scores'][mode]['pred'] == r['gold'] for r in group),
'native_wins_lost': sum(r['scores']['native']['pred'] == r['gold']
and r['scores'][mode]['pred'] != r['gold'] for r in group),
'nll': float(np.mean([r['scores'][mode]['nll'] for r in group])),
}
return table
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', required=True, type=Path)
parser.add_argument('--out', required=True, type=Path)
parser.add_argument('--resume', action='store_true', help='Keep completed batches')
parser.add_argument('--reuse-prefix', action='store_true', help='Run layers 0–18 once per input')
args = parser.parse_args()
args.out.mkdir(exist_ok=args.resume)
model = ScreeningModel(args.source/'weights',
json.loads((args.source/'model_config.json').read_text()), seconds=3600)
if any(model.config['layer_types'][ix] != 'full_attention' for ix in SITES):
raise ValueError('Scheduled layers must all have full attention')
model.reuse_prefix = args.reuse_prefix
tok = Tokenizer.from_file(str(args.source/'tokenizer.json'))
data = {split: problems(split, n) for split, n in
[('screen', 8), ('fit', 12), ('validation', 12), ('test', 32)]}
prompts = [r['prompt'] for xs in data.values() for r in xs]
if len(set(prompts)) != len(prompts):
raise ValueError('Prompt sets overlap')
manifest = args.out/'fixed-problems.json'
collected = args.out/'screen-rows.json'
if args.resume and manifest.exists() and json.loads(manifest.read_text()) != data:
raise ValueError('Fixed prompts changed')
write_json(manifest, data)
rows = json.loads(collected.read_text()) if args.resume and collected.exists() else []
if len(rows) % 4 or [r['id'] for r in rows] != [r['id'] for r in data['screen'][:len(rows)]]:
raise ValueError('Existing screen does not match the fixed prompt sequence')
for i in range(len(rows), len(data['screen']), 4):
rows.extend(evaluate(model, tok, data['screen'][i:i+4]))
write_json(args.out/'screen-rows.json', rows)
print('screen', len(rows), flush=True)
write_json(args.out/'screen-summary.json', summarize(rows))
if __name__ == '__main__':
main()
+173
View File
@@ -0,0 +1,173 @@
"""Differentiable Qwen text tail with streamed frozen weights and LiSA sites."""
import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.checkpoint import checkpoint
from crossqkv.lisa_train import causal_attention
from functional.model import PREFIX
def weight_chunks(tensor, start, end, rows=512):
width = tensor.shape[1]
for lo in range(start, end, rows):
hi = min(lo + rows, end)
yield torch.from_numpy(tensor.read(slice(lo * width, hi * width)).reshape(hi-lo, width))
tensor.evict()
class FrozenLinear(torch.autograd.Function):
"""Read only the requested output rows and stream them again for dX."""
@staticmethod
def forward(ctx, hidden, weight, start, end):
ctx.weight, ctx.start, ctx.end = weight, start, end
return torch.cat([F.linear(hidden, w) for w in weight_chunks(weight, start, end)], dim=-1)
@staticmethod
def backward(ctx, grad):
out = grad.new_zeros((*grad.shape[:-1], ctx.weight.shape[1]))
lo = 0
for w in weight_chunks(ctx.weight, ctx.start, ctx.end):
hi = lo + len(w)
out = out + grad[..., lo:hi] @ w
lo = hi
return out, None, None, None
def rotate(x, theta, fraction):
d = int(x.shape[-1] * fraction)
inv = theta ** (-torch.arange(0, d, 2, dtype=x.dtype, device=x.device) / d)
phase = torch.arange(x.shape[1], dtype=x.dtype, device=x.device)[:, None] * inv
angle = torch.cat((phase, phase), dim=-1)[None, :, None, :]
a, b = x[..., :d].chunk(2, dim=-1)
return torch.cat((x[..., :d] * angle.cos() + torch.cat((-b, a), -1) * angle.sin(),
x[..., d:]), dim=-1)
def gated_delta(q, k, v, g, beta):
q = q * (q.square().sum(-1, keepdim=True) + 1e-6).rsqrt() / math.sqrt(q.shape[-1])
k = k * (k.square().sum(-1, keepdim=True) + 1e-6).rsqrt()
state = v.new_zeros(v.shape[0], v.shape[2], k.shape[-1], v.shape[-1])
rows = []
for i in range(v.shape[1]):
qt, kt, vt = q[:, i], k[:, i], v[:, i]
state = state * g[:, i, :, None, None].exp()
delta = (vt - (state * kt.unsqueeze(-1)).sum(-2)) * beta[:, i, :, None]
state = state + kt.unsqueeze(-1) * delta.unsqueeze(-2)
rows.append((state * qt.unsqueeze(-1)).sum(-2))
return torch.stack(rows, dim=1)
class TorchTail(nn.Module):
"""Inputs start immediately before the first trainable recipient."""
def __init__(self, source_model, start, adapters=None):
super().__init__()
self.source = source_model
self.c = source_model.config
self.eps = source_model.eps
self.start = start
self.adapters = nn.ModuleDict({str(k): v for k, v in (adapters or {}).items()})
self._small = {}
def small(self, name):
if name not in self._small:
self._small[name] = torch.from_numpy(self.source.small(name))
return self._small[name]
def linear(self, h, name, start=0, end=None):
t = self.source.tensors[PREFIX + name + '.weight']
return FrozenLinear.apply(h, t, start, t.shape[0] if end is None else end)
def norm(self, x, name, centered=True):
w = self.small(name + '.weight')
return x * (x.square().mean(-1, keepdim=True) + self.eps).rsqrt() * (1+w if centered else w)
def gate_only(self, h, name):
heads, dim = self.c['num_attention_heads'], self.c['head_dim']
return torch.stack([self.linear(h, name+'q_proj', (2*j+1)*dim, (2*j+2)*dim)
for j in range(heads)], dim=2)
def native_scores(self, q, h, name):
c = self.c
k = self.linear(h, name+'k_proj').unflatten(-1, (c['num_key_value_heads'], c['head_dim']))
params = c['rope_parameters']
q = rotate(self.norm(q, name+'q_norm'), params['rope_theta'], params['partial_rotary_factor'])
k = rotate(self.norm(k, name+'k_norm'), params['rope_theta'], params['partial_rotary_factor'])
k = k.repeat_interleave(q.shape[2] // k.shape[2], dim=2)
return torch.einsum('bthd,bshd->bhts', q, k) / math.sqrt(q.shape[-1])
def full(self, h, layer, donor, lengths, mode, recipients, keep_teacher):
c = self.c
heads, kv_heads, dim = c['num_attention_heads'], c['num_key_value_heads'], c['head_dim']
name = f'layers.{layer}.self_attn.'
shared = layer in recipients and mode != 'native'
if not shared or keep_teacher:
packed = self.linear(h, name+'q_proj').unflatten(-1, (heads, 2*dim))
q, gate = packed.chunk(2, dim=-1)
if shared:
with torch.no_grad():
native = self.native_scores(q, h, name)
else:
native = self.native_scores(q, h, name)
else:
gate = self.gate_only(h, name)
native = None
if not shared:
scores = native
elif mode == 'direct':
scores = donor
elif mode == 'lisa':
pos = torch.arange(h.shape[1], device=h.device)[None, :]
scores = self.adapters[str(layer)](h, donor, pos)
elif mode == 'linear':
matrix = self.adapters[str(layer)]
scores = matrix(donor.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
else:
raise ValueError(f'Unknown mode {mode}')
v = self.linear(h, name+'v_proj').unflatten(-1, (kv_heads, dim))
out = causal_attention(scores, v, lengths) * gate.sigmoid()
return self.linear(out.flatten(-2), name+'o_proj'), scores, native
def linear_attention(self, x, layer):
p = f'layers.{layer}.linear_attn.'
c = self.c
kh, vh = c['linear_num_key_heads'], c['linear_num_value_heads']
kd, vd = c['linear_key_head_dim'], c['linear_value_head_dim']
projected = self.linear(x, p+'in_proj_qkv').transpose(1, 2)
kernel = self.small(p+'conv1d.weight')
convolved = F.conv1d(projected, kernel, padding=kernel.shape[-1]-1,
groups=projected.shape[1])[..., :x.shape[1]]
q, k, v = F.silu(convolved.transpose(1, 2)).split((kh*kd, kh*kd, vh*vd), dim=-1)
q = q.unflatten(-1, (kh, kd)).repeat_interleave(vh//kh, dim=2)
k = k.unflatten(-1, (kh, kd)).repeat_interleave(vh//kh, dim=2)
v = v.unflatten(-1, (vh, vd))
gate = self.linear(x, p+'in_proj_z').unflatten(-1, (vh, vd))
beta = self.linear(x, p+'in_proj_b').sigmoid()
a = self.linear(x, p+'in_proj_a')
g = -self.small(p+'A_log').exp() * F.softplus(a + self.small(p+'dt_bias'))
out = gated_delta(q, k, v, g, beta)
return self.linear((self.norm(out, p+'norm', centered=False)*F.silu(gate)).flatten(-2),
p+'out_proj')
def forward(self, h, donor, lengths, mode, recipients, keep_teacher=False):
side = {}
for layer, kind in enumerate(self.c['layer_types'][self.start:], self.start):
p = f'layers.{layer}.'
n = self.norm(h, p+'input_layernorm')
if kind == 'full_attention':
out, donor, native = self.full(n, layer, donor, lengths, mode, recipients,
keep_teacher)
side[layer] = (donor, native)
elif torch.is_grad_enabled() and n.requires_grad:
out = checkpoint(self.linear_attention, n, layer, use_reentrant=True)
else:
out = self.linear_attention(n, layer)
h = h + out
n = self.norm(h, p+'post_attention_layernorm')
x = F.silu(self.linear(n, p+'mlp.gate_proj')) * self.linear(n, p+'mlp.up_proj')
h = h + self.linear(x, p+'mlp.down_proj')
return self.norm(h, 'norm'), side
+9 -7
View File
@@ -90,7 +90,7 @@ class _FrozenVocabularyCE(torch.autograd.Function):
"""Exact full-vocabulary CE with a streamed frozen head in both passes."""
@staticmethod
def forward(ctx, hidden, targets, vocabulary):
def forward(ctx, hidden, targets, weights, vocabulary):
log_total = hidden.new_full((hidden.shape[0],), -torch.inf)
selected = hidden.new_zeros(hidden.shape[0])
for start, w in vocabulary():
@@ -98,24 +98,26 @@ class _FrozenVocabularyCE(torch.autograd.Function):
log_total = torch.logaddexp(log_total, logits.logsumexp(dim=-1))
belongs = (targets >= start) & (targets < start + w.shape[0])
selected[belongs] = logits[belongs, targets[belongs] - start]
ctx.save_for_backward(hidden, targets, log_total)
ctx.save_for_backward(hidden, targets, log_total, weights)
ctx.vocabulary = vocabulary
return (log_total - selected).mean()
return ((log_total - selected) * weights).sum() / weights.sum()
@staticmethod
def backward(ctx, gradient):
hidden, targets, log_total = ctx.saved_tensors
hidden, targets, log_total, weights = ctx.saved_tensors
grad_hidden = torch.zeros_like(hidden)
for start, w in ctx.vocabulary():
probs = (F.linear(hidden, w) - log_total[:, None]).exp()
belongs = (targets >= start) & (targets < start + w.shape[0])
probs[belongs, targets[belongs] - start] -= 1
grad_hidden.addmm_(probs, w)
return grad_hidden * (gradient / hidden.shape[0]), None, None
return grad_hidden * (gradient * weights[:, None] / weights.sum()), None, None, None
def language_model_loss(hidden, ids, lengths, vocabulary):
def language_model_loss(hidden, ids, lengths, vocabulary, answer_weight=1.0):
"""Train on all valid next-token targets, avoiding padding and final positions."""
positions = torch.arange(ids.shape[1] - 1, device=ids.device)
valid = positions[None, :] + 1 < lengths[:, None]
return _FrozenVocabularyCE.apply(hidden[:, :-1][valid], ids[:, 1:][valid], vocabulary)
weights = torch.where(positions[None, :] + 2 == lengths[:, None], answer_weight, 1.0)
return _FrozenVocabularyCE.apply(hidden[:, :-1][valid], ids[:, 1:][valid],
weights[valid].to(dtype=hidden.dtype), vocabulary)