Scaling laws
Study empirical scaling laws for parameters, data, and compute; account for transformer FLOPs; fit robust power laws with uncertainty; and evaluate a held-out extrapolation.
After this lesson you can
- Count non-embedding parameters and per-token transformer training FLOPs, including attention.
- State Kaplan's laws in N, D, and C and their joint form, interpreting exponents and irreducible loss.
- Fit power laws with Huber loss in log space and estimate exponent uncertainty by bootstrap.
- Run a local sweep of 1 to 30 million parameter models and validate extrapolation with a larger held-out model.
- Identify schedule, embedding accounting, and size-specific hyperparameter choices that bias measured exponents.
Before you start
- 20Pretraining token budgetPretraining run monitoringBatch size in tokens
- 18Transformer parameter and FLOP accounting
- 05Nonparametric bootstrapParametric bootstrapHuber M-estimatorM-estimators and Z-estimators
- 06Limited-memory BFGS
- 15Maximal update parametrizationHyperparameter transfer
- 13Excess risk decomposition
Before spending the budget
Imagine testing several small models before dedicating FLOPs to a large one. A loss-versus-compute curve lets you form a prediction, but a straight line fitting the tests does not guarantee it remains valid six orders of magnitude later. The useful decision involves more than which curve to fit: you also need to know what was counted, how each point trained, and how the prediction changes when data change.
A neural scaling law summarizes an empirical regularity: within a regime, loss or its reducible part decreases approximately as a power of resources. On logarithmic axes a power without a constant is a straight line; with an additive floor, total loss is no longer straight. Hestness and colleagues studied generalization curves in translation, language, images, and speech. Kaplan and colleagues later quantified relationships for language models, and Henighan and colleagues studied autoregressive modeling in images, video, and other modalities. Regularity across tasks does not make their exponents universal constants.
Count what the model executes
Parameter and FLOP accounting should accompany each curve. In a dense transformer with layers, width , standard multi-head attention, and MLP width , four attention matrices total approximately parameters per layer and two MLP matrices . Thus , omitting biases and normalizations. For SwiGLU, grouped attention, or different matrices, substitute the actual architecture. The embedding table has parameters; if input and output weights are tied, count it once in memory even though output projection still costs compute.
A multiplication and addition count as two FLOPs. Assuming backpropagation costs twice the forward pass, dense products associated with parameters cost roughly per token and for token exposures. For the transformer above, attention adds approximately training FLOPs per token at sequence length : in the forward pass, and attention over values together cost about per layer and token. Causal masks, kernels, recomputation, and effective length change constants. Output projection adds on the order of per training token even when its weights are tied to input. Report whether includes those weights and whether includes that product and attention.
For long windows or small models these omissions can matter. Porian and colleagues show that excluding final-layer cost particularly distorts small-model comparison. A FLOP estimate is not a GPU measurement: hardware utilization and memory determine actual time.
Three slices and a surface
Within their experimental regime, Kaplan and colleagues fitted the following relations for test loss in nats per token:
The first slice uses sufficient data and training to convergence; the second uses large models and early stopping with limited data; the third requires sufficient data and compute-optimal allocation with a sufficiently small batch. Their respective exponents were approximately , , and . counts non-embedding parameters; counts tokens; is compute adjusted to the small-batch regime, not necessarily a particular run’s measured cost. Scale coefficients depend on data and tokenizer.
Do not directly compare nats per token across different tokenizers: the same text sequence may produce different token counts. To compare the same text and protocol, normalize log-likelihood by bytes, as in bits per byte; retain boundary and context definitions too.
To combine capacity and data, Kaplan proposed an expression different from Chinchilla’s later sum:
In its joint fit, parameters differ slightly from individual slices. Do not mix coefficients from different tables. Its estimated critical batch also depends on loss, , with tokens and . It describes a step-versus-sample tradeoff under those experimental conditions, not a universal batch or exact equality.
Hoffmann and colleagues fitted the parametric law
represents irreducible loss within the assumed distribution and formalization; remaining terms model finite-capacity and finite-data or finite-training errors. The fitted cannot automatically be identified with true entropy: model misspecification, optimization, context, and distribution shifts can be absorbed into it. In the published fit, , , , , and for their units and data. These are not constants transferable to another corpus.
If and coefficients are positive, substitute and differentiate with respect to : the interior minimum satisfies . The valley depends on exponents, coefficients, and compute definition. The next lesson studies how to choose allocation and why training and inference optima can differ.
Fit a power without inventing certainty
If , the line on log axes is only when is known and . Fitting directly with decreases slope magnitude near the floor. Simultaneously estimating and the exponent is difficult when points cover a narrow interval: very different combinations can explain observed data and diverge under extrapolation.
For the joint law, write , , and . Then
Log-sum-exp evaluates the sum without unnecessarily large exponents. Minimize Huber loss of residuals : it is quadratic near zero and linear beyond threshold . The parameterization ensures positive coefficients, but does not make the joint problem convex. Use multiple initial points, inspect convergence and bounds, and compare solutions. Hoffmann used L-BFGS, a grid of starts, and ; the following cell uses a different threshold and a small grid for a quick demonstration.
A bootstrap resamples experimental units and repeats the fit. Its intervals reflect variation represented by that resampling, not architectural changes or the possibility that the law ceases to hold. If measurements share a run, they are not independent: resample by run or seed, not as isolated points. With few sizes, inspect retained points and selection bias; a narrow interval under a wrong model can mislead.
A possible explanation, not a universal theorem
Sharma and Kaplan studied a model in which data occupy a smooth manifold of intrinsic dimension and the network approximates a smooth function by regions. If regions resolve an approximately -dimensional volume, their typical diameter scales as . If local function approximation error is and relevant loss is quadratic in that error, reducible loss scales as . This intuition requires coverage, smoothness, and capacity-to-region assumptions. It does not prove real text has one intrinsic dimension or every architecture follows .
Bahri and colleagues distinguish variance-limited and resolution-limited regimes and relate the latter to the data manifold and certain kernel spectra in idealized limits. Different mechanisms can yield different exponents. An empirical fit describes an observed region; it does not identify the causal mechanism by itself.
Comparison depends on the schedule
A long schedule cut short has not followed the same learning-rate trajectory as one designed to finish at that budget. The figure is a mathematical control, not a reproduction of historical experiments. Porian and colleagues separated several factors: final-layer compute, warmup too long for small runs, and batch and other hyperparameter choices. In their ablation, correcting schedule decay after compute and warmup changed the optimal exponent approximately from to ; it did not by itself close the entire discrepancy. Do not attribute the Kaplan-Chinchilla difference only to cosine decay.
When designing a sweep, fix corpus, tokenizer, validation, FLOP criterion, and architecture, and record repeated exposures. Adjust warmup and duration for each budget and document how learning rate and batch are chosen per size. A parameterization such as μP may help transfer hyperparameters under its assumptions; it does not remove the need to verify them. Separate training seeds from validation and keep the largest model out of the fit until the prediction is frozen.
Lab: recovery and bootstrap
The cell’s points are synthetic, defined by a known law and perturbed with reproducible multiplicative noise. They test whether fitting can recover parameters in a favorable case; they are not LLM measurements. The cell uses analytic derivatives, bounded L-BFGS, and four starts. Bootstrap resamples independent observations from this grid. Its 20 replicates are only a quick demonstration: extreme percentiles are unstable with so few. A real experiment should use more replicates and respect the appropriate grouping unit.
import numpy as np
from scipy.optimize import minimize
from scipy.special import logsumexp
def fit_scaling_law(N, D, loss, starts=None):
N, D, loss = (np.asarray(x, dtype=float) for x in (N, D, loss))
if N.shape != D.shape or N.shape != loss.shape or N.ndim != 1:
raise ValueError('N, D y pérdida deben ser vectores de igual tamaño')
if len(N) < 6 or any(not np.all(np.isfinite(x)) or np.any(x <= 0) for x in (N,D,loss)):
raise ValueError('Se necesitan al menos seis observaciones positivas y finitas')
x, y, target = np.log(N), np.log(D), np.log(loss)
delta = 0.01
def objective(theta):
a, b, e, alpha, beta = theta
terms = np.vstack((a-alpha*x, b-beta*y, np.full_like(x,e)))
pred = logsumexp(terms, axis=0)
weights = np.exp(terms-pred)
residual = pred-target
magnitude = np.abs(residual)
value = np.where(magnitude <= delta, residual**2/2, delta*(magnitude-delta/2)).mean()
psi = np.clip(residual, -delta, delta) / len(x)
jac = np.vstack((weights[0],weights[1],weights[2],-x*weights[0],-y*weights[1]))
return value, jac @ psi
if starts is None:
starts = [(np.log(5),np.log(3),np.log(1),a,b) for a in (0.25,0.5) for b in (0.25,0.5)]
bounds = [(-10,15),(-10,15),(-10,5),(0.01,1.5),(0.01,1.5)]
results = [minimize(objective, init, jac=True, method='L-BFGS-B', bounds=bounds,
options={'maxiter':350, 'ftol':1e-12, 'gtol':1e-8}) for init in starts]
best = min(results, key=lambda result: result.fun)
a,b,e,alpha,beta = best.x
return {'E':np.exp(e),'A':np.exp(a),'B':np.exp(b),'alpha':alpha,'beta':beta,
'objective':best.fun,'converged':bool(best.success),'theta':best.x}
# Rejilla sintética explícita: no es un resultado de entrenamiento.
random = np.random.default_rng(71)
N,D = np.meshgrid(np.geomspace(1e2,1e6,8), np.geomspace(1e2,1e6,8))
N,D = N.ravel(),D.ravel()
truth = {'E':1.0,'A':8.0,'B':6.0,'alpha':0.35,'beta':0.30}
clean = truth['E'] + truth['A']/N**truth['alpha'] + truth['B']/D**truth['beta']
L = clean*np.exp(random.normal(0,0.003,len(clean)))
fit = fit_scaling_law(N,D,L)
print('Parámetros verdaderos:',truth)
print('Ajuste:',{key:round(float(fit[key]),4) for key in ('E','A','B','alpha','beta')})
print('Convergió:',fit['converged'])
# Bootstrap de observaciones: la incertidumbre no incluye cambio de dominio.
boot = []
for _ in range(20):
sample = random.integers(0,len(N),len(N))
trial = fit_scaling_law(N[sample],D[sample],L[sample],starts=[fit['theta']])
if trial['converged']:
boot.append((trial['alpha'],trial['beta']))
print('Bootstrap convergidos:',len(boot),'de 20')
if len(boot) >= 2:
interval = np.quantile(boot,[0.025,0.975],axis=0)
print('Intervalos 95 % alpha y beta:',np.round(interval,4))
else:
print('No hay suficientes ajustes convergidos para calcular intervalos')
print('Ejercicio FLOPs y factor:',6*7e9*2e12,2**(1/0.076))Local lab: predict before training
This sweep uses data generated by m20-l07. Set ORYON_DATA_DIR to the directory containing its manifest.json, tokenizer, and shards. Hashes are checked before opening memmaps. If those files are missing, first run the pretraining lab. Install torch, numpy, scipy, and tokenizers.
Full mode trains four MiniLlama architectures at three budgets and two seeds, 24 runs total, followed by a larger held-out model. Sizes and layer dimensions are explicit; the report counts actual non-embedding parameters and the tied embedding matrix once. Window sampling is with replacement: D counts tokens presented to the optimizer, not unique examples. It uses duration-adapted WSD, z-loss, and a common optimizer with fixed hyperparameters. This is not μP and does not eliminate possible hyperparameter differences between sizes.
Approximate compute sums 6*(N + embedding)*D and dense attention term 12*capas*contexto*anchura*D. The tied matrix is counted in the output head, norms are included in N, and the factor of three for backward is approximate. These are not hardware-measured FLOPs and do not discount masked causal positions. Budgets round to complete steps. Every point uses the same validation documents and prefixes with the same tokenizer, in nats per token; context resets with EOT per block. Shared validation compares the held-out point with the fit, but alone does not estimate generalization to another distribution.
L = E + A/(N/10^6)^α + B/(D/10^6)^β is fitted with positive parameters, log-sum-exp, Huber on log loss, and four L-BFGS-B initializations. The report flags parameters near bounds: numerical convergence does not guarantee exponent identification. Bootstrap resamples points and does not correct systematic bias or dependence among seeds; intervals can be unstable. Before training or evaluating the larger model, fit-before-holdout.json is saved with the fit and prediction; a copy is instantiated first to count parameters. The later report shows predicted and measured loss without turning isolated agreement into an extrapolation guarantee. Seeds and deterministic algorithms permit repetition in a compatible environment without promising identity across versions or devices.
As an additional comparison, a log-log line fits total loss versus N using highest-budget points, without an irreducible term. In full mode points have approximately equal compute, so D changes with N: that slope mixes capacity and data and does not identify a capacity law at fixed D. In short mode steps and D are equal for those points, but too few to support a scaling conclusion.
ORYON_QUICK=1 reduces models, validation data, budgets, and seeds to check the end-to-end path. Parameters estimated in that mode do not identify a scaling law. ORYON_SCALING_DIR chooses an output folder; use a new one to retain each experiment. Figure data must come from the real report and identify its mode, seeds, tokenizer, and budgets; it contains no document text.
"""Barrido MiniLlama reproducible con predicción congelada antes del modelo retenido."""
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
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_SCALING_DIR','./oryon-scaling'))
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
CONTEXT = 32 if QUICK else 128
BATCH, ACCUM = (2,1) if QUICK else (2,4)
SEEDS = (2007,) if QUICK else (2007,2008)
CONFIGS = ([(32,1,4),(48,1,4),(64,2,4),(80,2,4)] if QUICK else
[(128,4,4),(192,6,6),(256,8,8),(352,14,11)])
HOLDOUT = (96,3,4) if QUICK else (448,20,14)
BUDGETS = (1e14,3e14,1e15)
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 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 = ((4,8,12)[budget_index] if QUICK else max(4,math.ceil(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,'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); row['role']='fit'; rows.append(row)
print('Modelo',config,'presupuesto',budget,'semilla',seed,'pérdida',row['validation']['loss_nats_per_token'],flush=True)
fit = loss_fit(rows,bootstrap=0 if QUICK else 60)
fit_1d = one_dimensional_fit(rows)
# Se congela la predicción antes de crear o entrenar el modelo mayor.
held_width,held_layers,held_heads = HOLDOUT
with torch.random.fork_rng():
torch.manual_seed(SEEDS[0]); probe = MiniLlama(vocab,held_width,held_layers,held_heads)
held_counts = count(probe); held_per_token = flop_per_token(held_counts,held_width,held_layers); del probe
held_steps = 12 if QUICK else max(4,math.ceil(BUDGETS[-1]/held_per_token/(BATCH*ACCUM*CONTEXT)))
held_D = held_steps*BATCH*ACCUM*CONTEXT
frozen = {'fit':fit,'one_dimensional_fit':fit_1d,'heldout_config':HOLDOUT,'N_non_embedding':held_counts['non_embedding'],
'D_presented_tokens':held_D,'predicted_loss_nats_per_token':predict(fit,held_counts['non_embedding'],held_D),
'fit_rows':len(rows),'frozen_before_heldout_training':True}
(OUT/'fit-before-holdout.json').write_text(json.dumps(frozen,ensure_ascii=False,indent=2),encoding='utf-8')
held = train_one(HOLDOUT,2,SEEDS[0],windows,validation,eot,vocab); held['role']='holdout'
assert held['D_presented_tokens']==held_D and held['N_non_embedding']==held_counts['non_embedding']
result = {'config':{'quick':QUICK,'context':CONTEXT,'batch':BATCH,'accumulation':ACCUM,'seeds':SEEDS,
'budget_flops_requested':list(BUDGETS) if not QUICK else None,
'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)},
'fit':fit,'one_dimensional_fit':fit_1d,'prediction_before_holdout':frozen['predicted_loss_nats_per_token'],'models':rows+[held],
'limitations':'barrido pequeño, hiperparámetros fijos, exposiciones con reemplazo y validación común; ajuste inestable no demuestra una ley universal'}
(OUT/'scaling-report.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
print('Predicción congelada',result['prediction_before_holdout'],'pérdida medida',held['validation']['loss_nats_per_token'],flush=True)
print('Informe:',OUT/'scaling-report.json',flush=True)
if __name__=='__main__': main()npm run lab and open the connection link.Exercises
import numpy as np
from scipy.optimize import minimize
from scipy.special import logsumexp
def fit_scaling_law(N, D, L):
pass
Step 1 of 3. How does each region’s characteristic length h scale?
A scaling law is a quantitative hypothesis with an explicit validity domain and accounting. Scaling-law extrapolation is more useful when schedules, data, and hyperparameters are comparable and predictions are checked against a held-out experiment.