Parameter-efficient fine-tuning and LoRA from scratch
Account for full fine-tuning memory, compare PEFT families, derive low-rank LoRA updates, and implement, merge, and compare adapters with PEFT.
After this lesson you can
- Calculate full fine-tuning memory for weights, gradients, AdamW state, and activations, and compare PEFT alternatives.
- Classify additive, selective, and reparameterized PEFT methods by training and inference cost.
- Derive LoRA, explain B = 0 and α/r scaling, and calculate trainable parameters.
- Implement a LoRA layer, inject it into a Hugging Face model, and merge it into weights.
- Measure task intrinsic dimension with random projections.
Before you start
One model, many specializations
Suppose you must adapt a model to classify contracts, answer supervised medical questions, and follow an API format. Saving three full copies multiplies storage, while updating every weight requires memory for much more than parameters. The previous lesson tuned a small model with response supervision. Now separate the cost of retaining one base from learning each variant.
A fine-tuning memory budget must count weights, gradients, optimizer state, activations, and working memory. Change method and sequence in the figure: the bar uses an explicit architecture and shows its assumptions. Staying below the limit does not mean training will fit, because some real memory is omitted.
If an implementation keeps 16-bit weights, 16-bit gradients, a 32-bit master copy, and two 32-bit Adam moments, persistent memory totals bytes per trainable parameter. For parameters this is bytes before activations, buffers, and fragmentation. This is one recipe, not an AdamW constant: implementations can use different gradient or weight precision, no master copy, quantized states, or states sharded across devices. Adam state is created for parameters the optimizer updates. Freezing a matrix removes its gradients and moments, but not its weights or necessarily activations needed to propagate gradients to earlier modules.
Activations depend on microbatch, length, architecture, and attention kernel. Gradient accumulation can increase effective batch without increasing microbatch, but does not remove weights or states. Recomputation trades activation memory for compute; savings depend on what is stored. The figure counts only one hidden state per block, or one in its ideal recomputation model. It excludes materialized attention matrices and CUDA reserves. Use peak measurements to decide whether a configuration actually fits.
Persistent storage differs from peak memory. Optimizer moments survive between steps; temporary multiplication tensors may coexist only during part of a pass. Peak is not obtained by indiscriminately summing every size in a profile when those allocations are not alive together. Measure both framework-reserved and tensor-allocated maxima, and record precision, length, microbatch, and attention strategy. Reserved memory may exceed allocated memory because of allocator behavior.
In the calculator, full 32-bit fine-tuning uses four bytes of weights, four of gradients, and eight of moments per parameter with AdamW. The mixed assumption uses two for weights, two for gradients, four for a master copy, and eight for moments. Both total sixteen in this example, although reduced precision may change other components. For LoRA, base weights remain frozen and only factors have gradients and states; computation still passes through the base.
PEFT families
Parameter-efficient fine-tuning, or PEFT, keeps most of the base frozen and trains a small portion. Parameter count is only the beginning: activation memory, backward-pass cost, and whether an additional module runs at every inference also matter.
Houlsby and colleagues’ adapters insert small modules, typically with a bottleneck and nonlinearity, into blocks. Each task retains its own parameters and shares the base. The additional path can add latency; a general nonlinear function cannot simply be added to an existing linear matrix.
In prompt tuning and prefix tuning, continuous vectors are learned while the base remains fixed. Prompt tuning adds input embeddings; prefix tuning provides per-layer attention prefixes. Extra context consumes memory and compute, and variants using a network to parameterize a prefix have different parameters and states from a direct key-value prefix. Do not confuse these vectors with discrete in-context examples.
BitFit selects model biases for updates. Cost depends on whether the architecture has those biases; the same selection may be empty in bias-free models. (IA)³ learns vectors scaling internal activations. Both change small parameter sets, but are not equivalent or guaranteed to have identical quality. Some scales can merge into projections under specific conditions; other architecture and serving choices retain extra operations.
| Method | What it learns | Consequence for serving a variant |
|---|---|---|
| Adapter | An additional transformation per block | The extra path usually remains in inference. |
| Prompt or prefix | Input or attention vectors | Adds context positions or states. |
| BitFit | Selected biases | Retain the selection and base revision. |
| (IA)³ | Activation scales | Merging depends on where each scale applies. |
| LoRA | Linear-update factors | They can be merged into a weight copy. |
The calculator represents a prefix as directly trainable keys and values with KV-head width. This is one case: a network generating the prefix adds parameters and can be discarded or retained depending on implementation. It also models QLoRA with an ideal half-byte per frozen weight. Blocks, scales, and unquantized layers make real files or allocations larger. Tuning fewer parameters does not automatically mean processing fewer examples or sequences.
An update as a sum of directions
Let a frozen projection be . LoRA parameterizes its update as
For a column input , output is . Product has rank at most : it first projects into coordinates and then combines them in output space. At rank one, and the correction is . Vector selects which input component to read, and the direction added to the output. Move the vectors and see what happens when is zeroed.
The parameterization trains scalars versus for the full matrix. Factorization is not unique: for any invertible of size , . Counting factor parameters therefore differs from counting distinct degrees of freedom of a matrix of exact rank .
Hu and colleagues initialized randomly and . At initialization and the layer matches the base if bias and the rest of the model stay equal. Scale is a convention controlling branch magnitude; when changing rank, also record , initialization, and rate. No law guarantees identical effect or dynamics across all ranks.
For differentiable loss without dropout, write . The chain rule gives
With , the second gradient is zero at initialization, while the first may be nonzero if . Initializing both factors to zero would block both data gradients. An optimizer with decoupled weight decay may modify even with zero data gradient: distinguish gradient from the full optimizer update.
Which matrices and what rank?
In attention, q and o usually have dimension , but grouped-query attention can have fewer rows for k and v. Count actual dimensions of each rectangular projection; multiplying four times by overcounts when k and v are narrower. Feed-forward projections, embeddings, or other layers can also be adapted: number and effect depend on architecture and task.
Table 6 of the original work reports GPT-3 WikiSQL validation accuracy 73.4 at rank 1 and 73.7 at rank 4 when adapting q and v under its protocol. The authors caution that such low rank need not suffice for every task. This compares a particular matrix selection, data, optimizer, and evaluation, not a rule that rank 1 always suffices.
To understand what rank can approximate a fixed full update, decompose and order . If , cumulative energy of the first values is . The Eckart-Young theorem says truncated SVD minimizes Frobenius error among matrices of rank at most , with squared error equal to the sum of discarded .
This is a property of approximating an already observed matrix, not a LoRA performance guarantee. Training factors under a nonconvex loss with finite data and multiple layers can produce a different update. High retained energy also does not guarantee retained predictions, since inputs and layer sensitivity are not uniform. In the figure compare a real fine-tuning spectrum with recorded LoRA updates without confusing the best retrospective approximation with the trained result.
If the full update is exactly zero, its energy fraction is undefined: do not divide zero by zero or display a perfect curve. A small singular direction acting on frequent inputs or affecting a decisive logit can matter more than its contribution to global norm. Conversely, updates with similar spectra can point to different subspaces. Behavioral study needs outputs or held-out metrics, not just singular values.
Intrinsic dimension is not matrix rank
Task intrinsic dimension is an operational measure: choose a training procedure, initialization, random-subspace distribution, and performance threshold. Restrict the full update to , with and fixed projection , and seek the smallest dimension reaching that threshold. Results depend on dataset, metric, seeds, budget, and projection family. A finite sweep gives an uncertain estimate, not a unique mathematical dimension of the problem.
Aghajanyan and colleagues report an MRPC experiment where optimizing 200 parameters projected to the full space let RoBERTa reach 90% of full fine-tuning performance. In their experiments larger models tended to require smaller dimensions after a fixed number of pretraining updates. Neither observation forces every small sweep to reproduce that trend.
Dimension of a subspace of all parameters and rank of one specific matrix update are distinct constraints. A matrix may have low rank but be chosen in a space with many degrees of freedom; a parameter vector restricted to a low-dimensional subspace can induce high-rank matrices. The figure shows lab results for actually evaluated sizes and seeds: if no dimension reaches threshold, no crossing is invented.
To select a crossing, first define threshold calculation. The lab uses a fraction of full fine-tuning accuracy under its own protocol; reserve examples to select the first sweep dimension and others to evaluate that choice. With small samples, a few successes can reorder curves. Repeat seeds and estimate uncertainty before comparing methods; if the reference is very low, reaching a fraction of it may be trivial. The practice’s sparse projection is one subspace family, different from the paper’s structured transforms.
Preparing measured results.
Merge, switch, and serve
LoRA merging replaces with in a weight copy and removes the separate inference branch. In exact arithmetic and evaluation mode, expressions agree. Floating-point rounding differences are expected; with training dropout active they are not the same function. Verify logits with a precision-appropriate tolerance and compare again after saving and loading.
Merging a variant into a copy avoids separate branch computation, but many merged copies can multiply weight memory. A shared base with separate adapters allows variants to be switched or combined without duplicating the whole base, at the cost of adapter computation and management. Best serving design depends on concurrency, hardware, and kernels; measure latency and memory in your case.
To unmerge, restoring an intact copy of avoids accumulating errors from repeated addition and subtraction. On a quantized base, adding an update and requantizing can lose information; round-trip equality is not guaranteed. Check which weights remain frozen before and after injecting modules, and save the adapter’s exact base revision, scale, names, and configuration.
Lab: LoRA from scratch and PEFT
This lab fine-tunes post-trained Qwen2.5-0.5B-Instruct on a subset of UltraChat. It is not a base model. Loss retains only assistant responses and turn ends, rejects control markers in ordinary text, and separates train and validation by hashes of each user turn. This exclusion does not detect paraphrases.
LoRALinear freezes the original layer, uses random A and zero B, adds dropout only during training, and supports merging at evaluation. Unmerging restores an exact copy of the previous weight. Last-token logits for an example are checked before and after merging; bf16 rounding can change the result. Adapter weights are also saved and reloaded, one q projection compared with PEFT, and the same adapters reinstalled in the full model through PEFT to compare logits while reusing the in-memory base. Bitwise equivalence at low precision is not assumed.
Install compatible versions of PyTorch, Transformers, Datasets, Hugging Face Hub, Safetensors, and PEFT. Normal mode trains on up to 1,024 conversations for three epochs; ORYON_QUICK=1 reduces documents and updates to check flow without promising quality improvement. ORYON_LORA_RANK and ORYON_LORA_ALPHA set rank and scale. ORYON_ULTRACHAT_JSONL can use a real local file with split and messages; otherwise the dataset downloads with recorded revision. ORYON_LORA_DIR chooses the output folder. Use a machine with sufficient memory and release the GPU when finished.
"""LoRA propio sobre Qwen2.5-0.5B-Instruct y contraste de capa con PEFT."""
import copy, gc, hashlib, json, math, os, random
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
from datasets import load_dataset
from huggingface_hub import HfApi
from safetensors.torch import save_file, load_file
from transformers import AutoModelForCausalLM, AutoTokenizer
QUICK = os.getenv('ORYON_QUICK') == '1'
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
OUT = Path(os.getenv('ORYON_LORA_DIR', './oryon-lora'))
LOCAL = os.getenv('ORYON_ULTRACHAT_JSONL', '')
MODEL = 'Qwen/Qwen2.5-0.5B-Instruct'
REV = '7ae557604adf67be50417f59c2c2f167def9a775'
DATASET = 'HuggingFaceH4/ultrachat_200k'
SEED = 1610
RANK = int(os.getenv('ORYON_LORA_RANK', '4' if QUICK else '16'))
ALPHA = float(os.getenv('ORYON_LORA_ALPHA', str(RANK)))
MAX_LEN = 256 if QUICK else 512
TRAIN_DOCS = 6 if QUICK else int(os.getenv('ORYON_LORA_DOCS', '1024'))
VAL_DOCS = 4 if QUICK else 128
EPOCHS = 1 if QUICK else 3
MAX_UPDATES = 2 if QUICK else 0
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
DTYPE = torch.bfloat16 if DEVICE.type == 'cuda' else torch.float32
if RANK < 1 or not math.isfinite(ALPHA) or ALPHA <= 0 or TRAIN_DOCS < 1:
raise ValueError('El rango, la escala y el número de documentos deben ser positivos')
torch.set_num_threads(1)
def sha_bytes(data):
return hashlib.sha256(data).hexdigest()
def sha_json(value):
return sha_bytes(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8'))
def file_hash(path):
digest = hashlib.sha256()
with path.open('rb') as source:
for block in iter(lambda: source.read(1024 * 1024), b''): digest.update(block)
return digest.hexdigest()
class LoRALinear(nn.Module):
def __init__(self, base, rank, alpha, dropout=0.0):
super().__init__()
if not isinstance(base, nn.Linear) or rank < 1 or not math.isfinite(alpha) or alpha <= 0 or not 0 <= dropout < 1:
raise ValueError('Capa, rango, escala o dropout inválidos')
self.base = base
self.base.requires_grad_(False)
self.rank, self.alpha, self.scale = rank, alpha, alpha / rank
self.dropout = nn.Dropout(dropout)
self.A = nn.Linear(base.in_features, rank, bias=False, device=base.weight.device, dtype=torch.float32)
self.B = nn.Linear(rank, base.out_features, bias=False, device=base.weight.device, dtype=torch.float32)
nn.init.kaiming_uniform_(self.A.weight, a=math.sqrt(5))
nn.init.zeros_(self.B.weight)
self.merged = False
self._original = None
def forward(self, x):
y = self.base(x)
if self.merged: return y
update = self.B(self.A(self.dropout(x.to(self.A.weight.dtype)))) * self.scale
return (y + update).to(y.dtype)
def train(self, mode=True):
if mode and self.merged: raise RuntimeError('Desfusiona antes de entrenar')
return super().train(mode)
@torch.no_grad()
def merge(self):
if self.training: raise RuntimeError('Fusiona solo en evaluación, sin dropout activo')
if self.merged: raise RuntimeError('El adaptador ya está fusionado')
self._original = self.base.weight.detach().clone()
delta = (self.B.weight @ self.A.weight) * self.scale
self.base.weight.copy_((self.base.weight.float() + delta).to(self.base.weight.dtype))
self.merged = True
@torch.no_grad()
def unmerge(self):
if not self.merged: raise RuntimeError('El adaptador no está fusionado')
self.base.weight.copy_(self._original)
self._original = None
self.merged = False
def plain(tok, text):
markers = [x.content for x in tok.added_tokens_decoder.values() if x.special and x.content]
if any(marker in text for marker in markers): raise ValueError('Texto con marcador de control')
ids = tok.encode(text, add_special_tokens=False)
special = {i for i, item in tok.added_tokens_decoder.items() if item.special}
if any(i in special for i in ids) or tok.decode(ids, skip_special_tokens=False, clean_up_tokenization_spaces=False) != text:
raise ValueError('Texto no reversible o interpretado como control')
return ids
def render(tok, messages):
start, end = tok.convert_tokens_to_ids('<|im_start|>'), tok.convert_tokens_to_ids('<|im_end|>')
if start == tok.unk_token_id or end == tok.unk_token_id: raise ValueError('Faltan controles de Qwen')
ids, labels = [], []
for m in messages:
role, content = m.get('role'), m.get('content')
if role not in ('system', 'user', 'assistant') or not isinstance(content, str) or not content.strip():
raise ValueError('Turno inválido')
header, body, newline = [start] + plain(tok, role + '\n'), plain(tok, content), plain(tok, '\n')
ids += header + body + [end] + newline
labels += [-100] * len(header) + (body + [end] if role == 'assistant' else [-100] * (len(body) + 1)) + [-100] * len(newline)
if not any(m['role'] == 'user' for m in messages) or not any(x != -100 for x in labels[1:]) or len(ids) > MAX_LEN:
raise ValueError('Sin usuario, sin objetivo o fuera de contexto')
return {'ids': ids, 'labels': labels}
def source_rows():
if LOCAL:
path = Path(LOCAL)
digest = file_hash(path)
def rows(split):
with path.open(encoding='utf-8') as f:
for line in f:
if line.strip():
row = json.loads(line)
if row.get('split') == split: yield row
return rows, {'kind': 'jsonl local', 'sha256': digest}
revision = os.getenv('ORYON_SFT_DATA_REVISION', '')
if OFFLINE and not revision: raise ValueError('Fija ORYON_SFT_DATA_REVISION o aporta ORYON_ULTRACHAT_JSONL')
revision = revision or HfApi().dataset_info(DATASET, revision='main').sha
if not revision: raise ValueError('No se pudo fijar la revisión de UltraChat')
return lambda split: iter(load_dataset(DATASET, split=split, revision=revision, streaming=True)), {'kind': 'Hugging Face', 'id': DATASET, 'revision': revision}
def collect(tok, rows, split, count, forbidden):
accepted, seen, rejected = [], set(), 0
for item in rows(split):
try:
messages = item['messages']
if not isinstance(messages, list) or any(not isinstance(m, dict) or not isinstance(m.get('content'), str) for m in messages):
raise ValueError('Conversación inválida')
fingerprints = {sha_bytes(' '.join(m['content'].split()).casefold().encode('utf-8')) for m in messages if m.get('role') == 'user'}
if not fingerprints or fingerprints & (forbidden | seen): raise ValueError('Solapamiento exacto')
encoded = render(tok, messages)
except (KeyError, TypeError, ValueError):
rejected += 1
continue
seen.update(fingerprints)
encoded.update({'message_sha256': sha_json(messages), 'prompt_sha256': sorted(fingerprints)})
accepted.append(encoded)
if len(accepted) == count: break
if not accepted: raise ValueError('La partición no contiene ejemplos utilizables')
return accepted, seen, rejected
def inject(model, rank, alpha, dropout):
names = []
targets = {'q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj'}
for name, module in list(model.named_modules()):
if name.rsplit('.', 1)[-1] not in targets or not isinstance(module, nn.Linear): continue
parent_name, leaf = name.rsplit('.', 1)
parent = model.get_submodule(parent_name)
setattr(parent, leaf, LoRALinear(module, rank, alpha, dropout))
names.append(name)
if not names: raise ValueError('No se encontraron proyecciones previstas')
return names
def token_loss(model, row):
ids = torch.tensor([row['ids']], dtype=torch.long, device=DEVICE)
labels = torch.tensor([row['labels']], dtype=torch.long, device=DEVICE)
logits = model(input_ids=ids, use_cache=False).logits[:, :-1].float()
target = labels[:, 1:]
n = int((target != -100).sum())
return F.cross_entropy(logits.reshape(-1, logits.shape[-1]), target.reshape(-1), ignore_index=-100, reduction='sum'), n
@torch.inference_mode()
def validation(model, rows):
model.eval(); loss = count = 0
for row in rows:
value, n = token_loss(model, row); loss += float(value.item()); count += n
return {'nll_nats': loss, 'supervised_tokens': count, 'nats_per_token': loss / count}
@torch.no_grad()
def compare_peft(layer):
from peft import LoraConfig, __version__ as peft_version
from peft.tuners.lora.layer import Linear as PeftLinear
cfg = LoraConfig(r=layer.rank, lora_alpha=layer.alpha, lora_dropout=0.0, bias='none')
ref = PeftLinear(copy.deepcopy(layer.base), 'default', cfg, r=layer.rank, lora_alpha=layer.alpha).to(DEVICE).eval()
ref.lora_A['default'].to(dtype=torch.float32)
ref.lora_B['default'].to(dtype=torch.float32)
ref.lora_A['default'].weight.copy_(layer.A.weight)
ref.lora_B['default'].weight.copy_(layer.B.weight)
gen = torch.Generator(device=DEVICE).manual_seed(SEED + 1)
x = torch.randn((2, 3, layer.base.in_features), generator=gen, device=DEVICE, dtype=layer.base.weight.dtype)
actual, expected = layer(x).float(), ref(x).float()
error = float((actual - expected).abs().max().item())
if not torch.allclose(actual, expected, atol=0.02 if DTYPE == torch.bfloat16 else 1e-5, rtol=0.01 if DTYPE == torch.bfloat16 else 1e-5):
raise AssertionError('La capa propia y PEFT difieren más de la tolerancia declarada')
del ref, x, actual, expected
return {'peft_version': peft_version, 'max_abs': error, 'scope': 'Una proyección real q del modelo con los mismos pesos y entrada; no todo el modelo PEFT.'}
def main():
random.seed(SEED); torch.manual_seed(SEED)
if DEVICE.type == 'cuda': torch.cuda.manual_seed_all(SEED)
OUT.mkdir(parents=True, exist_ok=True)
tok = AutoTokenizer.from_pretrained(MODEL, revision=REV, local_files_only=OFFLINE)
rows, origin = source_rows()
val, val_prompts, val_rejected = collect(tok, rows, 'test_sft', VAL_DOCS, set())
train, _, train_rejected = collect(tok, rows, 'train_sft', TRAIN_DOCS, val_prompts)
model = AutoModelForCausalLM.from_pretrained(MODEL, revision=REV, local_files_only=OFFLINE,
dtype=DTYPE, attn_implementation='sdpa').to(DEVICE)
model.config.use_cache = False
model.requires_grad_(False)
model.eval()
check_ids = torch.tensor([val[0]['ids']], device=DEVICE)
with torch.no_grad():
base_logits = model(input_ids=check_ids, use_cache=False).logits[:, -1].float().cpu()
names = inject(model, RANK, ALPHA, 0.05)
with torch.no_grad():
initial_logits = model(input_ids=check_ids, use_cache=False).logits[:, -1].float().cpu()
initial_error = float((base_logits - initial_logits).abs().max().item())
if initial_error != 0: raise AssertionError('B = 0 no conservó la salida inicial')
del base_logits, initial_logits, check_ids
layers = [model.get_submodule(n) for n in names]
trainable = [p for p in model.parameters() if p.requires_grad]
expected = sum(RANK * (m.base.in_features + m.base.out_features) for m in layers)
if sum(p.numel() for p in trainable) != expected: raise AssertionError('Parámetros entrenables inesperados')
before = validation(model, val)
if DEVICE.type == 'cuda': model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant': False})
opt = torch.optim.AdamW(trainable, lr=2e-4, weight_decay=0.0)
steps = 0; logs = []; first_gradients = None
for epoch in range(EPOCHS):
order = list(train); random.Random(SEED + epoch).shuffle(order)
for row in order:
model.train(); opt.zero_grad(set_to_none=True)
loss, n = token_loss(model, row); (loss / n).backward()
if steps == 0:
max_a = max(float(m.A.weight.grad.abs().max().item()) for m in layers)
max_b = max(float(m.B.weight.grad.abs().max().item()) for m in layers)
first_gradients = {'max_abs_A': max_a, 'max_abs_B': max_b}
if max_a != 0: raise AssertionError('Con B inicial cero el gradiente de A debe ser cero')
torch.nn.utils.clip_grad_norm_(trainable, 1.0); opt.step()
steps += 1; logs.append({'step': steps, 'supervised_tokens': n, 'nats_per_token': float(loss.item() / n)})
if MAX_UPDATES and steps >= MAX_UPDATES: break
if MAX_UPDATES and steps >= MAX_UPDATES: break
after = validation(model, val)
del opt; gc.collect()
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
first = model.get_submodule(names[0])
peft = compare_peft(first)
sample = val[0]
ids = torch.tensor([sample['ids']], device=DEVICE)
with torch.no_grad():
original = model(input_ids=ids, use_cache=False).logits[:, -1].float().cpu()
for layer in layers: layer.merge()
merged = model(input_ids=ids, use_cache=False).logits[:, -1].float().cpu()
for layer in layers: layer.unmerge()
restored = model(input_ids=ids, use_cache=False).logits[:, -1].float().cpu()
if not all(torch.isfinite(x).all().item() for x in (original, merged, restored)):
raise ValueError('La comparación de fusión produjo logits no finitos')
merge_atol, merge_rtol = ((0.02, 0.01) if DTYPE == torch.bfloat16 else (1e-5, 1e-5))
merge_error = float((original - merged).abs().max().item())
merge_close = bool(torch.allclose(original, merged, atol=merge_atol, rtol=merge_rtol))
if not merge_close:
print('La fusión supera la tolerancia declarada; no se considera equivalente en esta ejecución.', flush=True)
restore_error = float((original - restored).abs().max().item())
if restore_error != 0: raise AssertionError('La desfusión no restauró exactamente los pesos')
adapter = {name + '.' + side: getattr(model.get_submodule(name), side).weight.detach().cpu().contiguous()
for name in names for side in ('A', 'B')}
adapter_path = OUT / 'adapter.safetensors'
save_file(adapter, str(adapter_path))
loaded = load_file(str(adapter_path))
if any(not torch.equal(adapter[k], loaded[k]) for k in adapter): raise AssertionError('El adaptador no se recuperó exactamente')
with torch.no_grad():
for name in names:
for side in ('A', 'B'):
weight = getattr(model.get_submodule(name), side).weight
weight.zero_(); weight.copy_(loaded[name + '.' + side].to(weight.device))
reloaded = model(input_ids=ids, use_cache=False).logits[:, -1].float().cpu()
reload_error = float((original - reloaded).abs().max().item())
if reload_error != 0: raise AssertionError('La recarga del adaptador no recuperó los logits')
# Reutiliza los pesos base, sin mantener dos copias del modelo grande.
for name in names:
parent_name, leaf = name.rsplit('.', 1)
parent = model.get_submodule(parent_name)
setattr(parent, leaf, getattr(parent, leaf).base)
from peft import LoraConfig, get_peft_model
cfg = LoraConfig(r=RANK, lora_alpha=ALPHA, lora_dropout=0.05, bias='none',
target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj'])
peft_model = get_peft_model(model, cfg).eval()
with torch.no_grad():
for name in names:
layer = peft_model.get_submodule('base_model.model.' + name)
layer.lora_A['default'].to(dtype=torch.float32)
layer.lora_B['default'].to(dtype=torch.float32)
layer.lora_A['default'].weight.copy_(loaded[name + '.A'].to(DEVICE))
layer.lora_B['default'].weight.copy_(loaded[name + '.B'].to(DEVICE))
peft_logits = peft_model(input_ids=ids, use_cache=False).logits[:, -1].float().cpu()
peft_model_error = float((original - peft_logits).abs().max().item())
if not torch.allclose(original, peft_logits, atol=0.02 if DTYPE == torch.bfloat16 else 1e-5,
rtol=0.01 if DTYPE == torch.bfloat16 else 1e-5):
raise AssertionError('El modelo PEFT y el propio difieren más de la tolerancia declarada')
report = {'model': MODEL, 'revision': REV, 'model_kind': 'postentrenado Instruct', 'dtype': str(DTYPE), 'seed': SEED,
'data': origin, 'train_hashes': [r['message_sha256'] for r in train], 'validation_hashes': [r['message_sha256'] for r in val],
'rejected': {'train': train_rejected, 'validation': val_rejected}, 'overlap': 'Exclusión exacta de turnos de usuario normalizados; no detecta paráfrasis.',
'config': {'rank': RANK, 'alpha': ALPHA, 'dropout': 0.05, 'max_context': MAX_LEN, 'epochs': EPOCHS, 'max_updates': MAX_UPDATES, 'lr': 2e-4},
'targets': names, 'trainable_parameters': expected, 'total_parameters': sum(p.numel() for p in model.parameters()),
'training': logs, 'first_gradients': first_gradients, 'before': before, 'after': after, 'peft_layer_check': peft,
'peft_model_max_abs_logits_last_token': peft_model_error,
'initial_max_abs_logits_last_token': initial_error, 'merge_max_abs_logits_last_token': merge_error,
'merge_allclose': merge_close, 'merge_tolerance': {'atol': merge_atol, 'rtol': merge_rtol},
'unmerge_max_abs_logits_last_token': restore_error, 'reload_max_abs_logits_last_token': reload_error,
'adapter_sha256': file_hash(adapter_path),
'limitations': 'Instruct ya postentrenado; validación limitada y solapamiento semántico no excluido. La fusión en bf16 redondea y puede alterar logits.'}
(OUT / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print('LoRA propio:', json.dumps(report, ensure_ascii=False), flush=True)
del peft_model, model, trainable, layers, first, original, merged, restored, reloaded, peft_logits, adapter, loaded; gc.collect()
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
if __name__ == '__main__':
main()npm run lab and open the connection link.Lab: intrinsic dimension
The experiment fine-tunes Pythia-70M and SmolLM2-135M on the same SST-2 rows using logits of two single-token verbalizers. Tokenizers and pretraining differ, so comparison does not identify a causal size effect. Use train for optimization and split validation into disjoint holdouts: one selects the smallest tested dimension reaching 90% of full fine-tuning accuracy, the other evaluates that selection. Exact cross-split duplicates are removed after whitespace and case normalization, but paraphrases remain. Prefix, review, and suffix are tokenized separately; above 128 tokens only the review is truncated, with each truncation counted. The fixed sparse projection has one signed entry per row; backward regenerates the same entries and computes the transpose without storing the matrix. It is a teaching alternative, not the original Fastfood projection. Within each model, trials use the same initial checkpoint, training order, and step count; coordinate and full-fine-tuning learning rates differ. The crossing depends on task, seed, optimizer, and budget; one run does not prove a scaling trend.
Install PyTorch, transformers, datasets, huggingface_hub, pandas, and pyarrow. Set ORYON_QUICK=1 to verify everything with two updates and very small sets; without it the full cell sweep is used. ORYON_OFFLINE=1 requires snapshots already in cache; ORYON_INTRINSIC_DIR chooses output. The projection test explicitly compares forward, transpose, and finite differences before loading weights. Measure RAM and VRAM and reduce sequence length if needed: batch is already one example.
"""SST-2: ajuste completo y subespacio aleatorio disperso, sin matriz P×d."""
import gc
import hashlib
import json
import math
import os
import random
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from huggingface_hub import hf_hub_download
from torch.func import functional_call
from torch.nn import functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer
QUICK = os.getenv('ORYON_QUICK') == '1'
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
OUT = Path(os.getenv('ORYON_INTRINSIC_DIR', './oryon-intrinsic'))
MODELS = {
'pythia': ('EleutherAI/pythia-70m', 'a39f36b100fe8a5377810d56c3f4789b9c53ac42'),
'smol': ('HuggingFaceTB/SmolLM2-135M', '93efa2f097d58c2a74874c7e644dbc9b0cee75a2'),
}
DATA = 'stanfordnlp/sst2'
DATA_REV = '8a5c65785cdc5a2668e3dc7369986b0a4d50b5c5'
SEED = 1616
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(1)
CHUNK = 262144
def digest(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for part in iter(lambda: f.read(1024 * 1024), b''): h.update(part)
return h.hexdigest()
def seed_for(name):
return int.from_bytes(hashlib.sha256((str(SEED) + ':' + name).encode()).digest()[:8], 'little') % (2**63 - 1)
def codes(n, d, device, generator):
# Una columna y un signo por fila; se regenera de forma idéntica en backward.
raw = torch.randint(0, 2**31, (n,), generator=generator, device=device, dtype=torch.int64)
return raw.bitwise_and(2**30 - 1).remainder(d), ((raw // (2**30)).to(torch.float32) * 2 - 1)
class Project(torch.autograd.Function):
@staticmethod
def forward(ctx, base, z, seed):
ctx.shape, ctx.seed, ctx.d = base.shape, seed, z.numel()
generator = torch.Generator(device=base.device).manual_seed(seed)
output = torch.empty_like(base).view(-1)
src = base.reshape(-1)
for start in range(0, src.numel(), CHUNK):
end = min(start + CHUNK, src.numel())
idx, sign = codes(end - start, ctx.d, base.device, generator)
output[start:end] = src[start:end] + z[idx] * sign / math.sqrt(ctx.d)
return output.view(ctx.shape)
@staticmethod
def backward(ctx, grad):
generator = torch.Generator(device=grad.device).manual_seed(ctx.seed)
flat = grad.reshape(-1)
result = torch.zeros(ctx.d, device=grad.device, dtype=grad.dtype)
for start in range(0, flat.numel(), CHUNK):
end = min(start + CHUNK, flat.numel())
idx, sign = codes(end - start, ctx.d, grad.device, generator)
result.scatter_add_(0, idx, flat[start:end] * sign / math.sqrt(ctx.d))
return None, result, None
def projection_test():
# Contrasta el backward contra matriz explícita y diferencias finitas.
base = torch.zeros(7, dtype=torch.float64)
z = torch.tensor([.1, -.2, .3], dtype=torch.float64, requires_grad=True)
v = torch.arange(1, 8, dtype=torch.float64)
out = Project.apply(base, z, 12)
grad, = torch.autograd.grad((out * v).sum(), z)
gen = torch.Generator().manual_seed(12)
idx, sign = codes(7, 3, base.device, gen)
matrix = torch.zeros(7, 3, dtype=torch.float64)
matrix[torch.arange(7), idx] = sign.to(torch.float64) / math.sqrt(3)
assert torch.allclose(out, matrix @ z, atol=1e-12)
assert torch.allclose(grad, matrix.T @ v, atol=1e-12)
assert torch.autograd.gradcheck(lambda q: Project.apply(base, q, 12), (z,), atol=1e-6)
print('Proyección implícita: ida, transpuesta y diferencias finitas verificadas.', flush=True)
def rows(tokenizer):
files = {name: hf_hub_download(DATA, f'default/sst2-{name}.parquet', repo_type='dataset',
revision=DATA_REV, local_files_only=OFFLINE)
for name in ('train', 'validation')}
tables = {name: pd.read_parquet(path) for name, path in files.items()}
rng = np.random.default_rng(SEED)
va = rng.permutation(len(tables['validation']))
count = 16 if QUICK else 400
def normalized(text): return ' '.join(text.split()).casefold()
seen = set()
reserved = []
for index in va:
key = normalized(tables['validation'].iloc[int(index)]['sentence'])
if key not in seen:
seen.add(key); reserved.append(index)
if len(reserved) == 2 * count: break
if len(reserved) != 2 * count: raise ValueError('No hay suficientes ejemplos retenidos distintos')
tr = []
for index in rng.permutation(len(tables['train'])):
key = normalized(tables['train'].iloc[int(index)]['sentence'])
if key not in seen:
seen.add(key); tr.append(index)
if len(tr) == (8 if QUICK else 2048): break
if len(tr) != (8 if QUICK else 2048): raise ValueError('No hay suficientes ejemplos train distintos')
splits = {'train': tr, 'validation': reserved[:count], 'test': reserved[count:]}
encoded, truncated = {}, {}
prefix = tokenizer.encode('Review:', add_special_tokens=False)
suffix = tokenizer.encode('\nSentiment:', add_special_tokens=False)
room = 128 - len(prefix) - len(suffix)
if room < 1: raise ValueError('La plantilla no cabe en el contexto')
for name, indices in splits.items():
table = tables['train' if name == 'train' else 'validation']
encoded[name] = []
truncated[name] = 0
for index in indices:
item = table.iloc[int(index)]
review = tokenizer.encode(' ' + item['sentence'].strip(), add_special_tokens=False)
truncated[name] += int(len(review) > room)
ids = prefix + review[:room] + suffix
assert len(ids) <= 128 and ids[-len(suffix):] == suffix
encoded[name].append((ids, int(item['label']), int(item['idx'])))
return encoded, {k: digest(v) for k, v in files.items()}, truncated
def score(model, sample, label_ids, params=None):
ids, label, _ = sample
x = torch.tensor([ids], device=DEVICE)
kwargs = {'input_ids': x, 'use_cache': False}
output = model(**kwargs) if params is None else functional_call(model, params, (), kwargs, tie_weights=True)
logits = output.logits[0, -1, label_ids].float()
return F.cross_entropy(logits[None], torch.tensor([label], device=DEVICE)), int(logits.argmax().item() == label)
def evaluate(model, samples, label_ids, z=None):
with torch.no_grad():
params = projected(model, z) if z is not None else None
values = [score(model, item, label_ids, params) for item in samples]
return {'accuracy': sum(v[1] for v in values) / len(values),
'correct': sum(v[1] for v in values), 'n': len(values),
'loss': sum(float(v[0]) for v in values) / len(values)}
def projected(model, z):
return {name: Project.apply(param, z, seed_for(name)) for name, param in model.named_parameters()}
def run_case(model, samples, label_ids, d):
random.seed(SEED); torch.manual_seed(SEED)
for p in model.parameters(): p.requires_grad_(d is None)
z = None if d is None else torch.nn.Parameter(torch.zeros(d, device=DEVICE))
optim = torch.optim.AdamW(model.parameters() if d is None else [z],
lr=2e-5 if d is None else 1e-4, weight_decay=0.)
steps = 2 if QUICK else 256
model.train()
for i in range(steps):
optim.zero_grad(set_to_none=True)
params = projected(model, z) if z is not None else None
loss, _ = score(model, samples['train'][i % len(samples['train'])], label_ids, params)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters() if d is None else [z], 1.)
optim.step()
del params, loss
model.eval()
result = {'dimension': d, 'steps': steps,
'validation': evaluate(model, samples['validation'], label_ids, z),
'test': evaluate(model, samples['test'], label_ids, z)}
del optim, z
gc.collect()
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
return result
def main():
projection_test()
if os.getenv('ORYON_INTRINSIC_TEST_ONLY') == '1': return
if DEVICE.type != 'cuda': raise RuntimeError('El barrido requiere GPU; usa ORYON_INTRINSIC_TEST_ONLY=1 para la prueba pequeña.')
OUT.mkdir(parents=True, exist_ok=True)
keys = os.getenv('ORYON_INTRINSIC_MODELS', 'pythia,smol').split(',')
if not keys or any(k not in MODELS for k in keys) or len(set(keys)) != len(keys):
raise ValueError('ORYON_INTRINSIC_MODELS admite pythia y smol sin duplicados')
results = []
hashes = None
for key in keys:
model_id, revision = MODELS[key]
tok = AutoTokenizer.from_pretrained(model_id, revision=revision, local_files_only=OFFLINE)
label_ids = [tok.encode(' negative', add_special_tokens=False), tok.encode(' positive', add_special_tokens=False)]
if any(len(x) != 1 for x in label_ids): raise ValueError('Los verbalizadores deben ser un solo token')
label_ids = [x[0] for x in label_ids]
samples, hashes, truncated = rows(tok)
cases = []
for d in ([4, 16, 64] if QUICK else [8, 32, 128, 512, 2048]) + [None]:
print('Modelo:', model_id, 'dimensión:', d if d else 'ajuste completo', flush=True)
torch.manual_seed(SEED)
model = AutoModelForCausalLM.from_pretrained(model_id, revision=revision, local_files_only=OFFLINE,
dtype=torch.float32, attn_implementation='sdpa').to(DEVICE)
model.config.use_cache = False
cases.append(run_case(model, samples, label_ids, d))
del model; gc.collect(); torch.cuda.empty_cache()
results.append({'model': model_id, 'model_revision': revision, 'label_ids': label_ids,
'truncated_by_split': truncated,
'split_ids': {name: [r[2] for r in val] for name, val in samples.items()}, 'cases': cases})
report = {'models': results, 'dataset': DATA, 'dataset_revision': DATA_REV,
'files_sha256': hashes, 'seed': SEED, 'quick': QUICK, 'torch': str(torch.__version__),
'device': str(DEVICE),
'projection': 'Una columna aleatoria y signo por parámetro, escala 1/sqrt(d); regeneración por bloques.',
'split_policy': 'Selección por semilla; se excluyen duplicados exactos tras normalizar espacios y mayúsculas, no paráfrasis.',
'limitations': 'Familias, tokenizadores y preentrenamiento distintos confunden la comparación de tamaño. Una semilla y un único presupuesto no garantizan monotonía ni una dimensión intrínseca universal.'}
(OUT / 'intrinsic-report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print('Informe:', OUT / 'intrinsic-report.json', flush=True)
if __name__ == '__main__': main()npm run lab and open the connection link.Lab: spectrum and rank
From ΔW spectrum to LoRA rank
This cell retrieves the previous lesson’s report and full checkpoint through ORYON_SFT_DIR, verifies pack hashes, and exactly reconstructs held-out validation. If tuning used local JSONL, set ORYON_ULTRACHAT_JSONL to the same file; for remote UltraChat, the cell uses the report’s pinned revision. PyTorch, Transformers, Datasets, and Safetensors are required. Output goes to ORYON_SPECTRUM_DIR.
SVD is computed for q, k, v, o, up, and down matrices of the difference between checkpoint and base of the same revision. Separately, rank 1, 2, 4, 8, 16, 32, and 64 LoRA adapters are tuned in those matrices, with α equal to rank and therefore constant α/r. All repeat recorded packs and updates and are evaluated on the same holdout. Losses are nats per supervised token, not accuracy or IFEval. The resulting file retains hashes, budgets, singular values, and configurations.
ORYON_QUICK=1 uses at most three updates and only initial, middle, and final layers to check flow. If the full checkpoint had more steps, this mode does not equal its budget and that must be stated in comparison. Truncated SVD minimizes each matrix’s Frobenius reconstruction error but does not prove corresponding LoRA rank reaches the same loss: adapters train separately. One task and seed do not establish a universal rank. Full tuning was done in l15; this cell does not retrain it.
"""Espectros del checkpoint SFT de l15 y barrido LoRA sobre los mismos paquetes.
Dependencias: torch, transformers, safetensors, datasets, huggingface_hub.
ORYON_SFT_DIR apunta a la salida de l15; ORYON_ULTRACHAT_JSONL debe ser el
mismo archivo si se usaron datos locales. ORYON_SPECTRUM_DIR elige la salida.
ORYON_QUICK=1 limita el barrido a tres actualizaciones y tres capas para QA.
"""
import gc, hashlib, json, math, os, platform
from collections import OrderedDict
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
from safetensors import safe_open
from transformers import AutoModelForCausalLM, AutoTokenizer
from datasets import load_dataset
ROOT = Path(os.getenv('ORYON_SFT_DIR', './oryon-sft'))
OUT = Path(os.getenv('ORYON_SPECTRUM_DIR', './oryon-lora-spectrum'))
LOCAL = os.getenv('ORYON_ULTRACHAT_JSONL', '')
QUICK = os.getenv('ORYON_QUICK') == '1'
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
RANKS = [1, 2, 4, 8, 16, 32, 64]
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(1)
def file_hash(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(1024 * 1024), b''): h.update(chunk)
return h.hexdigest()
def json_hash(value):
return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True,
separators=(',', ':')).encode('utf-8')).hexdigest()
def read_packs(path, report):
if file_hash(path) != report['training_packs_sha256']:
raise ValueError('Los paquetes no corresponden al informe SFT')
grouped = OrderedDict()
with path.open(encoding='utf-8') as f:
for line in f:
row = json.loads(line)
grouped.setdefault(int(row['update']), []).append(row)
expected = report['training']
if list(grouped) != [x['step'] for x in expected]:
raise ValueError('Las actualizaciones no coinciden con el informe')
for info, group in zip(expected, grouped.values(), strict=True):
processed = sum(len(x['input_ids']) for x in group)
targets = sum(sum(y != -100 for y in x['labels'][1:]) for x in group)
if (processed != info['processed_tokens'] or targets != info['assistant_tokens']
or len(group) != info['microbatches']):
raise ValueError('Los contadores de un paquete no coinciden')
return list(grouped.values())
def plain(tokenizer, text):
special = tokenizer.added_tokens_decoder
if any(t.special and t.content and t.content in text for t in special.values()):
raise ValueError('Texto con marcador especial')
ids = tokenizer.encode(text, add_special_tokens=False)
if any(i in {k for k, v in special.items() if v.special} for i in ids):
raise ValueError('El texto ordinario produjo un control')
if tokenizer.decode(ids, skip_special_tokens=False, clean_up_tokenization_spaces=False) != text:
raise ValueError('La tokenización no conserva el texto')
return ids
def tokenize_messages(tokenizer, messages):
ids, labels = [], []
if tokenizer.convert_tokens_to_ids('<|im_start|>') != 1 or tokenizer.convert_tokens_to_ids('<|im_end|>') != 2:
raise ValueError('No coinciden los controles de SmolLM2')
for m in messages:
role, content = m['role'], m['content']
if role not in ('system', 'user', 'assistant'): raise ValueError('Rol desconocido')
header = [1] + plain(tokenizer, role + '\n')
body = plain(tokenizer, content)
suffix = plain(tokenizer, '\n')
ids.extend(header + body + [2] + suffix)
labels.extend([-100] * len(header) + (body + [2] if role == 'assistant' else [-100] * (len(body) + 1)) + [-100] * len(suffix))
return {'input_ids': ids, 'labels': labels, 'segment_lengths': [len(ids)]}
def validation_rows(tokenizer, report):
expected = report['validation_messages_sha256']
if not expected or len(set(expected)) != len(expected): raise ValueError('Reserva inválida')
source = report['data']
if source['kind'] == 'jsonl local':
if not LOCAL or file_hash(LOCAL) != source['sha256']:
raise ValueError('Proporciona el mismo ORYON_ULTRACHAT_JSONL de l15')
def rows():
with open(LOCAL, encoding='utf-8') as f:
for line in f:
row = json.loads(line)
if row.get('split') == 'test_sft': yield row
iterable = rows()
elif source['kind'] == 'Hugging Face':
if OFFLINE: raise ValueError('La reserva de l15 procede de streaming remoto; desactiva ORYON_OFFLINE para recuperarla')
iterable = load_dataset(source['id'], split='test_sft', revision=source['revision'], streaming=True)
else: raise ValueError('Origen SFT no admitido')
wanted, found = set(expected), {}
for row in iterable:
try:
messages = [{'role': m['role'], 'content': m['content']} for m in row['messages']]
digest = json_hash(messages)
if digest in wanted and digest not in found: found[digest] = tokenize_messages(tokenizer, messages)
if len(found) == len(wanted): break
except (ValueError, KeyError, TypeError): continue
if len(found) != len(wanted): raise ValueError('No se recuperó exactamente la reserva de l15')
return [found[h] for h in expected]
def batch(row):
lengths = row['segment_lengths']
if not lengths or sum(lengths) != len(row['input_ids']) or len(row['labels']) != len(row['input_ids']):
raise ValueError('Paquete mal formado')
groups = torch.tensor([i for i, n in enumerate(lengths) for _ in range(n)], device=DEVICE)
positions = torch.tensor([[i for n in lengths for i in range(n)]], device=DEVICE)
same = groups[:, None] == groups[None, :]
mask = (same & torch.ones_like(same, dtype=torch.bool).tril())[None, None]
return (torch.tensor([row['input_ids']], device=DEVICE), torch.tensor([row['labels']], device=DEVICE), positions, mask)
def loss_sum(model, row):
ids, labels, pos, mask = batch(row)
logits = model(input_ids=ids, attention_mask=mask, position_ids=pos, use_cache=False).logits
target = labels[:, 1:]
count = int((target != -100).sum())
if not count: raise ValueError('Sin objetivos válidos')
loss = F.cross_entropy(logits[:, :-1].float().reshape(-1, logits.shape[-1]), target.reshape(-1), ignore_index=-100, reduction='sum')
return loss, count
@torch.inference_mode()
def validation(model, rows):
model.eval(); total = 0.; count = 0
for row in rows:
loss, n = loss_sum(model, row); total += float(loss); count += n
result = total / count
if not math.isfinite(result): raise ValueError('La pérdida de validación no es finita')
return {'nats_per_token': result, 'assistant_tokens': count}
class LoRALinear(nn.Module):
def __init__(self, base, rank):
super().__init__()
self.base = base
self.a = nn.Parameter(torch.empty(rank, base.in_features, device=base.weight.device))
self.b = nn.Parameter(torch.zeros(base.out_features, rank, device=base.weight.device))
nn.init.kaiming_uniform_(self.a, a=math.sqrt(5))
self.scale = 1.0 # alpha = r, escala constante en todos los rangos.
def forward(self, x):
return self.base(x) + F.linear(F.linear(x, self.a), self.b) * self.scale
@torch.no_grad()
def singular_values(self):
# QR reduce BA a una matriz r×r con los mismos valores singulares no nulos.
_, rb = torch.linalg.qr(self.b.float(), mode='reduced')
_, ra = torch.linalg.qr(self.a.float().T, mode='reduced')
values = torch.linalg.svdvals(rb @ ra.T).cpu().tolist()
if not all(math.isfinite(x) for x in values): raise ValueError('SVD de LoRA no finita')
fro2 = float((self.b.float() @ self.a.float()).square().sum())
if not math.isclose(sum(x*x for x in values), fro2, rel_tol=2e-4, abs_tol=1e-12):
raise AssertionError('La SVD reducida no conserva la norma de BA')
return values
def modules(model, layer):
block = model.model.layers[layer]
return {'q': (block.self_attn, 'q_proj'), 'k': (block.self_attn, 'k_proj'),
'v': (block.self_attn, 'v_proj'), 'o': (block.self_attn, 'o_proj'),
'up': (block.mlp, 'up_proj'), 'down': (block.mlp, 'down_proj')}
def train_rank(model, rank, packs, rows, layers, seed, config):
torch.manual_seed(seed)
if DEVICE.type == 'cuda': torch.cuda.manual_seed_all(seed)
for parameter in model.parameters(): parameter.requires_grad_(False)
for i in range(len(model.model.layers)):
for owner, name in modules(model, i).values(): setattr(owner, name, LoRALinear(getattr(owner, name), rank))
adapters = [p for p in model.parameters() if p.requires_grad]
trainable = sum(p.numel() for p in adapters)
opt = torch.optim.AdamW(adapters, lr=config['lr'], weight_decay=config['weight_decay'])
if DEVICE.type == 'cuda':
model.enable_input_require_grads(); model.gradient_checkpointing_enable()
model.train(); counts = []
for group in packs:
opt.zero_grad(set_to_none=True); total = 0
for row in group:
loss, n = loss_sum(model, row); loss.backward(); total += n
for p in adapters:
if p.grad is not None: p.grad.div_(total)
nn.utils.clip_grad_norm_(adapters, config['clip']); opt.step()
counts.append(total)
metrics = validation(model, rows)
spectra = {}
for i in layers:
spectra[str(i)] = {name: getattr(owner, attr).singular_values() for name, (owner, attr) in modules(model, i).items()}
result = {'rank': rank, 'alpha': rank, 'scale': 1., 'trainable_parameters': trainable,
'updates': len(packs), 'supervised_tokens': sum(counts), 'validation': metrics,
'singular_values': spectra}
del opt, adapters
return result
def main():
OUT.mkdir(parents=True, exist_ok=True)
report_path = ROOT / 'sft-report.json'
report = json.loads(report_path.read_text(encoding='utf-8'))
if report.get('checkpoint_saved') is False: raise ValueError('El ajuste de l15 no guardó checkpoint')
checkpoint = ROOT / 'final' / 'model.safetensors'
if not checkpoint.is_file(): raise FileNotFoundError(checkpoint)
packs = read_packs(ROOT / 'sft-training-packs.jsonl', report)
if QUICK: packs = packs[:3]
model_id, revision = report['model'], report['revision']
tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision, local_files_only=OFFLINE)
rows = validation_rows(tokenizer, report)
base = AutoModelForCausalLM.from_pretrained(model_id, revision=revision, local_files_only=OFFLINE, dtype=torch.float32, attn_implementation='sdpa').to(DEVICE)
base.config.use_cache = False
layers = sorted(set([0, len(base.model.layers)//2, len(base.model.layers)-1])) if QUICK else list(range(len(base.model.layers)))
baseline = validation(base, rows)
expected = report['before']['validation']['nats_per_token']
if abs(baseline['nats_per_token'] - expected) > 2e-4:
raise ValueError('La reserva recuperada no reproduce la pérdida inicial de l15')
full = {}
with safe_open(str(checkpoint), framework='pt', device='cpu') as saved:
available = set(saved.keys())
for i in layers:
full[str(i)] = {}
for key, (owner, name) in modules(base, i).items():
prefix = 'self_attn' if key in ('q', 'k', 'v', 'o') else 'mlp'
tensor_name = f'model.layers.{i}.{prefix}.{name}.weight'
if tensor_name not in available: raise ValueError(f'Falta {tensor_name} en el checkpoint')
delta = saved.get_tensor(tensor_name).to(DEVICE).float() - getattr(owner, name).weight.detach().float()
values = torch.linalg.svdvals(delta).cpu().tolist()
if not all(math.isfinite(x) for x in values): raise ValueError('SVD no finita')
if not math.isclose(sum(x*x for x in values), float(delta.square().sum()), rel_tol=2e-4, abs_tol=1e-12):
raise AssertionError('La SVD no conserva la norma de la actualización')
full[str(i)][key] = values
del delta
del base; gc.collect()
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
full_model = AutoModelForCausalLM.from_pretrained(ROOT / 'final', local_files_only=True,
dtype=torch.float32, attn_implementation='sdpa').to(DEVICE)
full_model.config.use_cache = False
full_validation = validation(full_model, rows)
if abs(full_validation['nats_per_token'] - report['after']['validation']['nats_per_token']) > 2e-4:
raise ValueError('El checkpoint no reproduce la pérdida final del informe de l15')
del full_model; gc.collect()
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
results = []
for rank in RANKS:
torch.manual_seed(report['seed'])
model = AutoModelForCausalLM.from_pretrained(model_id, revision=revision, local_files_only=OFFLINE, dtype=torch.float32, attn_implementation='sdpa').to(DEVICE)
model.config.use_cache = False
run = train_rank(model, rank, packs, rows, layers, report['seed'], report['config'])
results.append(run)
print('rango', rank, 'actualizaciones', run['updates'], 'NLL validación', run['validation']['nats_per_token'], flush=True)
del model; gc.collect()
if DEVICE.type == 'cuda': torch.cuda.empty_cache()
value = {'model': model_id, 'revision': revision, 'quick': QUICK, 'seed': report['seed'], 'layers': layers,
'source_report_sha256': file_hash(report_path), 'checkpoint_sha256': file_hash(checkpoint),
'training_packs_sha256': report['training_packs_sha256'], 'validation_messages_sha256': report['validation_messages_sha256'],
'environment': {'python': platform.python_version(), 'torch': str(torch.__version__), 'device': str(DEVICE),
'dtype': 'float32', 'full_svd': 'torch.linalg.svdvals', 'lora_svd': 'QR reducido de B y A.T, SVD de R_B R_A.T'},
'optimizer': {'kind': 'AdamW', 'lr': report['config']['lr'], 'weight_decay': report['config']['weight_decay'],
'clip': report['config']['clip'], 'adapter_dropout': 0.0, 'scale': 'alpha/r=1'},
'full_sft_updates': len(report['training']), 'lora_updates': len(packs), 'baseline': baseline,
'full_validation': full_validation, 'full_singular_values': full, 'lora_runs': results,
'limitations': 'Un único ajuste, una semilla y una reserva. La SVD truncada optimiza error de pesos, no garantiza rendimiento. LoRA se entrena por separado y no es la SVD truncada. La prueba corta puede tener distinto presupuesto que un checkpoint completo.'}
target = OUT / 'spectrum-report.json'
target.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print('Informe:', target, flush=True)
if __name__ == '__main__': main()
npm run lab and open the connection link.Exercises
The next cell checks the first two exercises. Use decimal GB for byte capacity and binary GiB for comparison with the interactive budget.
capas, rango, d, kv = 24, 16, 2048, 256
lora_qkvo = capas * rango * (2 * (d + d) + 2 * (d + kv))
bytes_persistentes = 1_500_000_000 * 16
print("Parámetros LoRA:", lora_qkvo)
print("Bytes sin activaciones:", bytes_persistentes)
print("GiB sin activaciones:", bytes_persistentes / 1024**3)Step 1 of 3. What is the adapted layer's initial output?
import numpy as np
class LoRALinear:
def __init__(self, W, A, B, alpha):
pass
def forward(self, x):
pass
def merge(self):
pass
def unmerge(self):
pass
def trainable_parameters(self):
pass
PEFT reduces updated parameters. Actual savings depend on what stays frozen, activations, and serving; rank, spectrum, and intrinsic dimension answer related but distinct questions.