Screen position-aware V-only attention reconstruction

This commit is contained in:
Pavlo Ratushnyi
2026-10-03 19:20:17 +02:00
parent 36e512af91
commit 47023abd3b
2 changed files with 88 additions and 13 deletions
+21 -5
View File
@@ -58,12 +58,28 @@ Across 13,248 head/query comparisons, the results were:
| --- | ---: | ---: | ---: |
| Copy V | 5.87% | 27.51% | 0.3680 |
| Learned 2×2 V→K | 8.07% | 31.19% | 0.3555 |
| Position-aware 2×2 V→K | 10.74% | 35.21% | 0.3479 |
| Position-aware ridge V→K | 26.77% | 55.02% | 0.3023 |
These large proxy errors make this specific cheap V-only transform unsuitable
for a full-model quality gate. They do not prove that every possible keyless
transform fails. In particular, a position-aware or indexer-assisted
`Wq_keyless` has not been trained or tested. No V-only memory or runtime speed
was measured.
The third candidate removes the model's default, unscaled NeoX RoPE
(64 rotated dimensions, base 10 million) from calibration K before fitting
the same per-pair map, then applies RoPE at each held-out position to the
predicted K. It used the same 57 calibration and 51 independent held-out
verifier windows, and the same 13,248 attention comparisons. The new result
was reproduced by `scripts/kv-keyless-attention.py --rope-base 10000000`.
The fourth candidate fits a full per-layer, per-head linear V→unrotated-K map
with ridge regularization. Ridge strength was chosen solely within the
calibration trace using a chronological training/validation split, then
refitted on all 57 calibration windows. No held-out rows selected its
strength. It improved this limited attention proxy, but a 30.2% relative
attention-output error and 26.8% best-key agreement remain far from a
demonstrated quality pass.
These large proxy errors make the tested V-only transforms unsuitable for
enabling a physical V-only cache now. They do not prove that every possible
keyless transform fails. A larger, more diverse calibration set and an
indexer-assisted `Wq_keyless` have not been tested. No V-only memory or
runtime speed was measured.
The maximum **theoretical** saving from deleting INT8 K codes and scales in
the current QSA layout is 528 bytes per token per QSA layer: 198 MiB of
+67 -8
View File
@@ -1,10 +1,10 @@
#!/usr/bin/env python3
"""Screen V-only attention on real verifier activations, outside serving.
Fit one tiny V-to-K map per QSA layer/head on a calibration trace, then
compare attention over held-out generated-token positions. This uses only the
captured subset of keys, not the model's complete sparse selection, so it is
not a full-model quality gate.
Fit pairwise and position-aware ridge V-to-K maps on a calibration trace,
then compare attention over held-out generated-token positions. This uses
only the captured subset of keys, not the model's complete sparse selection,
so it is not a full-model quality gate.
"""
import argparse
@@ -20,6 +20,7 @@ N_HEAD = 24
N_KV_HEAD = 2
HEAD_DIM = 256
WIDTH = N_KV_HEAD * HEAD_DIM
N_ROT = 64
def read_kv(path):
@@ -85,17 +86,69 @@ def approximate(values, coeff):
return out
def rotate_neox(keys, positions, rope_base, inverse=False):
"""Apply the default unscaled NeoX RoPE to the first 64 K dimensions."""
result = keys.copy()
pos = np.asarray(positions, dtype=np.float64).reshape(-1, 1, 1, 1)
pair = np.arange(N_ROT // 2, dtype=np.float64).reshape(1, 1, 1, -1)
angle = pos * np.power(rope_base, -2 * pair / N_ROT)
c, s = np.cos(angle), np.sin(angle)
if inverse:
s = -s
a = keys[..., :N_ROT // 2]
b = keys[..., N_ROT // 2:N_ROT]
result[..., :N_ROT // 2] = a * c - b * s
result[..., N_ROT // 2:N_ROT] = a * s + b * c
return result
def fit_position_aware_ridge(train_v, train_k_raw, held_out_v):
"""Fit a per-head full V→unrotated-K map with train-only ridge selection."""
out = np.empty_like(held_out_v)
chosen = {}
fractions = (0.001, 0.01, 0.1, 1.0, 10.0)
def predict(x, y, z, strength):
x_mean, y_mean = x.mean(axis=0), y.mean(axis=0)
xc, yc, zc = x - x_mean, y - y_mean, z - x_mean
gram = xc @ xc.T
ridge = strength * max(float(np.trace(gram) / len(x)), 1e-12)
return y_mean + (zc @ xc.T) @ np.linalg.solve(
gram + ridge * np.eye(len(x)), yc)
split = max(8, min(len(train_v) - 8, int(len(train_v) * 0.8)))
for layer in range(N_QSA):
for head in range(N_KV_HEAD):
x = train_v[:, layer, head]
y = train_k_raw[:, layer, head]
validation = [
(float(np.mean((predict(x[:split], y[:split], x[split:], strength) - y[split:]) ** 2)),
strength)
for strength in fractions
]
strength = min(validation)[1]
chosen[str(strength)] = chosen.get(str(strength), 0) + 1
out[:, layer, head] = predict(x, y, held_out_v[:, layer, head], strength)
return out, chosen
def softmax(scores):
e = np.exp(scores - np.max(scores))
return e / np.sum(e)
def analyze(calibration, held_out):
train_k, train_v, _, _ = read_kv(calibration)
def analyze(calibration, held_out, rope_base=1e7):
train_k, train_v, train_positions, _ = read_kv(calibration)
k, v, positions, counts = read_kv(held_out)
q = read_queries(held_out, positions, counts)
fitted = approximate(v, fit_pairs(train_v, train_k))
proxies = {'copy_v': v, 'pair_map': fitted}
unrotated = rotate_neox(train_k, train_positions, rope_base, inverse=True)
position_aware = approximate(v, fit_pairs(train_v, unrotated))
position_aware = rotate_neox(position_aware, positions, rope_base)
ridge_raw, chosen = fit_position_aware_ridge(train_v, unrotated, v)
ridge = rotate_neox(ridge_raw, positions, rope_base)
proxies = {'copy_v': v, 'pair_map': fitted, 'position_aware_pair_map': position_aware,
'position_aware_ridge': ridge}
sums = {name: {'top1': 0, 'top5_overlap': 0.0, 'output_error_sq': 0.0,
'output_reference_sq': 0.0} for name in proxies}
comparisons = 0
@@ -125,6 +178,8 @@ def analyze(calibration, held_out):
'attention_output_relative_l2': (data['output_error_sq'] / data['output_reference_sq']) ** 0.5}
for name, data in sums.items()}
return {'calibration_windows': len(train_k), 'held_out_windows': len(k),
'rope_base': rope_base,
'ridge_strength_counts': chosen,
'comparisons': comparisons, 'summary': summary,
'scope': 'subset of recorded generated-token keys only; not complete selected attention or model output'}
@@ -134,8 +189,12 @@ def main():
parser.add_argument('calibration', type=Path)
parser.add_argument('held_out', type=Path)
parser.add_argument('--output', type=Path)
parser.add_argument('--rope-base', type=float, default=1e7,
help='unscaled NeoX RoPE frequency base used by this model')
args = parser.parse_args()
result = analyze(args.calibration, args.held_out)
if not np.isfinite(args.rope_base) or args.rope_base <= 1:
parser.error('--rope-base must be finite and above 1')
result = analyze(args.calibration, args.held_out, args.rope_base)
encoded = json.dumps(result, indent=2) + '\n'
if args.output:
args.output.write_text(encoded)