QLoRA and NF4 quantization
Implement blockwise NF4 quantization with double quantization and compare it with bitsandbytes. Train a model of up to 3B that would not otherwise fit: a frozen 4-bit base, bf16 adapters, activation recomputation and a paged optimizer, measuring the difference from bf16 LoRA on a model that fits both ways.
After this lesson you can
- Derive NF4 levels from normal quantiles and quantize by block.
- Implement double quantization of scale constants and calculate the savings.
- Configure QLoRA with recomputation and a paged optimizer for a 3B model in 8 GB.
- Compare QLoRA quality and speed against bf16 LoRA on the same model.
Before you start
Four bits do not mean four times less total memory
According to its config.json, Qwen2.5-3B-Instruct has 36 blocks of width 2048, MLP projections of 11008, and a 151936-entry vocabulary with embeddings tied to output: about parameters. Storing them in bf16 alone costs GB. A laptop RTX 4060 has GB, some already occupied by driver, CUDA context, and desktop (the cited run started with GB free). Under the p08-l01 memory plan, the budget does not fit: weights must be joined by adapters, their gradients, AdamW moments, activations, and temporary memory. Full fine-tuning at 16 bytes per parameter for weights, gradients, and states would require about 49 GB.
In LoRA (p08-l02) we separated what is trained from what is not. The frozen base is read in every forward and backward pass but never updated; adapters are small but update each step. This asymmetry determines where to quantize:
- The base tolerates low-precision storage. It need only be reconstructed to bf16 when multiplying. If reconstruction error is small, the trained model is a slight perturbation of the original and adapters learn on that perturbation.
- The adapters do not. For Qwen2.5-3B with rank 16 on each block’s seven linear projections they total parameters, less than 1% of the model, so quantizing them would save little. An AdamW update has magnitude on the order of learning rate , much less than spacing between two levels of a 16-value grid: rounded to four bits, it would almost always return to the same code and training would not advance. We measure this when discussing merging.
QLoRA (Dettmers, Pagnoni, Holtzman, and Zettlemoyer, 2023) takes this recipe further: a four-bit base using a datatype designed for network weights (NF4), quantized scale constants themselves (double quantization), LoRA adapters on all linear layers, and paged optimizers for memory spikes. Its central result is that on its academic benchmarks (GLUE with RoBERTa-large, Super-NaturalInstructions with T5, and MMLU with 7B to 65B LLaMA), QLoRA with NF4 and double quantization matched 16-bit LoRA and full 16-bit fine-tuning, and enabled fine-tuning a 65B model on one 48 GB GPU. This lesson builds each part from scratch, compares with bitsandbytes, and ends with a lab fine-tuning the 3B on your card.
Before any definition, see the problem NF4 solves. The histogram shows weights of a real Qwen2.5-0.5B projection divided by their block’s absolute maximum, overlaid with the 16 NF4 and uniform-grid levels.
With blocks of 64, NF4 yields mean squared error and the uniform grid , 43% more. The figure shows why. Weight mass concentrates in the center, where NF4 packs levels, while the uniform grid spends six of sixteen levels in , where few weights lie and NF4 places only three. As block size grows, each block’s maximum grows, normalized weights shrink toward zero, and the gap increases until it doubles with .
Quantiles, zeros, and blocks
NF4’s idea is to distribute levels so each is used equally often. If normalized weights follow a distribution with cumulative distribution function , points dividing it into equal-probability pieces are its quantiles, (the quantile function). For a continuous variable this produces equiprobable codes, and no more information can be extracted from bits.
Proof
Since is continuous, for each the set is closed and nonempty, so its infimum satisfies ; and for every we have , so by continuity . Thus . Continuity also gives , so
with endpoint conventions and . For entropy, Gibbs’ inequality with uniform distribution gives, for any distribution over symbols, , that is , with equality if and only if .
∎Two qualifications matter. First, maximum entropy is not minimum squared error. The Lloyd-Max quantizer, minimizing expected squared error, places each threshold midway between representatives and each representative at its interval centroid; its levels are not quantiles. Second, the theorem concerns the distribution of normalized weights, which depends on block size because the divisor is the maximum of values.
Blockwise NF4 quantization (4-bit NormalFloat) applies this to approximately normal weights:
The table uses quantiles of the standard normal , with three design choices:
- Truncate tails. , so the extreme level uses probability and everything is divided by so the extreme is exactly 1. equals the mean of and , the final-quantile positions on 15- and 16-point grids.
- Include exact zero. A symmetric table with an even number of levels contains no 0. NF4 requires it: padding incomplete blocks and exactly zero weights must reconstruct without error.
- Accept asymmetry. Reserving 0 leaves 15 codes, not split equally. The paper takes quantiles on the positive side and on the negative.
In formulas, with :
plus 0. There are eight positive values in and seven negative values in . The levels are equally spaced in probability, so the intervals between thresholds have approximately equal mass under a normal distribution: the table is a practical approximation of the quantile quantizer in the theorem, with 0 and the endpoints enforced.
Under which normal distribution? Dividing by amounts to assuming that normalized weights have standard deviation , meaning that the block maximum is about away. But the maximum of independent normals is farther away: is for , for and for . With blocks of 64 the normalized weights are narrower than the table assumes, central codes are used more than outer ones, and entropy falls below 4 bits. You can see this in the figure: bits with and with .
Error decomposes by block. With ,
Each block’s normalized error is multiplied by the square of its scale. Larger blocks have larger scales (the maximum of more values) and concentrate more near 0, where a grid with few central levels performs poorly. That is why error grows with for both schemes, and faster for the uniform grid. In exchange, smaller blocks need more scales: the next section prices each one.
The definition gives one property for free: the weight with the largest absolute value in each block is normalized to , which is in the table, and is reconstructed without error. With and the matrix in the figure, that gives exact weights.
The uniform grid in the figure has 16 equally spaced levels between and , without an exact zero. It is the simplest symmetric version of uniform affine quantization; an int4 with exact zero or a least-squares fitted scale would behave differently, so the comparison measures a specific choice rather than “int4” in the abstract. Lower reconstruction error on one matrix does not by itself guarantee lower model loss: the lab tests that.
The bitsandbytes table
The bitsandbytes implementation (function create_normal_map) publishes the NF4 table its kernels use, rounded to float32. The next cell copies it literally, reconstructs the table from quantiles using the formulas above, and measures the difference. Probabilities are generated with torch.linspace in float32, as in the library.
import numpy as np
import torch
from scipy.stats import norm
NF4=np.array([-1.,-.6961928009986877,-.5250730514526367,-.39491748809814453,
-.28444138169288635,-.18477343022823334,-.09105003625154495,0.,
.07958029955625534,.16093020141124725,.24611230194568634,
.33791524171829224,.44070982933044434,.5626170039176941,
.7229568362236023,1.],dtype=np.float32)
p=np.float32(.9677083)
positive=norm.ppf(torch.linspace(float(p),.5,9)[:-1].numpy())
negative=-norm.ppf(torch.linspace(float(p),.5,8)[:-1].numpy())
constructed=np.sort(np.concatenate([negative,[0.],positive]))
constructed=constructed/constructed.max()
print('niveles NF4:',NF4.tolist())
print('Φ⁻¹(δ):',float(norm.ppf(float(p))),'media de 1-1/30 y 1-1/32:',(2-1/30-1/32)/2)
print('diferencia máxima de cuantiles y tabla:',float(np.max(np.abs(constructed-NF4))))
print('negativos, cero, positivos:',int((NF4<0).sum()),int((NF4==0).sum()),int((NF4>0).sum()))npm run lab and open the connection link.The maximum difference is on the order of , below float32 rounding: the table is exactly the quantile construction described.
The next cell checks the two qualifications to the theorem with Gaussian blocks of 64. It calculates the expected maximum , fits a 16-level table using Lloyd’s algorithm to minimize squared error in original units (with fixed, as in NF4), and compares error and entropy across the three tables.
from scipy import integrate
for B in (32,64,1024):
expected=integrate.quad(lambda x: 1-(2*norm.cdf(x)-1)**B,0,np.inf)[0]
print(f'B={B:>4}: E max|Z| = {expected:.3f}')
rng=np.random.default_rng(0)
blocks=rng.standard_normal((20000,64)).astype(np.float32)
a=np.abs(blocks).max(axis=1)
x=(blocks/a[:,None]).reshape(-1).astype(np.float64)
weight=np.repeat(a.astype(np.float64)**2,64)
lloyd=NF4.astype(np.float64).copy()
for _ in range(100):
code=np.searchsorted((lloyd[:-1]+lloyd[1:])/2,x)
for k in range(1,15):
mask=code==k
lloyd[k]=np.sum(weight[mask]*x[mask])/np.sum(weight[mask])
def report(levels):
code=np.searchsorted((levels[:-1]+levels[1:])/2,x)
mse=np.mean(weight*(x-levels[code])**2)
p=np.bincount(code,minlength=16)/code.size; p=p[p>0]
return mse,-(p*np.log2(p)).sum()
print('desviación típica de los pesos normalizados:',round(float(x.std()),3),'(NF4 supone 0.541)')
for name,levels in (('NF4',NF4.astype(np.float64)),('uniforme',np.linspace(-1,1,16)),('Lloyd-Max',lloyd)):
mse,h=report(levels)
print(f'{name:>9}: ECM por unidad de varianza {mse:.5f}, entropía {h:.3f} bits')
print('Lloyd-Max contiene el cero:',bool(np.any(lloyd==0)),'niveles centrales:',np.round(lloyd[6:10],3).tolist())npm run lab and open the connection link.NF4 is close to the squared-error optimum, with 7% more error than the Lloyd table, and far ahead of the uniform grid. The Lloyd table has no exact zero: NF4 buys that property at the cost of that small additional error.
Quantize and reconstruct
The code uses midpoints between consecutive levels as boundaries and assigns ties to the lower level. It rejects non-finite values, preserves shape, and pads only the last block to calculate its scale; padding is not returned as weights.
def quantize_blocks(weights,block=64,levels=NF4):
w=np.asarray(weights,dtype=np.float32)
if not isinstance(block,int) or block<=0 or w.size==0 or not np.isfinite(w).all():
raise ValueError('Pesos finitos no vacíos y bloque positivo requeridos')
flat=w.reshape(-1); count=flat.size
padding=(-count)%block
blocks=np.pad(flat,(0,padding)).reshape(-1,block)
scale=np.max(np.abs(blocks),axis=1).astype(np.float32)
normalized=np.divide(blocks,scale[:,None],out=np.zeros_like(blocks),where=scale[:,None]!=0)
boundaries=((levels[:-1]+levels[1:])/np.float32(2)).astype(np.float32)
code=np.searchsorted(boundaries,normalized,side='left').astype(np.uint8)
return code.reshape(-1)[:count],scale,w.shape
def dequantize_blocks(code,scale,shape,block=64,levels=NF4):
code=np.asarray(code,dtype=np.uint8)
if code.size!=int(np.prod(shape)) or len(scale)!=(code.size+block-1)//block or np.any(code>=len(levels)):
raise ValueError('Códigos o escalas incompatibles')
reconstructed=levels[code]*np.repeat(np.asarray(scale,dtype=np.float32),block)[:code.size]
return reconstructed.reshape(shape)
example=np.array([0.,-.2,.1,.8,-1.],dtype=np.float32)
q,s,shape=quantize_blocks(example,block=4)
print('control:',q.tolist(),'escalas',s.tolist(),'reconstrucción',dequantize_blocks(q,s,shape,4).tolist())npm run lab and open the connection link.In the check, the first block has scale : goes to code 7, to 15 (exact), and lies between and , closer to the first. The last block contains only and three padding zeros.
Scales also take space
With full blocks of 64 weights, a float32 scale adds bits per weight to the four index bits: 12.5% more than the ideal. Double quantization treats the scales as another tensor to quantize. If each scale is stored in 8 bits and a secondary float32 scale is shared by every 256 primary scales, the cost is
The saving relative to is bits per weight, the figure given by Dettmers and colleagues: about 3 GB for a 65B model. This calculation ignores the table, global offset, partial blocks and layers that are not quantized (embeddings and normalizations), which matter a great deal in a small model, as the 3B budget will show.
The implementation below performs an illustrative second quantization: it centers the scales by subtracting their mean (they are all positive, so without centering the sign would be wasted), uses symmetric 8-bit integers and one secondary scale per group. bitsandbytes also centers the scales, but encodes them with its dynamic 8-bit map in blocks of 256; our scheme illustrates composition rather than reproducing its bytes. When measuring, distinguish NF4 index error from the additional error of reconstructing scales.
def quantize_scales(scales,group=256):
x=np.asarray(scales,dtype=np.float32).reshape(-1)
if not len(x) or group<=0 or not np.isfinite(x).all(): raise ValueError('Escalas inválidas')
offset=np.float32(x.mean())
padding=(-len(x))%group
centered=np.pad(x-offset,(0,padding)).reshape(-1,group)
maxima=np.max(np.abs(centered),axis=1).astype(np.float32)
ratio=np.divide(centered,maxima[:,None],out=np.zeros_like(centered),where=maxima[:,None]!=0)
codes=np.rint(ratio*127).clip(-127,127).astype(np.int8).reshape(-1)[:len(x)]
return codes,maxima,offset
def dequantize_scales(codes,maxima,offset,group=256):
codes=np.asarray(codes,dtype=np.int8)
if len(maxima)!=(len(codes)+group-1)//group: raise ValueError('Grupos incompatibles')
return np.float32(offset)+codes.astype(np.float32)*np.repeat(maxima,group)[:len(codes)]/127
test_scales=np.array([.1,.2,.3,.4],dtype=np.float32)
sq,ss,off=quantize_scales(test_scales,group=2)
print('escalas originales:',test_scales.tolist(),'reconstruidas:',dequantize_scales(sq,ss,off,2).tolist())
print('bits ideales: simple',4+32/64,'doble',4+8/64+32/(64*256),
'ahorro',32/64-(8/64+32/(64*256)))npm run lab and open the connection link.A real matrix and comparison with bitsandbytes
The next experiment takes model.layers.0.self_attn.q_proj.weight from the Qwen2.5-0.5B-Instruct pinned in p08-l01, reads it with safetensors on CPU and converts it to float32. For each block size it calculates the normalized histogram, NF4 and uniform-grid mean squared errors, and code entropy: these are exactly the data in the interactive. Output identifies the revision and SHA-256 fingerprints of the file and matrix, so you can check that you are analyzing the same weights.
To run it, set P08_L03_WEIGHTS=1 before starting the lab. If you also set P08_L03_DIR to an absolute path, every cell in this lesson saves its JSON results there (weights.json has the interactive’s format). No existing file is overwritten: use a new directory to repeat an experiment. You need the p08-l01 snapshot in the Hugging Face cache or network access.
import os,hashlib,json
from pathlib import Path
def lab_dir():
value=os.environ.get('P08_L03_DIR')
if not value: return None
path=Path(value)
if not path.is_absolute(): raise ValueError('P08_L03_DIR debe ser una ruta absoluta')
path.mkdir(parents=True,exist_ok=True)
return path
def code_entropy(codes):
p=np.bincount(codes,minlength=16)/codes.size
p=p[p>0]
return float(-(p*np.log2(p)).sum())
weight_result=None
if os.environ.get('P08_L03_WEIGHTS')!='1':
print('Para analizar la matriz real, define P08_L03_WEIGHTS=1 (y, si quieres guardar, P08_L03_DIR) antes de iniciar el laboratorio.')
else:
from huggingface_hub import snapshot_download
from safetensors import safe_open
revision='7ae557604adf67be50417f59c2c2f167def9a775'
model_path=snapshot_download('Qwen/Qwen2.5-0.5B-Instruct',revision=revision,
allow_patterns=['*.json','*.safetensors','*.txt','*.tiktoken'])
weights_file=next(Path(model_path).glob('*.safetensors'))
with weights_file.open('rb') as f: weight_sha=hashlib.file_digest(f,'sha256').hexdigest()
key='model.layers.0.self_attn.q_proj.weight'
with safe_open(weights_file,framework='pt',device='cpu') as f:
weight_matrix=f.get_tensor(key).float().numpy()
weight_hash=hashlib.sha256(weight_matrix.tobytes()).hexdigest()
centered=(weight_matrix-weight_matrix.mean()).astype(np.float64)
kurtosis=float(np.mean(centered**4)/np.mean(centered**2)**2)
uniform=np.linspace(-1,1,16,dtype=np.float32)
edges=np.linspace(-1,1,49)
rows=[]
for block in (32,64,128,256,512,1024):
flat=weight_matrix.reshape(-1)
padded=np.pad(flat,(0,(-flat.size)%block)).reshape(-1,block)
scales=np.max(np.abs(padded),axis=1)
normalized=np.divide(padded,scales[:,None],out=np.zeros_like(padded),where=scales[:,None]!=0).reshape(-1)[:flat.size]
hist,_=np.histogram(normalized,bins=edges)
qn,sn,shape=quantize_blocks(weight_matrix,block,NF4)
qu,su,_=quantize_blocks(weight_matrix,block,uniform)
dn=dequantize_blocks(qn,sn,shape,block,NF4)
du=dequantize_blocks(qu,su,shape,block,uniform)
mse_n=float(np.mean((weight_matrix-dn).astype(np.float64)**2))
mse_u=float(np.mean((weight_matrix-du).astype(np.float64)**2))
rows.append({'block':block,'histogram':hist.tolist(),'mse_nf4':mse_n,'mse_uniform':mse_u,
'entropy_nf4':code_entropy(qn),'entropy_uniform':code_entropy(qu)})
weight_result={'revision':revision,'file_sha256':weight_sha,'matrix_sha256':weight_hash,
'key':key,'shape':list(weight_matrix.shape),'kurtosis':kurtosis,'bins':edges.tolist(),
'nf4':NF4.tolist(),'uniform':uniform.tolist(),'rows':rows}
print('revisión:',revision,'\narchivo:',weight_sha,'\nmatriz:',weight_hash,'forma:',weight_matrix.shape)
print('desviación típica:',round(float(weight_matrix.std()),5),'curtosis:',round(kurtosis,2),'(normal: 3)')
print(' B ECM NF4 ECM unif. razón H NF4 H unif.')
for r in rows:
print(f"{r['block']:>5} {r['mse_nf4']:.3e} {r['mse_uniform']:.3e} {r['mse_uniform']/r['mse_nf4']:6.3f} {r['entropy_nf4']:6.3f} {r['entropy_uniform']:7.3f}")
out=lab_dir()
if out:
target=out/'weights.json'
with target.open('x',encoding='utf-8') as f:
json.dump(weight_result,f,ensure_ascii=False,separators=(',',':'))
print('guardado:',target)npm run lab and open the connection link.The matrix is not normal: its kurtosis is about 22.8, versus 3 for a Gaussian, with much heavier tails. Even so, NF4 reduces error by a factor between 1.27 () and 2.04 () relative to the uniform grid, and code entropy falls from to bits as block size increases. The size 64 used by QLoRA is a compromise: with error falls a further 15%, but scales cost twice as much.
The bitsandbytes comparison checks three things separately: 4-bit codes (each byte packs two, the first in the high nibble), absmax scales, and reconstructed values. In addition to the real matrix it tests three edge cases: a block of zeros, a 70-value tensor with an incomplete block, and a block with values exactly at level midpoints, where tie-breaking matters. The cell launches a separate process using the interpreter at P08_PYTHON (the isolated p08-l01 environment with bitsandbytes), passes it the code of quantize_blocks and dequantize_blocks as you defined them, and releases the GPU on completion. Enable it with P08_L03_BNB=1 alongside P08_L03_WEIGHTS=1.
import inspect,subprocess,sys
bnb_report=None
if os.environ.get('P08_L03_BNB')!='1':
print('Para contrastar con bitsandbytes, define P08_L03_WEIGHTS=1 y P08_L03_BNB=1 (y P08_PYTHON si bitsandbytes está en otro entorno).')
else:
if weight_result is None: raise ValueError('Define también P08_L03_WEIGHTS=1: el contraste usa la misma matriz')
program='\n'.join(['import json,os','import numpy as np','import torch','import bitsandbytes as bnb',
'from safetensors import safe_open',f'NF4=np.array({NF4.tolist()!r},dtype=np.float32)',
inspect.getsource(quantize_blocks),inspect.getsource(dequantize_blocks),r'''
if not torch.cuda.is_available(): raise RuntimeError('El contraste usa CUDA')
with safe_open(os.environ['P08_L03_SAFETENSORS'],framework='pt',device='cpu') as f:
matrix=f.get_tensor('model.layers.0.self_attn.q_proj.weight').float().numpy()
def compare(values):
tensor=torch.from_numpy(values.copy()).cuda()
packed,state=bnb.functional.quantize_4bit(tensor,blocksize=64,quant_type='nf4',compress_statistics=False)
restored=bnb.functional.dequantize_4bit(packed,state).cpu().numpy()
raw=packed.cpu().numpy().reshape(-1)
library_codes=np.stack((raw>>4,raw&15),axis=1).reshape(-1)[:values.size]
codes,scales,shape=quantize_blocks(values,64,NF4)
own=dequantize_blocks(codes,scales,shape,64,NF4)
return {'codigos_distintos':int(np.count_nonzero(library_codes!=codes)),
'escalas_distintas':int(np.count_nonzero(state.absmax.cpu().numpy()!=scales)),
'valores_distintos':int(np.count_nonzero(restored!=own)),
'diferencia_maxima':float(np.max(np.abs(restored-own)))}
midpoints=((NF4[:-1]+NF4[1:])/np.float32(2)).astype(np.float32)
cases={'matriz':matrix,'ceros':np.zeros(64,dtype=np.float32),'cola':np.linspace(-1,1,70,dtype=np.float32),
'empates':np.pad(np.concatenate([np.array([-1.,1.],dtype=np.float32),midpoints]),(0,47))}
report={'bitsandbytes':bnb.__version__,'torch':torch.__version__,'device':torch.cuda.get_device_name(),
'casos':{name:compare(values) for name,values in cases.items()}}
print(json.dumps(report,ensure_ascii=False))
'''])
env=dict(os.environ,P08_L03_SAFETENSORS=str(weights_file),PYTHONUTF8='1')
child=subprocess.run([os.environ.get('P08_PYTHON',sys.executable),'-c',program],env=env,
capture_output=True,text=True,encoding='utf-8',timeout=900)
if child.returncode: raise RuntimeError('Falló el contraste: '+child.stderr[-4000:])
bnb_report=json.loads(child.stdout.strip().splitlines()[-1])
print('bitsandbytes',bnb_report['bitsandbytes'],'torch',bnb_report['torch'],bnb_report['device'])
for name,row in bnb_report['casos'].items(): print(f'{name:>8}:',row)
out=lab_dir()
if out:
with (out/'bitsandbytes.json').open('x',encoding='utf-8') as f: json.dump(bnb_report,f,ensure_ascii=False,indent=2)npm run lab and open the connection link.With bitsandbytes 0.50.2 on an RTX 4060, matrix indices, scales, and values match element by element, as do the partial tail and ties. All 64 indices differ in the zero block, but both reconstructions yield zero because the scale is zero: value parity does not imply byte parity. If your platform differs, first check ties and normalization arithmetic (division or multiplication by the reciprocal) before drawing conclusions; agreement on one matrix does not prove equivalence on other backends.
What passes through the backward pass
A QLoRA linear layer with input computes
with , and . Matrix is not stored: it is reconstructed in bf16 from codes and scales immediately before multiplication and discarded afterward. This is on-the-fly dequantization. Given , the chain rule yields the three relevant gradients:
is deliberately absent: the frozen base does not need the matrix, and it is never computed. But the base does participate in the backward pass: without the gradient would not reach adapters in earlier layers. With activation recomputation each block runs forward twice, so each base matrix is dequantized three times per step. That is QLoRA’s real speed cost: in the trial below the same 0.5B processed 79% as many tokens per second as its bf16 version.
The QLoRA training setup combines five choices, each with a different effect on memory:
- NF4 base with double quantization and bf16 computation (
load_in_4bit,bnb_4bit_quant_type='nf4',bnb_4bit_use_double_quant=True,bnb_4bit_compute_dtype=torch.bfloat16). Only the blocks’ linear layers are quantized; embeddings, normalizations and the output head retain their dtype. - Preparation for k-bit training (PEFT’s
prepare_model_for_kbit_training): enables recomputation, allows gradients to reach the input and converts nonquantized parameters to float32 for numerical stability in normalizations and embeddings. With a large vocabulary this doubles embedding memory. - LoRA adapters on all linear projections, in bf16 in this lab. The QLoRA paper found that applying LoRA to every linear layer enables it to match full fine-tuning; attention projections alone are insufficient.
- Activation recomputation, which trades activation memory across all layers for an extra forward pass.
- Paged optimizer (
PagedAdamW32bit). Its states are allocated in CUDA unified memory: if the GPU runs out of memory, the driver can evict pages to RAM and bring them back when the optimizer needs them, instead of failing for lack of memory. QLoRA introduced it to absorb recomputation spikes with long sequences. This differs from storing states in 8 bits, which reduces their size; moments here remain float32. In bitsandbytes 0.50.2 only states of parameters with at least elements (optim/optimizer.py) are paged: at rank 16 in the 3B this applies to ofgate_projandup_proj() and ofdown_proj, three per block, states out of ; in the 0.5B, whose largest adapter matrix is , none qualify. Whether paging actually moves pages also depends on system and driver unified-memory support; a paged optimizer does not prove any paging occurred.
The counters recorded by the lab let us complete the 3B budget. Parameter counts come from the short run cited below; bytes are calculated by multiplication:
| Component | Parameters | Format | Memory |
|---|---|---|---|
| Base linear layers | 2,774,532,096 | NF4 with double quantization (4.127 bits) | 1.431 GB |
| Embeddings, normalizations and biases | 311,406,592 | float32 after preparation | 1.246 GB |
| Adapters (rank 16, 7 projections × 36 blocks) | 29,933,568 | bf16 | 0.060 GB |
| Adapter gradients | 29,933,568 | bf16 | 0.060 GB |
| AdamW moments | 2 × 29,933,568 | float32 | 0.239 GB |
| Persistent total | 3.036 GB |
Peak PyTorch allocation in that run was GB: the remaining GB comprise activations, logits over 151936 tokens, temporary dequantized matrices and kernel workspace. The same model in bf16 would need GB for weights alone. The part that is not quantized (float32 embeddings) occupies almost as much as the entire quantized base: in small models with large vocabularies, NF4 is not the only lever.
Configure fine-tuning without confusing memory and quality
The p08-l01 candidate is Qwen2.5-0.5B-Instruct, licensed Apache-2.0. At the larger scale we use Qwen2.5-3B-Instruct, whose model card declares the qwen-research license; check its terms before using it outside the study. Comparing bf16 LoRA and QLoRA quality requires the same base model, batches, rank, modules, initialization, optimizer and evaluation: comparing loss for a quantized 3B against a bf16 0.5B would mix size and precision.
PyTorch allocated and reserved memory covers its own allocations, but not necessarily all driver memory or other CUDA allocators. mem_get_info() measures global free memory at the instant queried, including other applications; it is not an exact per-process peak either. The lab records both measurements and card capacity. A fine-tuning run finishing without running out of memory is evidence for that batch, sequence length, model and environment, not a guarantee for longer sequences.
Evaluation uses the frozen p08-l01 test: twelve memory-accounting questions with integer answers, distinct from training examples, generated using another template. During training prompt labels are masked and the answer is retained as the target. Twelve questions give a coarse signal: the 95% Wilson interval for 4 correct out of 12 runs from to . The lab therefore also measures held-out loss: mean cross-entropy per answer token over 64 examples using the training template that are never used for training. This continuous measure is much more sensitive to differences between LoRA and QLoRA than counting correct answers.
Merge without losing the adapter
Afterward, it is tempting to “merge” the adapter to serve a single model: . With a quantized base you must choose the format of , and that choice has consequences. The trained function is exactly with dequantized ; any subsequent rounding changes it. The next cell merges a rank-16 update into an NF4 matrix of and measures how much survives in three formats, for three relative sizes .
rng=np.random.default_rng(3)
base=(0.02*rng.standard_normal((512,512))).astype(np.float32)
codes,scales,shape=quantize_blocks(base,64,NF4)
base_q=dequantize_blocks(codes,scales,shape,64,NF4)
direction=rng.standard_normal((512,16)).astype(np.float32)@rng.standard_normal((16,512)).astype(np.float32)
print('tamaño códigos cambiados error NF4 error bf16 error fp32 (errores relativos a ‖sBA‖)')
for relative in (0.001,0.01,0.1):
delta=(direction*(relative*np.linalg.norm(base_q)/np.linalg.norm(direction))).astype(np.float32)
exact=base_q.astype(np.float64)+delta.astype(np.float64)
merged=(base_q+delta).astype(np.float32)
new_codes,new_scales,_=quantize_blocks(merged,64,NF4)
requantized=dequantize_blocks(new_codes,new_scales,shape,64,NF4)
bf16=torch.from_numpy(merged).bfloat16().float().numpy()
error=lambda m: np.linalg.norm(m-exact)/np.linalg.norm(delta)
print(f'{relative:>6} {float(np.mean(new_codes!=codes)):>14.4f} {error(requantized):>10.3f} {error(bf16):>10.3f} {error(merged):>10.2e}')npm run lab and open the connection link.With updates of 0.1% and 1% of the base norm, requantization to NF4 changes no codes: the entire update disappears and relative error exceeds 100% because scales also shift slightly. Even at 10%, most is lost. bf16 also changes the result: with 8 mantissa bits, a 0.1% update is below its relative resolution () and is lost, while a 1% update suffers 16.5% error. Only float32 preserves the update.
Lab: 3B QLoRA and comparison with bf16 LoRA
The lab trains three configurations, each in a separate process that releases the GPU on completion:
lora05: Qwen2.5-0.5B-Instruct in bf16 with LoRA.qlora05: the same 0.5B with an NF4 base and double quantization. Together withlora05it forms a clean comparison of quality and speed.qlora3: Qwen2.5-3B-Instruct with QLoRA, a model that would not fit in 8 GB in bf16.
All three share rank 16 with on all seven projections, PagedAdamW32bit with rate , microbatch 1, recomputation and the same sequence of examples. Initialization of is fixed by parameter name using a seed derived from the name, because the global seed alone does not produce identical adapters through two different loading paths; fingerprint adapter_initial_sha256 lets you verify that lora05 and qlora05 start from the same point. The p08-l01 test answers and held-out loss are recorded before and after training. prepare_model_for_kbit_training also changes the dtypes of parts of the base, so the comparison measures the full QLoRA recipe, not the isolated effect of NF4.
How to run it. Use the isolated p08-l01 environment (PyTorch with CUDA, Transformers 5.20.2, PEFT 0.21.2 and bitsandbytes 0.50.2). Before starting the lab, set the following, for example in PowerShell:
$env:P08_PYTHON = "C:\ruta\al\entorno\Scripts\python.exe" # intérprete con bitsandbytes
$env:P08_L03_DIR = "C:\ruta\nueva\p08-l03" # resultados de la lección
$env:P08_L03_ALL = "1" # o P08_L03_MODE = "qlora3" para una sola
$env:P08_L03_STEPS = "500" # pasos de entrenamiento (500 por defecto)
With 500 steps, training visits 500 distinct examples once. The first run downloads both models (about 7 GB total). To reread results from a directory without retraining, set only P08_L03_DIR.
import os, sys, json, subprocess
from pathlib import Path
training_results={}
modes=['lora05','qlora05','qlora3'] if os.environ.get('P08_L03_ALL')=='1' else ([os.environ['P08_L03_MODE']] if os.environ.get('P08_L03_MODE') else [])
if not modes:
existing=Path(os.environ['P08_L03_DIR']) if os.environ.get('P08_L03_DIR') else None
for mode in ('lora05','qlora05','qlora3'):
if existing and (existing/f'{mode}.json').is_file():
training_results[mode]=json.loads((existing/f'{mode}.json').read_text(encoding='utf-8'))
print('Resultados leídos:',', '.join(sorted(training_results)) or 'ninguno')
print('Para entrenar, define P08_L03_ALL=1 (o P08_L03_MODE) y P08_L03_DIR antes de iniciar el laboratorio.')
else:
destination=lab_dir()
if destination is None: raise ValueError('Define P08_L03_DIR para guardar los resultados del entrenamiento')
program = r'''
import gc, hashlib, importlib.metadata, json, math, os, re, time
from pathlib import Path
import torch
import bitsandbytes as bnb
from huggingface_hub import snapshot_download
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
mode=os.environ['P08_L03_MODE']
if mode not in ('lora05','qlora05','qlora3'): raise ValueError('modo inválido')
steps=int(os.environ.get('P08_L03_STEPS','500'))
if not 1<=steps<=2000: raise ValueError('P08_L03_STEPS debe estar entre 1 y 2000')
if not torch.cuda.is_available(): raise RuntimeError('Se necesita CUDA')
repo,revision=(('Qwen/Qwen2.5-3B-Instruct','aa8e72537993ba99e69dfaafa59ed015b17504d1')
if mode=='qlora3' else ('Qwen/Qwen2.5-0.5B-Instruct','7ae557604adf67be50417f59c2c2f167def9a775'))
path=snapshot_download(repo,revision=revision,allow_patterns=['*.json','*.safetensors','*.txt','*.tiktoken'])
output=Path(os.environ['P08_L03_TRAIN_RESULT'])
if not output.is_absolute() or output.exists(): raise ValueError('Salida absoluta y nueva requerida')
hashes={}
for f in sorted(Path(path).glob('*.safetensors')):
with f.open('rb') as stream: hashes[f.name]=hashlib.file_digest(stream,'sha256').hexdigest()
tok=AutoTokenizer.from_pretrained(path,local_files_only=True)
tokenizer_hashes={}
for name in ('tokenizer.json','tokenizer_config.json','vocab.json','merges.txt'):
file=Path(path)/name
if file.is_file():
with file.open('rb') as stream: tokenizer_hashes[name]=hashlib.file_digest(stream,'sha256').hexdigest()
template_sha=hashlib.sha256(str(tok.chat_template).encode('utf-8')).hexdigest()
def example(i):
n=1001+79*i; b=2**(1+i%3)
return {'prompt':f'Calcula el producto de {n} valores por {b} bytes por valor. Responde solo con un entero.','answer':n*b}
train=[example(i) for i in range(max(32,steps))]
heldout=[example(i) for i in range(5000,5064)]
cases=[(125000,2),(240000,4),(375000,8),(640000,2),(825000,4),(1150000,8),
(1430000,2),(1760000,4),(2190000,8),(2530000,2),(2870000,4),(3190000,8)]
evaluation=[{'id':f'mem-{i:02d}',
'prompt':f'Un tensor tiene {n} elementos y cada uno ocupa {b} bytes. ¿Cuántos bytes ocupa? Responde solo con un entero.',
'answer':n*b} for i,(n,b) in enumerate(cases)]
def digest_json(rows):
return hashlib.sha256(json.dumps(rows,ensure_ascii=False,sort_keys=True,separators=(',',':')).encode('utf-8')).hexdigest()
train_sha=digest_json(train); eval_sha=digest_json(evaluation); heldout_sha=digest_json(heldout)
def encode(row):
prefix=tok.apply_chat_template([{'role':'user','content':row['prompt']}],tokenize=False,add_generation_prompt=True)
prefix_ids=tok(prefix,add_special_tokens=False)['input_ids']
ids=tok(prefix+str(row['answer'])+tok.eos_token,add_special_tokens=False)['input_ids']
if ids[:len(prefix_ids)]!=prefix_ids or len(ids)>128: raise ValueError('Tokenización inesperada')
return ids,len(prefix_ids)
model=optimizer=batch=loss=out=states=paged=param=input_ids=labels=inputs=output_ids=None
try:
torch.manual_seed(47); torch.cuda.manual_seed_all(47)
torch.cuda.empty_cache(); torch.cuda.synchronize()
free_before,capacity=torch.cuda.mem_get_info(); torch.cuda.reset_peak_memory_stats()
options={'local_files_only':True,'dtype':torch.bfloat16}
if mode.startswith('qlora'):
options['quantization_config']=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',
bnb_4bit_compute_dtype=torch.bfloat16,bnb_4bit_use_double_quant=True)
options['device_map']={'':0}
model=AutoModelForCausalLM.from_pretrained(path,**options)
if mode=='lora05':
model=model.cuda()
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={'use_reentrant':False})
else:
model=prepare_model_for_kbit_training(model,use_gradient_checkpointing=True,
gradient_checkpointing_kwargs={'use_reentrant':False})
config=LoraConfig(r=16,lora_alpha=32,lora_dropout=0.,bias='none',
target_modules=['q_proj','k_proj','v_proj','o_proj','gate_proj','up_proj','down_proj'],task_type='CAUSAL_LM')
model=get_peft_model(model,config,autocast_adapter_dtype=False)
if not model.is_gradient_checkpointing: raise RuntimeError('La recomputación no quedó activada')
for name,param in model.named_parameters():
if param.requires_grad:
if 'lora_' not in name: raise ValueError('Parámetro base entrenable: '+name)
param.data=param.data.to(torch.bfloat16)
with torch.no_grad():
if 'lora_A' in name:
seed=int.from_bytes(hashlib.sha256(name.encode('utf-8')).digest()[:8],'little') % (2**63)
generator=torch.Generator(device='cpu').manual_seed(seed)
initial=torch.empty(param.shape,dtype=torch.float32)
torch.nn.init.kaiming_uniform_(initial,a=math.sqrt(5),generator=generator)
param.copy_(initial.to(device=param.device,dtype=param.dtype))
elif 'lora_B' in name: param.zero_()
else: raise ValueError('Adaptador inesperado: '+name)
adapter_hash=hashlib.sha256()
for name,param in sorted(model.named_parameters()):
if param.requires_grad:
adapter_hash.update(name.encode('utf-8')+b'\0')
adapter_hash.update(param.detach().cpu().contiguous().view(torch.uint16).numpy().tobytes())
base_dtypes={}
for name,param in model.named_parameters():
if not param.requires_grad:
tag=f'{type(param).__name__}:{param.dtype}'
base_dtypes[tag]=base_dtypes.get(tag,0)+param.numel()
trainable=sum(p.numel() for p in model.parameters() if p.requires_grad)
optimizer=bnb.optim.PagedAdamW32bit((p for p in model.parameters() if p.requires_grad),lr=2e-4,weight_decay=0.)
minimum_free=free_before
def evaluate():
global minimum_free
model.eval(); rows=[]
with torch.inference_mode():
for row in evaluation:
inputs=tok.apply_chat_template([{'role':'user','content':row['prompt']}],tokenize=True,
add_generation_prompt=True,return_tensors='pt',return_dict=True).to('cuda')
output_ids=model.generate(**inputs,max_new_tokens=16,do_sample=False,pad_token_id=tok.eos_token_id,use_cache=True)
generated=output_ids[0,inputs['input_ids'].shape[-1]:]
text=tok.decode(generated,skip_special_tokens=True).strip()
value=int(text) if re.fullmatch('[0-9]+',text) else None
eos_ids=model.generation_config.eos_token_id
eos_ids=eos_ids if isinstance(eos_ids,list) else [eos_ids]
rows.append({'id':row['id'],'output':text,'answer':row['answer'],'correct':value==row['answer'],
'generated_tokens':int(generated.numel()),
'ended_with_eos':bool(generated.numel() and int(generated[-1]) in eos_ids)})
torch.cuda.synchronize(); minimum_free=min(minimum_free,torch.cuda.mem_get_info()[0])
del inputs,output_ids
return rows
def heldout_loss():
model.eval(); total=0.; count=0
with torch.inference_mode():
for row in heldout:
ids,prefix=encode(row)
input_ids=torch.tensor([ids],device='cuda'); labels=input_ids.clone(); labels[:,:prefix]=-100
value=model(input_ids=input_ids,labels=labels,use_cache=False).loss
total+=float(value)*(len(ids)-prefix); count+=len(ids)-prefix
return total/count
before=evaluate(); loss_before=heldout_loss()
model.train(); losses=[]; total_tokens=0; tokens_hash=hashlib.sha256()
torch.cuda.synchronize(); start=time.perf_counter()
for i in range(steps):
ids,prefix=encode(train[i])
tokens_hash.update(json.dumps([ids,prefix],separators=(',',':')).encode('ascii'))
input_ids=torch.tensor([ids],device='cuda'); labels=input_ids.clone(); labels[:,:prefix]=-100
optimizer.zero_grad(set_to_none=True)
loss=model(input_ids=input_ids,labels=labels,use_cache=False).loss
if not torch.isfinite(loss): raise ValueError('Pérdida no finita')
loss.backward(); optimizer.step()
losses.append(float(loss.detach().cpu())); total_tokens+=len(ids)
torch.cuda.synchronize(); minimum_free=min(minimum_free,torch.cuda.mem_get_info()[0])
del input_ids,labels,loss
torch.cuda.synchronize(); duration=time.perf_counter()-start
states=[v for s in optimizer.state.values() for v in s.values() if torch.is_tensor(v)]
paged=[v for v in states if getattr(v,'is_paged',False)]
trainable_dtypes=sorted({str(p.dtype) for p in model.parameters() if p.requires_grad})
outputs=evaluate(); loss_after=heldout_loss()
torch.cuda.synchronize()
result={'mode':mode,'model':repo,'revision':revision,'weight_sha256':hashes,
'train_sha256':train_sha,'eval_sha256':eval_sha,'heldout_sha256':heldout_sha,
'trainable':trainable,'trainable_dtypes':trainable_dtypes,
'adapter_initial_sha256':adapter_hash.hexdigest(),'tokenizer_sha256':tokenizer_hashes,
'template_sha256':template_sha,'train_tokens_sha256':tokens_hash.hexdigest(),'base_dtypes':base_dtypes,
'steps':steps,'microbatch':1,'max_sequence':128,'checkpointing':bool(model.is_gradient_checkpointing),'optimizer':'PagedAdamW32bit',
'losses':losses,'train_tokens':total_tokens,'train_tokens_per_second':total_tokens/duration,
'heldout_loss_before':loss_before,'heldout_loss_after':loss_after,
'optimizer_tensor_states':len(states),'paged_tensor_states':len(paged),
'allocated_peak':torch.cuda.max_memory_allocated(),'reserved_peak':torch.cuda.max_memory_reserved(),
'free_before':free_before,'capacity':capacity,'minimum_free_sampled':minimum_free,
'before_correct':sum(r['correct'] for r in before),'before_outputs':before,
'eval_correct':sum(r['correct'] for r in outputs),'eval_total':len(outputs),'outputs':outputs,
'versions':{n:importlib.metadata.version(n) for n in ('torch','transformers','peft','bitsandbytes')},
'device':torch.cuda.get_device_name()}
with output.open('x',encoding='utf-8') as f: json.dump(result,f,ensure_ascii=False,indent=2)
print(json.dumps({k:result[k] for k in ('mode','steps','eval_correct','heldout_loss_after')},ensure_ascii=False),flush=True)
finally:
model=optimizer=batch=loss=out=states=paged=param=input_ids=labels=inputs=output_ids=None
gc.collect(); torch.cuda.empty_cache()
'''
for mode in modes:
target=destination/(mode+'.json')
if target.exists(): raise ValueError(f'{target} ya existe: usa un P08_L03_DIR nuevo')
env=dict(os.environ,P08_L03_MODE=mode,P08_L03_TRAIN_RESULT=str(target),PYTHONUTF8='1')
child=subprocess.run([os.environ.get('P08_PYTHON',sys.executable),'-c',program],env=env,
capture_output=True,text=True,encoding='utf-8',timeout=6*3600)
if child.returncode: raise RuntimeError('Falló '+mode+': '+child.stderr[-4000:])
training_results[mode]=json.loads(target.read_text(encoding='utf-8'))
print(mode,'guardado en',target)npm run lab and open the connection link.The next cell summarizes each configuration and, if both 0.5B runs are present, checks that they share experimental identity (revision, weights, data, tokens, template, initialization and steps) before comparing quality and speed. It refuses to compare if any fingerprint differs.
for mode in ('lora05','qlora05','qlora3'):
r=training_results.get(mode)
if not r: continue
print(f"{mode}: {r['model']} · {r['steps']} pasos · aciertos {r['before_correct']}/{r['eval_total']} → {r['eval_correct']}/{r['eval_total']}"
f" · pérdida reservada {r['heldout_loss_before']:.3f} → {r['heldout_loss_after']:.3f}")
print(f" asignado {r['allocated_peak']/1e9:.3f} GB · reservado {r['reserved_peak']/1e9:.3f} GB · libre mínimo {r['minimum_free_sampled']/1e9:.2f} de {r['capacity']/1e9:.2f} GB"
f" · {r['train_tokens_per_second']:.1f} tokens/s · estados paginados {r['paged_tensor_states']}/{r['optimizer_tensor_states']}")
print(f" entrenables {r['trainable']} {r['trainable_dtypes']} · base {r['base_dtypes']} · {r['versions']} · {r['device']}")
a=training_results.get('lora05'); b=training_results.get('qlora05')
if a and b:
keys=('revision','weight_sha256','train_sha256','eval_sha256','heldout_sha256','tokenizer_sha256','template_sha256',
'train_tokens_sha256','adapter_initial_sha256','steps','microbatch','max_sequence')
match={k:a[k]==b[k] for k in keys}
if not all(match.values()): raise ValueError(f'Las configuraciones no comparten identidad experimental: {match}')
print('identidad experimental de lora05 y qlora05: comprobada')
print('pérdida reservada final QLoRA − LoRA:',round(b['heldout_loss_after']-a['heldout_loss_after'],4))
print('razón QLoRA/LoRA de tokens por segundo:',round(b['train_tokens_per_second']/a['train_tokens_per_second'],3))
elif not training_results:
print('Sin resultados todavía: ejecuta la celda anterior con P08_L03_DIR.')npm run lab and open the connection link.What to expect. For full training, the reference is the QLoRA paper: with NF4, double quantization and LoRA on every linear layer, quality matched 16-bit LoRA on its academic benchmarks. In this lab, the final held-out loss of qlora05 should be very close to that of lora05, separated by a distance comparable to two seeds of the same method, with both well below their initial values; on the twelve-question test, a difference of one or two correct answers falls within the noise. QLoRA will be slower because of dequantization: expect a tokens-per-second ratio below 1. And qlora3 should finish with peak allocated memory well below 8 GB; for sequences of this size, the preceding budget suggests about 3.3 GB. The following table reports a short run of this same cell with P08_L03_STEPS=12, which checks that everything works end to end and establishes orders of magnitude, not conclusions about quality.
| Configuration (12 steps) | Correct before → after | Held-out loss before → after | Peak allocated / reserved | Tokens/s | Paged states |
|---|---|---|---|---|---|
| 0.5B LoRA bf16 | 0/12 → 4/12 | 1.350 → 0.748 | 1.221 / 1.315 GB | 86.4 | 0 / 672 |
| 0.5B QLoRA NF4 | 1/12 → 2/12 | 1.326 → 0.980 | 1.003 / 1.143 GB | 68.4 | 0 / 672 |
| 3B QLoRA NF4 | 8/12 → 10/12 | 1.712 → 0.131 | 3.311 / 3.597 GB | 44.9 | 216 / 1008 |
These figures are from PyTorch 2.11.0 with CUDA, Transformers 5.20.2, PEFT 0.21.2 and bitsandbytes 0.50.2 on an 8 GB RTX 4060 Laptop GPU; tokens per second were measured with no other GPU load, because other processes on the card drastically reduce throughput. Interpret them carefully:
- Memory. The 3B with QLoRA uses less than half the card, as the budget predicted. QLoRA on the 0.5B saves little compared with bf16 ( versus GB): in such a small model, the 136 million embedding parameters are converted to float32 and consume much of what NF4 saves on linear layers.
- Speed. QLoRA processed 79% as many tokens per second as bf16 LoRA on the same model: the cost of dequantizing three times per step.
- Quality. Twelve steps are insufficient for comparison: held-out loss falls in all three configurations, and the difference between
lora05andqlora05after so few steps depends on each run’s trajectory. Your full run answers whether QLoRA matches LoRA on this task. The paged states confirm the -element rule: 216 states in the 3B, none in the 0.5B.
Exercises
import numpy as np
LEVELS=np.array([-1.,-.6961928,-.52507305,-.39491749,-.28444138,-.18477343,-.09105004,0.,.0795803,.1609302,.2461123,.33791524,.44070983,.562617,.72295684,1.],dtype=np.float32)
def nf4_quantize(w,block=64):
return np.zeros(np.asarray(w).size,dtype=np.uint8),np.array([1.]),np.asarray(w).shape
def nf4_dequantize(codes,scales,shape,block=64):
return np.zeros(shape,dtype=np.float32)