Files
leleka/scripts/kv-keyless-feasibility.py
T
Pavlo Ratushnyi 4013e0c9bd
Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
Import tracked Strata Next source snapshot
2026-10-05 18:15:08 +02:00

155 lines
7.3 KiB
Python

#!/usr/bin/env python3
"""Offline screen for a V-only QSA cache from private verifier or half traces.
This does not change serving. It tests whether a tiny per-pair linear map from
stored V to the post-RoPE K resembles held-out K activations. The actual
Wq_keyless path and full-model quality gate remain separate work.
"""
import argparse
import json
from pathlib import Path
import struct
import numpy as np
N_LAYERS = 48
N_EMBD = 2560
HC = 4
N_HEAD = 24
N_KV_HEAD = 2
HEAD_DIM = 256
NKV = N_KV_HEAD * HEAD_DIM
STRIDE = 2 * N_EMBD + 2 * HC + N_HEAD * HEAD_DIM + 5 * NKV + 8
BASE = 2 * N_EMBD + 2 * HC + N_HEAD * HEAD_DIM + 2 * NKV + 8
V_OFFSET = BASE + NKV
K_OFFSET = BASE + 2 * NKV
def fit_pair_map(v_train, k_train):
# Shape: tokens x 128 pairs x 2 values. Fit independent 2x2 affine maps.
ones = np.ones((*v_train.shape[:2], 1), dtype=np.float64)
design = np.concatenate((v_train, ones), axis=2)
gram = np.einsum('tpd,tpe->pde', design, design)
rhs = np.einsum('tpd,tpe->pde', design, k_train)
ridge = 1e-4 * np.maximum(np.trace(gram, axis1=1, axis2=2) / 3, 1e-12)
gram += ridge[:, None, None] * np.eye(3)
return np.linalg.solve(gram, rhs)
def relative_l2(predicted, target):
return float(np.linalg.norm(predicted - target) / np.linalg.norm(target))
def load_verify(path):
# Debug verifier format: u32 T, i64 pos0, then 12 * T * (K512, V512) f32.
# Only row 0 of each window is unambiguously part of the accepted context;
# later rows can be speculative drafts and are excluded from this screen.
records = []
with path.open('rb') as source:
while header := source.read(12):
if len(header) != 12:
raise ValueError('truncated verifier trace header')
count, _pos0 = struct.unpack('<Iq', header)
if not 1 <= count <= 8:
raise ValueError(f'invalid verifier window width {count}')
payload = source.read(12 * count * 2 * NKV * 4)
if len(payload) != 12 * count * 2 * NKV * 4:
raise ValueError('truncated verifier trace payload')
values = np.frombuffer(payload, dtype='<f4').reshape(12, count, 2, NKV)
records.append(values[:, 0].copy())
if not records:
raise ValueError('empty verifier trace')
return np.stack(records) # windows x 12 QSA layers x (K,V) x 512
def analyze(path, train_fraction, trace_format, held_out_path=None):
size = path.stat().st_size
if trace_format == 'verify':
trace = load_verify(path)
samples = len(trace)
else:
record_bytes = N_LAYERS * STRIDE * 4
if not size or size % record_bytes:
raise ValueError(f'dump size {size} is not a whole number of {record_bytes}-byte records')
samples = size // record_bytes
trace = np.memmap(path, dtype='<f4', mode='r', shape=(samples, N_LAYERS, STRIDE))
held_out = None
if held_out_path is not None:
if trace_format != 'verify':
raise ValueError('independent held-out traces currently require --format verify')
held_out = load_verify(held_out_path)
train = samples if held_out is not None else int(samples * train_fraction)
test_count = len(held_out) if held_out is not None else samples - train
if train < 16 or test_count < 8:
raise ValueError('need at least 16 training and 8 held-out token records')
rows = []
total = {'k_sq': 0.0, 'copy_err_sq': 0.0, 'mean_err_sq': 0.0, 'pair_err_sq': 0.0}
for layer in range(3, N_LAYERS, 4):
if trace_format == 'verify':
k = trace[:, layer // 4, 0].reshape(samples, N_KV_HEAD, HEAD_DIM)
v = trace[:, layer // 4, 1].reshape(samples, N_KV_HEAD, HEAD_DIM)
if held_out is not None:
test_k = held_out[:, layer // 4, 0].reshape(test_count, N_KV_HEAD, HEAD_DIM)
test_v = held_out[:, layer // 4, 1].reshape(test_count, N_KV_HEAD, HEAD_DIM)
else:
v = np.asarray(trace[:, layer, V_OFFSET:V_OFFSET + NKV]).reshape(samples, N_KV_HEAD, HEAD_DIM)
k = np.asarray(trace[:, layer, K_OFFSET:K_OFFSET + NKV]).reshape(samples, N_KV_HEAD, HEAD_DIM)
if not np.isfinite(v).all() or not np.isfinite(k).all() or (held_out is not None and
(not np.isfinite(test_v).all() or not np.isfinite(test_k).all())):
raise ValueError(f'non-finite K/V activation at layer {layer}')
for head in range(N_KV_HEAD):
source = v[:, head].astype(np.float64)
target = k[:, head].astype(np.float64)
v_train = source[:train].reshape(train, 128, 2)
k_train = target[:train].reshape(train, 128, 2)
coeff = fit_pair_map(v_train, k_train)
test_source = test_v[:, head].astype(np.float64) if held_out is not None else source[train:]
k_test = test_k[:, head].astype(np.float64) if held_out is not None else target[train:]
v_test = test_source.reshape(test_count, 128, 2)
design = np.concatenate((v_test, np.ones((*v_test.shape[:2], 1))), axis=2)
pair = np.einsum('tpd,pde->tpe', design, coeff).reshape(-1, HEAD_DIM)
mean = np.broadcast_to(target[:train].mean(axis=0), k_test.shape)
values = {'layer': layer, 'head': head,
'k_rms': float(np.sqrt(np.mean(k_test ** 2))),
'v_rms': float(np.sqrt(np.mean(test_source ** 2))),
'copy_relative_l2': relative_l2(test_source, k_test),
'mean_relative_l2': relative_l2(mean, k_test),
'pair_map_relative_l2': relative_l2(pair, k_test)}
rows.append(values)
total['k_sq'] += float(np.sum(k_test ** 2))
total['copy_err_sq'] += float(np.sum((test_source - k_test) ** 2))
total['mean_err_sq'] += float(np.sum((mean - k_test) ** 2))
total['pair_err_sq'] += float(np.sum((pair - k_test) ** 2))
summary = {name.removesuffix('_err_sq') + '_relative_l2':
(value / total['k_sq']) ** 0.5
for name, value in total.items() if name != 'k_sq'}
return {'samples': samples, 'train_samples': train, 'held_out_samples': test_count,
'trace_format': trace_format,
'independent_held_out': held_out_path is not None,
'trace_bytes': size, 'summary': summary, 'layers': rows,
'scope': 'offline held-out K reconstruction, first token of each verifier window; no inference quality or memory claim'}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('dump', type=Path)
parser.add_argument('--format', choices=('verify', 'halves'), default='verify')
parser.add_argument('--train-fraction', type=float, default=0.6)
parser.add_argument('--held-out', type=Path,
help='independent verifier trace; train on every window of the first trace')
parser.add_argument('--output', type=Path)
args = parser.parse_args()
if not 0.1 <= args.train_fraction <= 0.9:
parser.error('--train-fraction must be 0.1..0.9')
result = analyze(args.dump, args.train_fraction, args.format, args.held_out)
encoded = json.dumps(result, indent=2) + '\n'
if args.output:
args.output.write_text(encoded)
print(json.dumps({k: result[k] for k in ('samples', 'train_samples', 'held_out_samples', 'summary', 'scope')}))
if __name__ == '__main__':
main()