Module contents
Lesson 11 of 26Advanced 115 min

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

Before spending the budget

Imagine testing several small models before dedicating 102410^{24} 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.

InteractiveHow much do you trust extrapolation?

Points measured in the lesson’s short run: loss in nats/token on the same validation texts versus estimated FLOPs. Circles are available fits; the diamond is a larger held-out model that never enters this fit. Click a circle or use the list below to exclude it.

7.6007.6147.6287.6427.656w32-l1-s4-seed2007: C=1.29e8, loss 7.62777w32-l1-s8-seed2007: C=2.58e8, loss 7.62683w32-l1-s12-seed2007: C=3.88e8, loss 7.62604w48-l1-s4-seed2007: C=2.13e8, loss 7.63447w48-l1-s8-seed2007: C=4.25e8, loss 7.63341w48-l1-s12-seed2007: C=6.38e8, loss 7.63213w64-l2-s4-seed2007: C=4.16e8, loss 7.62582w64-l2-s8-seed2007: C=8.32e8, loss 7.62362w64-l2-s12-seed2007: C=1.25e9, loss 7.62069w80-l2-s4-seed2007: C=5.83e8, loss 7.65220w80-l2-s8-seed2007: C=1.17e9, loss 7.64484w80-l2-s12-seed2007: C=1.75e9, loss 7.63808Held-out model: 7.63695 nats/token1.29e81.75e910×100×Estimated FLOPs · logarithmic axis

● Training runs used · empty circle: excluded · ◆ held-out model · band: pointwise bootstrap percentiles. 10× and 100× refer to the highest compute among included points. The vertical axis is also logarithmic and enlarged to show small differences.

Exclude or restore fit points

Fit L(C) = E + A(C/C₀)−α, with C₀ = 5.19e8, E = 0.00000, A = 7.63215, α = 0.00000. Residuals in log L are minimized using squares; E ≥ 0, E below the minimum loss, and 0 ≤ α ≤ 3 are imposed, with multiple initializations. The exponent reached zero: a flat curve does not identify E and A separately. The sweep mixes sizes and durations: a one-dimensional fit in C does not separately identify the effect of N and D.

The band uses 100 valid fits from 100 point resamples, seed 2011, 2.5th and 97.5th percentiles at each C; it is drawn only with at least 20 valid fits. It treats observations as exchangeable and excludes uncertainty from hyperparameters or corpus; the points share one seed, so it is neither a coverage guarantee nor a validation of extrapolation.

The short run uses tiny networks and 4, 8 or 12 steps, not the scale of the full experiment. The lab’s joint L(N,D) fit, distinct from this figure’s fit in C, froze a prediction of 7.62477 nats/token before measuring 7.63695; its exponents reached the optimizer boundary. These points do not establish a scaling law or support extrapolation by orders of magnitude. FLOPs include the tied head and dense attention as an estimate; D counts exposures with replacement.

Fit loss
Fit points
12 / 12
Exponent α
0.0000
Prediction at 10×
7.63215
Prediction at 100×
7.63215
Compare fits and observe how predictions change when points are removed.

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 LL layers, width dd, standard multi-head attention, and MLP width 4d4d, four attention matrices total approximately 4d24d^2 parameters per layer and two MLP matrices 8d28d^2. Thus Nnoemb≈12Ld2N_{\mathrm{noemb}}\approx12Ld^2, omitting biases and normalizations. For SwiGLU, grouped attention, or different matrices, substitute the actual architecture. The embedding table has VdVd 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 NN parameters cost roughly 6N6N per token and C≈6NDC\approx6ND for DD token exposures. For the transformer above, attention adds approximately 12LTd12LTd training FLOPs per token at sequence length TT: in the forward pass, QK⊤QK^\top and attention over values together cost about 4Td4Td per layer and token. Causal masks, kernels, recomputation, and effective length change constants. Output projection adds on the order of 6Vd6Vd per training token even when its weights are tied to input. Report whether NN includes those weights and whether CC 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:

L(N)≈(Nc/N)αN,L(D)≈(Dc/D)αD,L(Cmin⁡)≈(Cc/Cmin⁡)αC.L(N)\approx(N_c/N)^{\alpha_N},\qquad L(D)\approx(D_c/D)^{\alpha_D},\qquad L(C_{\min})\approx(C_c/C_{\min})^{\alpha_C}.

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 0,0760{,}076, 0,0950{,}095, and 0,0500{,}050. NN counts non-embedding parameters; DD counts tokens; Cmin⁡C_{\min} 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:

L(N,D)=[(NcN)αN/αD+DcD]αD.L(N,D)=\left[\left(\frac{N_c}{N}\right)^{\alpha_N/\alpha_D}+\frac{D_c}{D}\right]^{\alpha_D}.

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, Bcrit(L)≈B∗/L1/αBB_{\mathrm{crit}}(L)\approx B_*/L^{1/\alpha_B}, with B∗≈2⋅108B_*\approx2\cdot10^8 tokens and αB≈0,21\alpha_B\approx0{,}21. 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

L(N,D)=E+ANα+BDβ.L(N,D)=E+\frac{A}{N^\alpha}+\frac{B}{D^\beta}.

EE represents irreducible loss within the assumed distribution and formalization; remaining terms model finite-capacity and finite-data or finite-training errors. The fitted EE cannot automatically be identified with true entropy: model misspecification, optimization, context, and distribution shifts can be absorbed into it. In the published fit, E=1,69E=1{,}69, A=406,4A=406{,}4, B=410,7B=410{,}7, α=0,34\alpha=0{,}34, and β=0,28\beta=0{,}28 for their units and data. These are not constants transferable to another corpus.

InteractiveThe loss surface

Horizontal axes: log₁₀ N from 7 to 11 and log₁₀ D from 8 to 13. Height represents L(N,D), linearly rescaled between the extremes of the current surface; color also rescales as parameters change. Drag or use the controls to rotate. The projected line marks C=6ND and the point marks the optimum when it is within the domain; the line is drawn on top so it remains visible.

log₁₀ N → 11log₁₀ D → 13

Model L=E+A/Nᵅ+B/Dᵝ, with N and D in individual units. Initialized from the parametric fit by Hoffmann and colleagues, appendix D.2: E=1.69, A=406.4, B=410.7, α=0.34 and β=0.28. Under C≈6ND, the interior optimum satisfies N*=[αA(C/6)ᵝ/(βB)]¹⁄⁽ᵅ⁺ᵝ⁾ and D*=C/(6N*). Some areas extrapolate that fit rather than observed results; changing E does not change the optimal position.

1.69
406.4
410.7
0.34
0.28
22.00
−30°
35°
Optimal N
5.160e+9
Optimal D
3.230e+11
Optimal loss
2.139
Modify terms and rotate the surface; curves represent constant compute budgets under the stated approximation.

If C=6NDC=6ND and coefficients are positive, substitute D=C/(6N)D=C/(6N) and differentiate with respect to NN: the interior minimum satisfies αAN−α=βBD−β\alpha A N^{-\alpha}=\beta B D^{-\beta}. 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 L=E+AN−αL=E+AN^{-\alpha}, the line on log axes is log⁡(L−E)=log⁡A−αlog⁡N\log(L-E)=\log A-\alpha\log N only when EE is known and L>EL>E. Fitting log⁡L\log L directly with E>0E>0 decreases slope magnitude near the floor. Simultaneously estimating EE 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 a=log⁡Aa=\log A, b=log⁡Bb=\log B, and e=log⁡Ee=\log E. Then

log⁡L^i=LSE⁡(a−αlog⁡Ni, b−βlog⁡Di, e).\log \widehat L_i=\operatorname{LSE}(a-\alpha\log N_i,\ b-\beta\log D_i,\ e).

Log-sum-exp evaluates the sum without unnecessarily large exponents. Minimize Huber loss of residuals log⁡L^i−log⁡Li\log\widehat L_i-\log L_i: it is quadratic near zero and linear beyond threshold δ\delta. 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 δ=10−3\delta=10^{-3}; 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 dd and the network approximates a smooth function by regions. If NN regions resolve an approximately dd-dimensional volume, their typical diameter scales as h∝N−1/dh\propto N^{-1/d}. If local function approximation error is O(h2)O(h^2) and relevant loss is quadratic in that error, reducible loss scales as O(h4)=O(N−4/d)O(h^4)=O(N^{-4/d}). This intuition requires coverage, smoothness, and capacity-to-region assumptions. It does not prove real text has one intrinsic dimension or every architecture follows 4/d4/d.

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

InteractiveTraining schedules and bias

Analytic control, not measured training runs. For the selected size, D=C/(6N): the first two charts show relative rate and hypothetical loss during the budget; the third compares final losses for different sizes with the same C.

Estimated slope of log N* against log C for three budgets 10²⁰, 10²¹ and 10²²: matched 0.462; long horizon 0.425. The optimum is searched over 121 sizes from 10⁸ to 10¹¹: a boundary minimum limits interpretation.

We define η(t;H)=[1+cos(π min(t/H,1))]/2 and L(t)=1.69+406.4/N^0.34+410.7/t^0.28+λ(10⁹/N)^0.4 η(t;H), with H=D for the matched schedule and H=2·10¹³ for the long one. The loss curve starts at t=0.05D because the data term diverges at zero. The final term is a penalty chosen for this example: it is not derived from the learning curve and does not reproduce an experimental result. Change the assumed effect and check that the difference depends on the model.

In Porian and colleagues, accounting for the final layer, adjusting warmup, and tuning hyperparameters played an important role. After correcting compute and warmup, adding cosine decay moved the exponent from approximately 0.60 to 0.57; on its own it did not resolve the discrepancy. This simulation does not establish its cause.

21.00
9.00
0.50
Optimal N, matched
1.78e+9
Optimal N, long horizon
7.94e+9
L at chosen size
2.340 / 2.840
Compare a long horizon with schedules adapted to the budget using the figure's controlled model.

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 0,600{,}60 to 0,570{,}57; 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.

[ ]PythonBrowser
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.

[ ]Scaling sweep and held-out predictionLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericTraining budget
Estimate training FLOPs for a model with 7,000 million parameters and two trillion tokens, using C = 6ND without additional terms.
NumericHow much to halve loss?
If reducible loss is proportional to N raised to −0.076, by what factor must N be multiplied to halve that loss?
CodeFit a surface
Implement fit_scaling_law(N, D, L), returning positive E, A, B, alpha, and beta in that order. Fit E + A/N^alpha + B/D^beta by minimizing Huber loss with delta 0.01 on log-loss residuals. Use log-sum-exp, L-BFGS-B, and multiple starts. Reject vectors of different size, non-one-dimensional vectors, fewer than six points, or nonpositive or nonfinite values. The test checks recovery on a wide synthetic grid; good recovery here does not guarantee general identifiability.
import numpy as np
from scipy.optimize import minimize
from scipy.special import logsumexp

def fit_scaling_law(N, D, L):
  pass
Shift+Enter to run
QuizFrom five models to one 100 times larger
You fit five models with 1 to 10 million parameters and predict loss at 1,000 million. Which conclusion is justified?
ProofScaling and intrinsic dimension
Prove: Under an idealized smooth d-dimensional manifold model, explain why loss may follow a power with exponent inversely proportional to d.
0
Assume N regions of comparable volume, local function error of order h², and loss quadratic in that error.

Step 1 of 3. How does each region’s characteristic length h scale?

Key idea

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.