Start

Microcredencial Algoritmos verdes para la IA: diseño e implementación
Green NLP: Quantization
Natural language processing · Topic 2 · Instructor: Olga Zamaraeva


The task: answering questions about documents
+ question
model
- 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?
| question | What does the acronym PUE stand for? |
|---|---|
| reference | power usage effectiveness |
The check is simple and cheap. It also misses right answers that use other words.
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-fp16
16 bits per number
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
| quality | accuracy: right answers ÷ questions |
|---|---|
| energy | kWh, measured by CodeCarbon |
| carbon | g CO₂eq, from that energy |
| time | seconds for the whole quiz |
| memory | peak GPU memory, GB (in the quantized rows only) |
Weights are numbers
How the weights produce an answer
- Qwen2.5-1.5B with its trained weights, and the same model with random weights
A model is a collection of numbers
A computer stores every number as bits
Binary: the same place values as decimal, with powers of 2
- 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
Can integers store the weights?
A floating-point number has three parts
The IEEE 754 standard: sign, exponent, mantissa
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
- 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
Storing 13: the bias
Two exponent values are kept for special cases
One weight in FP16
FP16 can store only some numbers
Precision is a number of digits
Formats side by side
- 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
Flip the bits
Quantization and memory
What quantization is
Memory for the weights of our model
Qwen2.5-1.5B-Instruct: 1.5 billion weights (parameters), not the attention weights of Topic 1
The weights only. Running the model also needs memory for its intermediate values.
Which models fit on a 16 GB GPU?
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 * 1e9is 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
- 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
- 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
- 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
- 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
Fewer bits, fewer codes
Absmax from scratch
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.maxthe 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;lencounts them.- The error of each value is
values - dq; takenp.absof it first.
Choosing the range
Values not centered on 0: asymmetric quantization
An illustration, with values from −1 to 3
- 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
- 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
Clip the range
What activations are
- 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 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 α
The zero point and clipping
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
xmaxand β isxmin. - 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 belowlowwithlowand abovehighwithhigh.
Methods used in practice
GPTQ: the idea
GPTQ: quantization for GPT models, generative pre-trained transformers
- 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
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
Smaller blocks: less error, more bits
Quantizing after training, or during it
Start the installs for Notebook 02a now
The installs take a while: they can run in the background during the next slides
- Open Notebook 02a in Colab
- Runtime → Change runtime type → T4 GPU
- Run the first code cell, then the install cell in Step 0
- When the install cell finishes: Runtime → Restart session, once
- 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?
- The rounding: absmax with one scale for each row of a table. The text: the course notes, 2,048 tokens
BitNet: the idea
- 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
- 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 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
- 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
| Method | When it is used | Cost |
|---|---|---|
| Absmax, zero point (PTQ) | 8 bits; the basic building block of every method | almost none |
| Dynamic quantization (PTQ) | activations whose range changes a lot from input to input | extra work in every run |
| Static quantization (PTQ) | fast inference, when representative calibration data exists | a calibration run |
| GPTQ | 4 bits on a GPU, without retraining | calibration, layer by layer |
| GGUF block formats | running models on laptops and CPUs | one scale per block |
| QAT | the best accuracy at low precision, when training is affordable | training |
| BitNet | a model trained with three-level weights | training from scratch |
Is it worth it?
What measurements show
Two recent studies, on very different hardware
| Study and setting | Finding |
|---|---|
| Shi & Ding (2025): 11 quantization methods, models of 7B to 70B parameters, A100 and H100 GPUs | energy 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 4 | 3- 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
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
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 leaderboard | what is loaded |
|---|---|
| baseline-fp16 | Notebook 01a: Qwen2.5-1.5B-Instruct, 16 bits |
| gptq-int4 | first try: Qwen/Qwen2.5-1.5B-Instruct-GPTQ-Int4, quantized by the Qwen team with GPTQ |
| bnb-int8-fallback | if 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
Notebook 02a: Quantized measurement
- 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
- Load the quantized model: GPTQ first, then the fallback
- Run the same eight questions with CodeCarbon, and score them the same way
- Append a row to leaderboard.csv and compare it with your baseline
- 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
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
baseline
fewer bits
less text
- The same 16-bit model, given only the relevant documents
