Module contents
Stage 2 of 8Advanced 90 min

LoRA from scratch

Implement LoRA as an nn.Linear wrapper with zero initialization of B, alpha-over-r scaling, dropout, and merging into base weights, then inject it into a transformer model by module name. Verify that initialization leaves the model unchanged, test merge equivalence, and compare with PEFT.

After this lesson you can

  • Implement LoRALinear with merging and unmerging of weights.
  • Inject adapters into selected transformer model modules.
  • Verify initialization invariance and equivalence after merging.
  • Compare training and results with PEFT on a short task.

Before you start

A large update, a small representation

In the previous lesson you chose Qwen2.5-0.5B-Instruct and calculated the fine-tuning memory plan: with full fine-tuning, gradients and AdamW’s two moments multiply weight storage several times over. Low-Rank Adaptation (LoRA) addresses this cost at its source by freezing each pretrained matrix and training only a small-rank correction. Before using PEFT, implement it yourself because the details hidden by the library, initialization, scale, merging, and dtype, determine whether an adapter behaves as expected.

With the actual Qwen2.5-0.5B configuration (hidden_size 896, 14 query heads, and 2 key-value heads of dimension 64), a layer’s query projection q_proj is an 896×896896\times 896 matrix with 802,816 weights. A rank-r=8r=8 adapter adds 8⋅(896+896)=14.3368\cdot(896+896)=14.336 parameters, or 1.79%. Adapting q_proj, k_proj, v_proj, and o_proj, with key and value projections 128×896128\times 896, across all 24 layers trains 1,081,344 parameters against nearly 500 million in the model. AdamW state becomes small; frozen weights and activations remain.

How much information is lost by forcing the update to low rank? The figure answers for one matrix: take Pythia 14M, fine-tune all its weights for 20 steps on real text, and decompose the first layer’s attention-matrix change. This is the short lab run you will repeat below.

InteractiveHow much energy fits in a rank
Singular value σᵢ (maximum 8.48·10⁻³)1128Index i
  • Retained σᵢ (i ≤ r)
  • Discarded σᵢ
  • Gaussian, same shape and norm
4
Retained energy35.9 %
Relative Frobenius error0.800
Energy, Gaussian noise7.4 %
Stable rank9.23
Singular values of a Pythia 14M attention-matrix change (384 × 128) after 20 full fine-tuning steps. Blue bars are retained by a rank-r approximation; orange points are the spectrum of a Gaussian matrix with the same shape and norm, a reference for an unstructured update.

With r=4r=4, the rank used by the lab adapter, the best approximation retains 36% of energy; Gaussian noise would retain 7%. The update is much more concentrated than noise, but after 20 steps it is not low rank: r=32r=32 is needed to reach 83%. LoRA bets that this tension between “more concentrated than noise” and “not low rank” does not matter for the task, which must be measured through evaluations rather than spectra.

The LoRA implementation from scratch you will write wraps nn.Linear and realizes this definition with B\mat{B} initialized to zero and factor α/r\alpha/r. It is the practical version of low-rank adaptation from the LLM module.

By the rank of a product, rango⁡(BA)≤r\operatorname{rango}(\mat{B}\mat{A})\le r; it may be lower and initially, with B=0\mat{B}=\mat{0}, is zero. The factorization is not unique either: for any invertible R∈Rr×r\mat{R}\in\R^{r\times r}, (BR)(R−1A)=BA(\mat{B}\mat{R})(\mat{R}^{-1}\mat{A})=\mat{B}\mat{A}. Values of A\mat{A} and B\mat{B} separately do not identify the update, and the optimizer traverses a product parameterization that does not treat all rank-rr matrices equally: two pairs with the same product receive different gradients.

LoRA merging and equivalence replace W0\mat{W}_0 with W0+ΔW\mat{W}_0+\Delta\mat{W} for inference, removing the extra branch and returning latency to that of the base model. In exact arithmetic without dropout, (W0+ΔW)x=W0x+ΔWx(\mat{W}_0+\Delta\mat{W})\vb{x}=\mat{W}_0\vb{x}+\Delta\mat{W}\vb{x}; floating-point forms round at different points, so equivalence must be checked with an explicit numerical criterion developed here. Bias b\vb{b} does not change: adapting biases, normalizations, or the output head is another decision with another parameter count that must be recorded.

What the spectrum tells us

Let ΔW\Delta\mat{W} be a matrix change after full fine-tuning and ΔW=∑iσiuivi⊤\Delta\mat{W}=\sum_i\sigma_i\vb{u}_i\vb{v}_i\T its SVD, with σ1≥σ2≥⋯≥0\sigma_1\ge\sigma_2\ge\dots\ge 0. The question “how much is lost by forcing rank rr?” has an exact answer in the low-rank approximation by truncated SVD.

The proof is in m02. It gives the figure’s retained energy E(r)=∑i≤rσi2/∑iσi2E(r)=\sum_{i\le r}\sigma_i^2/\sum_i\sigma_i^2 and relative Frobenius error 1−E(r)\sqrt{1-E(r)} for the best approximation. A one-number summary is stable rank ∥M∥F2/σ12\|\mat{M}\|_F^2/\sigma_1^2, equal to 9.2 for the pictured matrix: a rank-kk matrix with equal singular values would have stable rank kk.

Now the assumptions, where reasoning often goes wrong. The theorem concerns one matrix and the weights’ Frobenius norm. It does not say LoRA training finds Mr\mat{M}_r (the optimizer follows another trajectory), that the same rank preserves loss, or that other layers share the spectrum. Layer output also depends on its input distribution: a low-energy direction may activate frequently and matter greatly to loss, while a high-energy direction may point to rarely occurring inputs. Truncated SVD minimizes matrix error without weighting inputs, not logit error. To study utility, measure activation or logit differences on held-out data.

Another figure-specific limitation: the update comes from 20 AdamW steps, which normalize each gradient coordinate separately; that nonlinear operation does not generally preserve gradient rank. One hypothesis to test in the lab is that longer fitting, or SGD, concentrates energy more. With 20 steps on a short subset, the figure is a measurement, not a law.

Why expect low rank? Aghajanyan and colleagues measured fine-tuning’s intrinsic dimension: with about 200 parameters randomly projected into the full space, RoBERTa reaches 90% of full fine-tuning performance on MRPC. This is a global parameter submanifold, not a matrix rank, but motivated the hypothesis. Hu and colleagues turned it into LoRA and tested GPT-3 175B: adapting Wq\mat{W}_q and Wv\mat{W}_v, table 6 reports WikiSQL accuracy 73.4% with r=1r=1 versus 73.8% with r=8r=8 and 73.5% with r=64r=64, and MultiNLI 91.3%, 91.6%, and 91.4%. With r=4r=4 on those two matrices, the checkpoint shrinks from about 350 GB to 35 MB. A small rank sufficing there does not imply it suffices for your task: rank and modules are LoRA hyperparameters selected by measurement.

Initialization, scale, and the first gradient

LoRA initializes B=0\mat{B}=\mat{0}, with A\mat{A} drawn randomly. With B=0\mat{B}=\mat{0}, the branch is exactly 0⋅(Ax)=0\mat{0}\cdot(\mat{A}\vb{x})=\vb{0} for finite inputs, and W0x+b+0\mat{W}_0\vb{x}+\vb{b}+\vb{0} is bit-for-bit the base-layer output, with or without branch dropout. The adapted model starts as the base model. Does a zero factor prevent the branch from learning? The chain rule answers.

Proof

With Frobenius product ⟨X,Y⟩=tr⁡(X⊤Y)\inner{\mat{X}}{\mat{Y}}=\operatorname{tr}(\mat{X}\T\mat{Y}), the differential is dL=⟨G,dΔW⟩=s⟨G,dB A⟩+s⟨G,B dA⟩d\Loss=\inner{\mat{G}}{d\Delta\mat{W}}=s\inner{\mat{G}}{d\mat{B}\,\mat{A}}+s\inner{\mat{G}}{\mat{B}\,d\mat{A}}. By cyclic trace invariance, tr⁡(G⊤dB A)=tr⁡(AG⊤dB)=⟨GA⊤,dB⟩\operatorname{tr}(\mat{G}\T d\mat{B}\,\mat{A})=\operatorname{tr}(\mat{A}\mat{G}\T d\mat{B})=\inner{\mat{G}\mat{A}\T}{d\mat{B}} and tr⁡(G⊤B dA)=⟨B⊤G,dA⟩\operatorname{tr}(\mat{G}\T\mat{B}\,d\mat{A})=\inner{\mat{B}\T\mat{G}}{d\mat{A}}. Since dL=⟨∂L/∂A,dA⟩+⟨∂L/∂B,dB⟩d\Loss=\inner{\partial\Loss/\partial\mat{A}}{d\mat{A}}+\inner{\partial\Loss/\partial\mat{B}}{d\mat{B}} for every dA,dBd\mat{A},d\mat{B}, the two gradients follow.

∎

For a linear layer without branch dropout, with batch {xn}\{\vb{x}_n\} and δn=∂L/∂yn\boldsymbol{\delta}_n=\partial\Loss/\partial\vb{y}_n, we have G=∑nδnxn⊤\mat{G}=\sum_n\boldsymbol{\delta}_n\vb{x}_n\T and hence ∂L/∂B=s∑nδn(Axn)⊤\partial\Loss/\partial\mat{B}=s\sum_n\boldsymbol{\delta}_n(\mat{A}\vb{x}_n)\T. With B=0\mat{B}=\mat{0}, the gradient of A\mat{A} is exactly zero and that of B\mat{B} is generally nonzero: it vanishes only if projections Axn\mat{A}\vb{x}_n or signals δn\boldsymbol{\delta}_n are degenerate. On the first step only B\mat{B} moves; from the second, B≠0\mat{B}\neq\mat{0} and A\mat{A} also receives a gradient. With branch dropout, replace xn\vb{x}_n by masked input x~n\tilde{\vb{x}}_n in both formulas: the branch’s G\mat{G} no longer equals the base weight’s.

Two optimizer nuances matter. With AdamW and weight decay, a parameter changes even with zero loss gradient because decay shrinks the parameter itself: do not confuse the gradient with the full optimizer step. Exact initialization also varies: Hu uses a Gaussian for A\mat{A}, while PEFT defaults to Kaiming uniform, the same as nn.Linear. To compare implementations, copy matrices; the same seed is insufficient if random generators are consumed in a different order.

What about scale α/r\alpha/r? Hu observes that with Adam adjusting α\alpha is approximately like adjusting learning rate, so fixes α\alpha to the first rr tried and leaves it unchanged: dividing by rr avoids retuning the learning rate when rank changes. Kalajdzievski argues that α/r\alpha/r slows learning as rr grows and proposes α/r\alpha/\sqrt{r} (rsLoRA, available in PEFT as use_rslora=True). With fixed α\alpha, moving from r=8r=8 to r=32r=32 divides the factor by 4 under Hu’s rule and by 2 under rsLoRA.

A layer that can be merged safely

The following class is an nn.Module wrapping an nn.Linear. It saves an exact weight copy before merging and restores it on unmerge rather than subtracting the update, for a reason shown shortly. The copy costs extra memory. It merges only in evaluation mode, rejects repeated merges, and blocks training and state_dict export while merged. An torch.save of the complete object bypasses that check, so unmerge before saving there too. Dropout applies to branch input during training and disappears in evaluation. Quantized weights, covered next lesson, and weights shared between modules are unsupported.

[ ]LoRALinear from scratchLocal GPU
import math
import torch
from torch import nn
from torch.nn import functional as F

class LoRALinear(nn.Module):
    def __init__(self,base,r,alpha,dropout=0.):
        super().__init__()
        if not isinstance(base,nn.Linear) or not isinstance(r,int) or r<=0 or not math.isfinite(alpha) or alpha<=0 or not 0<=dropout<1:
            raise ValueError('Configuración LoRA inválida')
        self.base=base
        self.base.requires_grad_(False)
        self.r=int(r); self.alpha=float(alpha); self.scale=self.alpha/self.r
        self.dropout=nn.Dropout(dropout)
        self.A=nn.Parameter(base.weight.new_empty((r,base.in_features)))
        self.B=nn.Parameter(base.weight.new_zeros((base.out_features,r)))
        nn.init.kaiming_uniform_(self.A,a=math.sqrt(5))
        self.register_buffer('_before_merge',None,persistent=False)
        self.merged=False
        self.train(base.training)
    def forward(self,x):
        if self.merged: return self.base(x)
        return self.base(x)+self.scale*F.linear(F.linear(self.dropout(x),self.A),self.B)
    @torch.no_grad()
    def merge(self):
        if self.merged: raise RuntimeError('Ya está fusionada')
        if self.training: raise RuntimeError('Fusiona solo en evaluación')
        delta=([email protected])*self.scale
        if not torch.isfinite(delta).all(): raise ValueError('Actualización no finita')
        merged_weight=self.base.weight+delta.to(self.base.weight.dtype)
        if not torch.isfinite(merged_weight).all(): raise ValueError('Fusión no finita')
        self._before_merge=self.base.weight.detach().clone()
        self.base.weight.copy_(merged_weight)
        self.merged=True
    @torch.no_grad()
    def unmerge(self):
        if not self.merged: raise RuntimeError('No está fusionada')
        self.base.weight.copy_(self._before_merge)
        self._before_merge=None
        self.merged=False
    def train(self,mode=True):
        if mode and self.merged: raise RuntimeError('Separa antes de entrenar')
        return super().train(mode)
    def _save_to_state_dict(self,destination,prefix,keep_vars):
        if self.merged: raise RuntimeError('Separa antes de guardar')
        super()._save_to_state_dict(destination,prefix,keep_vars)

torch.manual_seed(18)
layer=LoRALinear(nn.Linear(5,3),r=2,alpha=4,dropout=.2)
x=torch.randn(4,5)
assert torch.equal(layer(x),layer.base(x))
layer(x).square().mean().backward()
print('inicial: salida idéntica',True,'norma gradiente A',float(layer.A.grad.norm()),
      'norma gradiente B',float(layer.B.grad.norm()))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Output confirms the theorem in a tiny layer: bitwise-identical base output, exactly zero A\mat{A} gradient, and nonzero B\mat{B} gradient, with branch dropout active.

To inject adapters into a model, first freeze everything, then replace submodules identified by their full path (model.layers.0.self_attn.q_proj), not any name containing an ambiguous substring such as proj. One alternative registers a forward hook adding the branch to output; replacing the submodule is more explicit and exposes A\mat{A} and B\mat{B} in named_parameters and state_dict. The function rejects duplicate paths, paths that are not nn.Linear, and shared weights, since merging one of two paths sharing a weight would modify the other, and validates everything before touching the model.

[ ]Inject by full pathLocal GPU
def inject_lora(model,names,r,alpha,dropout=0.):
    if not isinstance(r,int) or r<=0 or not math.isfinite(alpha) or alpha<=0 or not 0<=dropout<1:
        raise ValueError('Configuración LoRA inválida')
    if not names or len(set(names))!=len(names): raise ValueError('Rutas vacías o duplicadas')
    modules=dict(model.named_modules())
    for name in names:
        if name not in modules or not isinstance(modules[name],nn.Linear):
            raise ValueError('La ruta no identifica una capa lineal: '+name)
        weight=modules[name].weight
        if sum(p is weight for _,p in model.named_parameters(remove_duplicate=False))!=1:
            raise ValueError('Peso compartido: '+name)
    model.requires_grad_(False)
    for name in names:
        model.set_submodule(name,LoRALinear(modules[name],r,alpha,dropout))
    return model

sample=nn.Sequential(nn.Linear(4,4),nn.ReLU(),nn.Linear(4,2))
inject_lora(sample,['0'],r=2,alpha=4)
trainable=[name for name,p in sample.named_parameters() if p.requires_grad]
assert trainable==['0.A','0.B']
print('parámetros entrenables:',trainable)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Injection changes model structure and hence names in state_dict. A file containing only A\mat{A} and B\mat{B} also needs base revision, paths, rank, α\alpha, and dropout to reconstruct the function. A merged-model file must declare that the update is already incorporated so the adapter is not applied twice.

Why restore instead of subtracting

The naive way to unmerge is W←(W0+ΔW)−ΔW\mat{W}\leftarrow(\mat{W}_0+\Delta\mat{W})-\Delta\mat{W}. In bf16, with an 8-bit significand, every addition rounds: fl⁡(fl⁡(W0+ΔW)−ΔW)\operatorname{fl}(\operatorname{fl}(\mat{W}_0+\Delta\mat{W})-\Delta\mat{W}) need not equal W0\mat{W}_0. The cell measures this on a matrix the size of Qwen’s q_proj, with weight standard deviation 0.02 and a rank-8 adapter. In the second part the adapter changes slightly between cycles, as when alternating training and merging for evaluation.

[ ]Merge and subtract in bf16Local GPU
torch.manual_seed(5)
W0=(torch.randn(896,896)*0.02).to(torch.bfloat16)
A=torch.empty(8,896); nn.init.kaiming_uniform_(A,a=math.sqrt(5))
B=torch.randn(896,8)*0.01
for changing in (False,True):
    W=W0.clone(); Bc=B.clone()
    for cycle in range(1,101):
        if changing: Bc=Bc+torch.randn(896,8)*0.001
        delta=(2.0*(Bc@A)).to(torch.bfloat16)
        W=W+delta; W=W-delta
        if cycle in (1,10,100):
            d=W.float()-W0.float()
            print('adaptador cambiante' if changing else 'adaptador fijo     ','ciclo',cycle,
                  'máx',f'{float(d.abs().max()):.2e}','rms',f'{float(d.square().mean().sqrt()):.2e}',
                  'pesos alterados',f'{float((d!=0).float().mean()):.1%}')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With a fixed adapter, one cycle already changes 7.9% of weights (up to 4,9⋅10−44{,}9\cdot10^{-4}, about one bf16 ulp at that scale), and later cycles repeat the same rounding: the error appears and remains. With a changing adapter, each cycle rounds at different locations and error accumulates like a random walk: RMS grows approximately with the square root of cycle count, from 1,7⋅10−51{,}7\cdot10^{-5} to 1,2⋅10−41{,}2\cdot10^{-4}, and after 100 cycles more than half of base weights differ from the originals. Restoring from the copy always gives zero error.

Another inference option leaves the base untouched: construct a new layer whose weight W0+ΔW\mat{W}_0+\Delta\mat{W} is calculated and stored in fp32, performs the product in fp32, and returns output in the input dtype. It doubles that matrix’s memory relative to bf16 (four bytes per element instead of two), and greater precision does not guarantee agreement with a LoRA branch computed and rounded in bf16. The lab compares it with bf16 merging.

[ ]Merge at fp32 precisionLocal GPU
class Fused32(nn.Module):
    def __init__(self,adapter):
        super().__init__()
        if adapter.training or adapter.merged: raise ValueError('Usa un adaptador separado en evaluación')
        with torch.no_grad():
            weight=adapter.base.weight.float()+adapter.scale*(adapter.B.float()@adapter.A.float())
            if not torch.isfinite(weight).all(): raise ValueError('Fusión no finita')
            bias=None if adapter.base.bias is None else adapter.base.bias.float().detach().clone()
        self.register_buffer('weight',weight.detach().clone())
        self.register_buffer('bias',bias)
    def forward(self,x):
        return F.linear(x.float(),self.weight,self.bias).to(x.dtype)

print('Fused32: peso y producto en fp32, salida en el dtype de la entrada.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Validating a bf16 merge needs a criterion, and “bf16 tolerance” is not a universal number. The lab uses the unmerged fp32 output as reference, the adapter-defined function computed at higher precision, and measures three errors against it. The unmerged model run in bf16 gives the floor: error bf16 incurs anyway. The bf16 merge and Fused32 are the candidates. A merge passes if relative RMS error does not exceed twice the floor; factor 2 is a convention fixed beforehand, not a result. For the test to be meaningful, the adapter effect, how far adapted output moves from the base, must be much greater than the floor. Otherwise a merge omitting factor α/r\alpha/r, or adding nothing, would also pass. Function compare measures all four quantities and the effect-to-floor ratio.

[ ]Compare against an fp32 referenceLocal GPU
def gap(a,b):
    e=a.float()-b.float()
    return {'max':float(e.abs().max()),'rms_rel':float(e.square().mean().sqrt()/b.float().square().mean().sqrt())}

def compare(unmerged_bf,merged_bf,fused_bf,ref,base):
    out={'efecto_adaptador':gap(base,ref),'suelo_bf16':gap(unmerged_bf,ref),
         'fusion_bf16':gap(merged_bf,ref),'fusion_fp32':gap(fused_bf,ref),
         'fusion_bf16_vs_sin_fusionar':gap(merged_bf,unmerged_bf)}
    floor=out['suelo_bf16']['rms_rel']
    out['criterio_fusion_bf16']=out['fusion_bf16']['rms_rel']<=2*floor
    out['criterio_fusion_fp32']=out['fusion_fp32']['rms_rel']<=2*floor
    out['efecto_sobre_suelo']=out['efecto_adaptador']['rms_rel']/floor
    return out

# Ejemplo sintético: el adaptador mueve la salida un 5 %; bf16 solo redondea.
torch.manual_seed(2)
ref=torch.randn(4096); base=ref-0.05*torch.randn(4096)
unmerged16=ref.to(torch.bfloat16)
for name,merged16 in (('fusión correcta',ref.to(torch.bfloat16)),('fusión que no suma nada',base.to(torch.bfloat16))):
    c=compare(unmerged16,merged16,merged16,ref,base)
    print(f"{name:24s} error {c['fusion_bf16']['rms_rel']:.4f}  suelo {c['suelo_bf16']['rms_rel']:.4f}",
          f" pasa {c['criterio_fusion_bf16']}  efecto/suelo {c['efecto_sobre_suelo']:.0f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Lab: spectrum, PEFT parity, and merging in Pythia

Now combine everything on a real model and real text. Pythia 14M (Apache-2.0) is small enough to fine-tune all weights in seconds, and WikiText-2 provides real text; both load at pinned revisions. The cell does four things:

  1. Full fine-tuning and spectrum. Train all parameters for 20 steps (batches of 2 sequences of 64 tokens, AdamW with rate 2⋅10−52\cdot10^{-5}) and compute singular values of the gpt_neox.layers.0.attention.query_key_value change. These are the first figure’s data. There are 16 distinct batches, so steps 17 to 20 repeat seen batches and loss falls: memorization, not learning.
  2. PEFT parity. Reload the base, inject your LoRALinear (r=4r=4, α=8\alpha=8, no dropout), and create the equivalent PEFT adapter; copy A\mat{A} and B\mat{B} between them and train both for 8 steps on the same batches with the same AdamW. Also record base-model loss on those batches.
  3. fp32 merging. Compare logits before and after merging, layer output, and exact weight restoration.
  4. bf16 merging with a tolerance criterion explained after the cell.

It needs PyTorch, Transformers, Datasets, and PEFT with CUDA (the p08-l01 environment works), about 40 MB downloaded the first time (model and WikiText-2), and one or two minutes total (GPU computation takes seconds; the remainder is loading and revision checks). If environment variable P08_L02_OUT is set to an absolute path before starting the lab, the cell saves a JSON there with the full result and provenance (revisions and SHA-256 hashes of weights and tokens); otherwise it only prints it. First, the versions used:

[ ]Comparison versionsLocal GPU
import sys,importlib.metadata as metadata
print('Python:',sys.version.split()[0])
print('paquetes:',{name:metadata.version(name) for name in ('torch','transformers','peft','datasets','accelerate')})
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Full fine-tuning, PEFT parity, and mergingLocal GPU
import os,json,time,hashlib
from pathlib import Path
spectrum_result=None
if not torch.cuda.is_available():
    print('Esta celda necesita una GPU CUDA.')
else:
    import copy,gc
    from datasets import load_dataset
    from huggingface_hub import snapshot_download
    from transformers import AutoModelForCausalLM, AutoTokenizer
    from peft import LoraConfig, get_peft_model
    out_dir=os.environ.get('P08_L02_OUT')
    if out_dir and not Path(out_dir).is_absolute(): raise ValueError('P08_L02_OUT debe ser una ruta absoluta')
    revision='cf967c0a9a04383db6f7b1108d86b2962634b4ac'
    data_revision='b08601e04326c79dfdd32d625aee71d232d685c3'
    path=snapshot_download('EleutherAI/pythia-14m',revision=revision,
                           allow_patterns=['*.json','*.safetensors','*.txt'])
    tokenizer=AutoTokenizer.from_pretrained(path,local_files_only=True)
    dataset=load_dataset('Salesforce/wikitext','wikitext-2-raw-v1',revision=data_revision,split='train')
    lines=[t for t in dataset['text'] if t.strip()][:128]
    ids=tokenizer('\n'.join(lines),add_special_tokens=False)['input_ids']
    if len(ids)<32*64: raise ValueError('Se necesitan más tokens')
    tokens=torch.tensor(ids[:32*64],dtype=torch.long).reshape(32,64)
    token_sha=hashlib.sha256(tokens.numpy().tobytes()).hexdigest()
    weight_file=next(Path(path).glob('*.safetensors'))
    with weight_file.open('rb') as f: weight_sha=hashlib.file_digest(f,'sha256').hexdigest()
    device='cuda'
    target='gpt_neox.layers.0.attention.query_key_value'
    batch_of=lambda i: tokens[(i*2)%32:(i*2)%32+2].to(device)
    try:
        # 1. Ajuste completo y espectro del cambio.
        torch.manual_seed(34); torch.cuda.manual_seed_all(34)
        full=AutoModelForCausalLM.from_pretrained(path,local_files_only=True,dtype=torch.float32).to(device).train()
        original=full.get_submodule(target).weight.detach().cpu().clone()
        optimizer=torch.optim.AdamW(full.parameters(),lr=2e-5,weight_decay=0.)
        full_losses=[]
        for i in range(20):
            optimizer.zero_grad(set_to_none=True)
            loss=full(input_ids=batch_of(i),labels=batch_of(i),use_cache=False).loss
            loss.backward(); optimizer.step(); full_losses.append(float(loss.detach().cpu()))
        delta=full.get_submodule(target).weight.detach().cpu().double()-original.double()
        singular=torch.linalg.svdvals(delta).tolist()
        del full,optimizer,loss
        torch.cuda.empty_cache()
        # 2. Paridad con PEFT: mismos A y B, lotes, optimizador y orden.
        torch.manual_seed(73); torch.cuda.manual_seed_all(73)
        ours=AutoModelForCausalLM.from_pretrained(path,local_files_only=True,dtype=torch.float32).to(device).eval()
        peft_base=copy.deepcopy(ours)
        initial_ids=batch_of(0)
        with torch.no_grad():
            reference=ours(input_ids=initial_ids,use_cache=False).logits
            base_losses=[float(ours(input_ids=batch_of(i),labels=batch_of(i),use_cache=False).loss) for i in range(8)]
        inject_lora(ours,[target],r=4,alpha=8,dropout=0.)
        config=LoraConfig(r=4,lora_alpha=8,lora_dropout=0.,bias='none',target_modules=[target])
        peft=get_peft_model(peft_base,config,autocast_adapter_dtype=False).eval()
        own=ours.get_submodule(target)
        lib=peft.get_base_model().get_submodule(target)
        with torch.no_grad():
            lib.lora_A['default'].weight.copy_(own.A)
            lib.lora_B['default'].weight.copy_(own.B)
            initial_diff=(ours(input_ids=initial_ids,use_cache=False).logits-reference).abs().max().item()
        opt_a=torch.optim.AdamW([own.A,own.B],lr=2e-3,weight_decay=0.)
        opt_b=torch.optim.AdamW([lib.lora_A['default'].weight,lib.lora_B['default'].weight],lr=2e-3,weight_decay=0.)
        losses_a=[]; losses_b=[]
        for i in range(8):
            opt_a.zero_grad(set_to_none=True); opt_b.zero_grad(set_to_none=True)
            la=ours(input_ids=batch_of(i),labels=batch_of(i),use_cache=False).loss
            lb=peft(input_ids=batch_of(i),labels=batch_of(i),use_cache=False).loss
            la.backward(); lb.backward(); opt_a.step(); opt_b.step()
            losses_a.append(float(la.detach().cpu())); losses_b.append(float(lb.detach().cpu()))
        del peft,peft_base,lib,opt_a,opt_b,la,lb
        # 3. Fusión en fp32 y sensibilidad del modelo.
        with torch.no_grad():
            unmerged=ours(input_ids=initial_ids,use_cache=False).logits
            repeated=ours(input_ids=initial_ids,use_cache=False).logits
            layer_input=torch.randn(2,64,own.base.in_features,device=device)
            layer_before=own(layer_input)
            hook=own.register_forward_hook(lambda m,i,o: o+1e-6*torch.randn_like(o))
            perturbed=ours(input_ids=initial_ids,use_cache=False).logits
            hook.remove()
        snapshot=own.base.weight.detach().clone(); own.merge()
        with torch.no_grad():
            merged=ours(input_ids=initial_ids,use_cache=False).logits
            layer_after=own(layer_input)
        own.unmerge(); restored=torch.equal(snapshot,own.base.weight)
        fp32={'fusion_logits':gap(merged,unmerged),'fusion_capa_max':float((layer_after-layer_before).abs().max()),
              'repeticion_max':float((repeated-unmerged).abs().max()),'ruido_1e-6_logits':gap(perturbed,unmerged),
              'logit_max':float(unmerged.abs().max()),'peso_restaurado':restored}
        # 4. bf16: capa y logits frente a la referencia fp32 sin fusionar.
        with torch.no_grad(): layer_base=own.base(layer_input)
        ours.to(dtype=torch.bfloat16)
        x16=layer_input.to(torch.bfloat16)
        with torch.no_grad():
            bf_unmerged=ours(input_ids=initial_ids,use_cache=False).logits; bf_layer_unmerged=own(x16)
        own.merge()
        with torch.no_grad():
            bf_merged=ours(input_ids=initial_ids,use_cache=False).logits; bf_layer_merged=own(x16)
        own.unmerge()
        ours.set_submodule(target,Fused32(own))
        with torch.no_grad():
            bf_fused32=ours(input_ids=initial_ids,use_cache=False).logits
            bf_layer_fused32=ours.get_submodule(target)(x16)
        ours.set_submodule(target,own)
        bf16={'capa':compare(bf_layer_unmerged,bf_layer_merged,bf_layer_fused32,layer_before,layer_base),
              'logits':compare(bf_unmerged,bf_merged,bf_fused32,unmerged,reference)}
        result={'model':'EleutherAI/pythia-14m','revision':revision,'weights_sha256':weight_sha,
                'dataset':'Salesforce/wikitext','data_revision':data_revision,'tokens_sha256':token_sha,
                'target':target,'full_steps':20,'lora_steps':8,'singular_values':singular,
                'full_losses':full_losses,'base_losses':base_losses,'own_losses':losses_a,'peft_losses':losses_b,
                'initial_max_logit_difference':initial_diff,'fp32':fp32,'bf16':bf16}
        spectrum_result=result
        print('pérdidas ajuste completo:',[round(v,3) for v in full_losses])
        print('pérdidas base / propia / PEFT:',[round(v,4) for v in base_losses],
              [round(v,4) for v in losses_a],[round(v,4) for v in losses_b])
        print('máxima diferencia propia menos PEFT:',max(abs(a-b) for a,b in zip(losses_a,losses_b)))
        print('logits con B=0 frente a la base, máx:',initial_diff)
        print('fp32:',json.dumps(fp32,indent=1))
        print('bf16:',json.dumps(bf16,indent=1))
        if out_dir:
            Path(out_dir).mkdir(parents=True,exist_ok=True)
            destination=Path(out_dir)/f'pythia-{time.strftime("%Y%m%d-%H%M%S")}.json'
            with destination.open('x',encoding='utf-8') as f: json.dump(result,f,ensure_ascii=False,indent=2)
            print('guardado en',destination)
    finally:
        for name in ('full','original','optimizer','ours','peft','peft_base','opt_a','opt_b','own','lib',
                     'initial_ids','reference','unmerged','merged','repeated','perturbed','snapshot',
                     'layer_input','layer_before','layer_after','layer_base','x16','bf_unmerged','bf_merged','bf_fused32',
                     'bf_layer_unmerged','bf_layer_merged','bf_layer_fused32',
                     'la','lb','loss','delta','hook'):
            globals().pop(name,None)
        gc.collect(); torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Energy by rankLocal GPU
if spectrum_result is None:
    print('Ejecuta antes la celda del laboratorio en una GPU CUDA.')
else:
    s=spectrum_result['singular_values']; total=sum(v*v for v in s)
    print('número de valores singulares:',len(s),'  primeros cuatro:',[f'{v:.3e}' for v in s[:4]])
    print('rango estable:',round(total/s[0]**2,2))
    for r in (1,4,8,16,32,64):
        energy=sum(v*v for v in s[:r])/total
        print(f'r={r:3d}  energía {energy:.3f}  error relativo de Frobenius {math.sqrt(1-energy):.3f}')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

What you should see

Spectrum. The 128 singular values match the first figure (with the versions above we reproduce every digit; another driver or GPU may change the last ones): energy 0.359 with r=4r=4, 0.505 with r=8r=8, and 0.832 with r=32r=32; stable rank 9.23.

InteractiveThe same task and initialization
Training loss (nats per token)6.535.2812345678Step (new batch each time)
  • Custom LoRA
  • PEFT (dashed, on top)
  • Unadapted base model
8
Custom LoRA6.40364
PEFT6.40364
Custom minus PEFT0.000000
Custom minus base−0.026
Max |custom − PEFT|0.000000
Pythia 14M training loss on eight new batches: unadapted base, custom LoRA, and PEFT with the same A, B, batches, and optimizer. Data come from the short lab run.

Parity. All eight losses from the custom implementation and PEFT match bit for bit in our run (maximum difference 0). This is expected if both perform the same floating-point operations in the same order; another PEFT version, initialization, or adapters promoted to fp32 may differ at rounding scale, in which case the criterion is that the difference not grow with steps. The figure does not show improvement. Each loss is measured on a batch the adapter has not seen, and after 8 steps remains within ±0,2\pm0{,}2 of base-model loss. This tests implementation, not learning.

fp32 merging. The merged-layer output differs from unmerged by at most 3,8⋅10−63{,}8\cdot10^{-6}, a few fp32 ulps for outputs of magnitude 10 to 30, as expected from rounding at different points. For logits, reaching absolute value 31.9, maximum difference rises to 0.0124. Is merging wrong? The cell injects Gaussian noise of standard deviation 10−610^{-6} into that same unmerged layer output, and logits change by up to 0.0084, with relative RMS 1,0⋅10−41{,}0\cdot10^{-4} versus 1,3⋅10−41{,}3\cdot10^{-4} for merging. This small model amplifies first-layer perturbations by about three orders of magnitude, and merging produces a perturbation comparable to fp32 rounding. Base weight is restored exactly, and two repeated unmerged forwards yield identical logits.

bf16 merging. The compare cell’s criterion applies here. Comparing merged and unmerged models directly, both in bf16, gives maximum logit difference 6.6: allclose fails with any reasonable tolerance. But the same unmerged model, merely run in bf16, differs from the fp32 reference by up to 8.0, with relative RMS 0.191: that is the floor. The bf16 merge is 0.188 and Fused32 is 0.181, so both pass. The trained adapter effect is the same order as the floor. At the layer, it changes output by 0.28% RMS and the bf16 floor is 0.27%; in logits, amplified by the network, effect is 12% and floor 19%. Effect-to-floor ratio is 1.0 at the layer and 0.6 in logits. With this adapter, the bf16 test cannot distinguish a correct merge from one adding nothing. Only the fp32 test, where the floor is orders of magnitude below the effect, is informative in Pythia. The next control therefore uses a larger adapter.

From the control to the p08-l01 model

Pythia supports spectrum and parity checks because it fits entirely in GPU memory with gradients, while the project model is Qwen. The final control repeats merging on it: load the pinned Qwen2.5-0.5B-Instruct revision in fp32, inject a rank-8 adapter into model.layers.0.self_attn.q_proj, check that with B=0\mat{B}=\mat{0} logits match the base, then give B\mat{B} Gaussian values of standard deviation 0.2 with a fixed seed, large enough for the adapter effect to comfortably exceed the layer’s bf16 floor. This is an arithmetic control, not a trained adapter: the real adapter is trained in p08-l04. Using fp32 outputs as reference, convert to bf16 and apply compare to the layer (with a fixed random input) and logits. Add a negative control, a merge omitting factor α/r\alpha/r, which the criterion should reject. If P08_MODEL_PATH was set in p08-l01, the cell uses that copy; otherwise it downloads the pinned revision (about 1 GB). It needs about 3 GB GPU memory.

[ ]Injection and merging in p08-l01 QwenLocal GPU
import os,json,time,hashlib
from pathlib import Path
if not torch.cuda.is_available():
    print('Este control necesita una GPU CUDA.')
else:
    import gc
    from huggingface_hub import snapshot_download
    from transformers import AutoModelForCausalLM,AutoTokenizer
    revision='7ae557604adf67be50417f59c2c2f167def9a775'
    path=os.environ.get('P08_MODEL_PATH') or snapshot_download('Qwen/Qwen2.5-0.5B-Instruct',revision=revision,
                           allow_patterns=['*.json','*.safetensors','*.txt','*.tiktoken'])
    try:
        tok=AutoTokenizer.from_pretrained(path,local_files_only=True)
        tokens=tok('Explica cuánto ocupa un tensor en memoria.',return_tensors='pt').input_ids.cuda()
        with next(Path(path).glob('*.safetensors')).open('rb') as f: weight_sha=hashlib.file_digest(f,'sha256').hexdigest()
        torch.manual_seed(51); torch.cuda.manual_seed_all(51)
        model=AutoModelForCausalLM.from_pretrained(path,dtype=torch.float32,local_files_only=True).cuda().eval()
        target='model.layers.0.self_attn.q_proj'
        with torch.no_grad(): base_logits=model(input_ids=tokens,use_cache=False).logits
        inject_lora(model,[target],r=8,alpha=16,dropout=0.)
        layer=model.get_submodule(target)
        layer_in=torch.randn(1,8,layer.base.in_features,device='cuda')
        with torch.no_grad():
            initial=model(input_ids=tokens,use_cache=False).logits
            layer.B.normal_(0,.2)
            reference=model(input_ids=tokens,use_cache=False).logits
            layer_ref=layer(layer_in); layer_base=layer.base(layer_in)
        model.to(dtype=torch.bfloat16)
        x16=layer_in.to(torch.bfloat16)
        with torch.no_grad():
            unmerged=model(input_ids=tokens,use_cache=False).logits; layer_unmerged=layer(x16)
            repeat=model(input_ids=tokens,use_cache=False).logits
        before=layer.base.weight.detach().clone()
        layer.merge()
        with torch.no_grad(): merged=model(input_ids=tokens,use_cache=False).logits; layer_merged=layer(x16)
        layer.unmerge()
        fused32=Fused32(layer); model.set_submodule(target,fused32)
        with torch.no_grad():
            fused=model(input_ids=tokens,use_cache=False).logits; layer_fused=fused32(x16)
            # Control negativo: una fusión que olvida el factor alfa/r.
            wrong=F.linear(x16,[email protected],layer.base.bias)
        model.set_submodule(target,layer)
        result_qwen={'revision':revision,'weights_sha256':weight_sha,'tokens':tokens.shape[1],'target':target,
            'B_cero_igual_a_base':bool(torch.equal(initial,base_logits)),
            'repeticion_bf16_max':float((repeat.float()-unmerged.float()).abs().max()),
            'base_restaurada':bool(torch.equal(before,layer.base.weight)),
            'logit_max_fp32':float(reference.abs().max()),
            'capa':compare(layer_unmerged,layer_merged,layer_fused,layer_ref,layer_base),
            'logits':compare(unmerged,merged,fused,reference,base_logits),
            'capa_fusion_sin_escala':compare(layer_unmerged,wrong,wrong,layer_ref,layer_base)['criterio_fusion_bf16'],
            'bytes_peso_bf16':layer.base.weight.numel()*2,'bytes_peso_fp32':fused32.weight.numel()*4}
        print(json.dumps(result_qwen,ensure_ascii=False,indent=1))
        out_dir=os.environ.get('P08_L02_OUT')
        if out_dir:
            Path(out_dir).mkdir(parents=True,exist_ok=True)
            destination=Path(out_dir)/f'qwen-{time.strftime("%Y%m%d-%H%M%S")}.json'
            with destination.open('x',encoding='utf-8') as f: json.dump(result_qwen,f,ensure_ascii=False,indent=2)
            print('guardado en',destination)
    finally:
        for name in ('model','layer','tokens','base_logits','initial','reference','unmerged','merged','repeat',
                     'before','fused32','fused','layer_in','x16','layer_ref','layer_base','layer_unmerged',
                     'layer_merged','layer_fused','wrong'):
            globals().pop(name,None)
        gc.collect(); torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In our short run, logits with B=0\mat{B}=\mat{0} match the base bit for bit, two bf16 forwards are identical, and the weight is restored exactly. At the layer, the adapter changes output by 8.4% relative RMS and the bf16 floor is 0.25%: a ratio of 33, so the test discriminates here. The bf16 merge is 0.19% and Fused32 is 0.18%, both below the floor, and the merge without factor α/r\alpha/r, omitting half the update because α/r=2\alpha/r=2, is rejected. For logits, Qwen’s bf16 floor is 6.0% (maximum difference 4.2 on a 12-token input) and adapter effect only 3.4%: bf16 obscures the adapter at that level, making logit comparison an end-to-end control rather than a sensitive test. The merged matrix occupies 1,605,632 bytes in bf16 and 3,211,264 in Fused32, excluding the restoration copy. These describe one input and random adapter; another GPU or version can change last digits, not the conclusions.

The general lesson: verify merge equivalence where the test has power. Always measure the effect-to-floor ratio; if it is of order 1, the test says nothing regardless of how good True looks.

Carry the procedure to p08-l03 and p08-l04, not the numbers: whenever model, dtype, PEFT version, or adapter changes, repeat three controls (identical output with B=0\mat{B}=\mat{0}, library parity, merge error against the bf16 floor) and save the JSON. Quantized-weight merging requires dequantization and its own error analysis; LoRALinear requires an ordinary nn.Linear precisely so that this is not hidden.

Exercises

ProofFirst update
Prove: Let ΔW=(α/r)BA, a differentiable loss depend on A and B only through ΔW, and G be its gradient with respect to ΔW. Assume B=0, nonzero α/r, and no branch dropout. Show that on the first step A's gradient is zero and B's generally is not.
0
Apply the chain rule with the Frobenius product and interpret the first optimizer step.

Step 1 of 3. What is A's gradient?

NumericLoRA scale
With α=32 and rank r=8, what is the scaling factor α/r?
NumericChanging rank
Keep α=32 and move to r=32. What is the new factor α/r? (With rsLoRA, α/√r, the factor would only halve.)
NumericAdapter parameters
Qwen2.5-0.5B's v_proj value projection is a 128 × 896 matrix (d_out=128, d_in=896). How many trainable parameters does a rank-r=16 LoRA adapter add?
NumericRetained energy
An update has singular values 3, 2, 1, and 1. What relative Frobenius error ‖ΔW − ΔW₂‖_F / ‖ΔW‖_F does the best rank-2 approximation incur?
CodeMerge without accumulated drift
Implement merge() and unmerge(). The object contains base, A, B, and scale; on merge save a matrix copy, add the update in place (base must remain the same tensor), and set merged. On unmerge restore the exact copy rather than subtracting. Raise RuntimeError for a repeated merge or unmerge without a prior merge.
import torch

class Adapter:
  def __init__(self,base,A,B,scale):
      self.base=base; self.A=A; self.B=B; self.scale=scale
      self.merged=False; self.saved=None
  def merge(self):
      pass
  def unmerge(self):
      pass
Shift+Enter to run
Quiz
You merged an adapter into a bf16 model and want to check that the merge is correct. Which check makes sense?
Quiz
By mistake, you initialize A=0 and B=0 and train with AdamW without weight decay. What happens?
Quiz
You want the model to adopt an answer format and, in another experiment, incorporate knowledge of a new domain. How do you choose modules to adapt?

Summary

Key idea

LoRA freezes W0\mat{W}_0 and trains ΔW=(α/r)BA\Delta\mat{W}=(\alpha/r)\mat{B}\mat{A}: r(din+dout)r(d_{\text{in}}+d_{\text{out}}) parameters instead of dindoutd_{\text{in}}d_{\text{out}}. With B=0\mat{B}=\mat{0} and random A\mat{A} the model starts exactly as the base while B\mat{B} still receives a gradient. Eckart, Young, and Mirsky quantify how much update energy fits in rank rr, not how much quality. Unmerge by restoring a copy rather than bf16 subtraction, and validate merge error against an fp32 reference alongside bf16’s own error floor. PEFT parity requires matching initial weights, data, optimizer, and order.