Compute-optimal training: Chinchilla and beyond
Derive compute-optimal parameter and token allocation, compare Chinchilla estimation approaches, and study inference-aware, data-constrained, and hyperparameter scaling.
After this lesson you can
- Derive N_opt and D_opt scaling from the parametric loss law and a fixed compute constraint.
- Reproduce IsoFLOP profile and parametric fitting approaches with locally trained models.
- Calculate training-plus-inference cost allocation for a given served-token volume.
- Apply data-constrained scaling to decide how many epochs to repeat.
- Set batch size and learning rate in light of compute, hyperparameter laws, and μP.
Before you start
One budget, many allocations
With the same training budget, you can choose a large network that sees few tokens or a smaller one that studies more. Hoffmann and colleagues compared more than 400 runs and trained Chinchilla with 70,000 million parameters and 1.4 trillion tokens. In their table, Gopher uses 280,000 million and 300,000 million, and GPT-3 175,000 million and 300,000 million. Chinchilla and Gopher had similar training budgets. The contrast asks which combination minimizes loss for given compute, not whether every smaller model is better.
Deriving the optimum
Use the previous lesson’s law, with positive , , and approximation . Compute-optimal allocation minimizes
Constant does not change the minimum’s position. For , the first-order conditions are
Multiply the first by and the second by and eliminate :
Substituting yields
Thus and . The interior minimum is global in this model: after substituting the constraint, the function of is a sum of two strictly convex exponentials that grows at both extremes. Including attention cost, embeddings, memory constraints, or architecture changes means no longer describes the whole budget and the optimum can change.
With and , the exponent of is approximately ; the exponent of is its complement. In this fit is not constant with unless . Do not confuse the mathematical optimum of a fitted law with a guarantee that real data follow it outside its range.
Three ways to estimate the frontier
Chinchilla studied three complementary approaches:
- Curve envelope: follow loss during each run and estimate which size gives minimum loss at each compute amount. Intermediate points of a long schedule may not match a run whose schedule ends at that budget.
- IsoFLOP profiles: train different sizes at the same budget with schedules adapted to each duration; fit a local loss curve against and find its minimum. Repeat for several and fit against .
- Parametric surface: jointly fit to observations and optimize the resulting expression. This gives a reusable surface at the cost of stronger dependence on functional form and optimizer.
In an IsoFLOP profile, parabola has a minimum at only if . If falls outside the observed size range, the minimum is an extrapolation, not a measured valley. Include sizes on both sides; if only descending points are available, broaden the sweep. Average or model repeated seeds and retain their dependencies in intervals. A narrow band does not correct a biased schedule or wrong curve family.
If bootstrap replicates with unidentified minima are discarded, report how many. Percentiles of the remainder are conditional on finding a valid minimum and do not represent failed replicates’ uncertainty. A high discard fraction signals a need for a broader sweep.
A ratio of about 20 tokens per parameter summarizes the studied range and approaches, not a universal constant. Besiroglu and colleagues reconstructed points from the published figure and reestimated the parametric approach. They noted that the published fit produced a policy near 70 tokens per parameter at Chinchilla scale, whereas their fit and the other two approaches were near 20. They also documented early optimizer termination affecting the original fit and bootstrap. Their intervals and conclusions depend on data reconstruction and procedure.
The discrepancy with Kaplan is not explained by one change either. Porian and colleagues separately studied final-layer accounting, warmup, schedule, and hyperparameters. The scaling-laws lesson showed why each definition matters. Compare complete protocols, not isolated exponents.
Paying for training and use
If a model is used many times, minimizing training alone can be the wrong decision. In the simple inference-aware scaling model, for served tokens and approximate cost per token, minimize
For and , the least training that reaches the target is
Substitute this expression and seek the minimum in . If , the parametric model cannot reach the target with finite resources. If , the minimum-training solution for that loss is recovered. As usage grows, inference cost penalizes larger models more and may justify training a smaller model longer. This calculation assumes one family and comparable loss, and counts FLOPs rather than price, latency, or energy.
Sardana and colleagues study the tradeoff explicitly. Quantization, batching, context length, memory, and hardware price also matter in practice. Llama 3 reports a corpus of about 15 trillion tokens and explains that smaller models trained beyond the training optimum to improve performance at equal inference budget. This decision does not establish a universal optimal token-to-parameter ratio.
Finite data and repeated epochs
When only unique tokens are available, presenting tokens repeats them. In Muennighoff and colleagues’ data-constrained model, define as repetitions after the first epoch and use
For , use . The model assigns each additional repetition fewer effective data than the previous one and approaches ; use a numerically stable function such as expm1 near zero. appears in one published fit and is not universal across corpora. Replacing only with is a partial model: the work also models effective parameters and fits its own surface.
In their experiments, loss differed little from unique data through roughly four epochs under the studied protocol; with more repetition, marginal performance eventually declined. This does not mean four epochs are always free or that more epochs should be forced when useful new data exist. Evaluate quality, duplication, mixture, domain shift, and validation: repeating noisy documents can worsen learning.
The optimum also depends on optimization
Hyperparameter scaling laws describe learning rates and batches that worked well in a regime. DeepSeek fitted and in its units and experiments. These formulas are not instructions to copy coefficients to another architecture: changing FLOP convention, optimizer, tokenizer, or regime calls for rechecking. Its sweep found a near-optimal band, not a unique exact point.
Critical batch size relates parallelism and sample efficiency; increasing it indiscriminately can reduce steps without improving loss per FLOP. μP proposes a parameterization facilitating hyperparameter transfer across widths under its conditions. In a real sweep, record schedule, warmup, batch, rate, seeds, and selection criterion; compare configurations with training and validation separated.
Lab: three quantitative decisions
The cell uses Hoffmann’s surface as an explicit model, not measured sweep data. First it calculates the optimum for a budget; then fixes that loss as a target and varies served tokens; finally it limits unique data and seeks an allocation under the partial effective-data model. Search bounds are declared and boundary optima rejected. Approximations and units are as described above.
import numpy as np
from scipy.optimize import minimize_scalar
E,A,B,alpha,beta = 1.69,406.4,410.7,.34,.28
def loss(N,D):
if not all(np.isfinite(x) and x>0 for x in (N,D)):
raise ValueError('N y D deben ser positivos y finitos')
return E+A*N**(-alpha)+B*D**(-beta)
def train_optimal(C):
if not np.isfinite(C) or C <= 0:
raise ValueError('C debe ser positivo y finito')
N = np.exp((np.log(alpha*A/(beta*B))+beta*(np.log(C)-np.log(6)))/(alpha+beta))
D = C/(6*N)
if not all(np.isfinite(x) and x>0 for x in (N,D)):
raise ValueError('Óptimo fuera del rango numérico')
return N,D,loss(N,D)
def cost_optimal(target,Q,k=2.):
if not all(np.isfinite(x) for x in (target,Q,k)) or target <= E or Q < 0 or k < 0:
raise ValueError('Se requiere pérdida objetivo > E y Q, k no negativos')
floor = (A/(target-E))**(1/alpha)
def values(logN):
N = np.exp(logN)
remaining = target-E-A*N**(-alpha)
if remaining <= 0:
return float('inf'),None
D = (B/remaining)**(1/beta)
return 6*N*D+k*N*Q,D
# Intervalo amplio declarado; comprueba que el óptimo no quede en los extremos.
lower,upper = np.log(floor)+1e-5,np.log(floor)+30
result = minimize_scalar(lambda x:values(x)[0],bounds=(lower,upper),method='bounded',
options={'xatol':1e-10})
if not result.success or min(result.x-lower,upper-result.x)<1e-3:
raise RuntimeError('Óptimo no identificado en el intervalo')
N = np.exp(result.x)
cost,D = values(result.x)
return N,D,cost
def effective_data(D,U,rstar=15.4):
if not all(np.isfinite(x) and x>0 for x in (D,U,rstar)):
raise ValueError('D, U y R* deben ser positivos y finitos')
if D <= U:
return D
R = D/U-1
return U*(1-rstar*np.expm1(-R/rstar))
def limited_optimal(C,U):
if not all(np.isfinite(x) and x>0 for x in (C,U)):
raise ValueError('C y U deben ser positivos y finitos')
# Rango de búsqueda explícito: 10⁵ a 10¹² parámetros.
lo,hi = np.log(1e5),np.log(1e12)
def f(logN):
N = np.exp(logN)
return loss(N,effective_data(C/(6*N),U))
result = minimize_scalar(f,bounds=(lo,hi),method='bounded')
if not result.success or min(result.x-lo,hi-result.x)<1e-3:
raise RuntimeError('Óptimo no identificado dentro del rango')
N = np.exp(result.x); D = C/(6*N)
return N,D,f(result.x)
C = 1e21
N,D,target = train_optimal(C)
print('Ajuste Hoffmann: exponente de N =',beta/(alpha+beta))
print('Con C=1e21, N, D, pérdida:',N,D,target)
print('Regla 20 tokens/parámetro:',np.sqrt(C/120),20*np.sqrt(C/120))
for Q in (0,1e12,1e13):
n,d,total = cost_optimal(target,Q)
print('Uso, N, D, coste total:',Q,n,d,total)
for U in (1e9,1e10,1e11):
n,d,value = limited_optimal(C,U)
print('Tokens únicos, N, D, épocas, pérdida:',U,n,d,d/U,value)
print('Datos efectivos en 1, 4, 16 y 40 épocas:',
[effective_data(e*1e10,1e10)/1e10 for e in (1,4,16,40)])
for q in (0,1e12,1e13):
n,d,cost=cost_optimal(target,q)
assert abs(loss(n,d)-target)<1e-9
assert cost>=0
assert abs(cost_optimal(target,0)[2]/C-1)<1e-6Local lab: measured profiles
This sweep uses the manifest, tokenizer, shards, and validation from m20-l07. Set ORYON_DATA_DIR to that directory and retain manifest.json; the program checks shard, tokenizer, and validation hashes before training. Install torch, numpy, scipy, and tokenizers. It uses m20-l11 MiniLlama with tied embeddings, causal attention, duration-adapted WSD, z-loss, and two seeds. Hyperparameters are fixed, not μP, and may not be optimal at every size.
Full mode runs six sizes and two seeds for each of three budgets between 10¹⁶ and 10¹⁷ FLOPs. D counts tokens presented with replacement, not unique tokens. For each architecture and budget, step count comes from approximate per-token cost rounded to a whole step: 6*(N + embedding) + 12*capas*contexto*anchura. The first term includes the tied head and the second approximates dense training attention. Compute actually assigned under this formula is recorded; these are not measured FLOPs and exact cost is not simultaneously assumed to be 6ND. If rounding separates points from their budget by more than 10%, the profile is marked unidentified.
Approach 1 takes the lowest observed point, even at an extreme, without claiming a global minimum. Approach 2 fits a parabola of loss against log N using the mean per size. It returns a vertex only with at least three sizes, positive curvature, and a vertex inside the observed range. To estimate D at that vertex, per-token cost is interpolated logarithmically between measured architectures; the intermediate model is an interpolation, not another trained run. The N_opt(C) exponent is fitted only if at least three valid profiles exist. Out-of-range optima and flat curves are reported as unidentified.
Approach 3 fits L(N,D)=E+A/(N/10^6)^α+B/(D/10^6)^β using Huber on log loss, log-sum-exp, and multiple initializations. It optimizes that surface using the sweep’s same per-token cost interpolation; a fit with parameters at bounds or a boundary minimum does not yield an identified optimum. Bootstrap resamples each seed as a shared block across sizes and budgets. With only two seeds there are very few combinations and bands do not capture systematic bias. The report states how many replicates converge and meet criteria. Such an interval does not validate the law outside the tested range.
Runs share validation documents and prefixes, tokenizer, and loss in nats per token. This compares conditions under that protocol, not generalization to another domain. The report contains seeds, size, presented tokens, loss, and budgets but no text. ORYON_QUICK=1 reduces size, context, and budgets to test the GPU path. Its profiles may have no minimum and must not be presented as a Chinchilla reproduction. ORYON_ISOFLOP_DIR selects an independent output directory.
"""Perfiles IsoFLOP reproducibles sobre los shards de m20-l07."""
import os, json, math, hashlib, gc
from pathlib import Path
from contextlib import nullcontext
os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG',':4096:8')
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from scipy.optimize import minimize, minimize_scalar
from scipy.special import logsumexp
from tokenizers import Tokenizer
QUICK = os.getenv('ORYON_QUICK') == '1'
DATA = Path(os.getenv('ORYON_DATA_DIR','./oryon-data'))
OUT = Path(os.getenv('ORYON_ISOFLOP_DIR','./oryon-isoflop'))
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
CONTEXT = 16 if QUICK else 128
BATCH, ACCUM = (1,1) if QUICK else (2,4)
SEEDS = (2007,2008)
CONFIGS = ([(32,1,4),(40,1,4),(48,1,4),(56,1,4),(64,1,4)] if QUICK else
[(128,4,4),(160,5,5),(192,6,6),(256,8,8),(352,14,11),(448,20,14)])
BUDGETS = (2e8,4e8,8e8) if QUICK else (1e16,3e16,1e17)
torch.set_num_threads(1)
torch.use_deterministic_algorithms(True)
def sha_file(path):
h = hashlib.sha256()
with path.open('rb') as f:
for block in iter(lambda:f.read(1024*1024),b''): h.update(block)
return h.hexdigest()
class RMSNorm(nn.Module):
def __init__(self,width): super().__init__(); self.weight = nn.Parameter(torch.ones(width))
def forward(self,x): return F.rms_norm(x,(x.shape[-1],),self.weight,1e-5)
def rotary(x):
_,_,length,dim = x.shape
frequencies = 1./(10000.**(torch.arange(0,dim,2,device=x.device,dtype=torch.float32)/dim))
angles = torch.arange(length,device=x.device,dtype=torch.float32)[:,None]*frequencies[None,:]
c,s = angles.cos()[None,None,:,:],angles.sin()[None,None,:,:]
even,odd = x[...,0::2].float(),x[...,1::2].float()
return torch.stack((even*c-odd*s,even*s+odd*c),dim=-1).flatten(-2).to(x.dtype)
class Block(nn.Module):
def __init__(self,width,heads):
super().__init__(); self.heads = heads; ff = 4*width
self.norm1,self.norm2 = RMSNorm(width),RMSNorm(width)
self.qkv = nn.Linear(width,3*width,bias=False); self.proj = nn.Linear(width,width,bias=False)
self.up,self.gate = nn.Linear(width,ff,bias=False),nn.Linear(width,ff,bias=False)
self.down = nn.Linear(ff,width,bias=False)
def forward(self,x):
b,t,d = x.shape; q,k,v = self.qkv(self.norm1(x)).chunk(3,dim=-1)
def split(z): return z.reshape(b,t,self.heads,d//self.heads).transpose(1,2)
q,k,v = rotary(split(q)),rotary(split(k)),split(v)
z = F.scaled_dot_product_attention(q,k,v,is_causal=True)
x = x+self.proj(z.transpose(1,2).contiguous().reshape(b,t,d)); h = self.norm2(x)
return x+self.down(F.silu(self.gate(h))*self.up(h))
class MiniLlama(nn.Module):
def __init__(self,vocab,width,layers,heads):
super().__init__()
if width%heads or (width//heads)%2: raise ValueError('La dimensión por cabeza debe ser par')
self.embedding = nn.Embedding(vocab,width); self.blocks = nn.ModuleList(Block(width,heads) for _ in range(layers)); self.norm = RMSNorm(width)
self.apply(self.initialize)
@staticmethod
def initialize(m):
if isinstance(m,(nn.Linear,nn.Embedding)): nn.init.normal_(m.weight,0.,.02)
def forward(self,ids):
x = self.embedding(ids)
for block in self.blocks: x = block(x)
return F.linear(self.norm(x),self.embedding.weight)
def count(model):
total = sum(p.numel() for p in model.parameters()); embedding = model.embedding.weight.numel()
return {'total_tied':total,'embedding_tied':embedding,'non_embedding':total-embedding}
def flop_per_token(counts,width,layers):
# Tres veces el coste de forward de matrices, incluida la cabeza ligada; atención densa QK y AV.
return 6*(counts['non_embedding']+counts['embedding_tied'])+12*layers*CONTEXT*width
def lr(step,total):
warmup = min(2 if QUICK else 200,max(1,total//4)); decay = min(2 if QUICK else 3000,max(1,total//5))
if step < warmup: return 3e-4*(step+1)/warmup
if step < total-decay: return 3e-4
return 3e-4*(.1+.9*(1-min(1.,(step-(total-decay)+1)/decay)))
class Windows:
def __init__(self,manifest):
self.shards,self.counts = [],[]
for row in manifest['groups']['fineweb/train']['shards']:
path = DATA/row['path']; dtype = np.dtype(manifest['dtype'])
if path.stat().st_size != row['tokens']*dtype.itemsize or sha_file(path) != row['sha256']: raise ValueError('Shard incompatible con manifiesto')
arr = np.memmap(path,mode='r',dtype=dtype); available = len(arr)-CONTEXT
if available > 0: self.shards.append(arr); self.counts.append(available)
if not self.shards: raise ValueError('No hay ventanas de entrenamiento')
self.cumulative = np.cumsum(self.counts,dtype=np.int64)
def batch(self,rng):
samples = []
for draw in rng.integers(0,int(self.cumulative[-1]),size=BATCH):
i = int(np.searchsorted(self.cumulative,draw,side='right'))
start = int(draw-(self.cumulative[i-1] if i else 0))
samples.append(np.asarray(self.shards[i][start:start+CONTEXT+1],dtype=np.int64))
values = torch.as_tensor(np.stack(samples),device=DEVICE)
return values[:,:-1],values[:,1:]
def validation_set(manifest,tokenizer):
spec = manifest['groups']['fineweb/validation']; path = DATA/spec['validation_jsonl']
if sha_file(path) != spec['validation_sha256']: raise ValueError('Validación incompatible')
samples = []
for line in path.read_text(encoding='utf-8').splitlines():
row = json.loads(line); text = row['text']
if hashlib.sha256(text.encode('utf-8')).hexdigest() != row['sha256']: raise ValueError('Hash del documento inválido')
ids = tokenizer.encode(text,add_special_tokens=False).ids
if not ids or tokenizer.decode(ids,skip_special_tokens=False)!=text: continue
samples.append(ids[:96 if QUICK else 1024])
if len(samples) >= (2 if QUICK else 20): break
if not samples: raise ValueError('No hay documentos de validación reversibles')
return samples
@torch.inference_mode()
def evaluate(model,validation,eot):
total,tokens = 0.,0
for ids in validation:
for start in range(0,len(ids),CONTEXT):
target = ids[start:start+CONTEXT]
x = torch.tensor([[eot]+target[:-1]],device=DEVICE)
y = torch.tensor(target,device=DEVICE)
total += float(F.cross_entropy(model(x)[0].float(),y,reduction='sum')); tokens += len(target)
return {'nll_nats':total,'tokens':tokens,'loss_nats_per_token':total/tokens}
def loss_fit(rows,bootstrap=0):
N = np.array([r['N_non_embedding'] for r in rows],dtype=np.float64)/1e6
D = np.array([r['D_presented_tokens'] for r in rows],dtype=np.float64)/1e6
Y = np.log(np.array([r['validation']['loss_nats_per_token'] for r in rows]))
x,y = np.log(N),np.log(D); delta = .1
def objective(z,which):
e,a,b,la,lb = z; alpha,beta = np.exp(la),np.exp(lb)
terms = np.array([np.full(len(which),e),a-alpha*x[which],b-beta*y[which]])
prediction = logsumexp(terms,axis=0); prob = np.exp(terms-prediction); residual = prediction-Y[which]
absolute = np.abs(residual); huber = np.where(absolute<=delta,.5*residual**2,delta*(absolute-.5*delta))
psi = np.clip(residual,-delta,delta)
jac = np.array([prob[0],prob[1],prob[2],-prob[1]*alpha*x[which],-prob[2]*beta*y[which]])
return float(huber.mean()),(jac*psi).mean(axis=1)
bounds = [(math.log(1e-5),math.log(100))]*3+[(math.log(.01),math.log(2.))]*2
def fit(which):
fits = []
for alpha,beta in ((.1,.1),(.3,.3),(.6,.2),(.2,.6)):
z = np.log([max(.01,float(np.exp(Y).min())*.6),1.,1.,alpha,beta])
result = minimize(objective,z,args=(which,),jac=True,bounds=bounds,method='L-BFGS-B',options={'maxiter':400})
if np.isfinite(result.fun): fits.append(result)
if not fits: raise RuntimeError('No se obtuvo ajuste finito')
return min(fits,key=lambda q:q.fun)
result = fit(np.arange(len(rows))); params = np.exp(result.x)
output = {'E':params[0],'A':params[1],'B':params[2],'alpha':params[3],'beta':params[4],
'units':'N y D medidos en millones','huber_delta_log_loss':delta,'objective':float(result.fun),
'optimizer_success':bool(result.success),'message':str(result.message),'starts':4,
'parameters_near_bounds':[name for name,value,(lower,upper) in zip(('E','A','B','alpha','beta'),result.x,bounds)
if min(value-lower,upper-value)<1e-4],
'warning':'Convergencia numérica no implica identificabilidad; los límites activos y la extrapolación necesitan cautela'}
if bootstrap:
rng = np.random.default_rng(2011); estimates=[]
for _ in range(bootstrap):
sample = rng.integers(0,len(rows),size=len(rows)); res = fit(sample)
if res.success: estimates.append(np.exp(res.x)[3:5])
output['bootstrap'] = {'seed':2011,'requested':bootstrap,'successful':len(estimates),
'alpha_beta_95_percentiles':np.percentile(estimates,[2.5,97.5],axis=0).tolist() if len(estimates)>=2 else None,
'warning':'remuestreo de puntos: no captura sesgos sistemáticos y puede ser inestable'}
return output
def predict(fit,N,D):
terms = [math.log(fit['E']),math.log(fit['A'])-fit['alpha']*math.log(N/1e6),math.log(fit['B'])-fit['beta']*math.log(D/1e6)]
return float(math.exp(logsumexp(terms)))
def one_dimensional_fit(rows):
"""Recta en log-log con presupuesto índice 2; no separa el efecto de D."""
selected = [r for r in rows if r['budget_index']==2]
x = np.log(np.array([r['N_non_embedding']/1e6 for r in selected],dtype=np.float64))
y = np.log(np.array([r['validation']['loss_nats_per_token'] for r in selected],dtype=np.float64))
slope,intercept = np.polyfit(x,y,1)
return {'A':float(np.exp(intercept)),'alpha':float(-slope),'points':len(selected),
'units':'N en millones; pérdida total en nats/token; sin término irreducible',
'selection':'índice de presupuesto 2; FLOPs aproximadamente constantes en FULL, D constante en QUICK',
'warning':'El ajuste confunde capacidad, datos y pérdida irreducible; no identifica una ley L(N) a D fijo en FULL'}
def profile(rows,budget,seeds):
selected = [r for r in rows if r['budget_index']==budget]
sizes = sorted({r['N_non_embedding'] for r in selected})
if len(sizes)<3: return {'status':'no identificado: menos de tres tamaños'}
mean_losses = []
fpt = []
for n in sizes:
group = [r for r in selected if r['N_non_embedding']==n]
by_seed = {r['seed']:r for r in group}
if any(seed not in by_seed for seed in seeds): return {'status':'no identificado: falta una semilla'}
mean_losses.append(float(np.mean([by_seed[seed]['validation']['loss_nats_per_token'] for seed in seeds])))
fpt.append(group[0]['flops_per_token_estimate'])
x=np.log(np.array(sizes,dtype=float)); y=np.array(mean_losses)
center=float(x.mean()); coeff=np.polyfit(x-center,y,2)
observed=int(np.argmin(y)); max_error=max(abs(r['training_flops_estimate']/BUDGETS[budget]-1) for r in selected)
result={'budget_target':BUDGETS[budget],'N':sizes,'mean_loss':mean_losses,'flops_per_token':fpt,
'observed_minimum_N':sizes[observed],'observed_minimum_loss':mean_losses[observed],
'coefficients_centered':coeff.tolist(),'logN_center':center,'max_relative_budget_error':max_error}
if max_error > .1:
result['status']='no identificado: presupuestos efectivos difieren más del 10 %'; return result
if not np.isfinite(coeff).all() or coeff[0]<=0:
result['status']='no identificado: parábola no convexa'; return result
vertex=center-coeff[1]/(2*coeff[0])
if not x[0] < vertex < x[-1]:
result['status']='no identificado: vértice fuera del rango medido'; return result
nopt=float(np.exp(vertex)); fopt=float(np.exp(np.interp(vertex,x,np.log(fpt))))
dopt=BUDGETS[budget]/fopt
result.update({'status':'identificado dentro del rango','N_opt':nopt,'D_opt_exposures':dopt,
'tokens_per_non_embedding_parameter':dopt/nopt,
'interpolation':'log FLOPs por token entre arquitecturas medidas'})
return result
def profile_exponent(profiles):
good = [p for p in profiles if p['status']=='identificado dentro del rango']
if len(good)<3: return None
return float(np.polyfit(np.log([p['budget_target'] for p in good]),np.log([p['N_opt'] for p in good]),1)[0])
def parametric_profile(fit,rows,budget):
if fit['parameters_near_bounds']:
return {'status':'no identificado: ajuste paramétrico en límite','parameters_near_bounds':fit['parameters_near_bounds']}
selected = [r for r in rows if r['budget_index']==budget]
uniq = {r['N_non_embedding']:r['flops_per_token_estimate'] for r in selected}
sizes = sorted(uniq); x=np.log(sizes); y=np.log([uniq[n] for n in sizes]); C=BUDGETS[budget]
def objective(logn):
n=math.exp(logn); d=C/math.exp(float(np.interp(logn,x,y)))
return predict(fit,n,d)
optimum=minimize_scalar(objective,bounds=(x[0],x[-1]),method='bounded')
if not optimum.success or min(optimum.x-x[0],x[-1]-optimum.x)<1e-3:
return {'status':'no identificado: mínimo paramétrico en frontera o fallo'}
n=math.exp(optimum.x); d=C/math.exp(float(np.interp(optimum.x,x,y)))
return {'status':'identificado dentro del rango','N_opt':n,'D_opt_exposures':d,'tokens_per_non_embedding_parameter':d/n,
'interpolation':'log FLOPs por token entre arquitecturas medidas'}
def train_one(config,budget_index,seed,windows,validation,eot,vocab):
width,layers,heads = config; torch.manual_seed(seed)
model = MiniLlama(vocab,width,layers,heads).to(DEVICE); counts = count(model)
per_token = flop_per_token(counts,width,layers)
total = max(4,round(BUDGETS[budget_index]/per_token/(BATCH*ACCUM*CONTEXT)))
optimizer = torch.optim.AdamW(model.parameters(),lr=3e-4,weight_decay=.1); rng = np.random.default_rng(seed)
for step in range(total):
for group in optimizer.param_groups: group['lr'] = lr(step,total)
model.train(); optimizer.zero_grad(set_to_none=True)
for _ in range(ACCUM):
x,y = windows.batch(rng)
with (torch.autocast('cuda',dtype=torch.bfloat16) if DEVICE.type=='cuda' and torch.cuda.is_bf16_supported() else nullcontext()):
logits = model(x).float(); ce = F.cross_entropy(logits.reshape(-1,vocab),y.reshape(-1))
loss = (ce+1e-5*torch.logsumexp(logits,dim=-1).square().mean())/ACCUM
if not torch.isfinite(loss): raise FloatingPointError('Pérdida no finita')
loss.backward()
nn.utils.clip_grad_norm_(model.parameters(),1.); optimizer.step()
model.eval(); val = evaluate(model,validation,eot)
row = {'width':width,'layers':layers,'heads':heads,'ff':4*width,'seed':seed,'budget_index':budget_index,'budget_target':BUDGETS[budget_index],'steps':total,
'N_non_embedding':counts['non_embedding'],'embedding_tied':counts['embedding_tied'],'total_tied':counts['total_tied'],
'D_presented_tokens':total*BATCH*ACCUM*CONTEXT,'flops_per_token_estimate':per_token,
'training_flops_estimate':per_token*total*BATCH*ACCUM*CONTEXT,'validation':val}
del model,optimizer; gc.collect()
if DEVICE.type=='cuda': torch.cuda.empty_cache()
return row
def main():
OUT.mkdir(parents=True,exist_ok=True); manifest_path = DATA/'manifest.json'
manifest = json.loads(manifest_path.read_text(encoding='utf-8')); tokenizer_path = DATA/manifest['tokenizer']['path']
if manifest['version']!=1 or manifest['dtype'] not in ('<u2','<u4') or sha_file(tokenizer_path)!=manifest['tokenizer']['sha256']: raise ValueError('Datos o tokenizador incompatibles')
tokenizer = Tokenizer.from_file(str(tokenizer_path)); eot = int(manifest['tokenizer']['eot_id']); vocab = eot+1
if tokenizer.get_vocab_size()!=eot or manifest['tokenizer']['model_vocab_size']!=vocab: raise ValueError('EOT o vocabulario incompatibles')
windows = Windows(manifest); validation = validation_set(manifest,tokenizer); rows = []
for config in CONFIGS:
for budget in range(3):
for seed in SEEDS:
row = train_one(config,budget,seed,windows,validation,eot,vocab); rows.append(row)
print('Modelo',config,'presupuesto',budget,'semilla',seed,'pasos',row['steps'],
'pérdida',row['validation']['loss_nats_per_token'],flush=True)
fit = loss_fit(rows,bootstrap=0)
# Bootstrap por ejecución completa de semilla, no por puntos dependientes.
if not QUICK:
seed_rng=np.random.default_rng(2013); cache={}; estimates=[]; bound_hits=0; repetitions=60
for _ in range(repetitions):
draw=tuple(sorted(SEEDS[i] for i in seed_rng.integers(0,len(SEEDS),size=len(SEEDS))))
if draw not in cache:
sample=[r for seed in draw for r in rows if r['seed']==seed]
cache[draw]=loss_fit(sample,bootstrap=0)
trial=cache[draw]
if trial['parameters_near_bounds']: bound_hits += 1
if trial['optimizer_success'] and not trial['parameters_near_bounds']:
estimates.append([trial['alpha'],trial['beta']])
fit['bootstrap']={'seed':2013,'requested':repetitions,'valid':len(estimates),'bound_hits':bound_hits,
'unit':'semilla agrupada entre tamaños y presupuestos',
'alpha_beta_95_percentiles':np.percentile(estimates,[2.5,97.5],axis=0).tolist() if len(estimates)>=2 else None,
'warning':'dos semillas producen solo tres remuestreos distintos; no incluye sesgo del modelo'}
profiles = [profile(rows,budget,SEEDS) for budget in range(3)]
parametric = [parametric_profile(fit,rows,budget) for budget in range(3)]
base_exponent = profile_exponent(profiles); rng=np.random.default_rng(2012)
samples=[[] for _ in profiles]; exponents=[]; n_boot=40 if QUICK else 200
for _ in range(n_boot):
# Una semilla se remuestrea como bloque para todos los tamaños y presupuestos.
seeds = [SEEDS[i] for i in rng.integers(0,len(SEEDS),size=len(SEEDS))]
trials = [profile(rows,budget,seeds) for budget in range(3)]
for i,p in enumerate(trials):
if p['status']=='identificado dentro del rango': samples[i].append(p['N_opt'])
exponent=profile_exponent(trials)
if exponent is not None: exponents.append(exponent)
for p, values in zip(profiles,samples):
p['bootstrap']={'seed':2012,'requested':n_boot,'valid':len(values),
'N_interval_95':np.percentile(values,[2.5,97.5]).tolist() if len(values)>=2 else None,
'unit':'semilla agrupada a través de tamaños y presupuestos',
'warning':'con dos semillas las bandas son muy discretas; no capturan sesgo del diseño'}
result = {'config':{'quick':QUICK,'context':CONTEXT,'batch':BATCH,'accumulation':ACCUM,'seeds':SEEDS,
'budget_flops_requested':list(BUDGETS),
'D_definition':'tokens presentados con muestreo con reemplazo, no tokens únicos',
'schedule':'WSD recalculado para cada duración','z_loss_coefficient':1e-5,
'flops':'6*(N no embedding + embedding ligado usado en cabeza)*D + 12*capas*contexto*anchura*D; aproximación de atención densa',
'validation':'mismos documentos y prefijos, contexto reiniciado con EOT; pérdida en nats/token'},
'source':{'manifest_sha256':sha_file(manifest_path),'tokenizer_sha256':sha_file(tokenizer_path),
'validation_sha256':manifest['groups']['fineweb/validation']['validation_sha256'],
'torch':torch.__version__,'device':str(DEVICE)},
'models':rows,'observed_and_quadratic_profiles':profiles,'parametric_fit':fit,'parametric_profiles':parametric,
'N_opt_exponent':base_exponent,
'exponent_bootstrap':{'requested':n_boot,'valid':len(exponents),
'interval_95':np.percentile(exponents,[2.5,97.5]).tolist() if len(exponents)>=2 else None,
'unit':'semilla agrupada a través de tamaños y presupuestos'},
'limitations':'semillas escasas, hiperparámetros fijos, exposiciones con reemplazo, validación común; no se atribuyen resultados de Chinchilla a este ensayo'}
(OUT/'isoflop-report.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
print('Perfiles:',[p['status'] for p in profiles],flush=True)
print('Informe:',OUT/'isoflop-report.json',flush=True)
if __name__=='__main__': main()npm run lab and open the connection link.Exercises
Step 1 of 3. What condition results from equating the Lagrange multipliers?
import numpy as np
def isoflop_minimum(N, L, n_boot=200, seed=17):
pass
The optimum depends on the question: minimum loss for one training run, total model-lifetime cost, or best use of limited data. Each answer requires a cost function, measurable assumptions, and validation.