QLoRA and fine-tuning in 8 GB
Study QLoRA's NF4 quantization, double quantization, and paged optimizers, then compare LoRA rank, scaling, learning rates, variants, and retention.
After this lesson you can
- Construct NF4 levels from normal quantiles and examine reconstruction error against uniform INT4.
- Calculate memory for a 3B NF4 model with double quantization and its QLoRA fine-tuning.
- Fine-tune a 1.5B to 3B model with QLoRA and compare with bfloat16 LoRA on a smaller model.
- Design rank, α, and learning-rate sweeps and apply rsLoRA, LoRA+, and DoRA.
- Measure LoRA learning and forgetting against full fine-tuning on a domain task.
Before you start
- 20Low-Rank AdaptationLoRA weight mergingFine-tuning memory accountingParameter-efficient fine-tuning methods
- 21Uniform symmetric and affine quantizationQuantization granularityActivation (gradient) checkpointing
- 09IEEE 754 and deep learning formatsCorrect rounding and rounding modesMachine epsilon and unit roundoff
- 00Device placement and CPU-GPU transfersWorker processes, pinned memory and prefetch
- 04Quantile functionUnivariate normal distribution
A compressed base still participates in computation
In LoRA you froze the base and trained small factors. Even so, keeping the base in bfloat16 costs about two bytes per parameter before activations and buffers. For three billion parameters that ideal count already reaches six billion bytes. What if the base is stored at four bits per weight and dequantized only for operations?
QLoRA combines a frozen block-quantized base with trainable adapters. In Dettmers and colleagues’ formulation, weights are often stored in NF4 and multiplication computed in bfloat16. Four-bit storage does not imply all products, gradients, and states are computed or stored in four bits. Actual precisions depend on implementation.
The compressed base, its scales, and adapters persist between steps. A layer needs the values required for multiplication, but a kernel may fuse dequantization and multiplication without materializing the entire matrix simultaneously. During backward, gradients pass through base computation to reach activations and adapters; the frozen base receives no update. The optimizer keeps gradients and states for parameters it actually trains.
The figure counts a specific Qwen2.5-3B geometry with q, k, v, and o adapters and assumes ideal four-bit storage for all weights. Some real embeddings, normalizations, metadata, and buffers may use another precision. The subtotal also excludes activations and fragmentation. When measuring fine-tuning, record allocated and reserved memory peaks, length, batch, precision, kernels, and devices. The complete budget distinguishes a useful estimate from a guarantee that cannot be made.
Block quantization: the role of the maximum
For weight block , take . If , normalize , choose level from a finite codebook, and reconstruct . Each level index occupies four bits for sixteen levels. Scale must also be saved. For an all-zero block, define zero output and scale without division by zero.
This is symmetric absolute-maximum quantization; other granularities and affine schemes use different conventions. Smaller blocks cost more in scales, but one extreme value affects fewer weights. Multiplying an outlier increases the maximum and brings most normalized values closer to zero. Results depend on block and codebook, not just the model’s global distribution.
The interactive uses an identified sample of real weights; changing an outlier is an explicit intervention on that sample. Its mean squared error is a reconstruction statistic for those weights, not model performance. Layer, block size, ties, and saturation rule matter when repeating the calculation.
The later cell holds out 256 weights from that matrix for error measurement while another 256 calibrate Lloyd-Max. With blocks of 64, observed mean squared error is approximately for NF4, for the chosen symmetric INT4, and for FP4. Lloyd-Max, calibrated on the first half, obtains approximately on the holdout. This measured example covers one layer and split; it does not show the ordering holds for other layers or generation quality.
NF4, quantiles, and squared error
NormalFloat4 uses a codebook of sixteen nonuniformly spaced values designed from standard-normal quantiles and adjusted to represent zero exactly. Levels concentrate near zero. QLoRA describes the construction and publishes the values; compatible implementations must use the same codebook, order, decision rule, and scale, not any similar quantile set.
Quantiles give intuition for allocating resolution where more mass lies, but distinguish reconstruction levels from decision boundaries. If is a continuous strictly increasing distribution function, boundaries for , plus infinite endpoints, divide the distribution into intervals of probability . Choosing levels at quantiles and assigning each value to the nearest level instead places boundaries at midpoints between levels. Those midpoints are generally not the quantiles that would make cells equiprobable.
Actual NF4 includes exact zero and per-block absmax scaling. The distribution after normalization by a finite block’s random maximum need not match a standard normal. Do not promise every level gets equal mass in all blocks or that NF4 has lower error than INT4 or FP4 on every sample. The experiment compares codebooks on the same block to test the hypothesis.
The criterion also matters. For fixed boundaries and squared loss, a positive-probability cell’s optimal representative is its conditional mean. For fixed representatives and squared distance, optimal assignment uses the nearest representative. Alternating these steps gives Lloyd-Max; it can converge to a local optimum and depends on initialization. Equal-probability cells do not by themselves imply minimum squared error. Here the one-dimensional Lloyd algorithm gives the same intuition of alternating assignments and centroids.
To see the mean condition, take positive-probability cell and minimize with respect to . Expanding the square gives derivative and positive second derivative. The optimal center is therefore the conditional mean. This requires a finite second moment in the cell. Changing centers also changes nearest-neighbor boundaries: one update does not prove the global minimum was found.
Quantizing the scales too
Double quantization reduces scale-constant cost. With blocks of 64 weights, one fp32 scale per block adds an average bits per weight. In the scheme described by Dettmers and colleagues, scales are centered and quantized to eight bits in groups of 256, with an additional fp32 constant per group. Ideal average accounting becomes
The difference is approximately bits per weight, excluding other metadata. For finite weight counts, incomplete blocks must be rounded up. The exercise states exactly what it includes; real files can retain tensors in other precisions, offsets, alignment, and metadata. Quantizing scales also adds reconstruction error, so savings must be evaluated alongside accuracy.
The first scale describes one weight block’s amplitude; the second describes a block of those scales. Before second quantization, the published method centers positive scales by subtracting their mean. Reconstruction recovers an approximate scale and then the normalized weight. The lab uses a teaching integer second quantizer, not bitsandbytes’ exact dynamic map, and states so in output. Slightly lower squared error on a particular set after this second approximation can arise from compensating rounding; it is not a general guarantee.
Peaks, paging, and model preparation
QLoRA’s paged optimizers use unified memory to move optimizer states between RAM and GPU when needed. Total size does not disappear, transfers can cost time, and avoiding failure depends on available memory, support, and access pattern. They do not automatically page all activations or guarantee freedom from out-of-memory errors. Activation recomputation trades storage for compute and may cause short-lived peaks worth measuring.
In a PEFT and bitsandbytes implementation, explicitly prepare the model for low-precision training and verify that adapters are the only intended trainable parameters. Preparation may keep normalizations or other components in fp32 and must coordinate with gradient-checkpointing mode and input gradients. Inspect names, types, and parameter counts and confirm finite loss and gradients before a long run.
Memory accounting must separate four-bit storage, scales, trainable factors, gradients, optimizer states, and activations. AdamW maintains moments for updated parameters; paging changes possible location, not logical quantity. Sequence length and microbatch affect activations and workspaces. If checkpointing, precision, or attention implementation changes, remeasure peak under the same load before attributing a difference to one option.
Merging deserves a separate test. Adding to a base already approximated by quantization and then requantizing introduces further rounding. Logits or quality may change even when the separate branch worked well; compare on the same examples before and after. Keeping base and adapter separate supports reproduction and avoids assuming subtraction exactly reverses quantization.
Rank, scale, and learning rate
LoRA hyperparameters interact: rank, scale , rate, initialization, dropout, and target matrices affect both parameter count and dynamics. If is fixed and changes, original scale changes too. A comparison fixing only rate and seed does not isolate adapter-capacity effects.
rsLoRA and other variants propose different modifications. rsLoRA studies to stabilize rank scaling under its assumptions. LoRA+ assigns different rates to factors; DoRA separates magnitude and direction; and PiSSA initializes the trainable part with base-matrix singular components and keeps a frozen residual.
These modifications are not interchangeable names. LoRA+ requires defining each group’s rate; DoRA adds parameters and normalization; PiSSA changes initialization and the residual accompanying the adapter. Compare cost and saving behavior as well as a held-out metric. A short test may not show paper trends and cannot justify claiming a variant always wins.
The next test applies LoRA+ and DoRA with PEFT to the same small transformation. For LoRA+ it verifies rates assigned to factors A and B; for DoRA it checks that the magnitude vector exists. Both updates freeze the base. One update on test-constructed data checks component wiring, not quality, and does not replace a held-out sweep. Install compatible PyTorch, Transformers, and PEFT to run locally.
import copy
import torch
from torch import nn
from peft import LoraConfig, get_peft_model
from peft.optimizers import create_loraplus_optimizer
torch.set_num_threads(1)
torch.manual_seed(17)
base = nn.Sequential(nn.Linear(8, 6, bias=False))
x = torch.arange(32, dtype=torch.float32).reshape(4, 8) / 32
target = x @ torch.arange(48, dtype=torch.float32).reshape(8, 6) / 48
for name in ('LoRA+', 'DoRA'):
model = get_peft_model(copy.deepcopy(base), LoraConfig(
r=2, lora_alpha=4, target_modules=['0'], use_dora=name == 'DoRA'))
trainable = [(n, p) for n, p in model.named_parameters() if p.requires_grad]
if name == 'LoRA+':
optimizer = create_loraplus_optimizer(model, torch.optim.AdamW,
lr=1e-3, loraplus_lr_ratio=4, weight_decay=0)
rates = {n: group['lr'] for group in optimizer.param_groups
for p in group['params'] for n, q in trainable if p is q}
assert all(rates[n] == (4e-3 if 'lora_B' in n else 1e-3) for n, _ in trainable)
else:
optimizer = torch.optim.AdamW([p for _, p in trainable], lr=1e-3, weight_decay=0)
assert any('lora_magnitude_vector' in n for n, _ in trainable)
frozen = [(p, p.detach().clone()) for p in model.parameters() if not p.requires_grad]
before = nn.functional.mse_loss(model(x), target)
before.backward()
assert all(p.grad is not None and torch.isfinite(p.grad).all() for _, p in trainable)
optimizer.step()
after = nn.functional.mse_loss(model(x), target)
assert torch.isfinite(after) and all(torch.equal(p, saved) for p, saved in frozen)
print(name, 'parámetros entrenables', sum(p.numel() for _, p in trainable),
'pérdida inicial/final', round(before.item(), 6), round(after.item(), 6))
if name == 'LoRA+': print('Tasas por factor:', rates)npm run lab and open the connection link.For example, to compare ranks at constant scale, vary together with . To study a convention with fixed , declare that scale changes. Neither choice alone gives a universal comparison. Record target matrices and rate as well as rank, and use the same validation protocol for every sweep cell. Optimization may need different rates under different parameterizations.
The sweep separates training, validation, and evaluation. Select hyperparameters on validation and reserve test for final comparison; record seeds and supervised tokens, not just steps. A heatmap has statistical noise and may not cover the optimum. If a run did not finish or produced nonfinite values, show it as missing or failed.
Learning and forgetting: a conditional comparison
Learning-forgetting tradeoffs require measuring both the new task and prior capabilities before and after with the same protocol. Lower domain loss does not automatically mean better answers on every benchmark; a decline on one evaluation does not prove loss of every individual capability.
Biderman and colleagues compared full fine-tuning and LoRA on Llama-2-7B with code and mathematics tasks, rate search, and ranks 16, 64, and 256. For supervised code tuning, they report HumanEval 0.358 at rank 16 and 0.417 at rank 64 after four epochs under their protocol. They also found domain-dependent forgetting patterns: curves suggest tradeoffs favoring LoRA for some code tuning and full fine-tuning for some mathematics tuning. In a multitask mixture, LoRA also matched several full-tuning metrics. The paper’s title summarizes a studied trend, not a universal law.
For rigorous comparison, fix the base model and data revisions, equalize the intended budget, and seek reasonable rates for each method. Retain paired results, uncertainty intervals, and a general holdout not chosen after viewing test. If model size, precision, and method all change together, the observed difference does not identify its cause.
Specify what equal budget means: equal updates, tokens, time, and energy are not equivalent conditions. A method improving sooner may be preferable under a data limit, another under memory or latency limits. In the lab record validation curves and decide configurations before consulting test examples. Domain and retention tasks answer different questions; declare format and avoid training on their answers.
Lab: NF4 from scratch
These 512 values are the first contiguous elements of tensor model.layers.0.self_attn.q_proj.weight from Qwen2.5-0.5B-Instruct, revision 7ae557604adf67be50417f59c2c2f167def9a775. SHA-256 of the original 1,024 BF16 bytes is 861548f7b00eb685bfa001da4ab30b9140c23bcb188b96c122be05ce0b97058b; reproduced numbers are exact float64 conversion of those BF16 values. They do not represent all model weights.
We construct levels from normal quantiles and compare with the QLoRA appendix E table. Exact zero makes the map asymmetric. Quantile levels and nearest-neighbor assignment do not make cells equiprobable: quantile boundaries would be needed. Each block uses its absolute maximum; zero blocks reconstruct exactly. Here INT4 uses 15 unique symmetric values and one redundant code; FP4 uses its 15 distinct values. Double quantization uses a teaching symmetric integer map, not bitsandbytes’ exact dynamic codes.
Lloyd-Max is fitted on the first 256 values normalized in blocks of 64 and evaluated on the next 256. Separation avoids measuring on the same elements, but weights come from one matrix and do not guarantee generalization to others. The code stores each index in one byte for readability; it does not measure physically packed four-bit memory.
"""Cuantización NF4 didáctica con pesos reales y referencias autocontenidas."""
import json
from statistics import NormalDist
import numpy as np
# El generador sustituye esta cadena por los 512 pesos BF16 reales del JSON.
W = np.asarray(json.loads('[-0.00193023681640625,-0.005218505859375,0.018798828125,0.012451171875,0.003997802734375,-0.0091552734375,0.005828857421875,-0.001708984375,0.0145263671875,-0.005126953125,-0.00848388671875,0.0238037109375,0.01123046875,0.00160980224609375,-0.01336669921875,-0.000728607177734375,-0.00201416015625,0.015380859375,-0.01080322265625,0.01416015625,-0.0147705078125,0.002044677734375,-0.00014972686767578125,-0.00775146484375,-0.000621795654296875,-0.007415771484375,0.0262451171875,-0.004058837890625,0.0146484375,-0.01226806640625,-0.00531005859375,-0.006103515625,0.00457763671875,0.004425048828125,-0.0002346038818359375,-0.0115966796875,0.004150390625,0.002685546875,-0.0086669921875,-0.003021240234375,0.0279541015625,0.055419921875,-0.0235595703125,-0.007720947265625,-0.003326416015625,0.01177978515625,0.0113525390625,0.004150390625,-0.00732421875,-0.01806640625,-0.0198974609375,-0.01153564453125,0.018798828125,-0.004119873046875,-0.00946044921875,-0.00439453125,0.008544921875,0.00640869140625,-0.00640869140625,0.0262451171875,0.002471923828125,-0.004913330078125,0.00421142578125,-0.007568359375,-0.0228271484375,-0.025634765625,0.00160980224609375,0.01385498046875,0.01904296875,0.006439208984375,0.005523681640625,0.01495361328125,0.02001953125,-0.04052734375,0.00946044921875,-0.004669189453125,-0.00457763671875,0.034912109375,-0.0108642578125,-0.006256103515625,0.01092529296875,0.0018768310546875,0.00469970703125,0.00075531005859375,0.00167083740234375,0.0030517578125,-0.00958251953125,-0.010498046875,0.00830078125,0.01239013671875,0.0230712890625,-0.002288818359375,-0.01397705078125,-0.0084228515625,-0.006256103515625,0.000255584716796875,0.01123046875,0.005889892578125,0.039794921875,-0.0014495849609375,-0.017333984375,0.012451171875,-0.0037841796875,-0.006195068359375,-0.0013275146484375,0.013916015625,0.0390625,0.004730224609375,-0.006500244140625,-0.0225830078125,0.007659912109375,0.000331878662109375,-0.0169677734375,0.005096435546875,-0.0038299560546875,-0.01458740234375,-0.03564453125,-0.00154876708984375,-0.0140380859375,0.00982666015625,-0.00982666015625,0.016845703125,-0.004058837890625,0.02392578125,0.033935546875,0.0245361328125,0.01092529296875,-0.00592041015625,-0.0111083984375,-0.01324462890625,0.0174560546875,0.0089111328125,0.0218505859375,0.013671875,-0.0159912109375,0.033447265625,-0.02099609375,-0.02978515625,-0.0277099609375,-0.0185546875,-0.006103515625,0.0025787353515625,0.0166015625,-0.0157470703125,0.006134033203125,0.0260009765625,0.0235595703125,-0.00811767578125,-0.005645751953125,-0.00885009765625,-0.022705078125,0.01300048828125,0.0062255859375,-0.006683349609375,-0.01611328125,-0.01531982421875,-0.0001888275146484375,-0.01416015625,-0.01318359375,0.00640869140625,-0.033447265625,-0.00494384765625,-0.0159912109375,-0.005401611328125,0.019287109375,-4.887580871582031e-06,0.0322265625,0.0062255859375,-0.006591796875,0.005828857421875,0.011474609375,0.0291748046875,0.016845703125,-0.001953125,0.0081787109375,0.01361083984375,-0.00799560546875,0.00135040283203125,0.036865234375,0.019287109375,0.0167236328125,-0.004241943359375,-0.0126953125,0.007049560546875,-0.02001953125,0.00121307373046875,0.004730224609375,-0.011474609375,-0.0069580078125,-0.005950927734375,0.0250244140625,0.03515625,0.0263671875,-0.00714111328125,0.006134033203125,0.005859375,-0.01531982421875,0.026123046875,0.0040283203125,-0.0037994384765625,0.0133056640625,-0.001953125,0.0174560546875,-0.02978515625,-0.010986328125,-0.00179290771484375,-0.0135498046875,-0.003936767578125,0.00653076171875,0.01336669921875,0.031005859375,-0.000682830810546875,0.007110595703125,-0.03515625,0.006103515625,-0.01336669921875,-0.0203857421875,0.01092529296875,-0.0030670166015625,-0.00762939453125,-0.00787353515625,0.0101318359375,-0.017578125,0.01336669921875,-0.031982421875,-0.002716064453125,0.005462646484375,-0.0038299560546875,-0.01251220703125,0.004302978515625,0.01141357421875,0.00994873046875,-0.00537109375,-0.0125732421875,0.021240234375,-0.02734375,-0.002593994140625,0.006378173828125,0.007781982421875,0.0257568359375,0.0028076171875,0.0002613067626953125,0.0208740234375,-0.003936767578125,-0.0022430419921875,-0.002960205078125,-0.01556396484375,0.00096893310546875,-0.005859375,0.00592041015625,0.00110626220703125,0.00921630859375,-0.0145263671875,0.0244140625,0.036376953125,0.0196533203125,0.00439453125,-0.0024261474609375,-0.031982421875,-0.00433349609375,-0.051025390625,0.02001953125,-0.005950927734375,-0.003570556640625,0.01092529296875,0.0361328125,0.00909423828125,0.00714111328125,0.03466796875,-0.040283203125,-0.023681640625,0.00160980224609375,5.054473876953125e-05,0.0022430419921875,0.048583984375,-0.0108642578125,-0.0196533203125,-0.0135498046875,-0.022705078125,-0.00958251953125,-0.0233154296875,0.021240234375,0.013427734375,0.008544921875,-0.023681640625,0.0035552978515625,0.00142669677734375,-0.0033111572265625,0.00372314453125,-0.01239013671875,0.00970458984375,-0.0150146484375,0.00372314453125,-0.00946044921875,0.002777099609375,0.0159912109375,-0.0157470703125,-0.044189453125,-0.0072021484375,-0.00836181640625,-0.006103515625,-0.01055908203125,0.003387451171875,0.040283203125,-0.0235595703125,0.0004730224609375,0.00933837890625,0.0001239776611328125,0.0269775390625,-0.005218505859375,-0.01519775390625,-0.003936767578125,-0.0059814453125,-0.01507568359375,-0.0022735595703125,-0.0164794921875,-0.0017242431640625,-0.01226806640625,-0.005462646484375,0.004638671875,0.0274658203125,0.0030059814453125,0.004974365234375,0.00885009765625,-0.01458740234375,-0.01031494140625,0.0005950927734375,-0.0026397705078125,-0.011962890625,-0.030517578125,0.0189208984375,-0.0023345947265625,0.004180908203125,-0.004150390625,-0.01239013671875,-0.004547119140625,0.010498046875,-0.018798828125,-0.033447265625,-0.0135498046875,0.0164794921875,-0.01507568359375,-0.00848388671875,-0.01190185546875,-0.0240478515625,-0.0050048828125,-0.028564453125,-0.00927734375,-0.0023651123046875,-0.002716064453125,0.0181884765625,0.00885009765625,-0.0186767578125,0.02197265625,0.0281982421875,0.00384521484375,-0.0057373046875,0.004791259765625,0.00543212890625,0.003936767578125,-0.0123291015625,0.01025390625,0.0242919921875,-0.002227783203125,0.0087890625,0.005096435546875,-0.031982421875,0.00274658203125,0.006072998046875,0.01458740234375,0.005828857421875,0.006591796875,0.000850677490234375,0.0211181640625,0.004364013671875,-0.0155029296875,0.0179443359375,0.0023651123046875,0.0074462890625,0.003143310546875,0.00116729736328125,0.0244140625,-0.006744384765625,-0.006805419921875,0.0147705078125,0.01434326171875,-0.006378173828125,-0.0159912109375,0.00130462646484375,-0.001800537109375,-0.0240478515625,-0.01031494140625,0.005615234375,0.029541015625,0.002166748046875,0.01007080078125,-0.032958984375,0.0228271484375,-0.01275634765625,-0.0166015625,-0.00933837890625,0.0162353515625,0.004425048828125,0.019287109375,-0.002838134765625,-0.0179443359375,-0.0172119140625,0.0032501220703125,0.01446533203125,-0.046875,-0.003814697265625,-0.00099945068359375,-0.0038299560546875,-0.01300048828125,-0.00579833984375,-0.007568359375,-0.0164794921875,0.009765625,-0.00139617919921875,0.000293731689453125,-0.0098876953125,0.00567626953125,-0.00933837890625,0.01275634765625,-0.004119873046875,-0.019287109375,-0.004791259765625,-0.00016117095947265625,-0.02392578125,-0.0037689208984375,0.002288818359375,-0.006256103515625,0.02294921875,0.0103759765625,-0.01287841796875,0.0028228759765625,-0.0023651123046875,-0.00616455078125,-0.00124359130859375,-0.0087890625,-0.015869140625,-0.0030517578125,-0.0123291015625,0.01019287109375,-0.0181884765625,0.037109375,-0.00445556640625,-0.01611328125,0.00103759765625,-0.01531982421875,-0.0257568359375,-0.0045166015625,0.02197265625,-0.0069580078125,0.00689697265625,0.01025390625,-0.00567626953125,-0.01953125,-0.01214599609375,0.0093994140625,0.001068115234375,0.010009765625,0.005035400390625,0.01409912109375,0.01141357421875,0.003509521484375,0.005706787109375,0.0145263671875,-0.00439453125,0.03369140625,0.01611328125,0.041748046875,0.03271484375,0.01275634765625,0.01806640625,0.006103515625,0.02490234375,-0.0087890625,0.00213623046875,0.0023345947265625,0.011962890625,0.013427734375,0.006622314453125,-0.01513671875,-0.0242919921875,-0.01129150390625,-0.007415771484375,-0.0089111328125,0.01397705078125,-0.0108642578125,0.002716064453125,0.017822265625,0.007232666015625,-0.0155029296875,0.0244140625,0.03076171875,0.0011444091796875,0.0078125,-0.0135498046875,-0.01239013671875,-0.03857421875,-0.0162353515625,-0.0091552734375,-0.026123046875,-0.0284423828125,-0.00154876708984375,-0.0177001953125,-0.004608154296875,0.0130615234375,0.03564453125,0.0021514892578125,0.0140380859375]'), dtype=np.float64)
CANONICAL = np.array([-1.0, -0.6961928009986877, -0.5250730514526367,
-0.39491748809814453, -0.28444138169288635, -0.18477343022823334,
-0.09105003625154495, 0.0, 0.07958029955625534, 0.16093020141124725,
0.24611230194568634, 0.33791524171829224, 0.44070982933044434,
0.5626170039176941, 0.7229568362236023, 1.0])
def nf4_from_quantiles():
normal = NormalDist(); offset = 0.9677083
pos = [normal.inv_cdf(p) for p in np.linspace(offset, .5, 9)[:-1]]
neg = [-normal.inv_cdf(p) for p in np.linspace(offset, .5, 8)[:-1]]
values = np.array(sorted(neg + [0.] + pos))
return values / values[-1]
def quantize(w, levels, block=64):
w = np.asarray(w, dtype=np.float64)
levels = np.asarray(levels, dtype=np.float64)
if w.ndim != 1 or not np.all(np.isfinite(w)) or not isinstance(block, int) or block < 1:
raise ValueError('Se necesita un vector finito y un tamaño de bloque positivo')
if levels.ndim != 1 or not 2 <= len(levels) <= 256 or not np.all(np.isfinite(levels)) or np.any(np.diff(levels) <= 0):
raise ValueError('Los niveles deben estar ordenados y ser distintos')
codes = np.empty(len(w), dtype=np.uint8); scales = []
for start in range(0, len(w), block):
part = w[start:start + block]; scale = float(np.max(np.abs(part)))
scales.append(scale)
normalized = part / scale if scale else np.zeros_like(part)
codes[start:start + block] = np.argmin(abs(normalized[:, None] - levels[None, :]), axis=1)
return codes, np.array(scales)
def dequantize(codes, scales, levels, block=64):
codes, scales, levels = np.asarray(codes), np.asarray(scales), np.asarray(levels)
if not isinstance(block, int) or block < 1 or scales.ndim != 1 or codes.ndim != 1 or levels.ndim != 1 or not np.all(np.isfinite(scales)) or np.any(scales < 0) or not np.all(np.isfinite(levels)):
raise ValueError('Bloque o escalas inválidos')
if len(scales) != (len(codes) + block - 1) // block: raise ValueError('Número de escalas incompatible')
if not np.issubdtype(codes.dtype, np.integer) or np.any(codes < 0) or np.any(codes >= len(levels)):
raise ValueError('Índices inválidos')
return levels[codes] * np.repeat(scales, block)[:len(codes)]
def double_quantize(scales, group=256):
# Control didáctico: enteros simétricos de 8 bits centrados por grupo.
# bitsandbytes emplea su propio mapa dinámico de 8 bits; no son códigos idénticos.
scales = np.asarray(scales, dtype=np.float64)
if scales.ndim != 1 or not np.all(np.isfinite(scales)) or np.any(scales < 0) or not isinstance(group, int) or group < 1:
raise ValueError('Escalas o tamaño de grupo inválidos')
packed = np.zeros(len(scales), dtype=np.int8); means, factors = [], []
for start in range(0, len(scales), group):
part = scales[start:start + group]; mean = float(part.mean())
span = float(np.max(np.abs(part - mean))); factor = span / 127 if span else 0.
packed[start:start + group] = np.rint((part - mean) / factor).clip(-127, 127).astype(np.int8) if factor else 0
means.append(mean); factors.append(factor)
return packed, np.asarray(means), np.asarray(factors)
def double_dequantize(packed, means, factors, group=256):
packed, means, factors = np.asarray(packed), np.asarray(means), np.asarray(factors)
if not isinstance(group, int) or group < 1 or packed.ndim != 1 or means.ndim != 1 or factors.ndim != 1:
raise ValueError('Estado de doble cuantización inválido')
if len(means) != (len(packed) + group - 1) // group or len(factors) != len(means) or not np.all(np.isfinite(means)) or not np.all(np.isfinite(factors)) or np.any(factors < 0):
raise ValueError('Escalas de segundo nivel inválidas')
restored = np.repeat(means, group)[:len(packed)] + packed * np.repeat(factors, group)[:len(packed)]
return np.maximum(restored, 0.)
def lloyd_max(train, n=16, iterations=30):
# Ajuste escalar por centroides en los valores de calibración normalizados.
centers = np.linspace(-1, 1, n)
for _ in range(iterations):
labels = np.argmin(abs(train[:, None] - centers), axis=1)
updated = np.array([train[labels == i].mean() if np.any(labels == i) else c for i, c in enumerate(centers)])
updated.sort()
if np.allclose(updated, centers, atol=1e-12, rtol=0): break
centers = updated
return centers
def mse(x, y): return float(np.mean((x - y) ** 2))
DERIVED = nf4_from_quantiles()
NF4 = CANONICAL.copy()
INT4 = np.linspace(-1, 1, 15) # entero simétrico con cero, un código redundante
FP4 = np.array([-1., -2/3, -1/2, -1/3, -1/4, -1/6, -1/192, 0.,
1/192, 1/6, 1/4, 1/3, 1/2, 2/3, 1.])
assert len(W) == 512 and np.allclose(DERIVED, CANONICAL, atol=2e-7, rtol=0)
assert np.count_nonzero(NF4 == 0) == 1
zero_code, zero_scale = quantize(np.zeros(65), NF4, 64)
assert np.array_equal(dequantize(zero_code, zero_scale, NF4, 64), np.zeros(65))
assert np.array_equal(quantize(np.array([-.4, .2]), NF4)[0], np.argmin(abs(np.array([-.4, .2])[:, None] / .4 - NF4), axis=1))
for bad in (np.nan, np.inf):
try: quantize(np.array([bad]), NF4)
except ValueError: pass
else: raise AssertionError('Se aceptó un peso no finito')
for bad_block in (0, -1):
try: quantize(np.array([0.]), NF4, bad_block)
except ValueError: pass
else: raise AssertionError('Se aceptó un bloque inválido')
train = W[:256]; test = W[256:]
train_scales = np.repeat([np.max(abs(train[i:i+64])) for i in range(0, len(train), 64)], 64)
calibration = train / train_scales
centers = lloyd_max(calibration)
results = {}
for name, levels in [('NF4', NF4), ('INT4 simétrico', INT4), ('FP4', FP4), ('Lloyd-Max calibrado', centers)]:
q, s = quantize(test, levels, 64)
results[name] = mse(test, dequantize(q, s, levels, 64))
q, scales = quantize(test, NF4, 64)
packed, means, factors = double_quantize(scales)
recovered = double_dequantize(packed, means, factors)
assert np.max(abs(recovered - scales)) <= (factors.max() / 2 + 1e-15)
double_error = mse(test, dequantize(q, recovered, NF4, 64))
print('NF4 desde cuantiles, error máximo frente a tabla publicada:', float(np.max(abs(DERIVED - CANONICAL))))
print('MSE en 256 pesos reservados:', results)
print('MSE NF4 con doble cuantización didáctica:', double_error)
print('Escalas originales:', scales, 'reconstruidas:', recovered)
print('Los índices usan uint8 en este ejemplo: el empaquetado real en 4 bits no está implementado.')Lab: QLoRA on GPU
We use Glaive Code Assistant, synthetic programming questions and solutions under Apache-2.0, at fixed revision 398ce053096475671e8d3872b8e5b28b59f8fcec. Questions are held out by normalized-text hash and exact duplicates removed among selected rows: this split does not detect paraphrases or prove absence of pretraining contamination. The same selection passes every included model tokenizer and answers are not truncated. The mask supervises only response and closing token in each model’s template.
Full mode compares QLoRA on Qwen2.5-3B-Instruct with bfloat16 LoRA on 0.5B and 1.5B. These are different sizes and initial weights, so the comparison does not isolate quantization. For an initial test set ORYON_QUICK=1: it uses only 0.5B, two updates, and a tiny holdout; it does not represent large-tuning quality. Each branch starts from its corresponding checkpoint, uses the same example order, and saves its own report.
QLoRA linear layers use NF4, double quantization, and bfloat16 compute, with prepare_model_for_kbit_training, gradient checkpointing, and PagedAdamW32bit; bfloat16 LoRA uses conventional AdamW. CUDA allocated and reserved peaks are from PyTorch’s allocator and may not include all external allocations; device-free memory is a snapshot, not its peak. Assistant-token NLL and two greedy held-out responses are partial signals: they neither execute nor verify generated code and are not a general benchmark. You can inspect held-out examples separately and later apply safe functional evaluation.
Install torch, transformers, accelerate, datasets, peft, and an bitsandbytes version compatible with your system and CUDA according to the official documentation. The experiment requires CUDA with bfloat16. The report records versions, each model’s resolved revision, question and answer hashes, tokens, and memory; dataset and models download if uncached. Each branch saves its adapter and tokenizer unless ORYON_QLORA_SKIP_SAVE=1 is set. ORYON_QLORA_DIR changes the results folder and ORYON_QLORA_CASE runs one branch. For offline use, supply ORYON_QLORA_JSONL with fields question and answer, point ORYON_OFFLINE=1 and ORYON_QLORA_MODEL_REVISION to the exact snapshot, and run one model per process. The local source is identified by SHA-256.
"""SFT técnico comparando QLoRA NF4 y LoRA bfloat16 con datos reservados."""
import gc
import hashlib
import json
import os
import random
from importlib.metadata import version
from pathlib import Path
from collections.abc import Mapping
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import HfApi
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
QUICK = os.getenv('ORYON_QUICK') == '1'
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
OUT = Path(os.getenv('ORYON_QLORA_DIR', './oryon-qlora'))
LOCAL_DATA = os.getenv('ORYON_QLORA_JSONL', '')
DATASET = 'glaiveai/glaive-code-assistant'
DATA_REV = '398ce053096475671e8d3872b8e5b28b59f8fcec'
SEED = 1717
MAX_CONTEXT = 512
TRAIN_COUNT, VAL_COUNT = (8, 4) if QUICK else (512, 64)
STEPS = 2 if QUICK else 200
ACCUM = 2 if QUICK else 4
LR = 2e-4
torch.set_num_threads(1)
def sha(text): return hashlib.sha256(text.encode('utf-8')).hexdigest()
def file_hash(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 source():
if LOCAL_DATA:
path = Path(LOCAL_DATA)
def read():
with path.open(encoding='utf-8') as f:
for line in f:
if line.strip(): yield json.loads(line)
return read(), {'kind': 'JSONL local', 'sha256': file_hash(path)}
if OFFLINE:
raise ValueError('En modo offline proporciona ORYON_QLORA_JSONL con preguntas y respuestas.')
data = load_dataset(DATASET, split='train', revision=DATA_REV, streaming=True)
return iter(data), {'kind': 'Hugging Face streaming', 'id': DATASET, 'revision': DATA_REV,
'license': 'Apache-2.0', 'source': 'preguntas y soluciones sintéticas de Glaive'}
def examples(tokenizers):
iterable, metadata = source()
train, val, seen, rejected = [], [], set(), 0
for row in iterable:
q, a = row.get('question'), row.get('answer')
if not isinstance(q, str) or not isinstance(a, str) or not q.strip() or not a.strip(): continue
q, a = q.strip(), a.strip()
# La selección por caracteres limita memoria antes de tokenizar.
if len(q) > 600 or len(a) > 1000: continue
key = sha(' '.join(q.split()).casefold())
if key in seen: continue
seen.add(key)
record = {'question': q, 'answer': a, 'question_sha256': key,
'answer_sha256': sha(a)}
try:
for tok in tokenizers: encode(tok, record)
except ValueError:
rejected += 1
continue
if int(key[:8], 16) % 10 == 0:
if len(val) < VAL_COUNT: val.append(record)
elif len(train) < TRAIN_COUNT: train.append(record)
if len(train) == TRAIN_COUNT and len(val) == VAL_COUNT: break
if len(train) != TRAIN_COUNT or len(val) != VAL_COUNT:
raise ValueError('No se obtuvieron suficientes filas únicas para ambas reservas')
metadata['rejected_by_tokenizer'] = rejected
return train, val, metadata
def encode(tokenizer, row):
for content in (row['question'], row['answer']):
if any(t and t in content for t in tokenizer.all_special_tokens):
raise ValueError('Contenido con grafía de token especial')
messages = [{'role': 'user', 'content': row['question']}]
prefix = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True)
full = tokenizer.apply_chat_template(messages + [{'role': 'assistant', 'content': row['answer']}],
tokenize=True, add_generation_prompt=False)
# Transformers puede devolver una lista o un BatchEncoding con input_ids.
if isinstance(prefix, Mapping): prefix = prefix['input_ids']
if isinstance(full, Mapping): full = full['input_ids']
if full[:len(prefix)] != prefix or len(full) <= len(prefix):
raise ValueError('La frontera de la plantilla no coincide')
if len(full) > MAX_CONTEXT:
raise ValueError('Ejemplo fuera del contexto; no se trunca el objetivo')
return {'ids': full, 'prefix': prefix, 'labels': [-100] * len(prefix) + full[len(prefix):],
'question_sha256': row['question_sha256'], 'answer_sha256': row['answer_sha256']}
def memory():
torch.cuda.synchronize()
free_bytes, total_bytes = torch.cuda.mem_get_info()
return {'allocated_bytes': torch.cuda.memory_allocated(), 'reserved_bytes': torch.cuda.memory_reserved(),
'peak_allocated_bytes': torch.cuda.max_memory_allocated(),
'peak_reserved_bytes': torch.cuda.max_memory_reserved(),
'device_free_bytes_snapshot': free_bytes, 'device_total_bytes': total_bytes}
def loss_for(model, row):
ids = torch.tensor([row['ids']], dtype=torch.long, device='cuda')
labels = torch.tensor([row['labels']], dtype=torch.long, device='cuda')
targets = int((labels[:, 1:] != -100).sum().item())
return model(input_ids=ids, labels=labels, use_cache=False).loss, targets
def evaluate(model, rows):
model.eval()
total, n = 0., 0
with torch.no_grad():
for row in rows:
loss, count = loss_for(model, row)
total += float(loss.item()) * count; n += count
if not n: raise ValueError('No hay tokens supervisados en validación')
return {'nats_sum': total, 'assistant_tokens': n, 'nats_per_token': total / n,
'examples': len(rows)}
def sample(model, tokenizer, rows):
model.eval()
results = []
with torch.no_grad():
for row in rows[:2]:
ids = torch.tensor([row['prefix']], dtype=torch.long, device='cuda')
generated = model.generate(input_ids=ids, max_new_tokens=64, do_sample=False,
pad_token_id=tokenizer.eos_token_id)[0, ids.shape[1]:].tolist()
results.append({'question_sha256': row['question_sha256'],
'text': tokenizer.decode(generated, skip_special_tokens=True),
'token_ids': generated})
return results
def run_case(name, model_id, revision, tokenizer, quantized, train, val, data_meta):
random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED); torch.cuda.manual_seed_all(SEED)
# Se exige el mismo conjunto de filas: no se descarta silenciosamente ninguna por modelo.
train_rows = [encode(tokenizer, row) for row in train]
val_rows = [encode(tokenizer, row) for row in val]
torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
kwargs = {'revision': revision, 'local_files_only': OFFLINE, 'dtype': torch.bfloat16,
'device_map': {'': 0}, 'attn_implementation': 'sdpa'}
if quantized:
kwargs['quantization_config'] = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type='nf4',
bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16)
model = AutoModelForCausalLM.from_pretrained(model_id, **kwargs)
load_memory = memory()
quantization_observed = None
if quantized:
import bitsandbytes as bnb
layers = [m for m in model.modules() if isinstance(m, bnb.nn.Linear4bit)]
states = [getattr(m.weight, 'quant_state', None) for m in layers]
if not layers or any(s is None or s.quant_type != 'nf4' or not s.nested for s in states):
raise RuntimeError('No se verificó NF4 con doble cuantización en todas las capas Linear4bit')
quantization_observed = {'linear4bit_layers': len(layers), 'quant_type': 'nf4',
'nested': True, 'blocks': sorted(set(s.blocksize for s in states))}
model.config.use_cache = False
if quantized:
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True,
gradient_checkpointing_kwargs={'use_reentrant': False})
else:
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant': False})
config = LoraConfig(r=16, lora_alpha=32, lora_dropout=.05, bias='none', task_type='CAUSAL_LM',
target_modules=['q_proj', 'k_proj', 'v_proj', 'o_proj', 'gate_proj', 'up_proj', 'down_proj'])
model = get_peft_model(model, config)
trainable = [(name, p) for name, p in model.named_parameters() if p.requires_grad]
if not trainable or any('lora_' not in name for name, _ in trainable):
raise RuntimeError('Hay parámetros entrenables ajenos a los adaptadores')
torch.cuda.reset_peak_memory_stats()
before = evaluate(model, val_rows)
before['samples'] = sample(model, tokenizer, val_rows)
eval_before_memory = memory()
if quantized:
import bitsandbytes as bnb
optimizer = bnb.optim.PagedAdamW32bit([p for _, p in trainable], lr=LR)
optimizer_name = 'bitsandbytes PagedAdamW32bit'
else:
optimizer = torch.optim.AdamW([p for _, p in trainable], lr=LR)
optimizer_name = 'torch AdamW'
torch.cuda.reset_peak_memory_stats()
model.train(); history = []
order = list(range(len(train_rows))); random.Random(SEED).shuffle(order)
for step in range(STEPS):
optimizer.zero_grad(set_to_none=True); count = 0; seen = 0; nll = 0.
for j in range(ACCUM):
row = train_rows[order[(step * ACCUM + j) % len(order)]]
loss, n = loss_for(model, row)
(loss * n).backward(); count += n; seen += len(row['ids']); nll += float(loss.item()) * n
for _, p in trainable:
if p.grad is not None: p.grad.div_(count)
torch.nn.utils.clip_grad_norm_([p for _, p in trainable], 1.)
optimizer.step()
history.append({'step': step + 1, 'processed_tokens': seen, 'assistant_tokens': count,
'nats_per_token': nll / count})
train_memory = memory()
torch.cuda.reset_peak_memory_stats()
after = evaluate(model, val_rows)
after['samples'] = sample(model, tokenizer, val_rows)
eval_after_memory = memory()
adapter_path = OUT / name / 'adapter'
save_adapter = os.getenv('ORYON_QLORA_SKIP_SAVE') != '1'
if save_adapter:
model.save_pretrained(adapter_path, safe_serialization=True)
tokenizer.save_pretrained(adapter_path)
report = {'case': name, 'model': model_id, 'revision': revision, 'quick': QUICK, 'seed': SEED,
'device_name': torch.cuda.get_device_name(0),
'versions': {x: version(x) for x in ('torch', 'transformers', 'peft', 'bitsandbytes', 'datasets')},
'data': data_meta, 'train_question_sha256': [x['question_sha256'] for x in train_rows],
'val_question_sha256': [x['question_sha256'] for x in val_rows],
'train_answer_sha256': [x['answer_sha256'] for x in train_rows],
'val_answer_sha256': [x['answer_sha256'] for x in val_rows],
'preview_questions': [row['question'] for row in val[:2]],
'adapter_saved': save_adapter, 'adapter_path': str(adapter_path) if save_adapter else None,
'config': {'max_context': MAX_CONTEXT, 'steps': STEPS, 'microbatches_per_step': ACCUM,
'learning_rate': LR, 'rank': 16, 'alpha': 32, 'dropout': .05,
'gradient_checkpointing': True, 'optimizer': optimizer_name,
'base': 'Lineales NF4 con doble cuantización' if quantized else 'bfloat16',
'compute_dtype': 'bfloat16'},
'quantization_observed': quantization_observed,
'trainable_parameters': sum(p.numel() for _, p in trainable),
'memory_cuda': {'load': load_memory, 'before_eval': eval_before_memory,
'train': train_memory, 'after_eval': eval_after_memory},
'before': before, 'after': after, 'training': history,
'limitations': 'NLL de respuestas retenidas no verifica ejecución ni corrección del código; un ensayo pequeño no establece calidad general ni causa por precisión. Los picos de PyTorch excluyen asignaciones externas y el volcado del dispositivo es instantáneo, no un pico.'}
path = OUT / f'{name}-report.json'
path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
print(name, 'NLL antes/después:', before, after, 'pico entrenamiento:', train_memory, flush=True)
del optimizer, model; gc.collect(); torch.cuda.empty_cache()
return report
def main():
if not torch.cuda.is_available() or not torch.cuda.is_bf16_supported():
raise RuntimeError('Este laboratorio requiere GPU CUDA con bfloat16')
try: import bitsandbytes
except ImportError as exc: raise RuntimeError('Instala bitsandbytes compatible con tu versión de CUDA') from exc
OUT.mkdir(parents=True, exist_ok=True)
if QUICK:
cases = [('qlora-0.5b', 'Qwen/Qwen2.5-0.5B-Instruct', True),
('lora-bf16-0.5b', 'Qwen/Qwen2.5-0.5B-Instruct', False)]
else:
cases = [('qlora-3b', 'Qwen/Qwen2.5-3B-Instruct', True),
('lora-bf16-0.5b', 'Qwen/Qwen2.5-0.5B-Instruct', False),
('lora-bf16-1.5b', 'Qwen/Qwen2.5-1.5B-Instruct', False)]
requested = os.getenv('ORYON_QLORA_CASE', '')
if requested:
cases = [case for case in cases if case[0] == requested]
if not cases: raise ValueError('ORYON_QLORA_CASE no corresponde al modo seleccionado')
ids = list(dict.fromkeys(case[1] for case in cases))
fixed_revision = os.getenv('ORYON_QLORA_MODEL_REVISION', '')
if fixed_revision and len(ids) != 1:
raise ValueError('ORYON_QLORA_MODEL_REVISION solo admite un modelo por ejecución')
if OFFLINE and not fixed_revision:
raise ValueError('En modo offline fija ORYON_QLORA_MODEL_REVISION al snapshot exacto y elige un caso')
revisions = {model_id: fixed_revision or HfApi().model_info(model_id, revision='main').sha for model_id in ids}
tokenizers = {model_id: AutoTokenizer.from_pretrained(model_id, revision=revisions[model_id],
local_files_only=OFFLINE) for model_id in ids}
train, val, meta = examples(list(tokenizers.values()))
for name, model_id, quantized in cases:
run_case(name, model_id, revisions[model_id], tokenizers[model_id], quantized, train, val, meta)
if __name__ == '__main__': main()npm run lab and open the connection link.Lab: sweep and forgetting
Rank, rate, and forgetting sweep
The cell tunes Qwen2.5-0.5B base on GSM8K and compares LoRA with α/r scaling, rsLoRA with α/√r, and full fine-tuning. It requires PyTorch, Transformers, and Datasets compatible with your GPU. Adapters modify q, k, v, o, and three MLP projections. Full tuning uses bfloat16 on CUDA and AdamW with states in parameter precision; do not assume an fp32 master copy. Gradient checkpointing, microbatch 1, and accumulation of two examples are used.
GSM8K training is split into two blocks before filtering: one for training and one for validation. Identical questions across training, validation, and official test are rejected. WikiText and ARC-Easy have independent validation and test splits with exact-match exclusion. Hashes and revisions or Dataset Viewer responses are recorded. These checks do not detect paraphrases or prior model contamination.
The sweep uses r=4, 16, and 64, fixed α=16, and several rates. Each run records validation answer-token loss, WikiText bits per byte, and ARC-Easy cloze with summed log probabilities, as in lesson 8. Test sets are read beforehand to exclude exact matches, but their results do not select hyperparameters. LoRA, rsLoRA, and full-tuning choices are frozen by validation NLL before test. Each winner is retrained with the same seed and data; testing stops if it does not reproduce validation loss within tolerance. Test adds greedy zero-shot GSM8K with last-number extraction, not lesson 8’s two-example protocol.
Equal steps and examples do not imply equal compute cost. Progress is saved after each configuration for resumption under an identical protocol; a model, data, or configuration change requires another ORYON_HPARAM_DIR folder. ORYON_QUICK=1 uses Qwen2.5-0.5B-Instruct, only four examples per split, two rates, and two updates. ORYON_HPARAM_SAMPLES can supply small Dataset Viewer responses in short mode; otherwise pinned revisions are queried. One seed and first rows do not establish that the rate optimum shifts or one method generally forgets less.
"""Barrido reproducible de LoRA, rsLoRA y ajuste completo con evaluación separada.
Requiere torch, transformers, datasets y huggingface_hub. ORYON_QUICK=1 reduce
datos y actualizaciones. ORYON_HPARAM_SAMPLES admite respuestas JSON del Dataset
Viewer para la prueba corta; sin esa variable se usan revisiones fijadas.
"""
import gc, hashlib, json, math, os, random, re, sys
from decimal import Decimal
from pathlib import Path
from urllib.parse import urlencode
import torch
from torch import nn
from torch.nn import functional as F
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
QUICK = os.getenv('ORYON_QUICK') == '1'
OFFLINE = os.getenv('ORYON_OFFLINE') == '1'
SAMPLES = os.getenv('ORYON_HPARAM_SAMPLES', '')
OUT = Path(os.getenv('ORYON_HPARAM_DIR', './oryon-lora-hparams'))
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
MODEL = 'Qwen/Qwen2.5-0.5B-Instruct' if QUICK else 'Qwen/Qwen2.5-0.5B'
REV = '7ae557604adf67be50417f59c2c2f167def9a775' if QUICK else '060db6499f32faf8b98477b0a26969ef7d8b9987'
SOURCES = {
'gsm-train': ('openai/gsm8k','main','train','740312add88f781978c0658806c59bc2815b9866'),
'gsm-test': ('openai/gsm8k','main','test','740312add88f781978c0658806c59bc2815b9866'),
'wiki-validation': ('Salesforce/wikitext','wikitext-2-raw-v1','validation','b08601e04326c79dfdd32d625aee71d232d685c3'),
'wiki-test': ('Salesforce/wikitext','wikitext-2-raw-v1','test','b08601e04326c79dfdd32d625aee71d232d685c3'),
'arc-validation': ('allenai/ai2_arc','ARC-Easy','validation','210d026faf9955653af8916fad021475a3f00453'),
'arc-test': ('allenai/ai2_arc','ARC-Easy','test','210d026faf9955653af8916fad021475a3f00453'),
}
SEED = 1717
CONTEXT = 512
RANKS = [4, 16, 64]
LRS = [5e-5, 2e-4] if QUICK else [5e-5, 2e-4, 8e-4]
FULL_LRS = [1e-5, 5e-5] if QUICK else [1e-5, 5e-5, 2e-4]
ALPHA = 16
MAX_UPDATES = 2 if QUICK else int(os.getenv('ORYON_HPARAM_UPDATES', '100'))
if MAX_UPDATES < 1: raise ValueError('El número de actualizaciones debe ser positivo')
torch.set_num_threads(1)
def digest_bytes(raw): return hashlib.sha256(raw).hexdigest()
def digest(value): return digest_bytes(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8'))
def file_hash(path):
h=hashlib.sha256()
with open(path,'rb') as f:
for block in iter(lambda:f.read(1024*1024),b''): h.update(block)
return h.hexdigest()
def rows(name, limit):
dataset, config, split, revision = SOURCES[name]
if SAMPLES:
if not QUICK: raise ValueError('Las muestras del visor solo se admiten en modo corto')
path=Path(SAMPLES)/(name+'.json'); raw=path.read_bytes(); obj=json.loads(raw)
items=[x['row'] for x in obj['rows'][:limit]]
metadata={'kind':'Dataset Viewer','dataset':dataset,'config':config,'split':split,
'sha256':digest_bytes(raw),'selection':'primeras filas','rows_used':len(items),
'url':'https://datasets-server.huggingface.co/rows?'+urlencode({'dataset':dataset,'config':config,'split':split,'offset':0,'length':len(obj['rows'])})}
else:
if OFFLINE: raise ValueError('Sin red, usa ORYON_HPARAM_SAMPLES en modo corto')
items=[]
for row in load_dataset(dataset,config,split=split,revision=revision,streaming=True):
items.append(row)
if len(items)>=limit: break
metadata={'kind':'Hugging Face streaming','dataset':dataset,'config':config,'split':split,
'revision':revision,'selection':'primeras filas','rows_sha256':digest(items)}
if not items: raise ValueError('Sin datos para '+name)
return items,metadata
def plain(tok,text):
special={i for i,t in tok.added_tokens_decoder.items() if t.special}
markers=[t.content for t in tok.added_tokens_decoder.values() if t.special and t.content]
if any(x in text for x in markers): raise ValueError('El texto contiene una grafía de control')
ids=tok.encode(text,add_special_tokens=False)
if any(i in special for i in ids): raise ValueError('El texto produjo un control')
if tok.decode(ids,skip_special_tokens=False,clean_up_tokenization_spaces=False)!=text: raise ValueError('Sin ida y vuelta exacta')
return ids
def encode_gsm(tok,row):
prefix_text='Question: '+row['question']+'\nAnswer:'
prefix=plain(tok,prefix_text)
whole=plain(tok,prefix_text+' '+row['answer'])
if whole[:len(prefix)]!=prefix: raise ValueError('Frontera ambigua entre pregunta y respuesta')
target=whole[len(prefix):]+[tok.eos_token_id]
ids=prefix+target
if len(ids)>CONTEXT or not prefix: raise ValueError('Ejemplo fuera de contexto')
return {'ids':ids,'labels':[-100]*len(prefix)+target,'question':row['question'],'answer':row['answer']}
def prepare(tok):
ntrain=4 if QUICK else int(os.getenv('ORYON_HPARAM_TRAIN','2048'))
nval=4 if QUICK else int(os.getenv('ORYON_HPARAM_VAL','128'))
ntest=4 if QUICK else int(os.getenv('ORYON_HPARAM_TEST','128'))
if min(ntrain,nval,ntest)<1: raise ValueError('Tamaños de muestra inválidos')
# La separación se fija antes de filtrar; ningún elemento de validación entra en train.
train_boundary=16 if QUICK else max(2*ntrain, ntrain+256)
val_boundary=8 if QUICK else max(4*nval, nval+64)
raw_train,mt=rows('gsm-train',train_boundary+val_boundary)
def convert(items,want):
out=[]
for row in items:
try: out.append(encode_gsm(tok,row))
except ValueError: continue
if len(out)==want: break
if len(out)<want: raise ValueError('No hay suficientes ejemplos válidos en la partición fijada')
return out
train=convert(raw_train[:train_boundary],ntrain)
val=convert(raw_train[train_boundary:train_boundary+val_boundary],nval)
raw_test,mtest=rows('gsm-test',max(ntest*4,ntest))
test=convert(raw_test,ntest)
def keys(group): return [digest(' '.join(x['question'].split()).casefold()) for x in group]
fingerprints=[keys(train),keys(val),keys(test)]
if any(len(x)!=len(set(x)) for x in fingerprints) or any(set(fingerprints[i])&set(fingerprints[j]) for i in range(3) for j in range(i)):
raise ValueError('Hay instrucciones idénticas entre o dentro de particiones')
others={}; metadata={'gsm-train':mt,'gsm-test':mtest}
for name in ('wiki-validation','wiki-test','arc-validation','arc-test'):
others[name],metadata[name]=rows(name,80 if QUICK and name.startswith('wiki') else 4 if QUICK else 800 if name.startswith('wiki') else 128)
def norm(text):return ' '.join(text.split()).casefold()
wiki_val={norm(x['text']) for x in others['wiki-validation'] if x.get('text','').strip()}
original=len(others['wiki-test'])
others['wiki-test']=[x for x in others['wiki-test'] if not x.get('text','').strip() or norm(x['text']) not in wiki_val]
metadata['wiki-test']['excluded_exact_overlap_rows']=original-len(others['wiki-test'])
arc_val={norm(x['question']) for x in others['arc-validation']}
original=len(others['arc-test'])
others['arc-test']=[x for x in others['arc-test'] if norm(x['question']) not in arc_val]
metadata['arc-test']['excluded_exact_overlap_rows']=original-len(others['arc-test'])
return {'train':train,'val':val,'test':test,'others':others,'metadata':metadata,'fingerprints':fingerprints}
def example_loss(model,row):
ids=torch.tensor([row['ids']],dtype=torch.long,device=DEVICE)
labels=torch.tensor(row['labels'][1:],dtype=torch.long,device=DEVICE)
logits=model(input_ids=ids,use_cache=False).logits[0,:-1].float()
count=int((labels!=-100).sum())
if not count: raise ValueError('Sin tokens de respuesta')
return F.cross_entropy(logits,labels,ignore_index=-100,reduction='sum'),count
@torch.inference_mode()
def domain_nll(model,rows):
model.eval(); total=0.; count=0
for row in rows:
loss,n=example_loss(model,row);total+=float(loss);count+=n
result=total/count
if not math.isfinite(result):raise ValueError('Pérdida no finita')
return {'nats_per_token':result,'assistant_tokens':count,'examples':len(rows)}
@torch.inference_mode()
def wiki_bpb(model,tok,rows):
text='\n'.join(x['text'] for x in rows if x.get('text','').strip())[:2048 if QUICK else 24000]
if not text: raise ValueError('WikiText vacío')
tokens=plain(tok,text); ids=[tok.eos_token_id]+tokens; total=0.; count=0
for first in range(1,len(ids),CONTEXT//2):
end=min(first+CONTEXT//2,len(ids)); start=max(0,end-CONTEXT)
x=torch.tensor([ids[start:end]],device=DEVICE); logits=model(input_ids=x,use_cache=False).logits[0].float()
positions=torch.arange(first-start-1,end-start-1,device=DEVICE); target=torch.tensor(ids[first:end],device=DEVICE)
total+=float(F.cross_entropy(logits[positions],target,reduction='sum'));count+=len(target)
if count!=len(tokens): raise AssertionError('Cada token de WikiText debe puntuarse una vez')
return {'nats':total,'tokens':count,'utf8_bytes':len(text.encode('utf-8')),'bits_per_byte':total/(math.log(2)*len(text.encode('utf-8'))),'text_sha256':digest_bytes(text.encode('utf-8'))}
def encode_pair(tok,context,choice):
spaces=len(context)-len(context.rstrip())
if spaces: choice=context[-spaces:]+choice;context=context[:-spaces]
prefix=plain(tok,context); whole=plain(tok,context+choice)
if whole[:len(prefix)]!=prefix: raise ValueError('Frontera de tokenización ambigua')
target=whole[len(prefix):]
if not target: raise ValueError('Opción vacía')
return prefix or [tok.eos_token_id],target
@torch.inference_mode()
def arc_accuracy(model,tok,rows):
correct=0; scored=0; rejected=0
for row in rows:
labels=row['choices']['label']; options=row['choices']['text']; context='Question: '+row['question']+'\nAnswer:'
try:
pairs=[encode_pair(tok,context,' '+choice) for choice in options]
if any(p!=pairs[0][0] for p,_ in pairs):raise ValueError('Prefijos distintos')
max_target=max(len(t) for _,t in pairs)
if max_target>=CONTEXT:raise ValueError('Opción demasiado larga')
scores=[]
for prefix,target in pairs:
prefix=prefix[-(CONTEXT-max_target):]; seq=prefix+target[:-1]
logits=model(input_ids=torch.tensor([seq],device=DEVICE),use_cache=False).logits[0].float()
positions=torch.arange(len(prefix)-1,len(prefix)-1+len(target),device=DEVICE)
indices=torch.tensor(target,device=DEVICE)
scores.append(float(F.log_softmax(logits[positions],dim=-1)[torch.arange(len(target),device=DEVICE),indices].sum()))
correct+=int(max(range(len(scores)),key=scores.__getitem__)==labels.index(row['answerKey']));scored+=1
except (ValueError,KeyError,IndexError):rejected+=1
if not scored:raise ValueError('ARC no contiene ejemplos puntuables')
return {'correct':correct,'total':scored,'accuracy':correct/scored,'rejected':rejected,'protocol':'ARC-Easy cloze, suma log p, cero ejemplos, como l08'}
def extract_number(text):
matches=re.findall(r'[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?',text)
return str(Decimal(matches[-1].replace(',','')).normalize()) if matches else None
@torch.inference_mode()
def gsm_accuracy(model,tok,rows):
model.eval(); outcomes=[]; limit=64 if QUICK else 256
for row in rows:
prefix=plain(tok,'Question: '+row['question']+'\nAnswer:')
if len(prefix)+limit>model.config.max_position_embeddings:raise ValueError('Generación excede el contexto')
generated=model.generate(input_ids=torch.tensor([prefix],device=DEVICE),do_sample=False,max_new_tokens=limit,
eos_token_id=tok.eos_token_id,pad_token_id=tok.eos_token_id,use_cache=True)[0,len(prefix):].tolist()
text=tok.decode(generated,skip_special_tokens=True)
pred=extract_number(text); expected=extract_number(row['answer'].split('####')[-1])
if expected is None:raise ValueError('GSM8K sin respuesta numérica explícita')
outcomes.append({'prediction':pred,'expected':expected,'correct':pred==expected,'tokens':len(generated),
'stopped':bool(generated and generated[-1]==tok.eos_token_id)})
return {'correct':sum(x['correct'] for x in outcomes),'total':len(outcomes),
'accuracy':sum(x['correct'] for x in outcomes)/len(outcomes),'items':outcomes,
'protocol':'GSM8K zero-shot greedy; último número explícito, sin ejecutar código; no es el protocolo de dos ejemplos de l08'}
class LoRALinear(nn.Module):
def __init__(self,base,rank,mode):
super().__init__();self.base=base;self.rank=rank
self.a=nn.Parameter(torch.empty(rank,base.in_features,device=base.weight.device,dtype=torch.float32))
self.b=nn.Parameter(torch.zeros(base.out_features,rank,device=base.weight.device,dtype=torch.float32))
nn.init.kaiming_uniform_(self.a,a=math.sqrt(5))
self.scale=ALPHA/(rank if mode=='lora' else math.sqrt(rank))
def forward(self,x):
return self.base(x)+(F.linear(F.linear(x.float(),self.a),self.b)*self.scale).to(x.dtype)
def inject(model,rank,mode):
for p in model.parameters():p.requires_grad_(False)
count=0
for layer in model.model.layers:
for owner,names in ((layer.self_attn,('q_proj','k_proj','v_proj','o_proj')),(layer.mlp,('up_proj','down_proj','gate_proj'))):
for name in names:
old=getattr(owner,name)
if not isinstance(old,nn.Linear):raise ValueError('Proyección no lineal')
wrapped=LoRALinear(old,rank,mode);setattr(owner,name,wrapped);count+=wrapped.a.numel()+wrapped.b.numel()
return count
def load_model():
if DEVICE.type=='cuda' and not torch.cuda.is_bf16_supported():raise RuntimeError('Este barrido requiere bfloat16 en CUDA')
dtype=torch.bfloat16 if DEVICE.type=='cuda' else torch.float32
model=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE,dtype=dtype,attn_implementation='sdpa').to(DEVICE)
model.config.use_cache=False
return model
def train(config,data):
torch.manual_seed(SEED)
if DEVICE.type=='cuda':torch.cuda.manual_seed_all(SEED)
model=load_model()
if config['mode']=='full':
for p in model.parameters():p.requires_grad_(True)
trainable=sum(p.numel() for p in model.parameters())
else:trainable=inject(model,config['rank'],config['mode'])
if DEVICE.type=='cuda':
if config['mode']!='full':model.enable_input_require_grads()
model.gradient_checkpointing_enable()
params=[p for p in model.parameters() if p.requires_grad]
opt=torch.optim.AdamW(params,lr=config['lr'],weight_decay=0.)
order=list(range(len(data['train'])));random.Random(SEED).shuffle(order)
tokens=0;processed=0;model.train()
for step in range(MAX_UPDATES):
opt.zero_grad(set_to_none=True); count=0
for j in range(2):
row=data['train'][order[(step*2+j)%len(order)]]
loss,n=example_loss(model,row);loss.backward();count+=n;processed+=len(row['ids'])
for p in params:
if p.grad is not None:p.grad.div_(count)
nn.utils.clip_grad_norm_(params,1.);opt.step();tokens+=count
model.eval();del opt,params
return model,{'updates':MAX_UPDATES,'processed_tokens':processed,'supervised_tokens':tokens,
'trainable_parameters':trainable,'unique_examples_used':len(set(order[(step*2+j)%len(order)] for step in range(MAX_UPDATES) for j in range(2))),
'available_examples':len(order),'order':order}
def evaluate(model,tok,data,split):
key='validation' if split=='val' else 'test'
return {'domain':domain_nll(model,data[split]),'wiki':wiki_bpb(model,tok,data['others']['wiki-'+key]),
'arc':arc_accuracy(model,tok,data['others']['arc-'+key])}
def release():
gc.collect()
if DEVICE.type=='cuda':torch.cuda.empty_cache()
def write_atomic(path,obj):
tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(obj,ensure_ascii=False,indent=2)+'\n',encoding='utf-8');os.replace(tmp,path)
def main():
OUT.mkdir(parents=True,exist_ok=True)
tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=OFFLINE)
data=prepare(tok)
settings={'protocol_version':2,'model':MODEL,'revision':REV,'quick':QUICK,'seed':SEED,'context':CONTEXT,'ranks':RANKS,
'lrs':LRS,'full_lrs':FULL_LRS,'alpha':ALPHA,'updates':MAX_UPDATES,'microbatch':1,'accumulation':2,
'optimizer':'AdamW','weight_decay':0.,'clip':1.,'dataset':data['metadata'],'fingerprints':data['fingerprints'],
'dtype':'bfloat16' if DEVICE.type=='cuda' else 'float32','device':str(DEVICE),'torch':str(torch.__version__),
'python':sys.version.split()[0]}
identity=digest(settings);progress_path=OUT/'hparam-progress.json'
if progress_path.exists():
progress=json.loads(progress_path.read_text(encoding='utf-8'))
if progress['identity']!=identity:raise ValueError('El progreso pertenece a otro protocolo')
else:progress={'identity':identity,'settings':settings,'baseline':None,'runs':[],'selected_configs':None,'selected_test':{}}
if progress['baseline'] is None:
model=load_model();progress['baseline']={'val':evaluate(model,tok,data,'val')}
del model;release();write_atomic(progress_path,progress)
configs=[{'mode':mode,'rank':r,'lr':lr} for mode in ('lora','rslora') for r in RANKS for lr in LRS]
configs += [{'mode':'full','rank':None,'lr':lr} for lr in FULL_LRS]
for config in configs:
if any(x['config']==config for x in progress['runs']):continue
model,training=train(config,data)
run={'config':config,'training':training,'validation':evaluate(model,tok,data,'val')}
progress['runs'].append(run);del model;release();write_atomic(progress_path,progress)
print('Validación',config,run['validation'],flush=True)
# Test ya se leyó para filtrar coincidencias; congela elecciones antes de evaluarlo.
if progress.get('selected_configs') is None:
progress['selected_configs']={}
for mode in ('lora','rslora','full'):
candidates=[x for x in progress['runs'] if x['config']['mode']==mode]
if not candidates:raise ValueError('Falta un método del barrido')
chosen=min(candidates,key=lambda x:x['validation']['domain']['nats_per_token'])
progress['selected_configs'][mode]=chosen['config']
write_atomic(progress_path,progress)
# Test solo para los tres ajustes ya elegidos por NLL de validación, más la base.
if 'test' not in progress['baseline']:
model=load_model();progress['baseline']['test']=evaluate(model,tok,data,'test')
progress['baseline']['test']['gsm_accuracy']=gsm_accuracy(model,tok,data['test'])
del model;release();write_atomic(progress_path,progress)
for mode in ('lora','rslora','full'):
if mode in progress['selected_test']:continue
config=progress['selected_configs'][mode]
selected=next(x for x in progress['runs'] if x['config']==config)
model,training=train(selected['config'],data)
repeat=domain_nll(model,data['val'])
if abs(repeat['nats_per_token']-selected['validation']['domain']['nats_per_token'])>0.005:
raise AssertionError('La repetición no reproduce la selección en validación')
test=evaluate(model,tok,data,'test');test['gsm_accuracy']=gsm_accuracy(model,tok,data['test'])
progress['selected_test'][mode]={'config':selected['config'],'repeated_validation':repeat,
'training':training,'test':test}
del model;release();write_atomic(progress_path,progress)
result={**progress,'limitations':'Una muestra y una semilla no establecen una tendencia. La selección usa NLL de validación; test no elige configuraciones. WikiText bpb y ARC-Easy son proxies parciales, no ausencia general de olvido. Primeras filas no son representativas.'}
write_atomic(OUT/'hparam-report.json',result)
print('Informe:',OUT/'hparam-report.json',flush=True)
if __name__=='__main__':main()
npm run lab and open the connection link.Exercises
This cell checks the budget with partial blocks and a normal-quantile counterexample. Counts exclude offsets, unquantized tensors, and other metadata.
from statistics import NormalDist
pesos = 3_000_000_000
bloques = (pesos + 63) // 64
grupos = (bloques + 255) // 256
nf4_sin_doble = (pesos + 1) // 2 + 4 * bloques
nf4_con_doble = (pesos + 1) // 2 + bloques + 4 * grupos
normal = NormalDist()
limite = (normal.inv_cdf(.125) + normal.inv_cdf(.375)) / 2
print("Bloques y grupos:", bloques, grupos)
print("Bytes sin doble cuantización:", nf4_sin_doble)
print("Bytes con doble cuantización:", nf4_con_doble)
print("Masa de la primera celda del contraejemplo:", normal.cdf(limite))
print("Factores de escala al pasar de 16 a 64:", 16/64, (16/64)**0.5)Step 1 of 3. Which interior boundaries make each interval have probability 1/K?
import numpy as np
# Tabla publicada en el apéndice E de QLoRA.
NF4 = np.array([-1., -.6961928009986877, -.5250730514526367,
-.39491748809814453, -.28444138169288635, -.18477343022823334,
-.09105003625154495, 0., .07958029955625534, .16093020141124725,
.24611230194568634, .33791524171829224, .44070982933044434,
.5626170039176941, .7229568362236023, 1.])
def quantize_nf4(w, block=64):
pass
def dequantize_nf4(codes, scales, block=64):
pass
QLoRA compresses frozen-base storage while preserving a computation and gradient path for adapters. Its memory, error, and quality depend on blocks, scales, precision, optimizer, data, and evaluation.