"""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()