Green NLP: QuantizationGreen AI, Topic 2 · Universidade da Coruña
Contents

Start

Cátedra Inditex–UDC de Algoritmos Verdes

Microcredencial Algoritmos verdes para la IA: diseño e implementación

Green NLP: Quantization

Natural language processing · Topic 2 · Instructor: Olga Zamaraeva

CITIC, Universidade da CoruñaFunding
Before the activity

The task: answering questions about documents

documents
+ question
→
language
model
→
answer
→
right or wrong?
  • Input: a few short documents about green AI, and a question. The model must answer from the documents, in one short sentence.
  • Model: Qwen2.5-1.5B-Instruct, a small general-purpose language model
  • Score: an answer is right if it contains the reference answer as whole words, ignoring capital letters. Accuracy = right answers ÷ all questions.
  • Two runs: with the documents, and without them. What do the documents add to accuracy, and to energy?
questionWhat does the acronym PUE stand for?
referencepower usage effectiveness

The check is simple and cheap. It also misses right answers that use other words.

Activity · 60–75 minutes, individual

Notebook 01a: Baseline measurement

  • Answer questions about a small set of documents, measured with CodeCarbon: energy, CO₂eq and quality, as rows of your leaderboard
  • The same quiz with no documents: what does the model know on its own?

Notebook 01a, in Colab, with a GPU

  • In Colab: Runtime → Change runtime type → T4 GPU
  • Download leaderboard.csv at the end: the next notebooks add rows to it

The plan

The same tasks, the same model, one change

Baseline
baseline-fp16
16 bits per number
→
Quantized
gptq-int4 or bnb-int8-fallback
4 or 8 bits per number
  • The same documents, the same questions, the same scoring rule
  • The same model, Qwen2.5-1.5B-Instruct
  • One change: how many bits store each of the model's numbers. This is quantization.

Each run is one row of your leaderboard

qualityaccuracy: right answers ÷ questions
energykWh, measured by CodeCarbon
carbong CO₂eq, from that energy
timeseconds for the whole quiz
memorypeak GPU memory, GB (in the quantized rows only)

Weights are numbers

How the weights produce an answer

inputThe capital of Galicia isthe model: 28 layers of tables1.5 billion weights (parameters)output: probability of each next tokenbefore training: random0.0262 0.0260 0.0273 0.0132 ….games0.014%blood0.014%拿来0.014%让自己0.012%Santiago: 0.0005%, rank 80,055 of 151,936 tokensgold output: Santiagoloss: the distance from itgradient: how to change each weighttraining, as in Topic 1:repeated over huge amountsof textafter training0.0127 −0.0087 0.0013 0.0025 …Santiago18%____9%(7%the6%Santiago: rank 1 of 151,936 tokensTraining finds the weights, and they then stay fixed: every answer comes from those stored numbers
  • Qwen2.5-1.5B with its trained weights, and the same model with random weights

A model is a collection of numbers

token embeddingsattention: query, key, value tablesfeed-forward tables× 28 layersQwen2.5-1.5Bone corner of the first query table: 1,536 × 1,536 numbers0.0127−0.00870.00130.0025−0.0041−0.00030.0009−0.0025−0.01940.00500.0181−0.02540.00480.0192−0.0045−0.00090.01350.00560.00590.0483−0.00990.0138−0.00040.0005all the tables together: 1,543,714,304 numbersthese are the parameters, also called the weightsSet by training, then fixed. How is each number stored?

A computer stores every number as bits

Binary: the same place values as decimal, with powers of 2

1 1 0 1 2 8 4 2 1 worth = 1 × 8 + 1 × 4 + 0 × 2 + 1 × 1 = 8 + 4 + 0 + 1 = 13
  • A bit is 0 or 1
  • Each position is worth twice the one to its right: 1, 2, 4, 8, …
  • A model's parameters are numbers: billions of them, all stored as bits

Integers

1 bit012 values2 bits000110114 values3 bits0000010100111001011101118 valueseach extra bit doubles the values: 4 bits give 16, 8 bits give 256INT4−80716 whole numbersINT8−1280127256 whole numbersIntegers (INT): whole numbers, evenly spaced, one step apart

Can integers store the weights?

all the weights of Qwen2.5-1.5B's layers: how many have each value−0.15−0.1−0.0500.050.10.15the only whole number on this whole axis: 0−1 is far off to the left, +1 far off to the right99.8% of the weights lie between −0.1 and 0.1. As whole numbers, they would all be 0

A floating-point number has three parts

The IEEE 754 standard: sign, exponent, mantissa

sign exponent: 5 bits mantissa: 10 bits + or − the scale: × 2 to some power the detail: ½ + ¼ + … (added to 1)

value = sign × (1 + mantissa) × 2exponent − bias

  • FP16: a 16-bit floating-point number. FP32 uses 32 bits.
  • The next slides show where the 1 and the bias in this formula come from

Moving the point

worth8421½¼⅛.the number× a power of 21101.8 + 4 + 1 = 13× 1 = 131101.4 + 2 + ½ = 6.5× 2 = 131101.2 + 1 + ¼ = 3.25× 4 = 131101.1 + ½ + ⅛ = 1.625× 8 = 13Each move of the point to the left halves the number. The power of 2 doubles, and the result stays 13: × 1, × 2, × 4, × 8, which is 2⁰, 2¹, 2², 2³.
  • The place values continue past the point: each position is worth half the one to its left. The same happens in decimal: 13 = 1.3 × 10¹

Storing 13: the leading 1

13 in binary1101= 8 + 4 + 0 + 1Move the point1.101× 2³worth1½¼⅛the previous slide: 1.625 × 8The leading 1The point goes right after the first digit that is not 0. In decimal, that digit can be 1 to 9.In binary that digit is always 1 and need not be stored: one bit saved.

Storing 13: the bias

5 bits can hold01531worth168421smallest00000= 0largest11111= 16 + 8 + 4 + 2 + 1 = 31negative: cannot be stored2 to this powerexponents in FP16−140.00006−70.00801+38+1532,768−140.00006−70.00801+38+1532,768specialspecial818The exponent is stored in 5 bits, and 5 bits hold whole numbers from 0 to 31Small numbers need negative exponents: 0.01 = 1.28 × 2⁻⁷FP16 covers small and large numbers: exponents −14 to +15, sizes 0.00006 to 32,768The bias: add 15 to every exponent. They fill 1 to 30, and 0 and 31 stay specialStored value = exponent + 15: −7 is stored as 8, +3 as 1813 in FP160116080412011010000000+stored: 16 + 2 = 18mantissa: the digits after the point, 101, then zerosstoring13 = 1.625 × 2³: exponent 3 → 3 + 15 = 18 → bits 10010readingbits 10010 = 18 → 18 − 15 = 3 → 1.625 × 2³ = 13

Two exponent values are kept for special cases

exponent bitsmantissa bitswhat the bits meanits valuestored 0stored 1 to 30stored 31000000000000000mantissa all 0: zero(0 + 0) × 2⁻¹⁴ = 0000000000000001any other: the tiniest numbers(0 + mantissa) × 2⁻¹⁴100101010000000any mantissa: ordinary, here 13(1 + mantissa) × 2stored − 15111110000000000mantissa all 0: infinitya result too large: above 65,504111110000000001any other: NaN, “not a number”a result with no value: 0 ÷ 0Only stored 0 and stored 31 are special. Every other exponent value is an ordinary number

One weight in FP16

a weight: the first number of the query table we saw, shown there rounded to 0.01270.01269531…= 1.625 × 2⁻⁷0010001010000000sign: +stored: 8, meaning 8 − 15 = −7mantissa: 101, then zerosThe mantissa is the same as for 13: 1 + ½ + ⅛ = 1.625Only the exponent differs: 2³ for 13, 2⁻⁷ for this weightEvery one of the 1.5 billion weights is stored like this: 16 bits each

FP16 can store only some numbers

16 bits0016180402011010000000½¼⅛+8 − 15 = −71 + ½ + ⅛ = 1.625+ 1.625 × 2⁻⁷ = 0.01269531250.01269530.01268770.01270290.01271060.01271820.0127258step: 0.00000760.01272 is not representable: it is stored as 0.012718216 bits make 65,536 combinations, and each combination stands for one numberEach tick is a representable number: one that FP16 can store. Nothing in between can be storedThe step is the distance from one representable number to the nextFP16 rounds any other number to the nearest representable number

Precision is a number of digits

3 digits, as in scientific notationon the number line: the distance to the next number1.23× 10⁻²= 0.01230.01230.01240.01250.00011.23× 10⁴= 12,30012,30012,40012,500100FP16 keeps about 3 digits in the same way1.625 × 2⁻⁷ = 0.01269530.01269530.01270290.01271060.00000761.953125 × 2⁹ = 1,0001,0001,000.51,0010.5Precision is a number of digits, not a distance: the last digit of a small number is worth very little

Formats side by side

10⁻⁴⁰10⁻³⁰10⁻²⁰10⁻¹⁰110¹⁰10²⁰10³⁰10⁴⁰the size of a number← smaller than 1larger than 1 →INT44 bits1 to 7INT88 bits1 to 127FP1616 bits6 × 10⁻⁸ to 65,504FP3232 bits10⁻⁴⁵ to 3.4 × 10³⁸BF1616 bits10⁻⁴⁰ to 3.4 × 10³⁸Qwen2.5-1.5B's weights: 97% lie between 0.001 and 0.1Other models differ in the details, but transformer weights are generally far below 1: training starts them near 0.FP16 covers such weights; INT8 and INT4 alone do not, because whole numbers start at 1.More exponent bits give a wider range: BF16 reaches as far as FP32 with half the bits.
  • A scale of sizes: each gridline is × 10¹⁰. 1 is in the middle, and 0 is not on it. Each float format stores the same sizes with a minus sign too
  • More mantissa bits give more precision: about 7 digits in FP32, 3 in FP16, 2 in BF16
Interactive

Flip the bits

Quantization and memory

What quantization is

six weights from the corner of the first query table, on the number linestored in 16 bits0.0127−0.00870.00130.0025−0.0041−0.0003rounded to steps of 0.00215 levels: 4 bits (2⁴ = 16)−0.012−0.010−0.008−0.006−0.004−0.00200.0020.0040.0060.0080.0100.0120.0140.016rounded to steps of 0.013 levels: 2 bits (2² = 4)−0.01000.010Quantization: store each weight with fewer bits, by rounding it to the nearest levelFewer bits give fewer combinations, and fewer levels. Each weight moves to its nearest level (the red lines): fewer levels, longer movesorange ticks: quantization levels, the numbers that can be stored

Memory for the weights of our model

Qwen2.5-1.5B-Instruct: 1.5 billion weights (parameters), not the attention weights of Topic 1

1.5 × 109​ parameters × 16 bits1parameter = 24 × 109​ bits × 1 byte8bits = 3 × 109​ bytes = 3 GB
6 GBFP32
32 bits
3 GBFP16
16 bits
1.5 GBINT8
8 bits
0.75 GBINT4
4 bits

The weights only. Running the model also needs memory for its intermediate values.

Try it · about 10 minutes

Which models fit on a 16 GB GPU?

The Python here runs in your browser. The first Run loads Python, which takes a few seconds.The same exercise as a notebook: beginner · advanced (Colab)

Replace each ___ with code. Run shows what your code prints. Run the tests also checks it and says what to fix.

Exercise 1 · Weight memory

Complete weight_memory_gb: memory in gigabytes = parameters × bits ÷ 8, divided by 109 bytes per GB. Then the loop checks 7B, 32B and 70B models in FP16, INT8 and INT4 against the 16 GB of a Colab T4. Ignore everything except the weights.

Hints
  • params_billion * 1e9 is the number of parameters.
  • Bits ÷ 8 gives bytes; bytes ÷ 1e9 gives gigabytes.
  • A model fits if its weights take less than the GPU's memory.

When quantization decides whether a model fits

Weight memory = parameters × bits ÷ 8, against the 16 GB of a Colab T4

7B32B70B FP16 14 GB INT8 7 INT4 3.5 FP16 64 GB INT8 32 INT4 16 FP16 140 GB INT8 70 INT4 35 16 GB: the whole GPU
  • 7B: all three fit. FP16, 14 GB, leaves almost no room for anything else.
  • 32B: only INT4 comes close, and it takes the whole GPU: in practice it does not fit.
  • 70B: none fits. Even INT4 needs more than twice the GPU.
  • Past some size, quantization is the only way to run a model on given hardware; past a larger size, it is no longer enough.

How model quality depends on the bits per weight

share of the next words the model guesses rightWhat is the capital of Galicia?0%25%50%16865432bits per weight44%16 bits… Santiago.44%8 bits… Santiago.44%6 bits… Santiago.44%5 bits… Santiago de Compostela.37%4 bits… Madrid.1%3 bitsbjectargestấ.Remotez哉Zуate…0%2 bitslànhasan[rand/std的背后樗搦icon…Each weight changes a little, and the changes of 1.3 billion weights add up: quality holds, then collapses
  • Qwen2.5-1.5B, rounded with absmax, the method of the next slides, on the text of the course notes. The methods later in this topic keep more quality at 4 bits

Absmax quantization

From weights to integer codes

the weights−0.1500.15INT4 codes−7−6−5−4−3−2−10123456736% of the weights fall in this one interval, and all get the code 0: many values, one code
  • Each weight is replaced by the code of its interval. Stored: the small integers, plus one number, the scale, to turn the codes back into weights. This is why it is lossy: inside an interval, weights can no longer be told apart

Absmax quantization

weights x00.0009−0.0025−0.01940.00500.0181−0.0254−α+αα = max |x|= 0.0254codes−7−6−5−4−3−2−101234567b: bits per weights = (2b−1 − 1) ÷ α4 bits: 7 ÷ 0.0254= 275.6x × scode = round(x × s)dequantize: code ÷ s
  • Six weights and INT4: the codes run to 7. With INT8 they run to 127: the codes are 18 times closer together. Zero stays exactly zero
Interactive

Fewer bits, fewer codes

Try it · about 15 minutes for both exercises

Absmax from scratch

The Python here runs in your browser, with NumPy. The first Run loads Python, which takes a few seconds.The same exercises as a notebook: beginner · advanced (Colab)

Replace each ___ with code. Do the exercises in order: the second one uses your first function.

Exercise 2 · Quantize and dequantize

Complete absmax_quantize and absmax_dequantize. qmax is the largest code of a signed bits-bit integer: 127 for 8 bits. alpha is the largest absolute value. The scale maps alpha to qmax. The cell should print the codes 64, 36, −89, 0, −22, −54, 127, 36, −23.

Hints
  • A signed bits-bit integer goes up to 2bits − 1 − 1.
  • np.abs(x) gives absolute values; np.max the largest one.
  • scale = qmax / alpha. Quantize: multiply by the scale, then round. Dequantize: divide by it.

Exercise 3 · Sweep the bit widths

Quantize the same values with 8, 4, 3 and 2 bits. For each, count the distinct codes the values use, and compute the mean and the largest absolute error.

Hints
  • set(q.tolist()) keeps each code once; len counts them.
  • The error of each value is values - dq; take np.abs of it first.

Choosing the range

Values not centered on 0: asymmetric quantization

An illustration, with values from −1 to 3

values−3−103β: smallest value, −1α: largest value, 3absmax−7−6−5−4−3−2−1012345675 codes never usedasymmetric0123456789101112131415every code in use: s = (2b − 1) ÷ (α − β) = 15 ÷ 4zero point z = round(−β × s) = round(3.75) = 4: the code of the value 0, stored with the scale
  • Both rows use INT4 codes. Weights center on 0, and absmax suits them; one-sided values do not, like the outputs of ReLU, a common step inside networks that replaces every negative value with 0

One large weight stretches the range for all

Absmax:α = max |x|s = 7 ÷ αcode = round(x × s)Every weight is multiplied by the same s. Follow one weight: x = 0.0483Both rows: the weights on one number lineif the largest weight were 0.15s = 7 ÷ 0.15 = 46.7the range: −0.15 to 0.15, with 15 codes−0.150.15largest: 0.15 × 46.7 = 70.0483 × 46.7 = 2.25round(2.25) = code 2the largest weight is 3.06s = 7 ÷ 3.06 = 2.29weightcode−3.06−7−2.62−6−2.19−5−1.75−4−1.31−3−0.88−2−0.44−1000.4410.8821.3131.7542.1952.6263.067largest: 3.06 × 2.29 = 7the range: −3.06 to 3.06, the same 15 codes0.0483 × 2.29 = 0.11, round(0.11) = code 0pink area: x × s below 0.5, rounded to code 0One large weight stretches the range: s shrinks, the codes move apart, and nearly every weight rounds to 0
  • The blue shape: how many weights have each value. On the real model, with one s for all its weights and 4 bits, 99.99% of the weights get the code 0
Interactive

Clip the range

What activations are

A neural network: neurons (circles) in layers. Every line between two neurons has a weightinputhidden layeroutputtable of weightstable of weightsx₁x₂x₃xₙw₁w₂w₃wₙThe activation of one neuron: a = f(w₁x₁ + w₂x₂ + … + wₙxₙ + b)ax₁ … xₙthe activations of the layer beforew₁ … wₙthe weights on the lines into the neuronbthe bias of the neuronfthe activation function, for example ReLU: negative sums become 0athe activation: the output of the neuronx₁ = 0.5w₁ = 0.4x₂ = −1.0w₂ = −0.3x₃ = 2.0w₃ = 0.2x₄ = 1.0w₄ = 0.10.80One neuron, worked through, with four inputs:w₁x₁ = 0.4 × 0.5 = 0.20w₂x₂ = −0.3 × (−1.0) = 0.30w₃x₃ = 0.2 × 2.0 = 0.40w₄x₄ = 0.1 × 1.0 = 0.10add the bias b = −0.2:0.20 + 0.30 + 0.40 + 0.10 − 0.20 = 0.80f = ReLU: 0.80 is not negative, it staysa = 0.80: this number goes on to the next layerx₁ = −0.19x₂ = −0.81x₃ = 0.33xₙ = −0.26w₁w₂w₃wₙThe river flows through…−0.00140.0083−0.0302−0.01040.00−0.17−0.07−4.980.06−0.12−0.010.27two weighted sums of the x: 3.343 and −1.542a = f(3.343) × (−1.542) = 3.229 × (−1.542) = −4.98inputhidden layeroutputtable of weightstable of weights12 + 7 = 19, 3 × 8 = …−0.00140.0083−0.0302−0.01040.050.440.15−0.200.190.17−0.120.03x₁ = −0.04x₂ = 0.53x₃ = −0.45xₙ = 0.68w₁w₂w₃wₙtwo weighted sums of the x: 0.455 and −0.716a = f(0.455) × (−0.716) = 0.279 × (−0.716) = −0.20The same weights, different inputs x₁ … xₙ: different sums and different activations, computed in every run
  • The numbers: 8 of the 8,960 hidden neurons in the feed-forward part of layer 15 of Qwen2.5-1.5B, with n = 1,536 inputs, at one token of each input (“near” and “2”). Green: the weights from the red neuron to the first four outputs
  • A neuron in this layer computes two weighted sums of its inputs, with two sets of weights and no bias, and multiplies f of the first sum by the second sum. Here f is SiLU, a smooth variant of ReLU

Activations: dynamic and static quantization

The river flows through…largest activation: 4.98−10−50510−4.98for i in range(10): …largest activation: 6.92−10−505106.92clipped12 + 7 = 19, 3 × 8 = …largest activation: 9.05−10−505109.05clippedcalibration dataEach input gives different activations: their largest value α is known only when the input arrivesDynamic quantization computes α for each input: the range covers all its activations, and every run does extra workStatic quantization fixes α in advance, from sample inputs: no extra work, and activations outside the range are clipped
  • The blue shapes: how many activations have each value, in the hidden layer of layer 15 of Qwen2.5-1.5B (square-root scale). Orange: the range from −α to α
Try it · about 20 minutes for both exercises

The zero point and clipping

These exercises use your absmax_quantize and absmax_dequantize from Exercise 2. Run that cell first.

Exercise 4 · Asymmetric quantization

Complete asymmetric_quantize and asymmetric_dequantize. The codes run from 0 to 2bits − 1. The scale s = (2bits − 1) ÷ (α − β) works as in absmax: values are multiplied by it. The zero point is the code that stands for 0.0. The cell compares both methods on one-sided values, at 4 bits.

Hints
  • In the code, α is xmax and β is xmin.
  • Quantize: multiply by the scale, then add the zero point.
  • Dequantize: subtract the zero point, then divide by the scale.

Exercise 5 · Clip before quantizing

Complete quantize_with_clipping: limit every value to [−clip, clip], then quantize with absmax. The loop compares no clipping with three clipping ranges on the 24 ordinary values and the outlier.

Hints
  • np.clip(x, low, high) replaces values below low with low and above high with high.

Methods used in practice

GPTQ: the idea

GPTQ: quantization for GPT models, generative pre-trained transformers

The original weightsx₁2x₂1Σ0.37 × 2 = 0.740.52 × 1 = 0.52y = 1.260.000.250.500.751.00w₁w₂0.370.52the weights and the quantization levels (orange marks)Each weight to its nearest levelx₁2x₂1Σ0.25 × 2 = 0.500.50 × 1 = 0.50y = 1.00error −0.260.000.250.500.751.00w₁w₂GPTQ: one weight at a timex₁2x₂1Σ0.000.250.500.751.00w₁w₂0.25 × 2 = 0.500.52 × 1 = 0.52y = 1.02lost 0.240.76 × 1 = 0.76y = 1.26+ 0.240.75 × 1 = 0.75y = 1.25error −0.01The next layer receives the output y = 1.26. The goal of GPTQ: keep y, even if a weight has to changeBoth weights go down, and their errors add up in y: 1.00 instead of 1.26GPTQ rounds w₁ first. y loses 0.37 − 0.25 = 0.12, times x₁ = 2: 0.24. w₂ is not rounded yetw₂ is raised to make up for the loss: 0.52 + 0.24 = 0.76, and y is 1.26 againThen w₂ is rounded: 0.75. It is far from 0.52, and y is close to 1.26
  • In a real table, each output has many weights, and the inputs change from run to run. GPTQ takes its x from the calibration data, and after each rounding it changes all the weights not yet rounded, to keep the outputs close on average over those inputs
  • For two weights, the correction is w₂ + (w₁ − rounded w₁) × x₁ ÷ x₂. With it, GPTQ reaches 4 bits per weight with little loss, without retraining

Frantar et al., “GPTQ: Accurate post-training quantization for generative pre-trained transformers,” ICLR 2023

Interactive

Watch GPTQ correct the next weight

GGUF: one scale per block of weights

GGUF (GGML Universal File): the file format of llama.cpp, a program that runs language models on laptops and CPUs. GGML is its library for computing with tables of numbers

96 neighboring weights in one row of a table, as bars: the height is the size of the weightone α for all: 3.06block 1: 32 weightsblock 2: 32 weightsblock 3: 32 weightsα = 0.50, s = 7 ÷ 0.50α = 3.06, s = 7 ÷ 3.06α = 0.29, s = 7 ÷ 0.29One large weight sets α for the whole row: next to it, the others look like 0Cut the row into blocks: short runs of neighboring weights, here 32 eachEach block gets its own α and s: the large weight now sets the scale of its own block onlyEach scale takes 16 bits: (32 × 4 + 16) ÷ 32 = 4.5 bits per weight
Interactive

Smaller blocks: less error, more bits

Quantizing after training, or during it

Post-training quantization (PTQ)every method so far: absmax, GPTQ, GGUF blockstrain with full-precision weights (16 or 32 bits)quantizeminutes to hoursQuantization-aware training (QAT)train with the rounding already in placea full training runweight,full precisionroundedweightforward passand lossupdate thefull-precision weightPTQ rounds a finished model: the weights are not trained further after roundingQAT includes the rounding in trainingThe loss is computed with the rounded weights: training finds weights that keep the loss low after rounding
Reminder

Start the installs for Notebook 02a now

The installs take a while: they can run in the background during the next slides

  1. Open Notebook 02a in Colab
  2. Runtime → Change runtime type → T4 GPU
  3. Run the first code cell, then the install cell in Step 0
  4. When the install cell finishes: Runtime → Restart session, once
  5. Leave the notebook open: we come back to it after the discussion

Notebook 02a, in Colab, with a GPU

Rounding after training: how few bits are possible?

Qwen2.5-1.5B with its layer weights rounded after training16 bits8 bits4 bits3 bitsmemory for the weights (GB)2.621.310.660.49next tokens of a text guessed right44.2%44.5%36.8%0.59%What is the capital of Galicia?The capital of Galicia is Santiago.The capital of Galicia is Santiago.The capital of Galicia is Madrid.bjectargest.R …BitNet is a language model built to go lower: 1.58 bits per weight, with the rounding in place from the first training step.Fewer bits: less memory for the same weightsRounded after training, the model stops working below 4 bitsThe answers show it: at 4 bits the model is wrong, and at 3 bits it writes no languageTo go below 4 bits, the rounding has to be part of the training
  • The rounding: absmax with one scale for each row of a table. The text: the course notes, 2,048 tokens

BitNet: the idea

Every weight has one of three levels: −1, 0 or +1 (ternary weights)−10+1b bits give 2ᵇ levels. Three levels:2ᵇ = 3, and b = log₂ 3 = 1.58 bits per weightx₁0.5x₂−1.0x₃2.0x₄1.0Σw₁ = 0.4w₂ = −0.3w₃ = 0.2w₄ = 0.1The neuron from “What activations are”, with its four weightsthe scale γ: the average size of the weights in the tableγ = (0.4 + 0.3 + 0.2 + 0.1) ÷ 4 = 0.25ww ÷ γnearest levelw₁0.41.6+1w₂−0.3−1.2−1w₃0.20.8+1w₄0.10.40The original weights0.4 × 0.5 = 0.20−0.3 × (−1.0) = 0.300.2 × 2.0 = 0.400.1 × 1.0 = 0.101.00y = w₁x₁ + w₂x₂ + w₃x₃ + w₄x₄y = 0.20 + 0.30 + 0.40 + 0.10 = 1.00The levelsx₁0.5x₂−1.0x₃2.0x₄1.0+1: add 0.5−1: subtract −1.0+1: add 2.00: leave outΣ3.5each weight is γ × its level:y = γ × (+1) × x₁ + γ × (−1) × x₂ + γ × (+1) × x₃ + γ × 0 × x₄y = γ × (x₁ − x₂ + x₃)× 0.25 = 0.875γ = 0.25y = 0.25 × (0.5 − (−1.0) + 2.0) = 0.25 × 3.5 = 0.875Absmax with 4 bits has 16 levels. BitNet uses only threeDivide and round as in absmax, with the average size of the weights in place of the largestOriginal weights: one multiplication for each inputLevels: every input is added, subtracted or left out, with no multiplicationOne multiplication for the whole neuron, by γ. The result, 0.875, is close to 1.00
  • In a real model, γ is the average over all the weights in one table. The activations x are rounded too: to 8-bit integers with absmax, measured for each token in every run
  • 1.58 bits is the smallest possible size. On a GPU, BitNet stores four weights in one 8-bit integer: 2 bits per weight

Ma et al., “The era of 1-bit LLMs: all large language models are in 1.58 bits,” 2024; Ma et al., “BitNet b1.58 2B4T technical report,” arXiv:2504.12285, 2025

BitNet training: the forward pass

the full-precision copy of each weightw₁ = 0.4w₂ = −0.3w₃ = 0.2w₄ = 0.1γ = (0.4 + 0.3 + 0.2 + 0.1) ÷ 4 = 0.25w ÷ γ−2−10120.4 ÷ 0.25 = 1.6−0.3 ÷ 0.25 = −1.20.2 ÷ 0.25 = 0.80.1 ÷ 0.25 = 0.4circle: w ÷ γ; square: its levellevel −1level 0level +1−½½0.5−1.02.01.0one training example: the inputs x and the desired output 1.5inputs xΣ+1: add 0.5−1: subtract −1.0+1: add 2.00: leave out0.5 − (−1.0) + 2.0 = 3.53.5 × 0.25 = 0.875desired output: 1.5error: 0.875 − 1.5 = −0.625loss: ½ × error² = 0.195During training, BitNet keeps a full-precision copy of each weightThe scale γ is the average size of the copiesEach copy is divided by γ and placed on its lineEach value goes to its nearest level: −1, 0 or +1. The orange marks are halfway between the levelsThe levels are the weights of the forward pass: they add an input, subtract it, or leave it outThe inputs are summed, and the sum is multiplied by γ: the output y of the neuronThe training example says y should be 1.5. The loss measures how far y is from that
  • A training example is a pair: the inputs, and the output the model should give for them. Training data supplies both. In a language model, the inputs come from the tokens of a text, and the desired output is the next token of that text
  • The example here is invented for the calculation: 1.5 is the output this neuron should learn to give for these four inputs

BitNet training: the update

The output of the forward pass00.511.52yy = 0.875desired: 1.5error = y − desired = −0.625loss = ½ × error² = 0.195As if the copies were the weights: y = w₁x₁ + w₂x₂ + w₃x₃ + w₄x₄weightinput xif w rises by 1, y …w₁ = 0.40.5rises by 0.5w₂ = −0.3−1.0falls by 1.0w₃ = 0.22.0rises by 2.0w₄ = 0.11.0rises by 1.0gradient = error × x(−0.625) × 0.5 = −0.3125(−0.625) × (−1.0) = +0.625(−0.625) × 2.0 = −1.25(−0.625) × 1.0 = −0.625change = −0.1 × gradientthe copy of wnew w = w − 0.1 × gradient (0.1 is the learning rate)−0.1 × (−0.3125) = +0.031250.4313−0.1 × 0.625 = −0.0625−0.3625−0.1 × (−1.25) = +0.1250.3250−0.1 × (−0.625) = +0.06250.1625y is too small: the forward pass gave 0.875 and the desired output is 1.5. The update has to raise yEach weight affects y through its input: raising w₂ lowers y, because x₂ is negativeThe gradient says how the loss changes when w rises. Negative: raising w lowers the lossEach copy moves against its gradient. The largest input, x₃ = 2, gives the largest changew₄ had level 0 and added nothing to y, but its copy moves too: the update ignores the rounding
  • The loss is ½ × error². Its gradient for each weight is error × x, if the copies are treated as the weights. Rounding itself has a gradient of 0 almost everywhere, which would stop all updates: treating the copies as the weights is the way around it (the straight-through estimator)

BitNet training: the next forward pass

the full-precision copies after the updatew₁ = 0.4313w₂ = −0.3625w₃ = 0.3250w₄ = 0.1625new γ = (0.4313 + 0.3625 + 0.3250 + 0.1625) ÷ 4 = 0.3203w ÷ γ−2−10120.4313 ÷ 0.3203 = 1.35−0.3625 ÷ 0.3203 = −1.130.3250 ÷ 0.3203 = 1.010.1625 ÷ 0.3203 = 0.51circle: w ÷ γ; square: its levellevel −1level 0level +1−½½0.5−1.02.01.0the same training example: the inputs x and the desired output 1.5inputs xΣ+1: add 0.5−1: subtract −1.0+1: add 2.0+1: add 1.00.5 − (−1.0) + 2.0 + 1.0 = 4.54.5 × 0.3203 = 1.441desired output: 1.5error: 1.441 − 1.5 = −0.059loss: ½ × error² = 0.002The update changed the copies. The next forward pass starts from themThe copies are larger: γ is larger tooEach copy is divided by the new γ. The hollow circles show the values before the updatew₄ is now past the orange mark: its level changes from 0 to +1. The other levels stayThe levels are the weights of this forward pass, and x₄ is now addedThe sum is larger, and γ is larger: y goes from 0.875 to 1.441The loss falls from 0.195 to 0.002. Training repeats these steps on new data
  • This is QAT with three levels. The model that runs after training keeps only the levels and the scale γ of each table

Which method, when

MethodWhen it is usedCost
Absmax, zero point (PTQ)8 bits; the basic building block of every methodalmost none
Dynamic quantization (PTQ)activations whose range changes a lot from input to inputextra work in every run
Static quantization (PTQ)fast inference, when representative calibration data existsa calibration run
GPTQ4 bits on a GPU, without retrainingcalibration, layer by layer
GGUF block formatsrunning models on laptops and CPUsone scale per block
QATthe best accuracy at low precision, when training is affordabletraining
BitNeta model trained with three-level weightstraining from scratch

Is it worth it?

What measurements show

Two recent studies, on very different hardware

Study and settingFinding
Shi & Ding (2025): 11 quantization methods, models of 7B to 70B parameters, A100 and H100 GPUsenergy efficiency up to 30% better (34B models)
waiting time (latency) of the slowest responses up to 70% shorter
code generation (HumanEval): share of generated programs that pass their tests, down by up to 92% for the 13B model; smaller models lose more quality
Husom et al. (2025): 28 quantized models, a Raspberry Pi 43- and 4-bit models used up to 79% less energy than 16-bit ones
for Qwen2.5 1.5B, our model: every 3-bit version used more energy per token than the 4-bit ones

Shi & Ding, “Systematic characterization of LLM quantization: a performance, energy, and quality perspective,” arXiv:2508.16712; Husom et al., “Sustainable LLM inference for edge AI,” ACM Transactions on Internet of Things 6(4), 2025, doi:10.1145/3767742

The hardware has to support the format

Peak throughput of the NVIDIA T4, the GPU in Colab, from its datasheet

FP328.1 TFLOPS
FP1665 TFLOPS
INT8130 TOPS
INT4260 TOPS

TFLOPS, TOPS: trillions of floating-point or integer operations per second

  • The T4 has special circuits, tensor cores, for 16-, 8- and 4-bit numbers
  • These are peak numbers: real runs are slower, and memory is often the limit
  • A format the hardware or the software cannot use directly is unpacked first: smaller, but not faster
Discussion · 10–15 minutes

When is quantization not worth it?

When would quantization not be worth it? Think of:

  • hardware or software that cannot compute in the lower precision
  • too few bits for the task: code, arithmetic, rare words
  • a small model, already close to its quality limit
  • calibration data unlike the real inputs
  • a quality check too weak to notice what broke

Discuss with your neighbor, then with the room.

Your turn

What we run

The same model family, two ways to load it with fewer bits

config in the leaderboardwhat is loaded
baseline-fp16Notebook 01a: Qwen2.5-1.5B-Instruct, 16 bits
gptq-int4first try: Qwen/Qwen2.5-1.5B-Instruct-GPTQ-Int4, quantized by the Qwen team with GPTQ
bnb-int8-fallbackif GPTQ does not install: the 16-bit model, quantized to 8 bits as it loads, with the bitsandbytes library
  • The same layers, the same tokens (pieces of words), the same training: only the stored numbers change
  • The software that computes with them changes too: the configuration is recorded with every row
  • gptq-int4 and bnb-int8-fallback are two different configurations: compare like with like
Activity · 90–125 minutes, individual

Notebook 02a: Quantized measurement

  1. Upload your three CSV files: leaderboard.csv (Notebook 01a), mt_leaderboard.csv and mt_eval_leaderboard.csv (Notebook 01e); without them, the notebook starts new ones
  2. Load the quantized model: GPTQ first, then the fallback
  3. Run the same eight questions with CodeCarbon, and score them the same way
  4. Append a row to leaderboard.csv and compare it with your baseline
  5. Translate the Galician passage again; grade it with BLEU, BERTScore and two LLM judges

Notebook 02a, in Colab, with a GPU

  • In Colab: Runtime → Change runtime type → T4 GPU
  • If you have not run the install cell yet: run it, then Runtime → Restart session, once
  • Download the three CSV files again before you close Colab

Share-out: what changed?

Compare your two rows

  • Which configuration loaded: gptq-int4 or bnb-int8-fallback?
  • Accuracy: the same as the baseline?
  • Energy and CO₂eq: lower, the same, higher?
  • Time? Peak memory (quantized rows only)?
  • The translation: did it change in a way a reader would notice?

Then compare with your neighbor

  • Same configuration, same numbers?
  • Run the quiz twice: how much do your own numbers vary between runs?

What comes next

Topics 2 and 3

Topic 2

  • A number is stored as bits; fewer bits, less memory
  • Quantization: scale, round, store the codes; rounding adds error
  • The range decides the error: outliers, clipping, the zero point, blocks
  • Savings and losses depend on the model, the task and the hardware: measure them

Topic 3: retrieval

Topic 2
baseline
→
Topic 2
fewer bits
→
Topic 3
less text
  • The same 16-bit model, given only the relevant documents

Thank you for your attention

Cátedra Inditex–UDC de Algoritmos Verdes
catedrainditexalgoritmosverdes.com
Contents
0:00