Files
leleka/scripts/prepare-keyless-routing.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

186 lines
9.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Derive Keyless query routing from actual GGUF projections (charter G7).
Implements the paper's projection into the value column space. The artifact
contains query-routing matrices, never predictions of cached K activations.
This linear initialization is not a model quality gate: the existing model's
Q/K RMS normalization and positional encoding need a separate retrofit fit.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import struct
import subprocess
import tempfile
import numpy as np
REPO = Path(__file__).resolve().parent.parent
MAGIC = b"SKLROUT1"
PAPER = "https://arxiv.org/html/2606.21848v1"
def query_routing(wq, wk, wv, rcond=1e-10):
"""Row-major projections: q=x Wq.T; q_keyless=q A; A Wv≈Wk.
Wq contains one query head, Wk/Wv its associated GQA value head.
A = Wk Wv.T pinv(Wv Wv.T), the factorized paper's effective Wq.
The score residual is computed without allocating hidden×hidden Ω.
"""
wq, wk, wv = (np.asarray(w, dtype=np.float64) for w in (wq, wk, wv))
if wq.ndim != 2 or wk.shape != wv.shape or wq.shape[1] != wk.shape[1]:
raise ValueError("inconsistent Q/K/V projection dimensions")
if wq.shape[0] != wk.shape[0] or not all(np.isfinite(w).all() for w in (wq, wk, wv)):
raise ValueError("nonfinite projections or inconsistent head width")
gram = wv @ wv.T
eig, vec = np.linalg.eigh(gram)
threshold = max(float(eig[-1]), 0.0) * rcond
live = eig > threshold
if not np.any(live):
raise ValueError("value projection has zero usable rank")
inverse = (vec[:, live] / eig[live]) @ vec[:, live].T
route = (wk @ wv.T) @ inverse
residual = wk - route @ wv
qgram = wq @ wq.T
reference_sq = float(np.sum(qgram * (wk @ wk.T)))
error_sq = max(0.0, float(np.sum(qgram * (residual @ residual.T))))
return route, {
"value_rank": int(np.sum(live)),
"head_dim": len(eig),
"value_gram_condition": float(eig[-1] / eig[live][0]),
"score_weight_relative_l2": float(np.sqrt(error_sq / reference_sq)) if reference_sq > 0 else None,
"key_subspace_relative_l2": float(np.linalg.norm(residual) / np.linalg.norm(wk)) if np.any(wk) else 0.0,
}
def load_tensor(binary, shard, name, root):
output = root / (name + ".f32")
run = subprocess.run([str(binary), "model", "export-tensor-f32", str(shard), name,
"--output", str(output)], capture_output=True, text=True)
if run.returncode:
raise RuntimeError(f"native projection export failed for {name}: {run.stderr[-1000:]}")
meta = json.loads(run.stdout)
dimensions = meta["dimensions"]
data = np.fromfile(output, dtype="<f4")
if data.size != int(np.prod(dimensions)) or not np.isfinite(data).all():
raise ValueError(f"invalid decoded projection: {name}")
if hashlib.sha256(output.read_bytes()).hexdigest() != meta["f32_sha256"]:
raise ValueError(f"export digest mismatch: {name}")
output.unlink()
# GGUF dimension zero is contiguous: [input, output] -> rows [output,input].
return data.reshape(tuple(reversed(dimensions))), meta
def prepare(args):
shards = [p.resolve(strict=True) for p in args.shard]
manifest = json.loads(args.manifest.read_text())
identities = manifest["files"]
entries = {Path(e.get("name", e.get("filename", ""))).name: e for e in identities}
if len(entries) != len(identities):
raise ValueError("manifest has duplicate or missing shard names")
if set(p.name for p in shards) != set(entries):
raise ValueError("provide exactly the manifest's verified source shards")
for p in shards:
if p.stat().st_size != entries[p.name]["size"]:
raise ValueError(f"source shard size mismatch: {p.name}")
if len(entries[p.name]["sha256"]) != 64:
raise ValueError("manifest must supply each verified model digest")
output = args.output.resolve()
if REPO == output or REPO in output.parents:
raise ValueError("routing weights must remain outside Git")
if output.exists() or Path(str(output) + ".json").exists():
raise ValueError("refusing to overwrite a routing artifact")
# Header readers inspect metadata; export uses the pinned native GGUF decoder.
import sys
sys.path.insert(0, str(REPO / "engine/strata/tools"))
from gguf_reader import GGUFFile
locations = {}
for shard in shards:
for tensor in GGUFFile(shard).tensors:
if tensor.name in locations:
raise ValueError(f"duplicate tensor across shards: {tensor.name}")
locations[tensor.name] = shard
layers = sorted({int(name.split(".")[1]) for name in locations
if name.startswith("blk.") and name.endswith(".attn_k.weight")})
if len(layers) != args.layers:
raise ValueError(f"expected {args.layers} QSA layers, found {len(layers)}")
output.parent.mkdir(parents=True, exist_ok=True)
old_mask = os.umask(0o077)
try:
with tempfile.TemporaryDirectory(prefix="query-route-", dir=output.parent) as tmp:
records, weights = [], []
for layer in layers:
row, tensors = {"layer": layer, "heads": []}, {}
for role in ("q", "k", "v", "q_norm", "k_norm"):
name = f"blk.{layer}.attn_{role}.weight"
if name not in locations:
raise ValueError(f"missing QSA tensor {name}")
tensors[role], row[role] = load_tensor(args.binary, locations[name], name, Path(tmp))
q, k, v = (tensors[role] for role in ("q", "k", "v"))
if q.shape != (args.heads * 2 * args.head_dim, k.shape[1]):
raise ValueError("expected Qwen interleaved per-head query/gate projection")
if k.shape != (args.kv_heads * args.head_dim, q.shape[1]) or v.shape != k.shape:
raise ValueError("unexpected GQA projection geometry")
q = q.reshape(args.heads, 2, args.head_dim, -1)[:, 0]
k = k.reshape(args.kv_heads, args.head_dim, -1)
v = v.reshape(args.kv_heads, args.head_dim, -1)
matrices = []
for head in range(args.heads):
kv_head = head // (args.heads // args.kv_heads)
route, metrics = query_routing(q[head], k[kv_head], v[kv_head], args.rcond)
row["heads"].append({"head": head, "kv_head": kv_head, **metrics})
matrices.append(route.T.astype("<f4"))
weights.append((layer, np.stack(matrices)))
records.append(row)
print(json.dumps({"layer": layer, "max_score_weight_relative_l2": max(
h["score_weight_relative_l2"] or 0 for h in row["heads"])}), flush=True)
with output.open("xb") as stream:
stream.write(struct.pack("<8s4I", MAGIC, 1, len(layers), args.heads, args.head_dim))
for layer, matrices in weights:
stream.write(struct.pack("<I", layer))
record = next(r for r in records if r["layer"] == layer)
for role in ("q", "k", "v"):
meta = record[role]
stream.write(struct.pack("<IQQ", meta["source_kind"], meta["source_bytes"],
int(meta["source_fnv1a64"], 16)))
stream.write(matrices.tobytes())
report = {"schema": 1, "method": "keyless-query-routing-linear-initialization",
"source": PAPER, "model_files": identities,
"source_identity": "previously verified manifest; size checked, full shards not rehashed",
"routing_sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
"pipeline": "unrotated query -> per-head routing -> RoPE; score against RoPE(V), retrieve raw V",
"normalization": "linear weight-space initialization only; source Q/K RMS norms recorded but not folded",
"quality_gate": "not_run", "experimental": True,
"rcond": args.rcond, "layers": records}
with Path(str(output) + ".json").open("x") as stream:
json.dump(report, stream, indent=2, allow_nan=False)
stream.write("\n")
finally:
os.umask(old_mask)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--binary", type=Path, required=True)
p.add_argument("--shard", type=Path, action="append", required=True)
p.add_argument("--manifest", type=Path, required=True)
p.add_argument("--output", type=Path, required=True)
p.add_argument("--layers", type=int, default=12)
p.add_argument("--heads", type=int, default=24)
p.add_argument("--kv-heads", type=int, default=2)
p.add_argument("--head-dim", type=int, default=256)
p.add_argument("--rcond", type=float, default=1e-10)
args = p.parse_args()
if min(args.layers, args.heads, args.kv_heads, args.head_dim) < 1 or args.heads % args.kv_heads:
p.error("invalid layer/head geometry")
if not 0 < args.rcond < 1:
p.error("rcond must lie strictly between zero and one")
prepare(args)
if __name__ == "__main__":
main()