Skip to content

Commit 4970e3a

Browse files
Adds quantization documentation
1 parent bff731e commit 4970e3a

File tree

4 files changed

+482
-0
lines changed

4 files changed

+482
-0
lines changed
Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"id": "35a7da8b",
6+
"metadata": {},
7+
"source": [
8+
"# Quantization in Keras\n",
9+
"Author: [Jyotinder Singh](https://x.com/Jyotinder_Singh)\n",
10+
"\n",
11+
"Date created: 2025/10/09\n",
12+
"\n",
13+
"Last modified: 2025/10/09\n",
14+
"\n",
15+
"Description: Overview of quantization in Keras (int8, float8, int4, GPTQ).\n",
16+
"\n",
17+
"Accelerator: GPU\n",
18+
"\n",
19+
"## Introduction\n",
20+
"\n",
21+
"Modern large models are often **memory- and bandwidth-bound**: most inference time is spent moving tensors between memory and compute units rather than doing math. Quantization reduces the number of bits used to represent the model's weights and (optionally) activations, which:\n",
22+
"\n",
23+
"* Shrinks model size and VRAM/RAM footprint.\n",
24+
"* Increases effective memory bandwidth (fewer bytes per value).\n",
25+
"* Can improve throughput and sometimes latency on supporting hardware with low-precision kernels.\n",
26+
"\n",
27+
"Keras provides first-class **post-training quantization (PTQ)** workflows which support pretrained models and expose a uniform API at both the model and layer level.\n",
28+
"\n",
29+
"At a high level, Keras supports:\n",
30+
"\n",
31+
"* Joint weight + activation PTQ in `int4`, `int8`, and `float8`.\n",
32+
"* Weight-only PTQ via **GPTQ** (2/3/4/8-bit) to maximize compression with minimal accuracy impact, especially for large language models (LLMs).\n",
33+
"\n",
34+
"**Terminology**\n",
35+
"* *Scale / zero-point:* Quantization maps real values `x` to integers `q` using a scale (and optionally a zero-point). Symmetric schemes use only a scale.\n",
36+
"* *Per-channel vs per-tensor:* A separate scale per output channel (e.g., per hidden unit) usually preserves accuracy better than a single scale for the whole tensor.\n",
37+
"* *Calibration:* A short pass over sample data to estimate activation ranges (e.g., max absolute value).\n",
38+
"\n",
39+
"\n",
40+
"## Quantization Modes\n",
41+
"\n",
42+
"Keras currently focuses on the following numeric formats. Each mode can be applied selectively to layers or to the whole model via the same API.\n",
43+
"\n",
44+
"* **`int8` (8-bit integer)**: **joint weight + activation** PTQ.\n",
45+
"\n",
46+
" * **How it works:** Values are linearly mapped to 8-bit integers with per-channel scales. Activations are calibrated using dynamic quantization (see note below).\n",
47+
" * **Why use it:** Good accuracy for many architectures; broad hardware support.\n",
48+
" * **What to expect:** ~4x smaller than FP32 parameters (~2x vs FP16) and lower activation bandwidth, with small accuracy loss on many tasks. Throughput gains depend on kernel availability and memory bandwidth.\n",
49+
"\n",
50+
"* **`float8` (FP8: E4M3 / E5M2 variants)**: Low-precision floating-point useful for training and inference on FP8-capable hardware.\n",
51+
"\n",
52+
" * **How it works:** Values are quantized to FP8 with a dynamic scale. Fused FP8 kernels on supported devices yield speedups.\n",
53+
" * **Why use it:** Mixed-precision training/inference with hardware acceleration while keeping floating-point semantics (since underflow/overflow characteristics differ from int).\n",
54+
" * **What to expect:** Competitive speed and memory reductions where FP8 kernels are available; accuracy varies by model, but is usually acceptable for most tasks.\n",
55+
"\n",
56+
"* **`int4`**: Ultra-low-bit **weights** for aggressive compression; activations remain in higher precision (int8).\n",
57+
"\n",
58+
" * **How it works:** Two signed 4-bit \"nibbles\" are packed per int8 byte. Keras uses symmetric per-output-channel scales to dequantize efficiently inside matmul.\n",
59+
" * **Why use it:** Significant VRAM/storage savings for LLMs with acceptable accuracy when combined with robust per-channel scaling.\n",
60+
" * **What to expect:** ~8× smaller than FP32 (~4× vs FP16) for weights; throughput gains depend on kernel availability and memory bandwidth. Competitive accuracy deltas for encoder-only architectures, may show larger regressions on decoder-only models.\n",
61+
"\n",
62+
"* **`GPTQ` (weight-only 2/3/4/8 bits)**: *Second-order, post-training* method minimizing layer output error.\n",
63+
"\n",
64+
" * **How it works (brief):** For each weight block (group), GPTQ solves a local least-squares problem using a Hessian approximation built from a small calibration set, then quantizes to low bit-width. The result is a packed weight tensor plus per-group parameters (e.g., scales).\n",
65+
" * **Why use it:** Strong accuracy retention at very low bit-widths without retraining; ideal for rapid LLM compression.\n",
66+
" * **What to expect:** Large storage/VRAM savings with small perplexity/accuracy deltas on many decoder-only models when calibrated on task-relevant samples.\n",
67+
"\n",
68+
"### Implementation notes\n",
69+
"\n",
70+
"* For `int4`, Keras packs signed 4-bit values (range ≈ [−8, 7]) and stores per-channel scales such as `kernel_scale`. Dequantization happens on the fly, and matmuls use 8-bit (unpacked) kernels.\n",
71+
"* Activation scaling for `int4` / `int8` / `float8` uses **AbsMax calibration** by default (range set by the maximum absolute value observed). Alternative calibration methods (e.g., percentile) may be added in future releases.\n",
72+
"* Per-channel scaling is the default for weights where supported, because it materially improves accuracy at negligible overhead.\n",
73+
"\n",
74+
"## Quantizing Keras Models\n",
75+
"\n",
76+
"Quantization is applied explicitly after layers or models are built. The API is designed to be predictable: you call quantize, the graph is rewritten, the weights are replaced, and you can immediately run inference or save the model.\n",
77+
"\n",
78+
"Typical workflow:\n",
79+
"\n",
80+
"1. **Build / load your FP model.** Train if needed. Ensure `build()` or a forward pass has materialized weights.\n",
81+
"2. **(GPTQ only)** For GPTQ, Keras runs a short calibration pass to collect activation statistics. You will need to provide a small, representative dataset for this purpose.\n",
82+
"3. **Invoke quantization.** Call `model.quantize(\"<mode>\")` or `layer.quantize(\"<mode>\")` with `\"int8\"`, `\"int4\"`, `\"float8\"`, or `\"gptq\"` (weight-only).\n",
83+
"4. **Use or save.** Run inference, or `model.save(...)`. Quantization state (packed weights, scales, metadata) is preserved on save/load.\n",
84+
"\n",
85+
"### Model Quantization"
86+
]
87+
},
88+
{
89+
"cell_type": "code",
90+
"execution_count": null,
91+
"id": "d9944077",
92+
"metadata": {},
93+
"outputs": [],
94+
"source": [
95+
"import keras\n",
96+
"import numpy as np\n",
97+
"\n",
98+
"# Sample training data.\n",
99+
"x_train = keras.ops.array(np.random.rand(100, 10))\n",
100+
"y_train = keras.ops.array(np.random.rand(100, 1))\n",
101+
"\n",
102+
"# Build the model.\n",
103+
"model = keras.Sequential([\n",
104+
" keras.layers.Dense(32, activation=\"relu\", input_shape=(10,)),\n",
105+
" keras.layers.Dense(1)\n",
106+
"])\n",
107+
"\n",
108+
"# Compile and fit the model.\n",
109+
"model.compile(optimizer=\"adam\", loss=\"mean_squared_error\")\n",
110+
"model.fit(x_train, y_train, epochs=1, verbose=0)\n",
111+
"\n",
112+
"# Quantize the model.\n",
113+
"model.quantize(\"int8\")"
114+
]
115+
},
116+
{
117+
"cell_type": "markdown",
118+
"id": "a9b1d974",
119+
"metadata": {},
120+
"source": [
121+
"**What this does:** Quantizes the weights of the supported layers, and re-wires their forward paths to be compatible with the quantized kernels and quantization scales.\n",
122+
"\n",
123+
"**Note**: Throughput gains depend on backend/hardware kernels; in cases where kernels fall back to dequantized matmul, you still get memory savings but smaller speedups.\n",
124+
"\n",
125+
"### Layer-wise Quantization\n",
126+
"\n",
127+
"The Keras quantization framework allows you to quantize each layer separately, without having to quantize the entire model using the same unified API."
128+
]
129+
},
130+
{
131+
"cell_type": "code",
132+
"execution_count": null,
133+
"id": "0df2aa1a",
134+
"metadata": {},
135+
"outputs": [],
136+
"source": [
137+
"from keras import layers\n",
138+
"\n",
139+
"input_shape = (10,)\n",
140+
"layer = layers.Dense(32, activation=\"relu\", input_shape=input_shape)\n",
141+
"layer.build(input_shape)\n",
142+
"\n",
143+
"layer.quantize(\"int4\") # Or \"int8\", \"float8\", etc."
144+
]
145+
},
146+
{
147+
"cell_type": "markdown",
148+
"id": "249deef4",
149+
"metadata": {},
150+
"source": [
151+
"**When to use layer-wise quantization**\n",
152+
"\n",
153+
"* To keep numerically sensitive blocks (e.g., small residual paths, logits) at higher precision while quantizing large projection layers.\n",
154+
"* To mix modes (e.g., attention projections in int4, feed-forward in int8) and measure trade-offs incrementally.\n",
155+
"* Always validate on a small eval set after each step; mixing precisions across residual connections can shift distributions.\n",
156+
"\n",
157+
"## Layer & model coverage\n",
158+
"\n",
159+
"Keras supports the following core layers in its quantization framework:\n",
160+
"\n",
161+
"* `Dense`\n",
162+
"* `EinsumDense`\n",
163+
"* `Embedding` (available in KerasHub)\n",
164+
"* `ReversibleEmbedding` (available in KerasHub)\n",
165+
"\n",
166+
"Any composite layers that are built from the above (for example, `MultiHeadAttention`, `GroupedQueryAttention`, feed-forward blocks in Transformers) inherit quantization support by construction. This covers the majority of modern encoder-only and decoder-only Transformer architectures.\n",
167+
"\n",
168+
"Since all KerasHub models subclass `keras.Model`, they automatically support the `model.quantize(...)` API. In practice, this means you can take a popular LLM preset, call a single function to obtain an int8/int4/GPTQ-quantized variant, and then save or serve it—without changing your training code.\n",
169+
"\n",
170+
"## Practical guidance\n",
171+
"\n",
172+
"* For GPTQ, use a calibration set that matches your inference domain (a few hundred to a few thousand tokens is often enough to see strong retention).\n",
173+
"* Measure both **VRAM** and **throughput/latency**: memory savings are immediate; speedups depend on the availability of fused low-precision kernels on your device."
174+
]
175+
},
176+
{
177+
"cell_type": "markdown",
178+
"id": "cce23bb3",
179+
"metadata": {},
180+
"source": []
181+
}
182+
],
183+
"metadata": {
184+
"language_info": {
185+
"name": "python"
186+
}
187+
},
188+
"nbformat": 4,
189+
"nbformat_minor": 5
190+
}

guides/md/quantization/overview.md

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
# Quantization in Keras
2+
3+
**Author:** [Jyotinder Singh](https://x.com/Jyotinder_Singh)<br>
4+
**Date created:** 2025/10/09<br>
5+
**Last modified:** 2025/10/09<br>
6+
**Description:** Overview of quantization in Keras (int8, float8, int4, GPTQ).
7+
8+
<img class="k-inline-icon" src="https://colab.research.google.com/img/colab_favicon.ico"/> [**View in Colab**](https://colab.research.google.com/github/keras-team/keras-io/blob/master/guides/ipynb/quantization/overview.ipynb) <span class="k-dot">•</span><img class="k-inline-icon" src="https://github.com/favicon.ico"/> [**GitHub source**](https://github.com/keras-team/keras-io/blob/master/guides/quantization/overview.py)
9+
10+
---
11+
12+
## Introduction
13+
14+
Modern large models are often **memory- and bandwidth-bound**: most inference time is spent moving tensors between memory and compute units rather than doing math. Quantization reduces the number of bits used to represent the model's weights and (optionally) activations, which:
15+
16+
* Shrinks model size and VRAM/RAM footprint.
17+
* Increases effective memory bandwidth (fewer bytes per value).
18+
* Can improve throughput and sometimes latency on supporting hardware with low-precision kernels.
19+
20+
Keras provides first-class **post-training quantization (PTQ)** workflows which support pretrained models and expose a uniform API at both the model and layer level.
21+
22+
At a high level, Keras supports:
23+
24+
* Joint weight + activation PTQ in `int4`, `int8`, and `float8`.
25+
* Weight-only PTQ via **GPTQ** (2/3/4/8-bit) to maximize compression with minimal accuracy impact, especially for large language models (LLMs).
26+
27+
> **Terminology**
28+
>
29+
> * *Scale / zero-point:* Quantization maps real values `x` to integers `q` using a scale (and optionally a zero-point). Symmetric schemes use only a scale.
30+
> * *Per-channel vs per-tensor:* A separate scale per output channel (e.g., per hidden unit) usually preserves accuracy better than a single scale for the whole tensor.
31+
> * *Calibration:* A short pass over sample data to estimate activation ranges (e.g., max absolute value).
32+
33+
---
34+
35+
## Quantization Modes
36+
37+
Keras currently focuses on the following numeric formats. Each mode can be applied selectively to layers or to the whole model via the same API.
38+
39+
* **`int8` (8-bit integer)**: **joint weight + activation** PTQ.
40+
41+
* **How it works:** Values are linearly mapped to 8-bit integers with per-channel scales. Activations are calibrated using dynamic quantization (see note below).
42+
* **Why use it:** Good accuracy for many architectures; broad hardware support.
43+
* **What to expect:** ~4x smaller than FP32 parameters (~2x vs FP16) and lower activation bandwidth, with small accuracy loss on many tasks. Throughput gains depend on kernel availability and memory bandwidth.
44+
45+
* **`float8` (FP8: E4M3 / E5M2 variants)**: Low-precision floating-point useful for training and inference on FP8-capable hardware.
46+
47+
* **How it works:** Values are quantized to FP8 with a dynamic scale. Fused FP8 kernels on supported devices yield speedups.
48+
* **Why use it:** Mixed-precision training/inference with hardware acceleration while keeping floating-point semantics (since underflow/overflow characteristics differ from int).
49+
* **What to expect:** Competitive speed and memory reductions where FP8 kernels are available; accuracy varies by model, but is usually acceptable for most tasks.
50+
51+
* **`int4`**: Ultra-low-bit **weights** for aggressive compression; activations remain in higher precision (int8).
52+
53+
* **How it works:** Two signed 4-bit "nibbles" are packed per int8 byte. Keras uses symmetric per-output-channel scales to dequantize efficiently inside matmul.
54+
* **Why use it:** Significant VRAM/storage savings for LLMs with acceptable accuracy when combined with robust per-channel scaling.
55+
* **What to expect:** ~8× smaller than FP32 (~4× vs FP16) for weights; throughput gains depend on kernel availability and memory bandwidth. Competitive accuracy deltas for encoder-only architectures, may show larger regressions on decoder-only models.
56+
57+
* **`GPTQ` (weight-only 2/3/4/8 bits)**: *Second-order, post-training* method minimizing layer output error.
58+
59+
* **How it works (brief):** For each weight block (group), GPTQ solves a local least-squares problem using a Hessian approximation built from a small calibration set, then quantizes to low bit-width. The result is a packed weight tensor plus per-group parameters (e.g., scales).
60+
* **Why use it:** Strong accuracy retention at very low bit-widths without retraining; ideal for rapid LLM compression.
61+
* **What to expect:** Large storage/VRAM savings with small perplexity/accuracy deltas on many decoder-only models when calibrated on task-relevant samples.
62+
63+
### Implementation notes
64+
65+
* For `int4`, Keras packs signed 4-bit values (range ≈ [−8, 7]) and stores per-channel scales such as `kernel_scale`. Dequantization happens on the fly, and matmuls use 8-bit (unpacked) kernels.
66+
* Activation scaling for `int4` / `int8` / `float8` uses **AbsMax calibration** by default (range set by the maximum absolute value observed). Alternative calibration methods (e.g., percentile) may be added in future releases.
67+
* Per-channel scaling is the default for weights where supported, because it materially improves accuracy at negligible overhead.
68+
69+
---
70+
71+
## Quantizing Keras Models
72+
73+
Quantization is applied explicitly after layers or models are built. The API is designed to be predictable: you call quantize, the graph is rewritten, the weights are replaced, and you can immediately run inference or save the model.
74+
75+
Typical workflow:
76+
77+
1. **Build / load your FP model.** Train if needed. Ensure `build()` or a forward pass has materialized weights.
78+
2. **(GPTQ only)** For GPTQ, Keras runs a short calibration pass to collect activation statistics. You will need to provide a small, representative dataset for this purpose.
79+
3. **Invoke quantization.** Call `model.quantize("<mode>")` or `layer.quantize("<mode>")` with `"int8"`, `"int4"`, `"float8"`, or `"gptq"` (weight-only).
80+
4. **Use or save.** Run inference, or `model.save(...)`. Quantization state (packed weights, scales, metadata) is preserved on save/load.
81+
82+
### Model Quantization
83+
84+
```python
85+
import keras
86+
import numpy as np
87+
88+
# Sample training data
89+
x_train = keras.ops.array(np.random.rand(100, 10))
90+
y_train = keras.ops.array(np.random.rand(100, 1))
91+
92+
# Build the model
93+
model = keras.Sequential([
94+
keras.layers.Dense(32, activation="relu", input_shape=(10,)),
95+
keras.layers.Dense(1)
96+
])
97+
98+
# Compile and fit the model
99+
model.compile(optimizer="adam", loss="mean_squared_error")
100+
model.fit(x_train, y_train, epochs=1, verbose=0)
101+
102+
# Quantize the model
103+
model.quantize("int8")
104+
```
105+
106+
**What this does:** Quantizes the weights of the supported layers, and re-wires their forward paths to be compatible with the quantized kernels and quantization scales.
107+
108+
**Note**: Throughput gains depend on backend/hardware kernels; in cases where kernels fall back to dequantized matmul, you still get memory savings but smaller speedups.
109+
110+
### Layer-wise Quantization
111+
112+
The Keras quantization framework allows you to quantize each layer separately, without having to quantize the entire model using the same unified API.
113+
114+
```python
115+
from keras import layers
116+
117+
input_shape = (10,)
118+
layer = layers.Dense(32, activation="relu", input_shape=input_shape)
119+
layer.build(input_shape)
120+
121+
layer.quantize("int4") # or "int8", "float8", etc.
122+
```
123+
124+
### When to use layer-wise quantization
125+
126+
* To keep numerically sensitive blocks (e.g., small residual paths, logits) at higher precision while quantizing large projection layers.
127+
* To mix modes (e.g., attention projections in int4, feed-forward in int8) and measure trade-offs incrementally.
128+
* Always validate on a small eval set after each step; mixing precisions across residual connections can shift distributions.
129+
130+
---
131+
132+
## Layer & model coverage
133+
134+
Keras supports the following core layers in its quantization framework:
135+
136+
* `Dense`
137+
* `EinsumDense`
138+
* `Embedding` (available in KerasHub)
139+
* `ReversibleEmbedding` (available in KerasHub)
140+
141+
Any composite layers that are built from the above (for example, `MultiHeadAttention`, `GroupedQueryAttention`, feed-forward blocks in Transformers) inherit quantization support by construction. This covers the majority of modern encoder-only and decoder-only Transformer architectures.
142+
143+
Since all KerasHub models subclass `keras.Model`, they automatically support the `model.quantize(...)` API. In practice, this means you can take a popular LLM preset, call a single function to obtain an int8/int4/GPTQ-quantized variant, and then save or serve it—without changing your training code.
144+
145+
## Practical guidance
146+
147+
* For GPTQ, use a calibration set that matches your inference domain (a few hundred to a few thousand tokens is often enough to see strong retention).
148+
* Measure both **VRAM** and **throughput/latency**: memory savings are immediate; speedups depend on the availability of fused low-precision kernels on your device.

0 commit comments

Comments
 (0)