AI Wiki中文/EN

QLoRA: store fewer bits, train the added factors

QLoRA

Pack NF4 indices, reconstruct a frozen base and distinguish scale metadata, training precision and paging.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A four-bit file does not imply four-bit multiplication

A base model can store each weight as a small code while performing matrix arithmetic after reconstructing a higher-precision value. During adaptation, the stored base codes can stay fixed while separate low-rank factors learn. These are three different decisions: storage, computation and which parameters change.

QLoRA combines a frozen quantized base with trainable LoRA factors. Its method includes NormalFloat4, double quantization of scale constants, and paged optimizers. Calling any small integer quantizer “QLoRA” skips those distinctions.

Our example packs 36 weight codes into 18 bytes, then actually trains a rank-two update. It also stores scale constants and computes in NumPy float64. The 18-byte number therefore describes only the packed code payload, not the program’s memory use or the complete model size.

Packed codes, scale overhead and trainable factors account for different costs and errors.
Packed codes, scale overhead and trainable factors account for different costs and errors.

Reconstruction is part of the forward pass

For a weight block ww, let a=max⁡j∣wj∣a=\max_j|w_j| and let c0,…,c15c_0,\ldots,c_{15} be the NF4 codebook values. A nearest-code reconstruction is:

kj=arg min⁡k∈{0,…,15}∣wj/a−ck∣,w^j=ackj(a>0).k_j=\operatorname*{arg\,min}_{k\in\{0,\ldots,15\}}|w_j/a-c_k|,\qquad \widehat w_j=a c_{k_j}\quad(a>0).

A zero block uses the exact zero code and reconstructs zeros without dividing by zero. This implementation breaks nearest-code ties by the first codebook index. NF4’s values are nonuniform, include zero, and are motivated by a normal-distribution quantile construction. The paper’s optimality language concerns that modeling choice; it should not be generalized into minimum error for every weight distribution, block scale or task.

The complete 16 numerical code values below come from QLoRA v1 Appendix E. They are facts about the format, not copied implementation code. After obtaining the indices, pack two into each byte:

uj=k2j+16k2j+1,k2j=uj mod 16,k2j+1=⌊uj/16⌋.u_j=k_{2j}+16k_{2j+1},\qquad k_{2j}=u_j\bmod16,\qquad k_{2j+1}=\lfloor u_j/16\rfloor.

For an odd count, the unused high nibble is padding and the original element count controls reconstruction. Shape, block size and scales are additional metadata.

Write the reconstructed frozen matrix as W^0\widehat W_0. The adapted layer, with the scale absorbed into the factors for this example, is:

h=W^0x+BAx.h=\widehat W_0x+BAx.

The paper usually stores the base in NF4 and computes in BF16 after dequantization. The factors are trainable; the discrete base codes are not updated by ordinary weight gradients. Frozen weights do not prevent input gradients from flowing through the layer. For a loss gradient g=∂L/∂hg=\partial\mathcal L/\partial h:

∂L∂x=(W^0+BA)⊤g.\frac{\partial\mathcal L}{\partial x}=(\widehat W_0+BA)^\top g.

That derivative can be needed to train adapters or other variables earlier in a network even though the base weights themselves are frozen.

Scales can be a meaningful fraction of storage. With four-bit codes and one 32-bit scale for every bb weights, idealized storage per weight is:

Bsingle=4+32b.B_{\mathrm{single}}=4+\frac{32}{b}.

At b=64b=64, this is 4.5 bits. Quantizing those scales to eight bits, with a 32-bit second-level scale per gg first-level scales, gives the paper’s amortized accounting:

Bdouble=4+8b+32bg.B_{\mathrm{double}}=4+\frac8b+\frac{32}{bg}.

For b=64,g=256b=64,g=256, this is 4.126953125 bits, saving 0.373046875 bits per weight relative to 4.5. The formula omits finite-block padding, offset and format metadata, optimizer states and activations. It is not a GPU-allocation measurement.

To inspect scale error without implementing FP8, our program uses a clearly different teaching proxy. For one finite group of scales, center at mean μ\mu, let rr be the largest absolute centered value, and use signed integers:

zj=round⁡ ⁣(127aj−μr),a^j=μ+r127zj(r>0).z_j=\operatorname{round}\!\left(127\frac{a_j-\mu}{r}\right),\qquad \widehat a_j=\mu+\frac r{127}z_j\quad(r>0).

Constant scales reconstruct directly when r=0r=0. This uniform integer proxy is not the paper’s eight-bit floating-point scale quantization. Its radius, mean and actual float64 arrays also have their own storage costs.

Keep the codes fixed while the factors improve

The complete NumPy program uses NF4 code values, real nibble packing and absolute-maximum blocks of eight weights. It freezes the reconstructed six-by-six base and trains rank-two factors against a declared synthetic target. It uses float64, not BF16, and contains no paged optimizer.

"""NF4 codebook, real nibble packing, frozen quantized base and trained factors.

Codebook numbers: Dettmers et al. QLoRA v1 Appendix E. Float64 arithmetic;
scale double quantization below is a uniform integer teaching proxy, not FP8.
"""
import json
import numpy as np

NF4=np.array([-1.,-.6961928009986877,-.5250730514526367,-.39491748809814453,-.28444138169288635,-.18477343022823334,-.09105003625154495,0.,.07958029955625534,.16093020141124725,.24611230194568634,.33791524171829224,.44070982933044434,.5626170039176941,.7229568362236023,1.])
def encode(weights,block=8):
    w=np.asarray(weights,float)
    if not w.size or not np.isfinite(w).all() or type(block) is not int or block<1:raise ValueError('Finite nonempty weights and positive block required')
    flat=w.ravel();codes=np.empty(flat.size,np.uint8);scales=[]
    for start in range(0,len(flat),block):
        v=flat[start:start+block];s=float(np.max(abs(v)));scales.append(s)
        norm=v/s if s else np.zeros_like(v);codes[start:start+len(v)]=np.argmin(abs(norm[:,None]-NF4),axis=1)
    padded=np.pad(codes,(0,len(codes)%2));packed=padded[::2]|(padded[1::2]<<4)
    return dict(packed=packed,scales=np.array(scales),shape=w.shape,block=block,count=len(flat))
def decode(state,scales=None):
    packed=state['packed'];codes=np.empty(2*len(packed),np.uint8);codes[::2]=packed&15;codes[1::2]=packed>>4;codes=codes[:state['count']]
    s=state['scales'] if scales is None else np.asarray(scales,float)
    if s.shape!=state['scales'].shape or not np.isfinite(s).all() or (s<0).any():raise ValueError('Matching finite nonnegative scales required')
    values=NF4[codes]*s[np.arange(len(codes))//state['block']]
    return values.reshape(state['shape'])
def quantize_scales(scales):
    x=np.asarray(scales,float)
    if x.ndim!=1 or not x.size or not np.isfinite(x).all() or (x<0).any():raise ValueError('Positive scale vector required')
    mean=float(x.mean());center=x-mean;radius=float(np.max(abs(center)))
    codes=np.zeros(len(x),np.int8) if radius==0 else np.rint(127*center/radius).astype(np.int8)
    return codes,mean,radius,np.maximum(0,mean+codes.astype(float)*radius/127)
def objective(a,b,base,x,y):
    err=x@(base+b@a).T-y;g=err.T@x/len(x)
    return float(np.sum(err**2)/(2*len(x))),b.T@g,g@a.T

def demo():
    rng=np.random.default_rng(19);w=rng.normal(size=(6,6));state=encode(w);base=decode(state);before=state['packed'].copy();scales=state['scales'].copy()
    x=np.eye(6);desired=w+np.outer(np.linspace(-.5,.5,6),np.array([.3,-.4,.1,.7,-.2,.5]));y=x@desired.T
    a=rng.normal(0,.1,(2,6));b=np.zeros((6,2));history=[]
    for i in range(2001):
        loss,ga,gb=objective(a,b,base,x,y)
        if i%250==0:history.append(dict(step=i,loss=loss))
        if i<2000:a-=.3*ga;b-=.3*gb
    delta=desired-base;sv=np.linalg.svd(delta,compute_uv=False);dq=quantize_scales(scales)
    return dict(quantization_rmse=float(np.sqrt(np.mean((w-base)**2))),packed_bytes=int(state['packed'].nbytes),weight_count=w.size,scale_count=len(scales),scale_proxy_max_error=float(np.max(abs(dq[3]-scales))),proxy_weight_rmse=float(np.sqrt(np.mean((w-decode(state,dq[3]))**2))),initial_loss=history[0]['loss'],final_loss=history[-1]['loss'],rank2_oracle_loss=float(np.sum(sv[2:]**2)/12),frozen=bool(np.array_equal(before,state['packed']) and np.array_equal(scales,state['scales'])),trace=history,theoretical_bits=dict(single=4+32/64,double=4+8/64+32/(64*256)),scope='36 weights packed to18 bytes plus float64 scales; scale proxy is not paper FP8; cost formula ignores metadata and is not process memory; no paged optimizer or GPU kernel')
if __name__=='__main__':print(json.dumps(demo(),allow_nan=False))

The base quantization RMSE is approximately 0.0651617. The 36 codes occupy 18 bytes and require five block scales; the scale proxy’s maximum absolute error is approximately 0.00172632. Applying that proxy gives weight RMSE approximately 0.0652064. It slightly worsens this example, so a second compression stage is not numerically free.

The adaptation loss falls from approximately 0.0729648 to 0.00331415 in 2,000 updates. The rank-two SVD oracle for this identity-design regression is approximately 0.00331415 as well. Both task adaptation and compensation for quantization error contribute to the desired update. This is not evidence that an arbitrary low-rank adapter can eliminate all quantization error.

Tests recover every codebook entry, verify the exact packed byte sequence, handle odd counts and zero blocks, and compare each reconstruction against an independent nearest-code oracle. They check factor gradients by finite differences, the constant-scale boundary and the proxy error bound. The original packed bytes and scales remain unchanged throughout factor training.

Scanning a fixed 16-entry codebook costs O(P)O(P) for PP weights, with a constant factor from the codebook search. The demonstration reconstructs the entire matrix in float64 and retains it. A fused device kernel can use another memory strategy; our allocation cannot establish its peak memory or throughput.

Three savings mechanisms solve different problems

NF4 reduces base-weight storage. Double quantization reduces scale overhead. Paged optimizers use memory-management mechanisms to accommodate optimizer-state pressure; they do not make every tensor four-bit or remove all activation costs. None of these effects is measured by the small CPU program.

Outliers and distribution shifts can make a codebook or block size unsuitable. Weight RMSE alone does not determine task quality. Merging factors into a dequantized base and requantizing generally changes the function again; compare outputs under the actual deployment format.

The base-model license, adaptation weights and implementation code may also have different terms. The cached author repository links its implementation dependencies and model conditions; a code license alone does not grant arbitrary rights to every released model. No upstream training script is run or copied here.

Account for the missing bytes

  1. Why are 18 packed bytes insufficient to describe this complete 36-weight object? Answer: The code payload also needs five scale constants, shape, block size and the original count. This NumPy program additionally creates reconstructed arrays and training state.
  2. Calculate the ideal bits per weight for block size 64 before and after double quantization with second-level group size 256. Answer: 4+32/64=4.54+32/64=4.5 and 4+8/64+32/(64⋅256)=4.1269531254+8/64+32/(64\cdot256)=4.126953125. Their difference is 0.373046875, excluding the stated overheads.
  3. If a block contains only zeros, what should the encoder do? Answer: Use the exact zero code and zero scale, avoiding division by zero. Reconstruction remains exactly zero.
  4. Why does a frozen quantized base still participate in backpropagation? Answer: Its linear map affects gradients with respect to inputs and earlier trainable variables. Freezing its weight updates does not erase that Jacobian.

Test the complete precision and adaptation configuration

Dettmers and colleagues distinguish storage types, compute types and trainable factors, then evaluate the combined system. Hu and colleagues supply the low-rank update mechanism. Reproducing those systems requires their model, quantization, optimizer, data and evaluation conditions; a matching acronym is not sufficient.

Use small exact checks to establish indexing, reconstruction and gradient logic first. Then measure held-out task results and actual peak device memory for the intended implementation. Our code provides the former checks and a transparent regression, not the latter deployment evidence.

Make a prediction, then check

Does a4-bit QLoRA base imply that forward and backward matrix arithmetic is4-bit?

Choose one answer

Learning objectives

  • Separate quantized storage from matrix arithmetic precision.
  • Account for scale overhead and explain double quantization.
  • Test adaptation while keeping packed base weights fixed.

Prerequisites & connections

Explore related knowledge →

References

  1. QLoRA: Efficient Finetuning of Quantized LLMs — v1
    Tim Dettmers; Artidoro Pagnoni; Ari Holtzman; Luke Zettlemoyer · 2023
  2. LoRA: Low-Rank Adaptation of Large Language Models — v2
    Edward J. Hu; Yelong Shen; Phillip Wallis; Zeyuan Allen-Zhu; Yuanzhi Li; Shean Wang; Lu Wang; Weizhu Chen · 2021

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author read QLoRA v1 PDF4/5 section3 and AppendixE16 numerical code values; LoRA v2 PDF4/5. Seven paired equations and four explained exercises. Original NF4 nibble packing, nearest-code oracle, zero/odd blocks, frozen-code factor training, SVD bound and all factor gradients. Uniform integer scale proxy explicitly not FP8; float64 teaching, no BF16/paging/GPU benchmark.

  • Single AI author read QLoRA v1 PDF4/5 section3 and AppendixE16 numerical code values; LoRA v2 PDF4/5. Seven paired equations and four explained exercises. Original NF4 nibble packing, nearest-code oracle, zero/odd blocks, frozen-code factor training, SVD bound and all factor gradients. Uniform integer scale proxy explicitly not FP8; float64 teaching, no BF16/paging/GPU benchmark.
  • Four computed SVG variants per topic;11 numeric/geometry tests and36 responsive cases passed. Twelve selected captures checked:seven final directly viewed,five byte-identical to previously viewed images. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.