Distilling LLMs
Study black-box, sequence, token-logit, on-policy and verified reasoning-trace distillation for language models.
After this lesson you can
- Distinguish black-box, logit and on-policy distillation by teacher access, cost and exposure bias.
- Explain sequence-level distillation as a mode-based approximation of divergence between sequence distributions.
- Implement token-logit distillation with teacher top-k and compare forward KL, reverse KL and generalized JSD.
- Implement on-policy distillation where the student generates and the teacher supplies the target distribution.
- Distill a 1.5B model into a 0.5B model of the same family and measure the performance gap recovered.
Before you start
A student with less capacity
A large model can supply responses, probabilities or corrections to a smaller model. Distillation turns that signal into student training data. Depending on available access, you may receive only text, query per-token distributions or ask the teacher to score prefixes generated by the student. Each option teaches something different and has a different cost.
Knowledge distillation starts with a teacher and student . It does not guarantee the student inherits all teacher capabilities: architecture, data and training budget limit what it can represent. Nor does it turn a teacher response into a true label. Keep examples and evaluations that were not used to select data or checkpoints.
Text, sequences and distributions
In black-box distillation you receive teacher text and use it as a supervised target. You need no access to logits, though you do need a data generation and filtering procedure. Orca studied training on explanations from larger models; a convincing explanation can contain an error, so retain provenance and verify what you can.
Alpaca illustrates black-box distillation: it fine-tuned LLaMA 7B on 52,000 instruction demonstrations generated using text-davinci-003. That number is dataset size, not a measure of correctness or a license guarantee for replication. Review teacher, data and student terms separately before generating or distributing examples.
Sequence-level distillation trains the student on a complete teacher-produced response. Kim and Rush approximate an expectation over sequences using a high-probability search output. The result is a point approximation to teacher cross-entropy, not the full KL: finite beam search does not guarantee finding the exact mode either. Choosing one response can eliminate valid alternatives or reproduce errors with high confidence.
With logit access, the per-token signal retains a distribution over alternatives. For temperature , let and . Forward KL satisfies
If the teacher is frozen, minimizing it is equivalent to minimizing cross-entropy with soft labels. With respect to the student’s unscaled logits, the gradient is . In particular it is when . If you multiply the loss by , the gradient becomes ; declare that convention when comparing temperatures. The factor is not cosmetic: it changes update scale.
Forward KL, reverse KL and JSD
Forward KL penalizes the student assigning little mass where the teacher has mass. Reverse KL penalizes the student placing mass where the teacher assigns very little. With a limited student family, this can produce different fits, often described as mass covering and mode seeking. These are intuitions depending on family and optimization, not universal guarantees about quality or diversity.
The generalized JSD used in GKD combines both distributions using :
This unnormalized expression tends to zero when approaches either endpoint. To obtain KL limits, define another scale . In a finite vocabulary with strictly positive probabilities,
Normalization changes scale relative to ; do not compare gradients or learning rates between them without adjusting it. Limits require care when probabilities are zero. The exercise explicitly implements this normalized version, with KLs defined at the endpoints.
This lab traverses a finite grid of 601 centers for a bimodal teacher and a single-bell student. JSD is divided by beta(1-beta); its endpoints are forward and reverse KL. The second part calculates exact occupancies of a binary chain and fits with frozen prefixes. It does not assume fitting on student prefixes always improves results.
"""Dos experimentos exactos de destilación en espacios discretos."""
import math
VOCABULARY = [-3,-2,-1,0,1,2,3]
def sigmoid(x):
return 1/(1+math.exp(-x)) if x >= 0 else math.exp(x)/(1+math.exp(x))
def normalize(values):
total = sum(values)
return [x/total for x in values]
def teacher(weight):
left = normalize([math.exp(-.5*((x+1.5)/.65)**2) for x in VOCABULARY])
right = normalize([math.exp(-.5*((x-1.5)/.65)**2) for x in VOCABULARY])
return [weight*x+(1-weight)*y for x,y in zip(left,right)]
def student(center):
return normalize([math.exp(-.5*((x-center)/.8)**2) for x in VOCABULARY])
def kl(p,q): return sum(x*math.log(x/y) for x,y in zip(p,q))
def divergence(p,q,method,beta):
if method == 'forward' or (method == 'jsd' and beta == 0): return kl(p,q)
if method == 'reverse' or (method == 'jsd' and beta == 1): return kl(q,p)
if method != 'jsd' or not 0 < beta < 1: raise ValueError('Método o coeficiente inválido')
mixture = [beta*x+(1-beta)*y for x,y in zip(p,q)]
return (beta*kl(p,mixture)+(1-beta)*kl(q,mixture))/(beta*(1-beta))
def fit_distribution(weight,method,beta):
p = teacher(weight)
center = -3.; q = student(center); loss = divergence(p,q,method,beta)
for i in range(1,601):
candidate = -3+i/100
next_q = student(candidate); value = divergence(p,next_q,method,beta)
if value < loss-1e-12: center,q,loss = candidate,next_q,value
return {'teacher':p,'student':q,'center':center,'loss':loss,
'forward':kl(p,q),'reverse':kl(q,p)}
def states(q0,q1,horizon):
result = []; weight = 0.
for _ in range(horizon):
result.append(weight)
weight = (1-weight)*q0+weight*q1
return result
def avg(values): return sum(values)/len(values)
def fit_at_weight(weight,capacity):
low,high = -12.,12.
for _ in range(60):
mid = (low+high)/2
grad = (1-weight)*(sigmoid(mid-capacity)-.1)+weight*(sigmoid(mid+capacity)-.9)
if grad > 0: high = mid
else: low = mid
return (low+high)/2
def binary_kl(p,q): return p*math.log(p/q)+(1-p)*math.log((1-p)/(1-q))
def sequence_experiment(capacity,horizon):
teacher_states = states(.1,.9,horizon)
teacher_weight = avg(teacher_states)
off_theta = fit_at_weight(teacher_weight,capacity)
on_theta = off_theta
for i in range(300):
own_weight = avg(states(sigmoid(on_theta-capacity),sigmoid(on_theta+capacity),horizon))
updated = fit_at_weight(own_weight,capacity)
iterations = i+1
if abs(updated-on_theta) < 1e-10: break
on_theta = (on_theta+updated)/2
def make(theta):
q0,q1 = sigmoid(theta-capacity),sigmoid(theta+capacity)
state = states(q0,q1,horizon)
per_step = [(1-w)*binary_kl(.1,q0)+w*binary_kl(.9,q1) for w in state]
return {'theta':theta,'q0':q0,'q1':q1,'state':state,'meanOwnKl':avg(per_step),'perStep':per_step}
off,on = make(off_theta),make(on_theta)
residual = abs(on_theta-fit_at_weight(avg(on['state']),capacity))
return {'teacherStates':teacher_states,'off':off,'on':on,'teacherWeight':teacher_weight,
'iterations':iterations,'residual':residual}
p = teacher(.5); q = student(.3)
assert abs(divergence(p,q,'jsd',0)-kl(p,q)) < 1e-14
assert abs(divergence(p,q,'jsd',1)-kl(q,p)) < 1e-14
assert abs(divergence(p,q,'jsd',.00001)-kl(p,q)) < .001
assert abs(divergence(p,q,'jsd',.99999)-kl(q,p)) < .001
for method in ('forward','reverse','jsd'):
result = fit_distribution(.5,method,.5)
assert abs(sum(result['teacher'])-1) < 1e-12 and abs(sum(result['student'])-1) < 1e-12
print('Ajuste discreto',method,': centro',result['center'],'pérdida',result['loss'],
'KL directa',result['forward'],'KL inversa',result['reverse'])
experiment = sequence_experiment(1.,20)
assert experiment['residual'] < 1e-8
for mode in ('off','on'):
row = experiment[mode]
print(mode,'theta',row['theta'],'q0',row['q0'],'q1',row['q1'],'KL prefijos propios',row['meanOwnKl'])
print('Ocupación media del maestro:',experiment['teacherWeight'],'residuo:',experiment['residual'])
print('JSD normalizada converge a las KL en β=0 y β=1; la JSD sin normalizar tiende a cero.')
print('Los prefijos propios se congelan al ajustar: no se deriva su distribución.')Top-k and missing mass
Before comparing logits by index, check teacher and student use exactly the same vocabulary, ID mapping, tokenizer, template and special tokens. Shared family or vocabulary size is not enough. If tokenizers segment differently, aligning index of one with index of another does not define a distribution over the same event.
Saving only the teacher’s largest values saves space, but renormalizing them within the subset changes the distribution. If you replace teacher probability outside top-k with zero while the student retains mass there, full reverse KL is infinite. One explicit alternative groups the tail into an “other” category: compute total teacher and student mass outside those IDs and compare categories. You obtain divergence of the aggregated partition, not full vocabulary divergence; how mass is distributed within the remainder is lost.
Compute the remainder before rounding or record precision error, retain temperature and mask, and check probabilities sum to one. A token index stored with insufficient precision or an omitted EOS can make a cache look plausible while teaching another objective. If teacher signals are precomputed, identify weights, tokenizer, data and code version so they can be reconstructed.
tokens = 10**9
top_k, bytes_logit, bytes_index, vocab = 32, 2, 4, 151936
top_bytes = tokens * top_k * (bytes_logit + bytes_index)
full_bytes = tokens * vocab * bytes_logit
print('Top-k: bytes y GB decimales:', top_bytes, top_bytes / 10**9)
print('Vocabulario completo: bytes y GB decimales:', full_bytes, full_bytes / 10**9)
print('Cociente completo / top-k:', full_bytes / top_bytes)The calculation includes only values and indices. It excludes metadata, remainder probabilities, compression and text storage. Actual size also depends on how many positions you choose to retain.
The student’s own prefixes
In conventional supervised training the student receives data or teacher prefixes. During generation it sees its own prefixes, including errors. On-policy distillation queries the teacher on student-generated sequences to train on those states too. This can help if prefixes are representative and the teacher can evaluate them; it also costs compute and may concentrate training on current policy errors.
Agarwal and colleagues propose GKD with configurable mixtures of sequences and divergences. MiniLLM starts from sequence-level reverse KL and derives a procedure accounting for the student’s output distribution. Minimizing token-level reverse KL on frozen student prefixes is one on-policy distillation variant; it is not automatically the exact sequence-level reverse KL gradient or a reproduction of MiniLLM. As in GRPO, changing policy changes the state distribution over which the average is taken.
This lab requires CUDA with bfloat16, torch, transformers, accelerate, peft, huggingface_hub and numpy. It uses Qwen2.5-1.5B-Instruct as teacher and Qwen2.5-0.5B-Instruct as student, with revisions and fingerprints in the report. Weights download to the usual cache if missing. Models load in stages and fast tokenizer, vocabulary, special-token and template identity is required before comparing logits.
The dataset is the same generated arithmetic as lesson 22 and the response is checked using an integer tag; splits exclude identical prompts, without guaranteeing those problems were absent from pretraining. As there, an exact response may count correct even when it reaches the limit without EOS; the report records termination. For each generated position, including closure when present, the teacher’s 32 most probable tokens and combined remaining mass are retained. Forward and reverse KL are exact for that aggregated partition, not the full vocabulary. Temperature is 2 and loss is multiplied by its square.
Off-policy uses teacher-generated prefixes; on-policy the student samples with full softmax and the teacher scores those prefixes in each round. Prefixes are frozen during the update: their distribution is not differentiated through. This example illustrates GKD, not an exact reproduction of MiniLLM. All four branches use the same initialization and step count, but token counts and teacher-query cost can differ. These are explicitly recorded along with validation, final test and checkpoints; they are not measured FLOPs.
For a technical test use ORYON_QUICK=1; normal mode offers the full flow. ORYON_DISTILL_DIR sets the results directory and ORYON_OFFLINE=1 requires models already cached. The abbreviated run does not demonstrate improvement, and the report does not extrapolate results to other problems.
"""Destilación por token con prefijos de maestro o alumno y KL de partición."""
import gc
import hashlib
import json
import math
import os
import random
import re
from collections.abc import Mapping
from pathlib import Path
import numpy as np
import torch
from huggingface_hub import snapshot_download
from peft import LoraConfig, PeftModel, get_peft_model
from transformers import AutoModelForCausalLM, AutoTokenizer
QUICK=os.getenv('ORYON_QUICK')=='1'; OFFLINE=os.getenv('ORYON_OFFLINE')=='1'
OUT=Path(os.getenv('ORYON_DISTILL_DIR','./oryon-distill'))
TEACHER='Qwen/Qwen2.5-1.5B-Instruct'; TREV='989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
STUDENT='Qwen/Qwen2.5-0.5B-Instruct'; SREV='7ae557604adf67be50417f59c2c2f167def9a775'
SEED=2220; DATA_SEED=220022
N_TRAIN,N_VAL,N_TEST=(8,4,4) if QUICK else (512,64,64)
MAX_NEW=12 if QUICK else 48; K=32; TEMP=2.; LR=1e-5
ROUNDS=1 if QUICK else 4; UPDATES=2 if QUICK else 32
torch.set_num_threads(1)
def sha(text): return hashlib.sha256(text.encode('utf-8')).hexdigest()
def file_hash(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for chunk in iter(lambda:f.read(1048576),b''): h.update(chunk)
return h.hexdigest()
def unpack(value): return value['input_ids'] if isinstance(value,Mapping) else value
def write_json(path,value): path.write_text(json.dumps(value,ensure_ascii=False,indent=2),encoding='utf-8')
def parse_answer(text):
if not isinstance(text,str) or len(text)>256: return None
match=re.fullmatch(r'\s*<answer>\s*([+-]?(?:0|[1-9][0-9]{0,7}))\s*</answer>\s*',text,flags=re.ASCII)
return int(match.group(1)) if match else None
def make_tasks():
tasks=[]
for a in range(2,41):
for b in range(2,21):
for op in ('+','-','*'):
if op in ('+','*') and a<b: continue
answer=a+b if op=='+' else a-b if op=='-' else a*b
text=f'Calculate {a} {op} {b}. Reply only as <answer>INTEGER</answer>.'
tasks.append({'id':sha(text),'prompt':text,'answer':answer})
random.Random(DATA_SEED).shuffle(tasks)
total=N_TRAIN+N_VAL+N_TEST
if total>len(tasks): raise ValueError('Faltan tareas')
groups=(tasks[:N_TRAIN],tasks[N_TRAIN:N_TRAIN+N_VAL],tasks[N_TRAIN+N_VAL:total])
ids=[{row['id'] for row in group} for group in groups]
if any(ids[i]&ids[j] for i in range(3) for j in range(i)): raise ValueError('Particiones solapadas')
return groups
def fingerprint(repo,revision):
folder=Path(snapshot_download(repo,revision=revision,local_files_only=OFFLINE,
allow_patterns=['*.safetensors','tokenizer.json','tokenizer_config.json']))
weights={p.name:file_hash(p) for p in sorted(folder.glob('*.safetensors'))}
if not weights: raise ValueError('No se encontraron los pesos del checkpoint')
return {'model':repo,'revision':revision,'weights_sha256':weights,
'tokenizer_sha256':{p.name:file_hash(p) for p in (folder/'tokenizer.json',folder/'tokenizer_config.json') if p.exists()}}
def check_tokenizers(a,b):
if a.get_vocab()!=b.get_vocab() or a.all_special_tokens!=b.all_special_tokens or a.all_special_ids!=b.all_special_ids:
raise ValueError('Vocabularios o tokens especiales distintos')
if a.special_tokens_map!=b.special_tokens_map or a.chat_template!=b.chat_template:
raise ValueError('Plantillas o asignaciones especiales distintas')
if a.backend_tokenizer.to_str()!=b.backend_tokenizer.to_str():
raise ValueError('El tokenizador rápido no es idéntico')
return {'vocabulary_size':len(a),'backend_sha256':sha(a.backend_tokenizer.to_str()),
'chat_template_sha256':sha(a.chat_template or ''),'special_tokens':a.all_special_tokens,
'special_ids':a.all_special_ids}
def prompt_ids(tok,text):
if any(s and s in text for s in tok.all_special_tokens): raise ValueError('Grafía de control en prompt')
ids=unpack(tok.apply_chat_template([{'role':'user','content':text}],tokenize=True,add_generation_prompt=True))
if not ids: raise ValueError('Prompt vacío')
return ids
def rollout(model,tok,task,seed,greedy):
prefix=prompt_ids(tok,task['prompt']); actions=[]
end={tok.convert_tokens_to_ids('<|im_end|>'),tok.convert_tokens_to_ids('<|endoftext|>')}
if None in end or tok.unk_token_id in end: raise ValueError('Faltan tokens de cierre')
generator=torch.Generator(device='cuda').manual_seed(seed); calls=consumed=0
with torch.inference_mode():
for _ in range(MAX_NEW):
x=torch.tensor([prefix+actions],device='cuda'); calls+=1; consumed+=x.numel()
logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,-1].float()
token=int(logits.argmax()) if greedy else int(torch.multinomial(logits.softmax(-1),1,generator=generator))
actions.append(token)
if token in end: break
content=actions[:-1] if actions[-1] in end else actions
special=any(t in tok.all_special_ids for t in content)
text=tok.decode(content,skip_special_tokens=False,clean_up_tokenization_spaces=False)
parsed=None if special else parse_answer(text)
return {'id':task['id'],'prefix':prefix,'actions':actions,'parsed':parsed,'answer':task['answer'],
'correct':parsed==task['answer'],'ended_with':'eos' if actions[-1] in end else 'límite',
'internal_special':special,'seed':seed,'calls':calls,'input_tokens':consumed}
def evaluate(model,tok,tasks):
rows=[rollout(model,tok,t,(SEED+1+int(t['id'][:16],16))%(2**63-1),True) for t in tasks]
return {'count':len(rows),'correct':sum(r['correct'] for r in rows),
'accuracy':sum(r['correct'] for r in rows)/len(rows),
'mean_length':sum(len(r['actions']) for r in rows)/len(rows),
'generated_tokens':sum(len(r['actions']) for r in rows),
'forward_calls':sum(r['calls'] for r in rows),'forward_input_tokens':sum(r['input_tokens'] for r in rows),
'rows':rows}
def load_model(repo,revision):
model=AutoModelForCausalLM.from_pretrained(repo,revision=revision,local_files_only=OFFLINE,
dtype=torch.bfloat16).to('cuda').eval()
model.config.use_cache=False
return model
def load_student(adapter=None,trainable=False):
base=load_model(STUDENT,SREV)
if adapter is None:
model=get_peft_model(base,LoraConfig(r=8,lora_alpha=16,lora_dropout=0.,bias='none',task_type='CAUSAL_LM',
target_modules=['q_proj','k_proj','v_proj','o_proj']))
else: model=PeftModel.from_pretrained(base,adapter,is_trainable=trainable)
model.eval()
if trainable and not any(p.requires_grad and 'lora_' in n for n,p in model.named_parameters()):
raise ValueError('No hay parámetros LoRA entrenables')
if trainable and any(p.requires_grad and 'lora_' not in n for n,p in model.named_parameters()):
raise ValueError('La base debe estar congelada')
return model
def teacher_targets(model,rows):
# Las posiciones corresponden a cada token generado, incluido EOS si existe.
total_calls=total_tokens=0; result=[]
with torch.inference_mode():
for row in rows:
prefix,actions=row['prefix'],row['actions']
if not prefix or not actions: raise ValueError('Secuencia vacía')
x=torch.tensor([prefix+actions],device='cuda'); total_calls+=1; total_tokens+=x.numel()
logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,len(prefix)-1:-1].float()/TEMP
if K<=0 or K>=logits.shape[-1]: raise ValueError('K fuera del vocabulario')
log_norm=logits.logsumexp(-1); top,indices=logits.topk(K,dim=-1)
remaining=logits.scatter(-1,indices,float('-inf')).logsumexp(-1)-log_norm
result.append({'id':row['id'],'prefix':prefix,'actions':actions,'indices':indices.cpu().tolist(),
'top_logp':(top-log_norm[:,None]).cpu().tolist(),'rest_logp':remaining.cpu().tolist()})
return result,{'forward_calls':total_calls,'forward_input_tokens':total_tokens,
'supervised_tokens':sum(len(r['actions']) for r in rows)}
def partition_kl(student_logits,teacher_logp,indices,reverse,temperature):
if temperature<=0 or not math.isfinite(temperature): raise ValueError('Temperatura inválida')
if student_logits.ndim!=2 or indices.ndim!=2 or teacher_logp.shape!=(indices.shape[0],indices.shape[1]+1):
raise ValueError('Formas incompatibles')
if student_logits.shape[0]!=indices.shape[0] or indices.shape[1]>=student_logits.shape[1]: raise ValueError('Partición inválida')
if bool((indices<0).any()) or bool((indices>=student_logits.shape[1]).any()): raise ValueError('ID inválido')
if indices.shape[1]>1 and bool((indices.sort(-1).values[:,1:]==indices.sort(-1).values[:,:-1]).any()): raise ValueError('IDs repetidos')
scaled=student_logits.float()/temperature
normalizer=scaled.logsumexp(-1); top=scaled.gather(-1,indices)-normalizer[:,None]
rest=scaled.scatter(-1,indices,float('-inf')).logsumexp(-1)-normalizer
q=torch.cat((top,rest[:,None]),-1); p=teacher_logp.float()
if not torch.isfinite(p).all() or not torch.isfinite(q).all(): raise ValueError('Probabilidad no finita')
if not torch.allclose(p.logsumexp(-1),torch.zeros_like(p[:,0]),atol=1e-5,rtol=1e-5): raise ValueError('Maestro no normalizado')
result=(q.exp()*(q-p)).sum(-1) if reverse else (p.exp()*(p-q)).sum(-1)
return result.mean()*temperature**2
def train_one(model,optimizer,row,reverse):
prefix,actions=row['prefix'],row['actions']; x=torch.tensor([prefix+actions],device='cuda')
logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,len(prefix)-1:-1]
indices=torch.tensor(row['indices'],device='cuda',dtype=torch.long)
teacher=torch.tensor([a+[b] for a,b in zip(row['top_logp'],row['rest_logp'])],device='cuda')
optimizer.zero_grad(set_to_none=True); loss=partition_kl(logits,teacher,indices,reverse,TEMP)
if not torch.isfinite(loss): raise ValueError('Pérdida no finita')
loss.backward(); torch.nn.utils.clip_grad_norm_([p for p in model.parameters() if p.requires_grad],1.)
optimizer.step()
return float(loss.detach()),len(actions),len(prefix)+len(actions)
def release(*objects):
# La llamada debe ir precedida de `del` de las referencias del llamador.
gc.collect(); torch.cuda.empty_cache()
def main():
if not torch.cuda.is_available(): raise RuntimeError('Este laboratorio requiere CUDA')
if not torch.cuda.is_bf16_supported(): raise RuntimeError('Este laboratorio requiere bfloat16 en CUDA')
OUT.mkdir(parents=True,exist_ok=True); random.seed(SEED); np.random.seed(SEED)
torch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)
train,val,test=make_tasks()
teacher_tok=AutoTokenizer.from_pretrained(TEACHER,revision=TREV,local_files_only=OFFLINE)
tok=AutoTokenizer.from_pretrained(STUDENT,revision=SREV,local_files_only=OFFLINE)
identity=check_tokenizers(teacher_tok,tok)
provenance=[fingerprint(TEACHER,TREV),fingerprint(STUDENT,SREV)]
teacher=load_model(TEACHER,TREV)
teacher_test=evaluate(teacher,teacher_tok,test)
teacher_validation=evaluate(teacher,teacher_tok,val)
teacher_rows=[rollout(teacher,teacher_tok,t,(SEED+int(t['id'][:16],16))%(2**63-1),True) for t in train]
off_targets,off_cost=teacher_targets(teacher,teacher_rows)
del teacher; release()
student=load_student(); baseline=evaluate(student,tok,test); baseline_validation=evaluate(student,tok,val)
del student; release()
runs=[]
for mode in ('off_forward','off_reverse','on_forward','on_reverse'):
random.seed(SEED); torch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)
run_dir=OUT/mode; run_dir.mkdir(parents=True,exist_ok=True)
student=load_student(trainable=True)
adapter=run_dir/'checkpoint-0'; student.save_pretrained(adapter,safe_serialization=True)
del student; release()
optim_path=run_dir/'optimizer.pt'; history=[]
total_train_tokens=total_supervised=total_generated=0
generation_calls=generation_input_tokens=0
teacher_scoring={'forward_calls':0,'forward_input_tokens':0,'supervised_tokens':0}
for round_index in range(ROUNDS):
if mode.startswith('on_'):
student=load_student(adapter,trainable=False)
rows=[rollout(student,tok,t,(SEED+round_index*len(train)+int(t['id'][:16],16))%(2**63-1),False) for t in train]
total_generated+=sum(len(r['actions']) for r in rows)
generation_calls+=sum(r['calls'] for r in rows); generation_input_tokens+=sum(r['input_tokens'] for r in rows)
del student; release()
teacher=load_model(TEACHER,TREV)
targets,cost=teacher_targets(teacher,rows)
del teacher; release()
for name in teacher_scoring: teacher_scoring[name]+=cost[name]
else: targets=off_targets
student=load_student(adapter,trainable=True)
params=[p for p in student.parameters() if p.requires_grad]; optimizer=torch.optim.AdamW(params,lr=LR)
if round_index>0: optimizer.load_state_dict(torch.load(optim_path,map_location='cpu',weights_only=True))
losses=[]
for update in range(UPDATES):
row=targets[(round_index*UPDATES+update)%len(targets)]
loss,supervised,processed=train_one(student,optimizer,row,mode.endswith('reverse'))
losses.append(loss); total_train_tokens+=processed; total_supervised+=supervised
adapter=run_dir/f'checkpoint-{(round_index+1)*UPDATES}'
student.save_pretrained(adapter,safe_serialization=True); torch.save(optimizer.state_dict(),optim_path)
validation=evaluate(student,tok,val)
history.append({'step':(round_index+1)*UPDATES,'validation':validation,'mean_loss':sum(losses)/len(losses),
'training_input_tokens':total_train_tokens,'supervised_tokens':total_supervised,
'student_generation_tokens':total_generated,'student_generation_calls':generation_calls,
'student_generation_input_tokens':generation_input_tokens,
'adapter_sha256':file_hash(adapter/'adapter_model.safetensors')})
del optimizer,params,student; release()
student=load_student(adapter,trainable=False); final=evaluate(student,tok,test)
del student; release()
runs.append({'condition':mode,'seed':SEED,'history':history,'test_after':final,
'teacher_scoring_cost':teacher_scoring if mode.startswith('on_') else off_cost,
'cost_note':'El cache fuera de política se comparte; costes de evaluación y generación se registran aparte, no son FLOPs medidos.'})
report={'source':'aritmética generada como m20-l22; no garantiza ausencia en preentrenamiento',
'models':provenance,'tokenizer_identity':identity,'quick':QUICK,'seed':SEED,'data_seed':DATA_SEED,
'splits':{'train':[r['id'] for r in train],'validation':[r['id'] for r in val],'test':[r['id'] for r in test]},
'config':{'top_k':K,'temperature':TEMP,'rounds':ROUNDS,'updates_per_round':UPDATES,'max_new_tokens':MAX_NEW,
'mask':'todos los tokens generados, incluido EOS; no hay padding','teacher':'prefijos greedy',
'student':'muestras softmax completo a temperatura 1, sin truncar',
'correctness':'respuesta estricta válida aunque alcance el límite sin EOS; la terminación se registra'},
'teacher_test':teacher_test,'student_baseline_test':baseline,'teacher_validation':teacher_validation,
'student_baseline_validation':baseline_validation,'runs':runs,
'off_policy_generation':{'generated_tokens':sum(len(r['actions']) for r in teacher_rows),
'forward_calls':sum(r['calls'] for r in teacher_rows),
'forward_input_tokens':sum(r['input_tokens'] for r in teacher_rows)},
'limits':'KL entre top-k del maestro y masa restante, no KL del vocabulario completo. Los prefijos on-policy se congelan durante cada ronda, por lo que el gradiente no incluye cambio de distribución de prefijos. No es la implementación exacta de MiniLLM. Muestras pequeñas no prueban mejora ni generalización.'}
write_json(OUT/'distill-report.json',report)
print('Informe:',OUT/'distill-report.json',flush=True)
if __name__=='__main__': main()npm run lab and open the connection link.Pretraining, pruning and reasoning
Distillation during pretraining applies teacher signal to large amounts of text, often without retaining every logit. Gemma 2 describes distillation in its small models. Minitron combines structural pruning and distillation: reducing layers or dimensions and then fitting with a teacher is a different intervention from training an independent student from scratch. Data, teacher and compute budgets are part of any comparison.
The Llama 3.2 model card says its 1B and 3B models incorporated Llama 3.1 8B and 70B logits as per-token targets during pretraining and used distillation after pruning to recover performance. Target access, pruning and training phase must be declared when comparing that procedure with SFT on generated responses.
A larger teacher does not always yield the best student under a fixed budget. Zhang and colleagues study the capacity gap in models below 3B and contrast it at 7B scale; this is an empirical result for their settings, not a universal law for every task. Busbridge and colleagues fit scaling laws including compute allocated to teacher and student: if a teacher already exists or is amortized across many students, the balance can differ from training one for a single student. Compare against SFT with explicit data, generation and training budgets, without treating equal updates as equal FLOPs.
Reasoning-trace distillation uses explained solutions as student data. When a verifiable answer exists, filtering by outcome reduces some errors, but a correct final answer does not prove every intermediate step valid. Retain both attempted and accepted sample counts; teacher cost includes rejected samples.
In table 16 of DeepSeek-R1, Qwen2.5-32B-Zero achieved 47.0 pass@1 on AIME 2024 and DeepSeek-R1-Distill-Qwen-32B achieved 72.6 under their protocol. This compares results of two specific pipelines, not a law that distillation always beats RL in small models or a comparison isolating all compute used.
Preparing distillation measurements.
The figure includes a QUICK run of both labs: 8 training, 4 validation and 4 test problems. The teacher got 0 of 4 validation problems correct and the initial student 4 of 4; one trace was accepted after 15 attempts. This sample is far too small to conclude the student beats the teacher or that a distillation variant improves: it checks the flow and explores how interpretation changes when the gap is negative. The report retains measured metrics; local paths were removed when preparing the copy included in the lesson.
The Qwen2.5-1.5B-Instruct teacher and Qwen2.5-0.5B-Instruct student share tokenizer and Apache 2.0 license. Split and parser are copied from the current m20-l22 version. An SFT on unfiltered teacher outputs and another on filtered traces are compared, both with the same initialization and update count; tokens and sampling cost, which can differ, are recorded.
Final-tag extraction adapts m20-l22’s strict verifier: it requires a nonempty explanation and exactly one final tag, passed to the same parser. Steps are not checked: for example, an explanation saying “the result is 3” can pass if it ends with the correct tag for 4. The teacher trace is obtained with a prompt requesting explanation; the student is fine-tuned with the original strict prompt. This transfer changes the instruction and can harm evaluation, which requires only the tag. Termination and reconstructed tokens must match the sample. A dataset with no valid traces is reported without training.
Training curves and budget gap use validation; test is evaluated at the end. Accuracy is greedy, with the same parser and horizon as the logit lab; an exact answer can count at the limit without EOS. trace-data.json retains traces, costs, attempts and reasons, and each complete branch saves adapter and fingerprint for inference. If ORYON_DISTILL_REPORT exists, both model revisions and fingerprints, splits, evaluation budget and initial student and teacher actions are checked before combining results. If they do not match, results stay separate. Equal update counts do not imply equal token counts or FLOPs.
Install PyTorch, transformers, PEFT and dependencies compatible with CUDA and bfloat16. ORYON_QUICK=1 runs two updates and few prompts; without it the reader’s full protocol is used. Outputs go to ORYON_TRACES_DIR. Measure RAM and VRAM before running. A short result does not guarantee the teacher produces valid traces or that distillation improves the student. Sources: sequence distillation, on-policy distillation and DeepSeek-R1.
"""Trazas del maestro filtradas por respuesta y SFT del alumno."""
import gc
import hashlib
import json
import math
import os
import random
import re
from collections import Counter
from collections.abc import Mapping
from pathlib import Path
import numpy as np
import torch
from huggingface_hub import snapshot_download
from peft import LoraConfig,get_peft_model
from transformers import AutoModelForCausalLM,AutoTokenizer
QUICK=os.getenv('ORYON_QUICK')=='1'; OFFLINE=os.getenv('ORYON_OFFLINE')=='1'
OUT=Path(os.getenv('ORYON_TRACES_DIR','./oryon-traces'))
TEACHER='Qwen/Qwen2.5-1.5B-Instruct'; TEACHER_REV='989aa7980e4cf806f80c7fef2b1adb7bc71aa306'
STUDENT='Qwen/Qwen2.5-0.5B-Instruct'; STUDENT_REV='7ae557604adf67be50417f59c2c2f167def9a775'
SEED=2220; DATA_SEED=220022
N_TRAIN,N_VAL,N_TEST=(8,4,4) if QUICK else (512,64,64)
EVAL_MAX=12 if QUICK else 48; TRACE_MAX=48 if QUICK else 128
ATTEMPTS=2 if QUICK else 4; UPDATES=2 if QUICK else 128
torch.set_num_threads(1)
def sha(text): return hashlib.sha256(text.encode('utf-8')).hexdigest()
def file_hash(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for chunk in iter(lambda:f.read(1048576),b''): h.update(chunk)
return h.hexdigest()
def write_json(path,value): path.write_text(json.dumps(value,ensure_ascii=False,indent=2),encoding='utf-8')
def unpack(value): return value['input_ids'] if isinstance(value,Mapping) else value
def parse_answer(text):
# Copiado de grpo_lab.py de m20-l22; no se evalúa código generado.
if not isinstance(text,str) or len(text)>256: return None
match=re.fullmatch(r'\s*<answer>\s*([+-]?(?:0|[1-9][0-9]{0,7}))\s*</answer>\s*',text,flags=re.ASCII)
return int(match.group(1)) if match else None
def decode_answer(tok,actions,end):
if not actions: raise ValueError('No hay tokens generados')
content=actions[:-1] if actions[-1] in end else actions
internal_special=any(token in tok.all_special_ids for token in content)
text=tok.decode(content,skip_special_tokens=False,clean_up_tokenization_spaces=False)
return text, None if internal_special else parse_answer(text), internal_special
def make_tasks():
tasks=[]
for a in range(2,41):
for b in range(2,21):
for op in ('+','-','*'):
if op in ('+','*') and a<b: continue
answer=a+b if op=='+' else a-b if op=='-' else a*b
text=f'Calculate {a} {op} {b}. Reply only as <answer>INTEGER</answer>.'
tasks.append({'id':sha(text),'prompt':text,'answer':answer,'a':a,'b':b,'operation':op})
random.Random(DATA_SEED).shuffle(tasks)
total=N_TRAIN+N_VAL+N_TEST
if total>len(tasks): raise ValueError('Faltan problemas distintos')
train=tasks[:N_TRAIN]; val=tasks[N_TRAIN:N_TRAIN+N_VAL]; test=tasks[N_TRAIN+N_VAL:total]
ids=[{x['id'] for x in part} for part in (train,val,test)]
if any(ids[i]&ids[j] for i in range(3) for j in range(i+1,3)): raise ValueError('Solapamiento exacto de prompts')
return train,val,test
def trace_answer(text):
# Solo se verifica la etiqueta final; la explicación no se verifica paso a paso.
if not isinstance(text,str) or text.count('<answer>')!=1 or text.count('</answer>')!=1: return None
match=re.search(r'(<answer>[^<>]*</answer>)\s*$',text,flags=re.ASCII)
if match is None or not text[:match.start()].strip(): return None
return parse_answer(match.group(1))
def files(repo,revision):
path=Path(snapshot_download(repo,revision=revision,local_files_only=OFFLINE,allow_patterns=['*.safetensors','tokenizer.json','tokenizer_config.json']))
weights={p.name:file_hash(p) for p in sorted(path.glob('*.safetensors'))}
if not weights: raise ValueError('Faltan pesos safetensors')
return {'weights':weights,'tokenizer':{n:file_hash(path/n) for n in ('tokenizer.json','tokenizer_config.json')}}
def load_model(repo,revision,dtype):
tok=AutoTokenizer.from_pretrained(repo,revision=revision,local_files_only=OFFLINE)
model=AutoModelForCausalLM.from_pretrained(repo,revision=revision,dtype=dtype,local_files_only=OFFLINE).to('cuda').eval()
model.config.use_cache=False
return tok,model
def prefix(tok,prompt):
if any(s and s in prompt for s in tok.all_special_tokens): raise ValueError('Token de control en el prompt')
return unpack(tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=True,add_generation_prompt=True))
def sample(tok,model,prompt,seed,max_new,greedy=False):
ids=prefix(tok,prompt); actions=[];gen=torch.Generator(device='cuda').manual_seed(seed)
end={tok.convert_tokens_to_ids('<|im_end|>'),tok.convert_tokens_to_ids('<|endoftext|>')};inputs=0
if len(ids)+max_new>model.config.max_position_embeddings: raise ValueError('Horizon fuera de contexto')
with torch.inference_mode():
for _ in range(max_new):
x=torch.tensor([ids+actions],device='cuda');inputs+=x.numel()
logits=model(input_ids=x,use_cache=False).logits[0,-1].float()
token=int(logits.argmax()) if greedy else int(torch.multinomial((logits/.8).softmax(-1),1,generator=gen))
actions.append(token)
if token in end: break
text,answer,internal=decode_answer(tok,actions,end)
return {'text':text,'actions':actions,'answer':answer,'internal_special':internal,
'ended':actions[-1] in end,'end_token':actions[-1],'seed':seed,'input_tokens':inputs}
def evaluate(tok,model,tasks):
rows=[]
for row in tasks:
result=sample(tok,model,row['prompt'],(SEED+1+int(row['id'][:16],16))%(2**63-1),EVAL_MAX,True)
rows.append({'id':row['id'],'correct':result['answer']==row['answer'],'length':len(result['actions']),
'actions':result['actions'],'input_tokens':result['input_tokens'],'ended':result['ended']})
return {'count':len(rows),'correct':sum(r['correct'] for r in rows),'accuracy':sum(r['correct'] for r in rows)/len(rows),
'mean_length':sum(r['length'] for r in rows)/len(rows),'rows':rows,'generated_tokens':sum(r['length'] for r in rows),
'forward_calls':sum(r['length'] for r in rows),'forward_input_tokens':sum(r['input_tokens'] for r in rows)}
def trace_prompt(task):
return f"Calculate {task['a']} {task['operation']} {task['b']}. Explain briefly and finish with <answer>INTEGER</answer>."
def collect_traces(tok,teacher,tasks):
accepted=[]; records=[]; reasons=Counter(); attempts=0; generated=0; inputs=0
eos=tok.convert_tokens_to_ids('<|im_end|>')
for task in tasks:
for attempt in range(ATTEMPTS):
seed=(SEED+int(task['id'][:16],16)+1000+attempt)%(2**63-1)
out=sample(tok,teacher,trace_prompt(task),seed,TRACE_MAX)
attempts+=1;generated+=len(out['actions']);inputs+=out['input_tokens']
answer=None if out['internal_special'] else trace_answer(out['text'])
if out['end_token']!=eos: reason='sin terminación im_end'
elif answer is None: reason='formato o explicación ausente'
elif answer!=task['answer']: reason='respuesta incorrecta'
else: reason='aceptada'
reasons[reason]+=1
records.append({'id':task['id'],'attempt':attempt,'seed':seed,'generated_tokens':len(out['actions']),
'reason':reason,'text_sha256':sha(out['text'])})
if reason=='aceptada':
accepted.append({'id':task['id'],'prompt':task['prompt'],'text':out['text'],'actions':out['actions']})
break
return accepted,records,{'attempts':attempts,'generated_tokens':generated,'autoregressive_input_tokens':inputs,
'accepted':len(accepted),'requested_prompts':len(tasks),'reasons':dict(reasons)}
def collect_unfiltered(tok,teacher,tasks):
rows=[];reasons=Counter();tokens=inputs=0; eos=tok.convert_tokens_to_ids('<|im_end|>')
for task in tasks:
seed=(SEED+int(task['id'][:16],16))%(2**63-1)
out=sample(tok,teacher,task['prompt'],seed,EVAL_MAX,True)
tokens+=len(out['actions']); inputs+=out['input_tokens']
if out['end_token']!=eos or out['internal_special'] or not out['text'].strip():
reasons['terminación o contenido inválido']+=1;continue
rows.append({'id':task['id'],'prompt':task['prompt'],'text':out['text'],'actions':out['actions']})
return rows,{'requested_prompts':len(tasks),'accepted':len(rows),'generated_tokens':tokens,
'autoregressive_input_tokens':inputs,'reasons':dict(reasons),
'note':'No se filtra por corrección; sí se exige terminación y contenido válidos.'}
def encode_trace(tok,row):
prompt=prefix(tok,row['prompt']);messages=[{'role':'user','content':row['prompt']},{'role':'assistant','content':row['text']}]
full=unpack(tok.apply_chat_template(messages,tokenize=True,add_generation_prompt=False))
eos=tok.convert_tokens_to_ids('<|im_end|>')
if full[:len(prompt)]!=prompt: raise ValueError('Frontera de plantilla incompatible')
end=full.index(eos,len(prompt))
if full[end+1:]!=tok.encode('\n',add_special_tokens=False): raise ValueError('Sufijo inesperado')
ids=full[:end+1]
if ids[len(prompt):]!=row['actions']: raise ValueError('La traza no reconstruye los tokens muestreados')
return ids,len(prompt)
def train_sft(tok,model,rows,val,test):
model=get_peft_model(model,LoraConfig(r=8,lora_alpha=16,lora_dropout=0.,bias='none',task_type='CAUSAL_LM',
target_modules=['q_proj','k_proj','v_proj','o_proj'])).eval()
params=[p for n,p in model.named_parameters() if p.requires_grad and 'lora_' in n]
if not params or len(params)!=sum(p.requires_grad for p in model.parameters()): raise ValueError('Solo LoRA entrenable')
valid=[]; invalid=Counter()
for row in rows:
try: valid.append(encode_trace(tok,row))
except ValueError as exc: invalid[str(exc)]+=1
before=evaluate(tok,model,test);before_val=evaluate(tok,model,val);history=[];processed=supervised=0
if not valid: return {'status':'sin trazas verificadas utilizables','test_before':before,'validation_before':before_val,'history':[],
'invalid':dict(invalid),'training_pairs':0},model
opt=torch.optim.AdamW(params,lr=1e-5)
for step in range(UPDATES):
ids,start=valid[step%len(valid)];x=torch.tensor([ids],device='cuda')
logits=model(input_ids=x,attention_mask=torch.ones_like(x),use_cache=False).logits[0,start-1:-1].float()
target=x[0,start:];loss=-logits.log_softmax(-1).gather(1,target[:,None]).mean()
if not torch.isfinite(loss): raise ValueError('Pérdida SFT no finita')
opt.zero_grad(set_to_none=True);loss.backward();torch.nn.utils.clip_grad_norm_(params,1.);opt.step()
processed+=len(ids);supervised+=len(ids)-start
if QUICK or step+1==UPDATES or (step+1)%32==0:
validation=evaluate(tok,model,val)
history.append({'step':step+1,'validation':validation,
'processed_tokens':processed,'supervised_tokens':supervised,
'eval_generation_input_tokens':validation['forward_input_tokens']})
return {'status':'completo','test_before':before,'validation_before':before_val,'history':history,'invalid':dict(invalid),
'training_pairs':len(valid),'steps':UPDATES,'processed_tokens':processed,'supervised_tokens':supervised,
'test_after':evaluate(tok,model,test)},model
def same_tokenizers(a,b):
if not a.is_fast or not b.is_fast: raise ValueError('Se necesitan tokenizadores rápidos')
if (a.get_vocab()!=b.get_vocab() or a.all_special_tokens!=b.all_special_tokens or a.all_special_ids!=b.all_special_ids
or a.special_tokens_map!=b.special_tokens_map or a.chat_template!=b.chat_template
or a.backend_tokenizer.to_str()!=b.backend_tokenizer.to_str()):
raise ValueError('Tokenizadores o plantillas distintos')
return {'backend_sha256':sha(a.backend_tokenizer.to_str()),'vocabulary_size':len(a)}
def comparable(external,report):
if external.get('quick')!=QUICK or external.get('seed')!=SEED or external.get('data_seed')!=DATA_SEED: return False
if external.get('splits')!=report['splits'] or external.get('config',{}).get('max_new_tokens')!=EVAL_MAX: return False
models=external.get('models',[])
if len(models)!=2:return False
for item,name,revision,ours in zip(models,(TEACHER,STUDENT),(TEACHER_REV,STUDENT_REV),report['models']):
if item.get('model')!=name or item.get('revision')!=revision or item.get('weights_sha256')!=ours['weights']: return False
if item.get('tokenizer_sha256')!=ours['tokenizer']: return False
for key in ('teacher_test','student_baseline_test','teacher_validation','student_baseline_validation'):
prior=external.get(key,{}).get('rows',[]);now=report.get(key,{}).get('rows',[])
expected=report['splits']['validation' if key.endswith('validation') else 'test']
if not expected or len(prior)!=len(expected) or len(now)!=len(expected): return False
if any(a.get('id')!=b.get('id') or a.get('id')!=task_id or a.get('actions')!=b.get('actions') for a,b,task_id in zip(prior,now,expected)): return False
return True
def main():
if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported(): raise RuntimeError('Se necesita CUDA con bfloat16')
OUT.mkdir(parents=True,exist_ok=True)
random.seed(SEED);np.random.seed(SEED);torch.manual_seed(SEED);torch.cuda.manual_seed_all(SEED)
train,val,test=make_tasks(); teacher_info=files(TEACHER,TEACHER_REV);student_info=files(STUDENT,STUDENT_REV)
teacher_tok,teacher=load_model(TEACHER,TEACHER_REV,torch.bfloat16)
student_tok=AutoTokenizer.from_pretrained(STUDENT,revision=STUDENT_REV,local_files_only=OFFLINE)
identity=same_tokenizers(teacher_tok,student_tok)
teacher_test=evaluate(teacher_tok,teacher,test)
teacher_validation=evaluate(teacher_tok,teacher,val)
unfiltered,ordinary_cost=collect_unfiltered(teacher_tok,teacher,train)
verified,attempts,trace_cost=collect_traces(teacher_tok,teacher,train)
write_json(OUT/'trace-data.json',{'verified':verified,'unfiltered':unfiltered,'attempts':attempts,
'verified_cost':trace_cost,'unfiltered_cost':ordinary_cost})
del teacher,teacher_tok;gc.collect();torch.cuda.empty_cache()
runs=[];baseline=None;baseline_validation=None
for condition,rows,cost in (('sft',unfiltered,ordinary_cost),('verified_traces',verified,trace_cost)):
random.seed(SEED);np.random.seed(SEED);torch.manual_seed(SEED);torch.cuda.manual_seed_all(SEED)
tok,student=load_model(STUDENT,STUDENT_REV,torch.bfloat16)
result,student=train_sft(tok,student,rows,val,test)
if result['status']=='completo':
dest=OUT/condition;dest.mkdir(parents=True,exist_ok=True)
student.save_pretrained(dest,safe_serialization=True);tok.save_pretrained(dest)
result['adapter']={'path':str(dest),'sha256':file_hash(dest/'adapter_model.safetensors'),
'model':STUDENT,'revision':STUDENT_REV,'seed':SEED,
'note':'Solo inferencia; no contiene estado del optimizador.'}
write_json(dest/'manifest.json',result['adapter'])
if baseline is None:baseline=result['test_before'];baseline_validation=result['validation_before']
elif [r['actions'] for r in baseline['rows']]!=[r['actions'] for r in result['test_before']['rows']]:
raise ValueError('Las ramas no comparten el alumno inicial')
elif [r['actions'] for r in baseline_validation['rows']]!=[r['actions'] for r in result['validation_before']['rows']]:
raise ValueError('Las ramas no comparten la validación inicial')
runs.append({'condition':condition,'seed':SEED,**result,'teacher_generation_cost':cost})
del student,tok;gc.collect();torch.cuda.empty_cache()
report={'source':'Aritmética y verificador de m20-l22; solo respuesta final verificada',
'quick':QUICK,'seed':SEED,'data_seed':DATA_SEED,
'models':[teacher_info,student_info],'model_ids':[{'model':TEACHER,'revision':TEACHER_REV},
{'model':STUDENT,'revision':STUDENT_REV}],
'tokenizer_identity':identity,'splits':{'train':[x['id'] for x in train],'validation':[x['id'] for x in val],
'test':[x['id'] for x in test]},
'config':{'max_new_tokens':EVAL_MAX,'trace_max_tokens':TRACE_MAX,'attempts_per_prompt':ATTEMPTS,
'updates':UPDATES,'teacher_trace_temperature':.8,'sampling':'softmax completo'},
'teacher_test':teacher_test,'student_baseline_test':baseline,'teacher_validation':teacher_validation,
'student_baseline_validation':baseline_validation,'runs':runs,'trace_attempts':attempts,
'trace_data_sha256':file_hash(OUT/'trace-data.json'),
'limits':'La extracción de la etiqueta final adapta el protocolo estricto de l22: una explicación previa contradictoria también puede pasar. Solo confirma el entero final, no los pasos. Maestro y alumno usan distinta precisión de la originalmente registrada en l22: aquí ambos usan bfloat16. El prompt de trazas pide explicación; evaluación usa la instrucción estricta de l22. Costes en tokens no son FLOPs; prompts sintéticos pueden aparecer en preentrenamiento.'}
# El otro laboratorio es opcional; no se mezclan informes si difieren filas o protocolo.
external_path=Path(os.getenv('ORYON_DISTILL_REPORT','./oryon-distill/distill-report.json'))
if external_path.exists():
ext=json.loads(external_path.read_text(encoding='utf-8'))
report['other_report']={'path':str(external_path),'sha256':file_hash(external_path),'compatible':comparable(ext,report)}
if report['other_report']['compatible']: report['runs'].extend(ext['runs'])
else:report['other_report']={'compatible':False,'reason':'informe de logits ausente'}
write_json(OUT/'distill-gap-report.json',report)
print('Informe:',OUT/'distill-gap-report.json','trazas aceptadas:',len(verified),flush=True)
if __name__=='__main__': main()npm run lab and open the connection link.One way to report recovery is for a higher-is-better metric. If the denominator is zero or too small, the ratio is uninformative; if the student beats the teacher it can exceed one, and if it worsens relative to baseline it can be negative. Accompany it with original scores, uncertainty and budget, not just a percentage.
Before reusing a teacher’s weights, data or outputs, review applicable licenses and terms. Technical availability of logits or responses does not itself authorize every form of redistribution or training. Retain sources and revisions in the report so another person can check scope.
Exercises
Step 1 of 3. Which term of KL(pT || qT) depends on student logits?
import numpy as np
def generalized_jsd_loss(student_logits, teacher_logits, beta, temperature, mask):
pass
Distillation chooses which distribution to imitate, on which prefixes and with what teacher access. Sequence and top-k approximations save resources at the cost of changing available information.