intuitiveai

Quantization & LoRA

Two different ways to save memory

LoRA freezes a base weight matrix and trains a low-rank update. Quantization stores an approximation of weights using fewer bits. They solve different problems: adapter capacity versus representation cost. QLoRA combines a frozen quantized base with trainable adapters; four-bit storage does not mean every computation uses four bits.

Start with matrix shapes and linear layers. In this lesson, use a tiny matrix to understand the forward pass before considering a GPU-sized model.

Initializing Interactive Playground...

Follow every matrix

Use a column input x=[2,1], W=[[1,0],[0,1]], A=[[1,−1]], B=[[0.5],[−0.5]], rank=1 and alpha=2. A has shape 1×2; B has shape 2×1. First Ax=1. Then BAx=[0.5,−0.5]. Scale by alpha/r=2 and add Wx: y=[3,0].

Merging gives Wmerged=[[2,−1],[−1,2]], whose product with x is also [3,0]. If you keep adding the adapter after merging, you get [4,−1]: the update was counted twice. The lab checks both paths and that the original W stays unchanged.

This tiny rank-one adapter has four parameters, as many as W itself. Savings appear when r(d_in+d_out) is much smaller than d_in×d_out. For a 4096×4096 projection and rank 8, the adapter has 65,536 entries—not a 99.6% reduction in total training memory.

Measure the approximation

For signed four-bit symmetric quantization, this lab chooses codes −7…7. With max absolute weight 1, scale=1/7. A weight 0.3 rounds to code 2 and returns as 2/7≈0.285714. Adding an outlier 10 changes the shared scale to 10/7, rounding 0.3 to zero. Per-block scaling can reduce this damage but needs more metadata.

Compare base, adapter, quantized base and quantized-plus-adapter outputs on the same held-out input. Measure output error as well as weight error. This is uniform quantization, not NF4, and Python floats do not demonstrate actual packed storage or GPU speed.

Experiment notes

Record your experiment

Keep four-bit precision and turn on the outlier. Predict the reconstructed value of 0.3. Then change adapter rank and explain why the quantization error does not change.

Feedback & sharing

Helpful?