Module contents
Lesson 13 of 26Advanced 105 min

Data mixtures and synthetic data

Study domain mixtures, DoReMi, mixing laws and RegMix, synthetic pretraining data, web rephrasing, and recursive model collapse.

After this lesson you can

  • Define domain weights and token allocations and calculate average epochs per domain.
  • Implement a small DoReMi setup with a reference model, Group DRO proxy, and resulting weights.
  • Fit a mixing law with small models and predict per-domain loss for a new mixture.
  • Generate synthetic pretraining data with a local model and measure its effect on a small model.
  • Explain iterative Gaussian model collapse and how replacing versus accumulating data changes the dynamics.

Before you start

A mixture is a decision, not a list

A fixed training budget can be allocated among web text, code, mathematics, books, or languages in different proportions. Increasing one domain increases exposure to its examples and reduces exposure to others; effects depend on cross-domain transfer, quality, and evaluation. The best proportion cannot be inferred simply by counting documents.

A data mixture assigns weights ri≥0r_i\geq0 with ∑iri=1\sum_i r_i=1. If training processes DD tokens and domain ii has UiU_i unique tokens, allocating fraction rir_i implies approximately riD/Uir_iD/U_i epochs on that domain. This is an average under uniform token sampling: varying document length, sampling with replacement, deduplication, and changing schedules alter actual coverage. Retain token counts, provenance, and sampling rules, not just file percentages.

The Pile grouped 22 domains in a corpus of about 800 GB and used heuristic weights. Raising a small source can expose valuable content but also repeat it many times. Average evaluation can hide degradation on an important language or task: report per-domain loss and state the use distribution weighting each result.

Reweighting with DoReMi

InteractiveDoReMi step by step

Deterministic three-domain control: this is not language-model training. The chart shows weights per step; the vertical mark indicates the selected step. Loss values are per token in this example, equal within each domain.

Web
proxy 2.200
reference 1.484
clipped excess 0.716
Code
proxy 2.900
reference 1.714
clipped excess 1.186
Mathematics
proxy 3.600
reference 2.044
clipped excess 1.556

We set floors h=(1.4; 1.6; 1.9), initial gaps g=(0.8; 1.3; 1.7), and reference h+(1−q)(0.28; 0.38; 0.48). At each step λᵢ=max(hᵢ+gᵢ−refᵢ,0); α′ᵢ∝αᵢexp(ηλᵢ), αᵢ=(1−c)α′ᵢ+c/3 and gᵢ←gᵢexp(−0.11αᵢ). The last equation is a teaching model of learning, not a trained network. The displayed average includes weights from steps 1 to t; at t=0 the uniform initialization is shown.

In DoReMi, algorithm 1, the per-token excess is clipped before averaging, weights are smoothed, and their time average is returned. An imperfect reference or changes in dynamics can change priority; this control does not guarantee a universal trajectory.

0.70
0.50
0.02
0
Web: weight / average
0.333 / 0.333
Code: weight / average
0.333 / 0.333
Mathematics: weight / average
0.333 / 0.333
Change step size and reference in an explicit educational control.

DoReMi learns weights using small models before training the main model. It first trains a reference on a declared mixture and freezes its parameters. It then trains a proxy using Group DRO, updating domain weights from proxy excess loss relative to the reference. Finally it averages weights along the trajectory and trains a new model on that mixture. The method is described in the original paper.

For a minibatch with nin_i valid tokens from domain ii, compare the same tokens and masks in both models. The published algorithm calculates

λi=1ni∑t∈imax⁡(ℓproxy,t−ℓref,t,0).\lambda_i=\frac{1}{n_i}\sum_{t\in i}\max(\ell_{\mathrm{proxy},t}-\ell_{\mathrm{ref},t},0).

The maximum is applied before averaging: media⁡(max⁡(x,0))\operatorname{media}(\max(x,0)) is not generally max⁡(media⁡(x),0)\max(\operatorname{media}(x),0). Excess aims to weight what the reference already predicts better than the proxy; high loss in both may be irreducible noise rather than an easy opportunity. The reference defines the comparison and may itself be wrong or biased.

With rate η\eta, positive weights αi\alpha_i, and smoothing c∈[0,1]c\in[0,1], an exponentiated-gradient update takes

α~i=αieηλi,αi+=(1−c)α~i∑jα~j+cK.\tilde\alpha_i=\alpha_i e^{\eta\lambda_i},\qquad \alpha_i^{+}=(1-c)\frac{\tilde\alpha_i}{\sum_j\tilde\alpha_j}+\frac{c}{K}.

In code, subtract the maximum log value before exponentiating to avoid overflow. Smoothing mixes with uniform and keeps mass on all domains when c>0c>0. The proxy updates using weighted losses and final weights average updates rather than necessarily taking the last step. If a domain is absent from a minibatch, explicitly define how its excess is estimated; the lab uses per-domain batches to avoid division by zero.

In the published experiments, a 280-million-parameter reference and proxy optimized weights for an 8,000-million-parameter model. On The Pile, the main model reached baseline accuracy about 2.6 times faster under the paper’s protocol. That ratio promises no improvement for another mixture or the reduced lab. Transfer across scales, architectures, and tokenizers needs checking. A lower-weight domain can improve indirectly through transfer; weight is not a causal measure of its value.

Learning a mixing law

InteractiveThe mixture simplex

Each vertex assigns all training to one domain. Color shows the loss predicted by the measured fit; small points are nondominated mixtures on a discrete grid, not a guarantee of the continuous frontier.

Preparing the mixture visualization.

Law fitted by domain: Lᵢ=cᵢ+exp(bᵢ+tᵢ₁r₁+tᵢ₂r₂), r₃=1−r₁−r₂. Coefficients use realized proportions, not requested proportions. Quick run with seed 1310, 48 steps per mixture, 15 fit mixtures and 5 held-out mixtures. The pure vertex of the third domain is held out for evaluation; parts of the map may lie outside the convex region of the fit and are extrapolations. Colors are predictions, not direct measurements at each point; the experiment does not establish transfer to large models.

κ₂(J) is the ratio between the largest and smallest singular values of the unnormalized Jacobian. A very high condition number indicates sensitivity and possible lack of parameter identification; it depends on scale and has no universal threshold. Convergence and a small RMSE do not guarantee stable coefficients.

33.3 %
50.0 %
TinyStories
33.3 %
FineWeb-Edu
33.3 %
WikiText-2
33.3 %
Explore predicted losses for measured domains and compare them with fit errors.

A mixing law models each validation loss LiL_i as a function of training proportions r\mathbf r. Ye and colleagues studied expressions of the following form at fixed size and duration:

Li(r)=ci+kiexp⁡(∑jtijrj).L_i(\mathbf r)=c_i+k_i\exp\left(\sum_j t_{ij}r_j\right).

Cross terms allow changing one domain’s proportion to affect another. The fitted matrix describes associations within the experiment; it does not prove each coefficient is a transferable causal effect. Since proportions sum to one, parameter and intercept identifiability need care. Hold out mixtures to evaluate predictions outside the fit, keep budget and tokenizer constant, and compare per-domain errors, not only the average. The figure uses domains and the short run stated in its legend: these are not code or mathematics measurements if those corpora are absent.

RegMix frames search as regression over many small mixtures. In the paper’s experiment, 512 one-million-parameter models were trained for one billion tokens each; the predicted mixture was later evaluated with a one-billion-parameter model. This does not guarantee that twenty tiny runs identify an optimal mixture for another model.

A mixture can also change over time. Cooldown can reserve budget for high-quality content or domains of interest; compare a schedule with a fixed mixture using the same total tokens and a predefined validation protocol. Order, learning rate, and starting point can change the outcome, so equal cumulative proportions do not imply equivalent training.

Generate, filter, and measure

Synthetic pretraining data can turn topic, audience, or example seeds into explanations and exercises. Textbooks Are All You Need presented phi-1, with 1,300 million parameters, using a mixture including 6,000 million selected web tokens and one billion synthetic-material tokens. Coding results depend on the whole process, including subsequent fine-tuning. Clear generated text does not guarantee correct facts or solutions.

Web rephrasing uses documents as seeds for versions in other styles. WRAP studied mixing original and rephrased text and reported nearly threefold acceleration in its C4 experiment. That result depends on teacher, domain, style, budget, and evaluation and must be measured before transfer. Retain originals and provenance where appropriate, detect duplicates between versions, filter personal data, and review claims. Do not use benchmarks or solutions as seeds, and separate evaluation topics and documents. A held-out seed does not prove the teacher never saw the information before.

To attribute a change to mixture, fix initialization, tokenizer, processed-token count, and schedule; compare multiple seeds when feasible, and report per-domain loss and filter rejections. A small local-teacher sample tests the full path but does not reproduce a paper’s millions of tokens or results. Synthetic text quality, diversity, and distribution matter as well as quantity.

When one generation teaches the next

Model collapse studies what happens when new generations learn from samples produced by earlier models. Shumailov and colleagues analyzed conditions where sampling and approximation errors degrade a distribution. Gerstgrasser and colleagues studied accumulating real and synthetic data as an alternative to replacement. Accumulation can change dynamics; it does not itself guarantee that every system preserves diversity or truth.

InteractiveGaussians across generations

Generation 0: n samples from N(0,1). We fit mean and variance by maximum likelihood, then take n samples from the fit. Replace discards the previous set; accumulate keeps it. Both branches start with the same sample and use the same standard noise sequence.

At the selected step: means 0.129 / 0.129; sizes 100 / 100. Tails are empirical fractions of the set used for fitting, with threshold fixed relative to the initial distribution; they are not exact probabilities of the fitted Gaussian.

Conditioned on the initial fit, the expectation under replacement is s₀²[(n−1)/n]^t, because MLE variance uses denominator n. A trajectory can rise or fall, and accumulation does not guarantee retaining the tails for every seed. This example illustrates one finite-error mechanism, not every phenomenon of collapse from recursive training.

100
13
0
Variance, replace
1.256
Variance, accumulate
1.256
Tail |x| > 2
7.0 % / 7.0 %
Compare replacement with accumulation and observe trajectories, not only a mean.

For an exact mechanism, start from a Gaussian with known variance σ02\sigma_0^2. At each generation draw n≥2n\geq2 independent samples from the previous fitted Gaussian and estimate mean and variance by maximum likelihood with divisor nn. Conditional on the previous variance,

E[σ^t2∣σ^t−12]=n−1nσ^t−12,E[σ^t2]=(n−1n)tσ02.\mathbb E[\widehat\sigma_t^2\mid\widehat\sigma_{t-1}^2]=\frac{n-1}{n}\widehat\sigma_{t-1}^2,\qquad \mathbb E[\widehat\sigma_t^2]=\left(\frac{n-1}{n}\right)^t\sigma_0^2.

The first equality is the MLE estimator’s bias; the second follows by iterated expectation. It describes an expectation, not a monotonic decrease in every trajectory. If a first real sample is also estimated before generation one, count that extra fit. The estimated mean also drifts randomly: a tail defined relative to a fixed origin need not decrease in every run or on average. Changing estimator, model, sample size, or accumulation protocol changes the conclusion.

Lab: replacement and accumulation

The cell starts from a known Gaussian for the replacement formula. The accumulation experiment retains an initial real sample and adds synthetic samples at each step. It measures variance and mass beyond fixed thresholds −2-2 and 22, averaging trajectories. Monte Carlo uncertainty and mean drift matter.

The second control generates text from an artificial grammar explicit in the cell. Seeds separate train and test samples, although identical sentences can appear in both because support is finite. A bigram model with positive smoothing generates text and is refitted with replacement or accumulation. Test loss and conditional entropy, both in nats per token, are distinct quantities and need not decline together. This is a checkable mechanism, not a web measurement or a general LLM demonstration.

[ ]PythonBrowser
import numpy as np
from scipy.special import ndtr

def gaussian_trials(n=32,generations=20,trials=400,seed=71):
    rng=np.random.default_rng(seed)
    # Reemplazo parte de la distribución verdadera, conocida exactamente.
    mean=np.zeros(trials); var=np.ones(trials)
    replacement=[var.copy()]
    for _ in range(generations):
        samples=mean[:,None]+np.sqrt(var)[:,None]*rng.standard_normal((trials,n))
        mean=samples.mean(axis=1); var=samples.var(axis=1,ddof=0)
        replacement.append(var.copy())
    sigma=np.sqrt(np.maximum(var,1e-30))
    replacement_tail=ndtr((-2-mean)/sigma)+ndtr((mean-2)/sigma)
    # Acumulación conserva la muestra real inicial y añade muestras sintéticas.
    original=rng.standard_normal((trials,n))
    total=original.sum(axis=1); total2=(original**2).sum(axis=1); count=n
    mean=total/count; var=np.maximum(0,total2/count-mean**2)
    accumulated=[var.copy()]
    for _ in range(generations):
        samples=mean[:,None]+np.sqrt(var)[:,None]*rng.standard_normal((trials,n))
        total+=samples.sum(axis=1); total2+=(samples**2).sum(axis=1); count+=n
        mean=total/count; var=np.maximum(0,total2/count-mean**2)
        accumulated.append(var.copy())
    sigma=np.sqrt(np.maximum(var,1e-30))
    tail=ndtr((-2-mean)/sigma)+ndtr((mean-2)/sigma)
    return np.asarray(replacement),np.asarray(accumulated),replacement_tail,tail

rep,acc,replacement_tail,tail=gaussian_trials()
print('Varianza media reemplazo pasos 0, 10, 20:',np.round(rep[[0,10,20]].mean(axis=1),4))
print('Esperanza teórica reemplazo pasos 0, 10, 20:',np.round((31/32)**np.array([0,10,20]),4))
print('Error estándar de la media al paso 20:',round(float(rep[-1].std(ddof=1)/np.sqrt(len(rep[-1]))),4))
print('Varianza media acumulación pasos 0, 10, 20:',np.round(acc[[0,10,20]].mean(axis=1),4))
print('Masa media de cola reemplazo, |x|>2, paso 20:',round(float(replacement_tail.mean()),4))
print('Mediana de masa de cola reemplazo, paso 20:',round(float(np.median(replacement_tail)),4))
print('Masa media de cola acumulada, |x|>2, paso 20:',round(float(tail.mean()),4))
print('Masa de cola de la distribución inicial:',round(float(2*ndtr(-2)),4))
print('Épocas del ejercicio de mezcla:',0.30*100000/10000)

# Gramática artificial explícita; semillas distintas producen train y test independientes.
vocab=['.','ana','luis','mara','mira','busca','dibuja','luna','rio','mapa','cometa','en','casa','parque','bosque']
V=len(vocab); index={word:i for i,word in enumerate(vocab)}
def make_text(seed,sentences):
    rng=np.random.default_rng(seed); words=[]
    for _ in range(sentences):
        subject=rng.choice(['ana','luis','mara'])
        verb=rng.choice(['mira','busca','dibuja'])
        obj=rng.choice(['luna','rio','mapa','cometa'],p=[.35,.35,.28,.02])
        place=rng.choice(['casa','parque','bosque'])
        words.extend([subject,verb,obj,'en',place,'.'])
    return np.array([index[w] for w in words],dtype=int)

train=make_text(12,300); test=make_text(13,100)
def counts_for(tokens):
    previous=np.concatenate(([index['.']],tokens[:-1]))
    counts=np.zeros((V,V))
    np.add.at(counts,(previous,tokens),1)
    return counts

def probabilities(counts,alpha=.05):
    return (counts+alpha)/(counts.sum(axis=1,keepdims=True)+alpha*V)

def generate(P,length,rng):
    cumulative=np.cumsum(P,axis=1); previous=index['.']
    result=np.empty(length,dtype=int)
    for i in range(length):
        previous=min(V-1,int(np.searchsorted(cumulative[previous],rng.random())))
        result[i]=previous
    return result

def metrics(P):
    previous=np.concatenate(([index['.']],test[:-1]))
    nll=-np.log(P[previous,test]).mean()
    marginal=np.bincount(previous,minlength=V)/len(previous)
    entropy=-(marginal[:,None]*P*np.log(P)).sum()
    return float(nll),float(entropy)

def ngram_recursion(mode,seed=44,steps=15):
    rng=np.random.default_rng(seed); base=counts_for(train); current=base.copy()
    output=[]
    for step in range(steps+1):
        P=probabilities(current)
        if step in (0,5,15): output.append((step,*metrics(P)))
        if step<steps:
            synthetic=generate(P,len(train),rng)
            updated=counts_for(synthetic)
            current=updated if mode=='reemplazar' else current+updated
    return output

print('Bigramas: generación, pérdida en test y entropía condicional en contextos de test')
print('Reemplazo:',ngram_recursion('reemplazar'))
print('Acumulación:',ngram_recursion('acumular'))

Local lab: measured weights and laws

This lab uses three real domains: TinyStories and FineWeb-Edu from the m20-l07 manifest, and WikiText-2 at the revision pinned in code. Set ORYON_DATA_DIR to the m20-l07 directory; tokenizer, each shard, and validation-document hashes are checked. WikiText uses train, validation, and test splits: exact matches with held-out text and m20-l07 validation documents used here are excluded from training. The m20-l07 shards cannot exclude all partial cross-source overlaps, limiting loss interpretation. Install torch, numpy, scipy, datasets, and tokenizers.

First a reference is trained with uniform weights. The proxy then queries the frozen reference on the same tokens, clips per-token excess loss before domain averaging, and updates weights with exponentiated gradient and uniform smoothing. The proxy gradient uses each domain’s per-token loss with those weights. Final mixture weights are the time average of updated weights. The report saves each excess, weights, and seed. Short-mode reference and proxy are small demonstrations, not replications of paper scale.

To estimate a law, twenty proxies are trained with identical step count, tokenizer, and initialization. Five mixtures are held out of the fit and per-domain prediction error reported. The same validation documents are used for all mixtures: this holdout measures prediction for other proportions, not fit generalization to different texts. The form is L_i(r)=c_i+exp(b_i+t_i1*r1+t_i2*r2), with r3=1-r1-r2; the intercept absorbs a redundant simplex coefficient. The report shows convergence and the unnormalized Jacobian’s spectral condition number. It depends on parameter scale, but a large value warns of sensitivity. Convergence does not guarantee coefficient identification. Requested weights and actual presented-token proportions can differ, especially in short mode; the law fits the latter. A held-out mixture may lie outside the fitted envelope, with no guarantee of reliable extrapolation or causality.

Finally, two final models start from the same parameter hash and consume the same token count: one uses uniform mixture and the other the DoReMi average. Per-domain loss and actual presented tokens are recorded, not just an average. Corpus sizes are available tokens that may contain repetitions; presented-to-available token ratio does not prove how many unique documents were seen. Steps sample with replacement and attention may cross EOT as in m20-l07. During evaluation each context block starts with EOT and retains no previous-block tokens, so loss also depends on that protocol. One seed and a small validation set cannot establish general improvements or transfer of weights to another size or tokenizer.

Full mode trains twenty proxies and two final models with about 20 million non-embedding parameters, plus the DoReMi reference and proxy. ORYON_QUICK=1 reduces size and steps only to check flow; its results do not reproduce published figures. Report mixture-report.json saves configuration, hashes, mixtures, weights, fit, and errors without corpus text. ORYON_MIXTURE_DIR chooses an output folder. After DoReMi, each mixture, and each final model, atomic progress is saved: if interrupted, repeat the cell with the same folder, code, configuration, and data. The program rejects detected changes in configuration, data hashes, PyTorch version, or device; use another folder if code or those conditions change. Mixtures initialize independently with the same seed, so resuming between them does not alter training. Runtimes depend on the machine and must not be extrapolated to other budgets.

[ ]DoReMi and a three-domain mixing lawLocal GPU
"""DoReMi y ley de mezcla con tres fuentes reales y un tokenizador común."""
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 least_squares
from tokenizers import Tokenizer
from datasets import load_dataset

QUICK=os.getenv('ORYON_QUICK')=='1'
DATA=Path(os.getenv('ORYON_DATA_DIR','./oryon-data'))
OUT=Path(os.getenv('ORYON_MIXTURE_DIR','./oryon-mixture'))
DEVICE=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
CONTEXT=16 if QUICK else 128
PROXY=(32,1,4) if QUICK else (128,4,4)
FINAL=(64,2,4) if QUICK else (320,12,10)
REF_STEPS=60 if QUICK else 4000
PROXY_STEPS=60 if QUICK else 4000
MIX_STEPS=48 if QUICK else 4000
FINAL_STEPS=80 if QUICK else 8000
WIKI_REV='b08601e04326c79dfdd32d625aee71d232d685c3'
SEED=1310
torch.set_num_threads(1);torch.use_deterministic_algorithms(True)

def file_sha(path):
    h=hashlib.sha256()
    with path.open('rb') as f:
        for b in iter(lambda:f.read(1024*1024),b''): h.update(b)
    return h.hexdigest()
def text_sha(s): return hashlib.sha256(s.encode('utf-8')).hexdigest()
def model_sha(model):
    h=hashlib.sha256()
    for p in model.state_dict().values():h.update(p.detach().cpu().numpy().tobytes())
    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):
    _,_,t,d=x.shape; freq=1./(10000.**(torch.arange(0,d,2,device=x.device,dtype=torch.float32)/d))
    angle=torch.arange(t,device=x.device,dtype=torch.float32)[:,None]*freq[None,:]
    c,s=angle.cos()[None,None,:,:],angle.sin()[None,None,:,:]; a,b=x[...,0::2].float(),x[...,1::2].float()
    return torch.stack((a*c-b*s,a*s+b*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(a):return a.reshape(b,t,self.heads,d//self.heads).transpose(1,2)
        q,k,v=rotary(split(q)),rotary(split(k)),split(v)
        a=F.scaled_dot_product_attention(q,k,v,is_causal=True)
        x=x+self.proj(a.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,config):
        super().__init__();width,layers,heads=config
        if width%heads or (width//heads)%2:raise ValueError('Dimensión de cabeza incompatible')
        self.embedding=nn.Embedding(vocab,width);self.blocks=nn.ModuleList(Block(width,heads) for _ in range(layers));self.norm=RMSNorm(width)
        self.apply(self.init)
    @staticmethod
    def init(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)

class Windows:
    def __init__(self,arrays):
        self.arrays=[];counts=[]
        for arr in arrays:
            available=len(arr)-CONTEXT
            if available>0:self.arrays.append(arr);counts.append(available)
        if not counts:raise ValueError('Dominio sin ventanas suficientes')
        self.cumulative=np.cumsum(counts,dtype=np.int64)
        self.tokens=sum(len(a) for a in self.arrays)
    def batch(self,rng):
        draw=int(rng.integers(0,int(self.cumulative[-1])));i=int(np.searchsorted(self.cumulative,draw,side='right'))
        pos=draw-(int(self.cumulative[i-1]) if i else 0)
        row=torch.as_tensor(np.array(self.arrays[i][pos:pos+CONTEXT+1],dtype=np.int64),device=DEVICE)
        return row[:-1][None,:],row[1:][None,:]

def read_l07(manifest,tokenizer):
    arrays=[];validation=[];val_hashes=set();dtype=np.dtype(manifest['dtype'])
    for domain in ('tiny','fineweb'):
        shards=[]
        for row in manifest['groups'][domain+'/train']['shards']:
            path=DATA/row['path']
            if path.stat().st_size!=row['tokens']*dtype.itemsize or file_sha(path)!=row['sha256']:raise ValueError('Shard incompatible')
            shards.append(np.memmap(path,mode='r',dtype=dtype))
        arrays.append(Windows(shards));spec=manifest['groups'][domain+'/validation'];path=DATA/spec['validation_jsonl']
        if file_sha(path)!=spec['validation_sha256']:raise ValueError('Validación incompatible')
        tokens=[]
        for line in path.read_text(encoding='utf-8').splitlines():
            row=json.loads(line);text=row['text']
            if text_sha(text)!=row['sha256']:raise ValueError('Documento de validación incompatible')
            val_hashes.add(text_sha(text));ids=tokenizer.encode(text,add_special_tokens=False).ids
            if ids and tokenizer.decode(ids,skip_special_tokens=False)==text:tokens.append(ids[:64 if QUICK else 1024])
            if len(tokens)>=(2 if QUICK else 20):break
        if not tokens:raise ValueError('Sin evaluación por dominio')
        validation.append(tokens)
    return arrays,validation,val_hashes

def read_wiki(tokenizer,eot,forbidden):
    dataset=load_dataset('Salesforce/wikitext','wikitext-2-raw-v1',revision=WIKI_REV)
    validation=[];eval_hash=set(forbidden);validation_hash=hashlib.sha256()
    for split in ('validation','test'):
        for row in dataset[split]:
            text=row['text']
            if len(text.strip())<100:continue
            eval_hash.add(text_sha(text))
            if split=='validation' and len(validation)<(2 if QUICK else 20):
                ids=tokenizer.encode(text,add_special_tokens=False).ids
                if ids and tokenizer.decode(ids,skip_special_tokens=False)==text:
                    validation.append(ids[:64 if QUICK else 1024]);validation_hash.update(bytes.fromhex(text_sha(text)))
    limit=500 if QUICK else 20000; tokens=[];docs=duplicates=0;train_hash=hashlib.sha256()
    for row in dataset['train']:
        text=row['text']
        if len(text.strip())<100:continue
        if text_sha(text) in eval_hash:duplicates+=1;continue
        tokens.extend(tokenizer.encode(text,add_special_tokens=False).ids+[eot]);docs+=1;train_hash.update(bytes.fromhex(text_sha(text)))
        if docs>=limit:break
    if not validation or len(tokens)<=CONTEXT:raise ValueError('WikiText sin datos suficientes')
    info={'dataset':'Salesforce/wikitext','config':'wikitext-2-raw-v1','revision':WIKI_REV,
          'train_fingerprint':dataset['train']._fingerprint,'validation_fingerprint':dataset['validation']._fingerprint,
          'train_documents':docs,'excluded_exact_eval_matches':duplicates,
          'train_documents_hash_sequence_sha256':train_hash.hexdigest(),
          'validation_documents_hash_sequence_sha256':validation_hash.hexdigest(),
          'note':'Se excluyen coincidencias exactas con textos de validación disponibles; los shards de entrenamiento de l07 no permiten descartar solapamientos parciales entre dominios'}
    return Windows([np.asarray(tokens,dtype=np.int64)]),validation,info

def per_token(model,x,y):
    logits=model(x).float()
    return F.cross_entropy(logits.reshape(-1,logits.shape[-1]),y.reshape(-1),reduction='none')
def precision():return torch.autocast('cuda',dtype=torch.bfloat16) if DEVICE.type=='cuda' and torch.cuda.is_bf16_supported() else nullcontext()
def weights_update(weights,excess,eta=1.,smooth=.001):
    weights=np.asarray(weights,dtype=np.float64);excess=np.asarray(excess,dtype=np.float64)
    if weights.ndim!=1 or excess.shape!=weights.shape or not np.all(np.isfinite(weights)) or not np.all(np.isfinite(excess)) or np.any(weights<=0):raise ValueError('Pesos o excesos inválidos')
    if not np.isfinite(eta) or eta<0 or not 0<=smooth<=1:raise ValueError('Hiperparámetros inválidos')
    with np.errstate(over='ignore',invalid='ignore'):z=np.log(weights)+eta*excess
    if not np.all(np.isfinite(z)):raise ValueError('Actualización fuera del rango numérico')
    z-=z.max();u=np.exp(z);u/=u.sum()
    return (1-smooth)*u+smooth/len(u)

@torch.inference_mode()
def evaluate(model,validation,eot):
    model.eval();results=[]
    for docs in validation:
        total,count=0.,0
        for ids in docs:
            for start in range(0,len(ids),CONTEXT):
                y=ids[start:start+CONTEXT];x=torch.tensor([[eot]+y[:-1]],device=DEVICE);target=torch.tensor(y,device=DEVICE)
                total+=float(F.cross_entropy(model(x)[0].float(),target,reduction='sum'));count+=len(y)
        results.append({'nll_nats':total,'tokens':count,'loss_nats_per_token':total/count})
    return results

def schedule(step,total):
    warmup=min(2 if QUICK else 200,max(1,total//4));decay=min(2 if QUICK else 1000,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)))

def train_mixture(config,steps,proportions,domains,validation,eot,vocab,seed):
    torch.manual_seed(seed);model=MiniLlama(vocab,config).to(DEVICE);rng=np.random.default_rng(seed);opt=torch.optim.AdamW(model.parameters(),lr=3e-4,weight_decay=.1)
    initial_sha=model_sha(model)
    counts=np.zeros(len(domains),dtype=int)
    for step in range(steps):
        for group in opt.param_groups:group['lr']=schedule(step,steps)
        domain=int(rng.choice(len(domains),p=proportions));counts[domain]+=CONTEXT;x,y=domains[domain].batch(rng)
        opt.zero_grad(set_to_none=True)
        with precision():loss=per_token(model,x,y).mean()
        if not torch.isfinite(loss):raise FloatingPointError('Pérdida no finita')
        loss.backward();nn.utils.clip_grad_norm_(model.parameters(),1.);opt.step()
    measured=evaluate(model,validation,eot)
    info={'seed':seed,'steps':steps,'initial_sha256':initial_sha,'requested_mix':list(map(float,proportions)),
          'actual_tokens':counts.tolist(),'actual_mix':(counts/counts.sum()).tolist(),
          'exposure_over_available_tokens':[float(counts[i]/domains[i].tokens) for i in range(len(domains))],
          'validation':measured,'parameters_total':sum(p.numel() for p in model.parameters()),
          'non_embedding_parameters':sum(p.numel() for p in model.parameters())-model.embedding.weight.numel()}
    return model,info

def learn_doremi(ref,domains,vocab,steps):
    ref.eval();torch.manual_seed(SEED+1);proxy=MiniLlama(vocab,PROXY).to(DEVICE)
    opt=torch.optim.AdamW(proxy.parameters(),lr=3e-4,weight_decay=.1);rng=np.random.default_rng(SEED+2)
    alpha=np.full(len(domains),1./len(domains));history=[]
    for step in range(steps):
        for group in opt.param_groups:group['lr']=schedule(step,steps)
        opt.zero_grad(set_to_none=True);terms=[];excess=[]
        for domain in domains:
            x,y=domain.batch(rng)
            with torch.no_grad(),precision():baseline=per_token(ref,x,y).detach()
            with precision():proxy_loss=per_token(proxy,x,y)
            terms.append(proxy_loss.mean());excess.append(float((proxy_loss.detach()-baseline).clamp_min(0).mean()))
        alpha=weights_update(alpha,excess)
        loss=sum(float(alpha[i])*terms[i] for i in range(len(domains)))
        if not torch.isfinite(loss):raise FloatingPointError('Pérdida proxy no finita')
        loss.backward();nn.utils.clip_grad_norm_(proxy.parameters(),1.);opt.step()
        history.append({'step':step+1,'weights':alpha.tolist(),'positive_token_excess':excess})
    average=np.mean([x['weights'] for x in history],axis=0)
    del proxy,opt;gc.collect()
    if DEVICE.type=='cuda':torch.cuda.empty_cache()
    return average,history

def fit_laws(rows):
    fit=[r for r in rows if r['split']=='fit'];held=[r for r in rows if r['split']=='holdout']
    x=np.array([r['actual_mix'][:2] for r in fit]);test_x=np.array([r['actual_mix'][:2] for r in held]);outputs=[]
    if len({tuple(r) for r in x})<4:raise ValueError('No hay suficientes mezclas distintas para ajustar')
    for domain in range(3):
        y=np.array([r['validation'][domain]['loss_nats_per_token'] for r in fit]);test_y=np.array([r['validation'][domain]['loss_nats_per_token'] for r in held])
        def fun(z):return z[0]+np.exp(z[1]+x@z[2:])-y
        def jac(z):
            v=np.exp(z[1]+x@z[2:])
            return np.column_stack((np.ones(len(x)),v,v*x[:,0],v*x[:,1]))
        y0=max(float(y.min())*.5,1e-3);starts=[[y0,math.log(y0),0.,0.],[y0,math.log(y0),-.2,.2],[y0,math.log(y0),.2,-.2]]
        candidates=[least_squares(fun,s,jac=jac,bounds=([0.,-20.,-20.,-20.],[100.,20.,20.,20.]),max_nfev=5000,x_scale='jac') for s in starts]
        best=min(candidates,key=lambda v:float(np.sum(v.fun**2)));z=best.x
        pred=z[0]+np.exp(z[1]+test_x@z[2:])
        condition=float(np.linalg.cond(jac(z)))
        lower=np.array([0.,-20.,-20.,-20.]);upper=np.array([100.,20.,20.,20.])
        at_bounds=[name for name,val,lo,hi in zip(('c','b','t1','t2'),z,lower,upper) if min(val-lo,hi-val)<1e-4]
        outputs.append({'c':float(z[0]),'b':float(z[1]),'t':[float(z[2]),float(z[3])],
            'train_rmse':float(np.sqrt(np.mean(best.fun**2))),'holdout_rmse':float(np.sqrt(np.mean((pred-test_y)**2))),
            'holdout_predictions':pred.tolist(),'optimizer_success':bool(best.success),'parameters_near_bounds':at_bounds,
            'jacobian_condition':condition if np.isfinite(condition) else None,
            'note':'r3=1-r1-r2; el intercepto absorbe el coeficiente redundante del símplex'})
    return outputs

def save_progress(path,state):
    temporary=path.with_suffix('.tmp')
    temporary.write_text(json.dumps(state,ensure_ascii=False,indent=2),encoding='utf-8')
    temporary.replace(path)

def main():
    OUT.mkdir(parents=True,exist_ok=True);path=DATA/'manifest.json';manifest=json.loads(path.read_text(encoding='utf-8'))
    tok_path=DATA/manifest['tokenizer']['path']
    if manifest['version']!=1 or manifest['dtype'] not in ('<u2','<u4') or file_sha(tok_path)!=manifest['tokenizer']['sha256']:raise ValueError('Manifiesto o tokenizador incompatibles')
    tok=Tokenizer.from_file(str(tok_path));eot=int(manifest['tokenizer']['eot_id']);vocab=eot+1
    if tok.get_vocab_size()!=eot or manifest['tokenizer']['model_vocab_size']!=vocab:raise ValueError('EOT incompatible')
    domains,validation,forbidden=read_l07(manifest,tok);wiki,wiki_validation,wiki_info=read_wiki(tok,eot,forbidden)
    domains.append(wiki);validation.append(wiki_validation);names=['TinyStories','FineWeb-Edu','WikiText-2']
    uniform=np.full(3,1/3)
    identity={'resume_version':1,'manifest_sha256':file_sha(path),'tokenizer_sha256':file_sha(tok_path),
        'wiki':wiki_info,'quick':QUICK,'context':CONTEXT,'proxy':PROXY,'final':FINAL,
        'steps':[REF_STEPS,PROXY_STEPS,MIX_STEPS,FINAL_STEPS],'seed':SEED,
        'torch':str(torch.__version__),'numpy':np.__version__,'device':str(DEVICE),
        'gpu':torch.cuda.get_device_name(DEVICE) if DEVICE.type=='cuda' else None,
        'autocast_bf16':bool(DEVICE.type=='cuda' and torch.cuda.is_bf16_supported())}
    # La identidad serializada usa listas tanto en el primer arranque como al reanudar.
    identity=json.loads(json.dumps(identity))
    progress_path=OUT/'mixture-progress.json'
    if progress_path.exists():
        progress=json.loads(progress_path.read_text(encoding='utf-8'))
        if progress.get('identity')!=identity:raise ValueError('La configuración o los datos cambiaron: usa otro directorio de salida')
        print('Reanudación:',len(progress['mixtures']),'mezclas y',len(progress['final_models']),'modelos finales ya medidos',flush=True)
    else:
        progress={'identity':identity,'reference':None,'doremi':None,'mixtures':[],'final_models':[]}
    if progress['doremi'] is None:
        ref,ref_info=train_mixture(PROXY,REF_STEPS,uniform,domains,validation,eot,vocab,SEED)
        learned,trace=learn_doremi(ref,domains,vocab,PROXY_STEPS)
        progress['reference']=ref_info;progress['doremi']={'weights_mean':learned.tolist(),'trace':trace}
        save_progress(progress_path,progress)
        del ref;gc.collect()
        if DEVICE.type=='cuda':torch.cuda.empty_cache()
    ref_info=progress['reference'];learned=np.asarray(progress['doremi']['weights_mean']);trace=progress['doremi']['trace']
    rng=np.random.default_rng(SEED+3);mixes=[uniform,*np.eye(3)]
    mixes.extend(rng.dirichlet(np.ones(3),size=16));rows=progress['mixtures']
    if [row['index'] for row in rows]!=list(range(len(rows))) or len(rows)>len(mixes):raise ValueError('Progreso de mezclas incompatible')
    for i,row in enumerate(rows):
        if not np.array_equal(np.asarray(row['requested_mix']),np.asarray(mixes[i])) or row['split']!=('holdout' if i in (3,7,11,15,19) else 'fit'):
            raise ValueError('Orden o proporciones de mezclas incompatibles')
    for i,mix in enumerate(mixes):
        if i<len(rows):continue
        model,row=train_mixture(PROXY,MIX_STEPS,np.asarray(mix),domains,validation,eot,vocab,SEED+4)
        row['index']=i;row['split']='holdout' if i in (3,7,11,15,19) else 'fit';rows.append(row)
        save_progress(progress_path,progress)
        print('Mezcla',i,'pérdidas',[round(v['loss_nats_per_token'],4) for v in row['validation']],flush=True)
        del model;gc.collect()
        if DEVICE.type=='cuda':torch.cuda.empty_cache()
    laws=fit_laws(rows);final=progress['final_models']
    if [row['name'] for row in final]!=['uniforme','doremi'][:len(final)]:raise ValueError('Progreso de modelos finales incompatible')
    for label,mix in [('uniforme',uniform),('doremi',learned)]:
        if any(row['name']==label for row in final):continue
        model,row=train_mixture(FINAL,FINAL_STEPS,mix,domains,validation,eot,vocab,SEED+5)
        row['name']=label;final.append(row);save_progress(progress_path,progress);del model;gc.collect()
        if DEVICE.type=='cuda':torch.cuda.empty_cache()
    if final[0]['initial_sha256']!=final[1]['initial_sha256']:raise AssertionError('Inicializaciones de comparación distintas')
    result={'domains':names,'config':{'quick':QUICK,'seed':SEED,'context':CONTEXT,'reference_steps':REF_STEPS,
        'proxy_steps':PROXY_STEPS,'mixture_steps':MIX_STEPS,'final_steps':FINAL_STEPS,'batch_sequences':1,
        'D_definition':'tokens objetivo presentados; muestreo por ventanas con reemplazo',
        'doremi':'recorte por token antes de la media, gradiente exponenciado, suavizado 0.001 y promedio temporal',
        'law':'L_i(r)=c_i+exp(b_i+t_i1*r1+t_i2*r2), r3=1-r1-r2',
        'law_fit':'Mínimos cuadrados, jacobiano analítico, escalado jac y hasta 5000 evaluaciones por inicio; convergencia no prueba identificabilidad.'},
        'source':{'manifest_sha256':file_sha(path),'tokenizer_sha256':file_sha(tok_path),'wiki':wiki_info,
            'l07_validation_sha256':[manifest['groups'][x+'/validation']['validation_sha256'] for x in ('tiny','fineweb')],
            'torch':torch.__version__,'device':str(DEVICE)},
        'domain_source_tokens':[d.tokens for d in domains],'reference':ref_info,'doremi':{'weights_mean':learned.tolist(),'trace':trace},
        'mixtures':rows,'laws':laws,'final_models':final,
        'limitations':'Muestreo con reemplazo, muestras pequeñas y posibles coincidencias aproximadas entre fuentes; no se demuestra transferencia ni mejora general.'}
    (OUT/'mixture-report.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
    print('Pesos medios DoReMi:',learned.tolist(),flush=True)
    print('RMSE mezclas reservadas:',[v['holdout_rmse'] for v in laws],flush=True)
    print('Informe:',OUT/'mixture-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.

Local lab: synthetic text

Teacher Qwen/Qwen2.5-0.5B-Instruct generates short passages from explicit combinations of topics, audiences, and approaches with pinned revision and seed. Benchmark questions and held-out documents are not used to build prompts. Install torch, transformers, accelerate, tokenizers, and numpy, and point ORYON_DATA_DIR to the m20-l07 directory containing TinyStories and FineWeb-Edu training and validation. The code checks its manifest, tokenizer, shard, and validation-document hashes.

The filter removes overly short text, exact duplicates after normalization, and candidates with 5-gram Jaccard at least 0.8. To save memory it checks only candidates sharing one of four fingerprints: this is not exhaustive and does not verify truth, usefulness, or pedagogical quality. It checks the held-out documents it will evaluate for matches, but does not use them to build prompts or compare against original training text. A pretrained teacher may previously have seen evaluation documents; semantic independence is not guaranteed. Inspect and validate the material before use.

Two MiniLlamas train with identical architecture, initialization seed, step count, and tokenizer. The first receives real windows; the second replaces one quarter with synthetic windows, retaining the same real-domain proportion and an independent generator per domain. Sampling is with replacement. Both are evaluated on the same held-out real documents without benchmarks: per-token NLL is accumulated and divided by UTF-8 bytes for bits per byte, resetting context with EOT per block. The report records paired per-domain differences; do not infer general improvement from one seed or a small sample.

By default, two million synthetic tokens are sought and two seeds trained; that path is for the reader and can take substantial time. ORYON_QUICK=1 reduces generation and student size to check flow, not quality. ORYON_SYNTH_DIR selects where to write generated data and report; use a new folder. ORYON_SYNTH_TEACHER and ORYON_SYNTH_REVISION jointly change teacher and revision. The report includes filter limits, budgets, and hashes.

[ ]Local teacher and synthetic mixtureLocal GPU
"""Generación didáctica con docente local y ablación de preentrenamiento pareada.

Requiere la salida de la lección m20-l07, torch, transformers, tokenizers,
numpy y accelerate. ORYON_QUICK=1 comprueba el recorrido con presupuestos diminutos.
"""
import gc
import hashlib
import json
import math
import os
import re
import unicodedata
from pathlib import Path

os.environ.setdefault('TOKENIZERS_PARALLELISM', 'false')
import numpy as np
import torch
import transformers
from torch import nn
from torch.nn import functional as F
from tokenizers import Tokenizer
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.utils.hub import cached_file

QUICK = os.getenv('ORYON_QUICK') == '1'
DATA = Path(os.getenv('ORYON_DATA_DIR', './oryon-data'))
OUT = Path(os.getenv('ORYON_SYNTH_DIR', './oryon-synthetic'))
TEACHER = os.getenv('ORYON_SYNTH_TEACHER', 'Qwen/Qwen2.5-0.5B-Instruct')
REVISION = os.getenv('ORYON_SYNTH_REVISION', '7ae557604adf67be50417f59c2c2f167def9a775')
TARGET_TOKENS = int(os.getenv('ORYON_SYNTH_TOKENS', '400' if QUICK else '2000000'))
MAX_ATTEMPTS = int(os.getenv('ORYON_SYNTH_ATTEMPTS', '16' if QUICK else '50000'))
STEPS = int(os.getenv('ORYON_SYNTH_STEPS', '8' if QUICK else '20000'))
CONTEXT, BATCH, ACCUM = (32, 2, 1) if QUICK else (128, 2, 4)
WIDTH, LAYERS, HEADS, FF = (64, 2, 4, 192) if QUICK else (384, 8, 6, 1024)
SEEDS = (2013,) if QUICK else (2013, 2014)
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
GEN_SEED = 2037
TOPICS = ('fractions', 'geometric patterns', 'probability', 'water cycle', 'plant cells',
          'electric circuits', 'energy conservation', 'sound waves', 'logical inference',
          'computer variables', 'algorithms', 'measurement', 'ecosystems', 'gravity',
          'chemical reactions', 'maps', 'astronomy', 'materials', 'graphs', 'statistics',
          'climate', 'motion', 'light', 'simple machines')
AUDIENCES = ('curious children', 'secondary school students', 'beginning adult learners', 'new undergraduate students')
ANGLES = ('an everyday analogy', 'a short worked example', 'a common misconception', 'a conceptual explanation')


def digest(data):
    return hashlib.sha256(data).hexdigest()


def file_hash(path):
    h = hashlib.sha256()
    with path.open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            h.update(block)
    return h.hexdigest()


def normalized(text):
    return ' '.join(unicodedata.normalize('NFC', text).casefold().split())


def shingles(text):
    words = re.findall(r'\w+', normalized(text), flags=re.UNICODE)
    return {' '.join(words[i:i+5]) for i in range(len(words)-4)}


def keys(shingle_set):
    # Solo cuatro huellas seleccionadas: búsqueda candidata aproximada, no exhaustiva.
    return sorted(int.from_bytes(hashlib.sha256(s.encode('utf-8')).digest()[:8], 'big') for s in shingle_set)[:4]


class Deduper:
    def __init__(self):
        self.hashes, self.items, self.index = set(), [], {}

    def add(self, text):
        norm = normalized(text)
        h = digest(norm.encode('utf-8'))
        grams = shingles(text)
        if h in self.hashes:
            return False, 'exacto'
        if not grams:
            return False, 'sin 5-gramas'
        candidates = set()
        for key in keys(grams):
            candidates.update(self.index.get(key, ()))
        for i in candidates:
            other = self.items[i]
            if len(grams & other) / len(grams | other) >= .8:
                return False, 'casi duplicado candidato'
        self.hashes.add(h)
        i = len(self.items)
        self.items.append(grams)
        for key in keys(grams):
            self.index.setdefault(key, []).append(i)
        return True, 'retenido'


def validate_data():
    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'):
        raise ValueError('Manifiesto incompatible con m20-l07')
    if file_hash(tokenizer_path) != manifest['tokenizer']['sha256']:
        raise ValueError('Hash del tokenizador incorrecto')
    tokenizer = Tokenizer.from_file(str(tokenizer_path))
    eot = int(manifest['tokenizer']['eot_id'])
    if tokenizer.get_vocab_size() != eot:
        raise ValueError('EOT o vocabulario incompatibles')
    validation = {}
    for domain in ('tiny', 'fineweb'):
        spec = manifest['groups'][domain+'/validation']
        path = DATA/spec['validation_jsonl']
        if file_hash(path) != spec['validation_sha256']:
            raise ValueError('Hash de validación incorrecto')
        rows = []
        for line in path.read_text(encoding='utf-8').splitlines():
            row = json.loads(line); text = row['text']
            if digest(text.encode('utf-8')) != row['sha256']:
                raise ValueError('Documento de validación alterado')
            ids = tokenizer.encode(text, add_special_tokens=False).ids
            if ids and tokenizer.decode(ids, skip_special_tokens=False) == text:
                rows.append((text, ids))
            if len(rows) >= (2 if QUICK else 20):
                break
        if not rows:
            raise ValueError(f'No hay validación reversible para {domain}')
        validation[domain] = rows
    return manifest, tokenizer, eot, validation, {'manifest_sha256':file_hash(manifest_path),
        'tokenizer_sha256':file_hash(tokenizer_path), 'source':manifest['sources'],
        'validation_sha256':{d:manifest['groups'][d+'/validation']['validation_sha256'] for d in validation}}


def generate_textbook(tokenizer, validation):
    if TARGET_TOKENS <= 0 or MAX_ATTEMPTS <= 0:
        raise ValueError('Los presupuestos de generación deben ser positivos')
    config_path = Path(cached_file(TEACHER, 'config.json', revision=REVISION))
    snapshot = config_path.parent
    snapshot_revision = snapshot.name if snapshot.parent.name == 'snapshots' else None
    if snapshot_revision and re.fullmatch(r'[0-9a-f]{40}',REVISION) and snapshot_revision != REVISION:
        raise ValueError('La revisión resuelta no coincide con la solicitada')
    teacher_tokenizer = AutoTokenizer.from_pretrained(TEACHER, revision=REVISION)
    dtype = torch.bfloat16 if DEVICE.type == 'cuda' and torch.cuda.is_bf16_supported() else torch.float32
    options = {'revision':REVISION, 'dtype':dtype}
    if DEVICE.type == 'cuda':
        options['device_map'] = {'':'cuda:0'}
    model = AutoModelForCausalLM.from_pretrained(TEACHER, **options).eval()
    if DEVICE.type != 'cuda': model.to(DEVICE)
    loaded_revision = getattr(model.config, '_commit_hash', None)
    if loaded_revision and loaded_revision != REVISION:
        raise ValueError('La revisión del docente cargado no coincide')
    tokenizer_revision = teacher_tokenizer.init_kwargs.get('_commit_hash')
    if tokenizer_revision and tokenizer_revision != REVISION:
        raise ValueError('La revisión del tokenizador del docente no coincide')
    weight_files = sorted(snapshot.glob('*.safetensors')) or sorted(snapshot.glob('pytorch_model*.bin'))
    if not weight_files:
        raise ValueError('No se encontraron los archivos de pesos del snapshot cargado')
    teacher_info = {'id':TEACHER, 'revision_requested':REVISION, 'revision_loaded':loaded_revision,
        'tokenizer_revision_loaded':tokenizer_revision, 'snapshot_revision':snapshot_revision,
        'config_sha256':file_hash(config_path), 'weights_sha256':{p.name:file_hash(p) for p in weight_files},
        'dtype':str(dtype), 'torch':torch.__version__,
        'transformers':transformers.__version__,
        'seed':GEN_SEED, 'temperature':.8, 'top_p':.9, 'max_new_tokens':64 if QUICK else 192,
        'topics':list(TOPICS), 'audiences':list(AUDIENCES), 'angles':list(ANGLES)}
    torch.manual_seed(GEN_SEED)
    if DEVICE.type == 'cuda': torch.cuda.manual_seed_all(GEN_SEED)
    deduper = Deduper()
    # Los documentos reservados solo sirven para rechazar coincidencias; nunca se incorporan al entrenamiento.
    for rows in validation.values():
        for text, _ in rows: deduper.add(text)
    records, total, reasons = [], 0, {}
    for i in range(MAX_ATTEMPTS):
        topic = TOPICS[i % len(TOPICS)]
        audience = AUDIENCES[(i // len(TOPICS)) % len(AUDIENCES)]
        angle = ANGLES[(i // (len(TOPICS)*len(AUDIENCES))) % len(ANGLES)]
        prompt = (f'Write a short educational textbook passage about {topic} for {audience}. '
                  f'Use {angle}. Explain the concept clearly without referring to tests or benchmarks.')
        messages = [{'role':'user','content':prompt}]
        inputs = teacher_tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True,
                         return_dict=True, return_tensors='pt').to(DEVICE)
        with torch.inference_mode():
            output = model.generate(**inputs, max_new_tokens=teacher_info['max_new_tokens'], do_sample=True,
                         temperature=.8, top_p=.9, pad_token_id=teacher_tokenizer.eos_token_id)
        text = teacher_tokenizer.decode(output[0, inputs['input_ids'].shape[1]:], skip_special_tokens=True).strip()
        del inputs, output
        if len(text) < 40 or 'as an ai language model' in text.casefold():
            reason = 'formato o longitud'
        else:
            accepted, reason = deduper.add(text)
            if accepted:
                ids = tokenizer.encode(text, add_special_tokens=False).ids
                if ids and tokenizer.decode(ids, skip_special_tokens=False) == text:
                    records.append({'topic':topic,'audience':audience,'angle':angle,'text':text,
                                    'sha256':digest(text.encode('utf-8')), 'student_tokens':len(ids)})
                    total += len(ids)
                else:
                    reason = 'tokenización no reversible'
        reasons[reason] = reasons.get(reason, 0)+1
        if (i+1) % (4 if QUICK else 100) == 0:
            print('Generación:',i+1,'intentos,',total,'/',TARGET_TOKENS,'tokens retenidos',flush=True)
        if total >= TARGET_TOKENS:
            break
    del model, teacher_tokenizer
    gc.collect()
    if DEVICE.type == 'cuda': torch.cuda.empty_cache()
    if total < TARGET_TOKENS:
        raise RuntimeError(f'Solo se obtuvieron {total}/{TARGET_TOKENS} tokens tras {MAX_ATTEMPTS} intentos; revise calidad o presupuesto')
    path = OUT/'textbook-train.jsonl'
    with path.open('w', encoding='utf-8') as stream:
        for record in records: stream.write(json.dumps(record, ensure_ascii=False)+'\n')
    return records, {'teacher':teacher_info,'attempts':sum(reasons.values()),'filter_counts':reasons,
        'retained_documents':len(records),'retained_student_tokens':total,'sha256':file_hash(path),
        'near_duplicate_method':'candidatos que comparten uno de los cuatro mínimos SHA-256 de 5-gramas; Jaccard ≥ 0,8; no exhaustivo',
        'limitation':'el filtro es superficial y no verifica la exactitud; el docente puede haber visto datos reservados en su preentrenamiento'}


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
    freq=1/(10000.**(torch.arange(0,dim,2,device=x.device,dtype=torch.float32)/dim))
    angle=torch.arange(length,device=x.device,dtype=torch.float32)[:,None]*freq[None,:]
    c,s=angle.cos()[None,None,:,:],angle.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):
        super().__init__(); self.n1,self.n2=RMSNorm(WIDTH),RMSNorm(WIDTH)
        self.qkv,self.proj=nn.Linear(WIDTH,3*WIDTH,bias=False),nn.Linear(WIDTH,WIDTH,bias=False)
        self.up,self.gate,self.down=nn.Linear(WIDTH,FF,bias=False),nn.Linear(WIDTH,FF,bias=False),nn.Linear(FF,WIDTH,bias=False)
    def forward(self,x):
        b,t,d=x.shape; q,k,v=self.qkv(self.n1(x)).chunk(3,dim=-1)
        def split(z): return z.reshape(b,t,HEADS,d//HEADS).transpose(1,2)
        z=F.scaled_dot_product_attention(rotary(split(q)),rotary(split(k)),split(v),is_causal=True)
        x=x+self.proj(z.transpose(1,2).contiguous().reshape(b,t,d)); h=self.n2(x)
        return x+self.down(F.silu(self.gate(h))*self.up(h))


class MiniLlama(nn.Module):
    def __init__(self,vocab):
        super().__init__(); self.embedding=nn.Embedding(vocab,WIDTH)
        self.blocks=nn.ModuleList(Block() for _ in range(LAYERS)); self.norm=RMSNorm(WIDTH)
        self.apply(self.initialize)
    @staticmethod
    def initialize(layer):
        if isinstance(layer,(nn.Linear,nn.Embedding)): nn.init.normal_(layer.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)


class Pool:
    def __init__(self,arrays):
        self.arrays=[a for a in arrays if len(a)>CONTEXT]
        self.counts=np.cumsum([len(a)-CONTEXT for a in self.arrays],dtype=np.int64)
        if not self.arrays: raise ValueError('El dominio no contiene ventanas suficientes')
    def window(self, rng):
        draw=int(rng.integers(0,int(self.counts[-1])))
        index=int(np.searchsorted(self.counts,draw,side='right'))
        start=draw-(int(self.counts[index-1]) if index else 0)
        return np.asarray(self.arrays[index][start:start+CONTEXT+1],dtype=np.int64)


def make_pools(manifest,tokenizer,eot,records):
    pools={}
    for domain in ('tiny','fineweb'):
        arrays=[]
        for row in manifest['groups'][domain+'/train']['shards']:
            path=DATA/row['path']; dtype=np.dtype(manifest['dtype'])
            if path.stat().st_size != row['tokens']*dtype.itemsize or file_hash(path)!=row['sha256']:
                raise ValueError('Shard incompatible')
            arrays.append(np.memmap(path,mode='r',dtype=dtype))
        pools[domain]=Pool(arrays)
    synth=[]
    for row in records:
        synth.extend(tokenizer.encode(row['text'],add_special_tokens=False).ids)
        synth.append(eot)
    pools['synth']=Pool([np.asarray(synth,dtype=np.int32)])
    return pools


@torch.inference_mode()
def evaluate(model,validation,eot):
    model.eval(); report={}
    for domain,rows in validation.items():
        total,tokens,byte_count=0.,0,0
        for text,ids in rows:
            byte_count+=len(text.encode('utf-8'))
            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)
        report[domain]={'documents':len(rows),'document_sha256':[digest(text.encode('utf-8')) for text,_ in rows],
            'tokens':tokens,'bytes':byte_count,'nll_nats':total,
            'nats_per_token':total/tokens,'bits_per_byte':total/(math.log(2)*byte_count)}
    return report


def train_arm(arm,seed,pools,validation,eot,vocab):
    torch.manual_seed(seed)
    model=MiniLlama(vocab).to(DEVICE)
    initial_hash=hashlib.sha256(b''.join(v.detach().cpu().numpy().tobytes() for v in model.state_dict().values())).hexdigest()
    parameters=sum(p.numel() for p in model.parameters())
    optimizer=torch.optim.AdamW(model.parameters(),lr=3e-4,weight_decay=.1)
    rngs={domain:np.random.default_rng(seed+offset) for domain,offset in (('tiny',0),('fineweb',1),('synth',2))}
    counts={'tiny':0,'fineweb':0,'synth':0}
    for step in range(STEPS):
        model.train(); optimizer.zero_grad(set_to_none=True)
        for micro in range(ACCUM):
            samples=[]
            for item in range(BATCH):
                i=(step*ACCUM+micro)*BATCH+item
                domain=(('synth','tiny','fineweb','tiny','synth','fineweb','tiny','fineweb')[i%8]
                        if arm=='mixed' else ('tiny' if i%2==0 else 'fineweb'))
                samples.append(pools[domain].window(rngs[domain])); counts[domain]+=CONTEXT
            values=torch.as_tensor(np.stack(samples),device=DEVICE)
            with torch.autocast(device_type=DEVICE.type,dtype=torch.bfloat16,enabled=DEVICE.type=='cuda' and torch.cuda.is_bf16_supported()):
                logits=model(values[:,:-1]).float()
                loss=F.cross_entropy(logits.reshape(-1,vocab),values[:,1:].reshape(-1))/ACCUM
            if not torch.isfinite(loss): raise FloatingPointError('Pérdida no finita')
            loss.backward()
        nn.utils.clip_grad_norm_(model.parameters(),1.)
        optimizer.step()
    val=evaluate(model,validation,eot)
    result={'arm':arm,'seed':seed,'initial_state_sha256':initial_hash,'parameters':parameters,
        'steps':STEPS,'training_tokens':counts,'validation':val}
    del model, optimizer
    gc.collect()
    if DEVICE.type=='cuda': torch.cuda.empty_cache()
    return result


def main():
    if STEPS<=0: raise ValueError('El entrenamiento necesita pasos positivos')
    if STEPS*BATCH*ACCUM % 8:
        raise ValueError('El número de ventanas debe ser múltiplo de 8 para mantener exactamente la mezcla 25/37,5/37,5')
    OUT.mkdir(parents=True,exist_ok=True)
    if (OUT/'textbook-train.jsonl').exists() or (OUT/'synthetic-report.json').exists():
        raise FileExistsError('Usa una carpeta ORYON_SYNTH_DIR nueva para no sobrescribir un ensayo')
    torch.set_num_threads(1)
    manifest,tokenizer,eot,validation,source=validate_data()
    records,synthetic=generate_textbook(tokenizer,validation)
    pools=make_pools(manifest,tokenizer,eot,records)
    runs=[]; differences=[]
    for seed in SEEDS:
        pair=[train_arm(arm,seed,pools,validation,eot,eot+1) for arm in ('real','mixed')]
        assert pair[0]['initial_state_sha256']==pair[1]['initial_state_sha256']
        assert sum(pair[0]['training_tokens'].values())==sum(pair[1]['training_tokens'].values())
        runs.extend(pair)
        differences.append({'seed':seed,'mixed_minus_real_bits_per_byte':{
            domain:pair[1]['validation'][domain]['bits_per_byte']-pair[0]['validation'][domain]['bits_per_byte']
            for domain in validation}})
        print('Semilla',seed,'bpb real y mezcla',[(r['arm'],{d:round(v['bits_per_byte'],5) for d,v in r['validation'].items()}) for r in pair],flush=True)
    report={'quick':QUICK,'source':source,'synthetic':synthetic,'runs':runs,'paired_differences':differences,
        'protocol':{'target_synthetic_fraction':.25,'sampling':'ventanas por posiciones fijas; proporciones iguales entre dominios reales y RNG separado por dominio',
                    'same_initial_state_and_steps':True,'validation':'documentos reales reservados de m20-l07, sin benchmarks; contexto reiniciado con EOT',
                    'no_test_prompts':'semillas temáticas escritas para este laboratorio; sin usar textos ni preguntas reservadas',
                    'architecture':{'width':WIDTH,'layers':LAYERS,'heads':HEADS,'ff':FF,'context':CONTEXT},
                    'optimizer':{'name':'AdamW','learning_rate':3e-4,'weight_decay':.1,'batch':BATCH,'accumulation':ACCUM},
                    'byte_metric':'NLL total en nats dividida por ln(2) y bytes UTF-8 completos de los documentos reversibles'},
        'limitations':['El docente puede haber visto los documentos reservados en su preentrenamiento.',
                       'La validación se consulta para filtrar duplicados, aunque no para construir prompts; la separación no garantiza ausencia de coincidencias semánticas ni corrección factual.',
                       'No se compara el texto sintético contra los textos originales de entrenamiento real.',
                       'QUICK prueba el recorrido, no demuestra mejora ni calidad ni significación estadística.',
                       'La distribución de ventanas y las exposiciones a documentos dependen de las longitudes y del muestreo con reemplazo.']}
    path=OUT/'synthetic-report.json'
    path.write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8')
    print('Datos retenidos:',synthetic['retained_documents'],'documentos,',synthetic['retained_student_tokens'],'tokens; informe:',path,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

NumericRepetition by domain
A domain has 10,000 million unique tokens and receives 30% of training on 100,000 million tokens. How many average epochs does it receive?
CodeUpdate domain weights
Implement doremi_update(weights, proxy, reference, domains, eta=1., smooth=.001). Each proxy and reference element is nonnegative NLL loss for the same token, and domains contains its integer domain from 0 to K−1. Clip each token difference at zero before averaging by domain. Apply exponentiated gradient to weights, normalize stably, and mix smooth with uniform. Accept zero weights, require every domain in the batch, and reject invalid or nonfinite weights, losses, or hyperparameters. Return the K updated weights.
import numpy as np

def doremi_update(weights, proxy, reference, domains, eta=1., smooth=.001):
  pass
Shift+Enter to run
ProofPropagating bias
Prove: Prove the expected MLE variance of iterated Gaussians under replacement.
0
Start from a Gaussian with known variance σ₀². At each step draw n≥2 independent samples and calculate sample variance with divisor n.

Step 1 of 3. Conditioned on the previous generation, what is the MLE estimator expectation?

QuizA small valuable domain
You have a small valuable domain. You could repeat it, reserve some for cooldown, or generate rephrasings. Which decision is best justified before committing to full training?
Key idea

A mixture is chosen with an explicit objective, domains, and evaluation. Synthetic samples can add coverage, but benefits and the risk of feeding errors back must be measured on held-out data.