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
179 lines
8.7 KiB
Python
179 lines
8.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Offline frozen-Qwen query-routing distillation, with separate teacher holdout.
|
|
|
|
Trains only A in q'=q A. It does not synthesize cached keys. Targets are
|
|
causal attention distributions from the ordinary normalized, RoPE Q/K path.
|
|
All captures and generated routing weights must stay outside the repository.
|
|
"""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import struct
|
|
import numpy as np
|
|
|
|
|
|
def read_trace(path):
|
|
layers = {}
|
|
with path.open('rb') as f:
|
|
if f.read(8) != b'SKLTRACE':
|
|
raise ValueError('invalid teacher capture')
|
|
version, count, heads, kv, dim = struct.unpack('<5I', f.read(20))
|
|
if (version, count, heads, kv, dim) != (1, 12, 24, 2, 256):
|
|
raise ValueError('unsupported teacher geometry')
|
|
while header := f.read(12):
|
|
layer, pos, tokens = struct.unpack('<3i', header)
|
|
if not 0 <= pos <= 4096 or not 0 < tokens <= 4096 or pos + tokens > 4096:
|
|
raise ValueError('teacher extent exceeds offline bound')
|
|
arrays = []
|
|
for h in (heads, kv, kv):
|
|
raw = f.read(tokens*h*dim*4)
|
|
array = np.frombuffer(raw, dtype='<f4')
|
|
if array.size != tokens*h*dim or not np.isfinite(array).all():
|
|
raise ValueError('truncated/nonfinite teacher activations')
|
|
arrays.append(array.reshape(tokens, h, dim))
|
|
layers.setdefault(layer, []).append((pos, arrays))
|
|
result = {}
|
|
for layer, chunks in layers.items():
|
|
chunks.sort(key=lambda c: c[0])
|
|
expected = 0
|
|
for pos, arrays in chunks:
|
|
if pos != expected:
|
|
raise ValueError('noncontiguous teacher positions')
|
|
expected += len(arrays[0])
|
|
result[layer] = [np.concatenate([c[1][i] for c in chunks]) for i in range(3)]
|
|
if len(result) != count:
|
|
raise ValueError('missing QSA teacher layer')
|
|
return result
|
|
|
|
|
|
def rotate(x, positions, inverse=False):
|
|
"""NeoX partial RoPE, last axis 256, positions matching the token axis."""
|
|
angle = np.asarray(positions)[:, None] * np.power(1e7, -2*np.arange(32)/64)
|
|
co, si = np.cos(angle).astype('f4'), np.sin(angle).astype('f4')
|
|
if inverse:
|
|
si = -si
|
|
y = x.copy()
|
|
a, b = x[..., :32], x[..., 32:64]
|
|
y[..., :32] = a*co - b*si
|
|
y[..., 32:64] = a*si + b*co
|
|
return y
|
|
|
|
|
|
def softmax(scores, mask):
|
|
scores = np.where(mask, scores, -1e30)
|
|
weights = np.exp(scores - scores.max(axis=-1, keepdims=True))
|
|
return weights / weights.sum(axis=-1, keepdims=True)
|
|
|
|
|
|
def dataset(arrays, seed, queries=128, keys=512):
|
|
q, k, v = arrays
|
|
if len(q) <= 32:
|
|
raise ValueError('teacher prompt must contain more than 32 positions')
|
|
rng = np.random.default_rng(seed)
|
|
qp = np.sort(rng.choice(np.arange(min(32,len(q)-1),len(q)), min(queries,len(q)-32), replace=False))
|
|
kp = np.unique(np.r_[0, rng.choice(len(k), min(keys,len(k)), replace=False)])
|
|
heads = np.arange(24)//12
|
|
qn = q[qp].transpose(1,0,2).copy()
|
|
vr = rotate(v[kp][:,heads].transpose(1,0,2), kp)
|
|
raw_v = v[kp][:,heads].transpose(1,0,2).copy()
|
|
teacher = rotate(qn, qp) @ k[kp][:,heads].transpose(1,2,0) / 16
|
|
mask = (kp[None,:] <= qp[:,None])[None,:,:]
|
|
target = softmax(teacher, mask)
|
|
return qn, qp, vr, raw_v, mask, teacher, target
|
|
|
|
|
|
def evaluate(matrix, data):
|
|
q, qp, v, raw_v, mask, teacher, target = data
|
|
logits = rotate(q @ matrix.transpose(0,2,1), qp) @ v.transpose(0,2,1) / 16
|
|
probabilities = softmax(logits, mask)
|
|
kl = np.sum(target * (np.log(np.maximum(target,1e-30)) - np.log(np.maximum(probabilities,1e-30))), axis=-1)
|
|
reference, actual = target @ raw_v, probabilities @ raw_v
|
|
rel = np.linalg.norm(actual-reference, axis=(1,2))/np.maximum(np.linalg.norm(reference,axis=(1,2)),1e-20)
|
|
return {'mean_attention_kl': float(kl.mean()), 'max_head_attention_kl': float(kl.mean(axis=1).max()),
|
|
'mean_head_output_relative_l2': float(rel.mean()), 'max_head_output_relative_l2': float(rel.max())}
|
|
|
|
|
|
def objective_gradient(matrix, data):
|
|
q, qp, v, raw_v, mask, teacher, target = data
|
|
logits = rotate(q @ matrix.transpose(0,2,1), qp) @ v.transpose(0,2,1) / 16
|
|
probabilities = softmax(logits, mask)
|
|
# Per-head objective; heads are independent parameter sets.
|
|
loss = np.sum(target*(np.log(np.maximum(target,1e-30))-np.log(np.maximum(probabilities,1e-30))),axis=-1).mean(axis=-1)
|
|
dlogits = (probabilities-target) / len(qp)
|
|
dq = rotate(dlogits @ v / 16, qp, inverse=True)
|
|
return loss, dq.transpose(0,2,1) @ q
|
|
|
|
|
|
def fit(matrix, data, steps, rate):
|
|
q, qp, v, raw_v, mask, teacher, target = data
|
|
initial = rotate(q @ matrix.transpose(0,2,1), qp) @ v.transpose(0,2,1) / 16
|
|
# A least-squares scalar fixes the K-RMS/raw-V scale mismatch before distillation.
|
|
alpha = np.sum(np.where(mask, initial*teacher,0),axis=(1,2))/np.maximum(np.sum(np.where(mask, initial**2,0),axis=(1,2)),1e-20)
|
|
matrix = matrix * alpha[:,None,None]
|
|
first, second = np.zeros_like(matrix), np.zeros_like(matrix)
|
|
for step in range(1,steps+1):
|
|
_, gradient = objective_gradient(matrix, data)
|
|
first = .9*first + .1*gradient
|
|
second = .999*second + .001*gradient**2
|
|
matrix -= rate*(first/(1-.9**step))/(np.sqrt(second/(1-.999**step))+1e-8)
|
|
if not np.isfinite(matrix).all():
|
|
raise ValueError('nonfinite fitted query route')
|
|
return matrix
|
|
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser(description=__doc__)
|
|
for name in ('initial','train','holdout','output'):
|
|
parser.add_argument('--'+name,type=Path,required=True)
|
|
parser.add_argument('--steps',type=int,default=200)
|
|
parser.add_argument('--queries',type=int,default=1024)
|
|
parser.add_argument('--keys',type=int,default=512)
|
|
parser.add_argument('--learning-rate',type=float,default=.003)
|
|
args=parser.parse_args()
|
|
if args.train.resolve()==args.holdout.resolve():
|
|
parser.error('holdout must be a separate teacher prompt')
|
|
repo=Path(__file__).resolve().parent.parent
|
|
if repo==args.output.resolve() or repo in args.output.resolve().parents:
|
|
parser.error('generated routing weights must be outside the repository')
|
|
if args.output.exists() or Path(str(args.output)+'.json').exists():
|
|
parser.error('refusing to overwrite a routing artifact')
|
|
if not 1<=args.steps<=10000 or not 0<args.learning_rate<=.1 or not 1<=args.queries<=4096 or not 1<=args.keys<=4096:
|
|
parser.error('invalid optimization settings')
|
|
train, holdout=read_trace(args.train),read_trace(args.holdout)
|
|
source=args.initial.read_bytes()
|
|
magic,version,count,heads,dim=struct.unpack_from('<8s4I',source)
|
|
if (magic,version,count,heads,dim)!=(b'SKLROUT1',1,12,24,256):
|
|
raise ValueError('invalid initial routing artifact')
|
|
offset=24; output=bytearray(source[:24]); results=[]
|
|
for ordinal in range(count):
|
|
layer=struct.unpack_from('<I',source,offset)[0]
|
|
prefix=source[offset:offset+64]; offset+=64
|
|
matrix=np.frombuffer(source,dtype='<f4',count=heads*dim*dim,offset=offset).reshape(heads,dim,dim).copy()
|
|
offset+=matrix.nbytes
|
|
training, testing=dataset(train[layer],1700+layer,args.queries,args.keys), dataset(holdout[layer],8300+layer,args.queries,args.keys)
|
|
row={'layer':layer,'initial_train':evaluate(matrix,training),'initial_holdout':evaluate(matrix,testing)}
|
|
matrix=fit(matrix,training,args.steps,args.learning_rate)
|
|
row.update({'fitted_train':evaluate(matrix,training),'fitted_holdout':evaluate(matrix,testing)})
|
|
results.append(row); print(json.dumps(row),flush=True)
|
|
output.extend(prefix); output.extend(matrix.astype('<f4').tobytes())
|
|
if offset!=len(source):
|
|
raise ValueError('initial artifact contains trailing data')
|
|
report=json.loads(Path(str(args.initial)+'.json').read_text())
|
|
report.update({'method':'keyless-query-routing-frozen-attention-distillation','quality_gate':'not_run',
|
|
'routing_sha256':hashlib.sha256(output).hexdigest(),'calibration':{
|
|
'objective':'causal teacher attention KL, only query-routing matrices fitted; all model weights frozen',
|
|
'steps':args.steps,'learning_rate':args.learning_rate,'queries':args.queries,'keys':args.keys,
|
|
'train_sha256':hashlib.sha256(args.train.read_bytes()).hexdigest(),
|
|
'holdout_sha256':hashlib.sha256(args.holdout.read_bytes()).hexdigest(),'layers':results}})
|
|
args.output.parent.mkdir(parents=True,exist_ok=True)
|
|
old=os.umask(0o077)
|
|
try:
|
|
with args.output.open('xb') as f: f.write(output)
|
|
with Path(str(args.output)+'.json').open('x') as f:json.dump(report,f,indent=2,allow_nan=False)
|
|
finally:os.umask(old)
|
|
|
|
|
|
if __name__=='__main__':main()
|