-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Adds Quantization documentation #2189
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JyotinderSingh
wants to merge
8
commits into
keras-team:master
Choose a base branch
from
JyotinderSingh:quantization-docs
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+549
−0
Open
Changes from 1 commit
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
4970e3a
Adds quantization documentation
JyotinderSingh 23fba61
Update guides/md/quantization/overview.md
JyotinderSingh a5c6141
Update guides/md/quantization/overview.md
JyotinderSingh 90eb08a
improves consistency
JyotinderSingh 2d61c85
improves consistency
JyotinderSingh 791043f
address reviews
JyotinderSingh 6b9cc18
improve formatting and add missing note
JyotinderSingh 42ae2a4
remove warning block
JyotinderSingh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,190 @@ | ||
{ | ||
"cells": [ | ||
{ | ||
"cell_type": "markdown", | ||
"id": "35a7da8b", | ||
"metadata": {}, | ||
"source": [ | ||
"# Quantization in Keras\n", | ||
"Author: [Jyotinder Singh](https://x.com/Jyotinder_Singh)\n", | ||
"\n", | ||
"Date created: 2025/10/09\n", | ||
"\n", | ||
"Last modified: 2025/10/09\n", | ||
"\n", | ||
"Description: Overview of quantization in Keras (int8, float8, int4, GPTQ).\n", | ||
"\n", | ||
"Accelerator: GPU\n", | ||
"\n", | ||
"## Introduction\n", | ||
"\n", | ||
"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", | ||
"\n", | ||
"* Shrinks model size and VRAM/RAM footprint.\n", | ||
"* Increases effective memory bandwidth (fewer bytes per value).\n", | ||
"* Can improve throughput and sometimes latency on supporting hardware with low-precision kernels.\n", | ||
"\n", | ||
"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", | ||
"\n", | ||
"At a high level, Keras supports:\n", | ||
"\n", | ||
"* Joint weight + activation PTQ in `int4`, `int8`, and `float8`.\n", | ||
"* Weight-only PTQ via **GPTQ** (2/3/4/8-bit) to maximize compression with minimal accuracy impact, especially for large language models (LLMs).\n", | ||
"\n", | ||
"**Terminology**\n", | ||
"* *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", | ||
"* *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", | ||
"* *Calibration:* A short pass over sample data to estimate activation ranges (e.g., max absolute value).\n", | ||
"\n", | ||
"\n", | ||
"## Quantization Modes\n", | ||
"\n", | ||
"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", | ||
"\n", | ||
"* **`int8` (8-bit integer)**: **joint weight + activation** PTQ.\n", | ||
"\n", | ||
" * **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", | ||
" * **Why use it:** Good accuracy for many architectures; broad hardware support.\n", | ||
" * **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", | ||
"\n", | ||
"* **`float8` (FP8: E4M3 / E5M2 variants)**: Low-precision floating-point useful for training and inference on FP8-capable hardware.\n", | ||
"\n", | ||
" * **How it works:** Values are quantized to FP8 with a dynamic scale. Fused FP8 kernels on supported devices yield speedups.\n", | ||
" * **Why use it:** Mixed-precision training/inference with hardware acceleration while keeping floating-point semantics (since underflow/overflow characteristics differ from int).\n", | ||
" * **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", | ||
"\n", | ||
"* **`int4`**: Ultra-low-bit **weights** for aggressive compression; activations remain in higher precision (int8).\n", | ||
"\n", | ||
" * **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", | ||
" * **Why use it:** Significant VRAM/storage savings for LLMs with acceptable accuracy when combined with robust per-channel scaling.\n", | ||
" * **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", | ||
"\n", | ||
"* **`GPTQ` (weight-only 2/3/4/8 bits)**: *Second-order, post-training* method minimizing layer output error.\n", | ||
"\n", | ||
" * **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", | ||
" * **Why use it:** Strong accuracy retention at very low bit-widths without retraining; ideal for rapid LLM compression.\n", | ||
" * **What to expect:** Large storage/VRAM savings with small perplexity/accuracy deltas on many decoder-only models when calibrated on task-relevant samples.\n", | ||
"\n", | ||
"### Implementation notes\n", | ||
"\n", | ||
"* 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", | ||
"* 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", | ||
"* Per-channel scaling is the default for weights where supported, because it materially improves accuracy at negligible overhead.\n", | ||
"\n", | ||
"## Quantizing Keras Models\n", | ||
"\n", | ||
"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", | ||
"\n", | ||
"Typical workflow:\n", | ||
"\n", | ||
"1. **Build / load your FP model.** Train if needed. Ensure `build()` or a forward pass has materialized weights.\n", | ||
"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", | ||
"3. **Invoke quantization.** Call `model.quantize(\"<mode>\")` or `layer.quantize(\"<mode>\")` with `\"int8\"`, `\"int4\"`, `\"float8\"`, or `\"gptq\"` (weight-only).\n", | ||
"4. **Use or save.** Run inference, or `model.save(...)`. Quantization state (packed weights, scales, metadata) is preserved on save/load.\n", | ||
"\n", | ||
"### Model Quantization" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"id": "d9944077", | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"import keras\n", | ||
"import numpy as np\n", | ||
"\n", | ||
"# Sample training data.\n", | ||
"x_train = keras.ops.array(np.random.rand(100, 10))\n", | ||
"y_train = keras.ops.array(np.random.rand(100, 1))\n", | ||
"\n", | ||
"# Build the model.\n", | ||
"model = keras.Sequential([\n", | ||
" keras.layers.Dense(32, activation=\"relu\", input_shape=(10,)),\n", | ||
" keras.layers.Dense(1)\n", | ||
"])\n", | ||
"\n", | ||
"# Compile and fit the model.\n", | ||
"model.compile(optimizer=\"adam\", loss=\"mean_squared_error\")\n", | ||
"model.fit(x_train, y_train, epochs=1, verbose=0)\n", | ||
"\n", | ||
"# Quantize the model.\n", | ||
"model.quantize(\"int8\")" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"id": "a9b1d974", | ||
"metadata": {}, | ||
"source": [ | ||
"**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", | ||
"\n", | ||
"**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", | ||
"\n", | ||
"### Layer-wise Quantization\n", | ||
"\n", | ||
"The Keras quantization framework allows you to quantize each layer separately, without having to quantize the entire model using the same unified API." | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"id": "0df2aa1a", | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"from keras import layers\n", | ||
"\n", | ||
"input_shape = (10,)\n", | ||
"layer = layers.Dense(32, activation=\"relu\", input_shape=input_shape)\n", | ||
"layer.build(input_shape)\n", | ||
"\n", | ||
"layer.quantize(\"int4\") # Or \"int8\", \"float8\", etc." | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"id": "249deef4", | ||
"metadata": {}, | ||
"source": [ | ||
"**When to use layer-wise quantization**\n", | ||
"\n", | ||
"* To keep numerically sensitive blocks (e.g., small residual paths, logits) at higher precision while quantizing large projection layers.\n", | ||
"* To mix modes (e.g., attention projections in int4, feed-forward in int8) and measure trade-offs incrementally.\n", | ||
"* Always validate on a small eval set after each step; mixing precisions across residual connections can shift distributions.\n", | ||
"\n", | ||
"## Layer & model coverage\n", | ||
"\n", | ||
"Keras supports the following core layers in its quantization framework:\n", | ||
"\n", | ||
"* `Dense`\n", | ||
"* `EinsumDense`\n", | ||
"* `Embedding` (available in KerasHub)\n", | ||
"* `ReversibleEmbedding` (available in KerasHub)\n", | ||
"\n", | ||
"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", | ||
"\n", | ||
"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", | ||
"\n", | ||
"## Practical guidance\n", | ||
"\n", | ||
"* 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", | ||
"* Measure both **VRAM** and **throughput/latency**: memory savings are immediate; speedups depend on the availability of fused low-precision kernels on your device." | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"id": "cce23bb3", | ||
"metadata": {}, | ||
"source": [] | ||
} | ||
], | ||
"metadata": { | ||
"language_info": { | ||
"name": "python" | ||
} | ||
}, | ||
"nbformat": 4, | ||
"nbformat_minor": 5 | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
# Quantization in Keras | ||
|
||
**Author:** [Jyotinder Singh](https://x.com/Jyotinder_Singh)<br> | ||
**Date created:** 2025/10/09<br> | ||
**Last modified:** 2025/10/09<br> | ||
**Description:** Overview of quantization in Keras (int8, float8, int4, GPTQ). | ||
|
||
<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) | ||
|
||
--- | ||
|
||
## Introduction | ||
|
||
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: | ||
|
||
* Shrinks model size and VRAM/RAM footprint. | ||
* Increases effective memory bandwidth (fewer bytes per value). | ||
* Can improve throughput and sometimes latency on supporting hardware with low-precision kernels. | ||
|
||
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. | ||
|
||
At a high level, Keras supports: | ||
|
||
* Joint weight + activation PTQ in `int4`, `int8`, and `float8`. | ||
* Weight-only PTQ via **GPTQ** (2/3/4/8-bit) to maximize compression with minimal accuracy impact, especially for large language models (LLMs). | ||
|
||
> **Terminology** | ||
> | ||
> * *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. | ||
> * *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. | ||
> * *Calibration:* A short pass over sample data to estimate activation ranges (e.g., max absolute value). | ||
|
||
--- | ||
|
||
## Quantization Modes | ||
|
||
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. | ||
|
||
* **`int8` (8-bit integer)**: **joint weight + activation** PTQ. | ||
|
||
* **How it works:** Values are linearly mapped to 8-bit integers with per-channel scales. Activations are calibrated using dynamic quantization (see note below). | ||
* **Why use it:** Good accuracy for many architectures; broad hardware support. | ||
* **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. | ||
|
||
* **`float8` (FP8: E4M3 / E5M2 variants)**: Low-precision floating-point useful for training and inference on FP8-capable hardware. | ||
|
||
* **How it works:** Values are quantized to FP8 with a dynamic scale. Fused FP8 kernels on supported devices yield speedups. | ||
* **Why use it:** Mixed-precision training/inference with hardware acceleration while keeping floating-point semantics (since underflow/overflow characteristics differ from int). | ||
* **What to expect:** Competitive speed and memory reductions where FP8 kernels are available; accuracy varies by model, but is usually acceptable for most tasks. | ||
|
||
* **`int4`**: Ultra-low-bit **weights** for aggressive compression; activations remain in higher precision (int8). | ||
|
||
* **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. | ||
* **Why use it:** Significant VRAM/storage savings for LLMs with acceptable accuracy when combined with robust per-channel scaling. | ||
* **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. | ||
|
||
* **`GPTQ` (weight-only 2/3/4/8 bits)**: *Second-order, post-training* method minimizing layer output error. | ||
|
||
* **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). | ||
* **Why use it:** Strong accuracy retention at very low bit-widths without retraining; ideal for rapid LLM compression. | ||
* **What to expect:** Large storage/VRAM savings with small perplexity/accuracy deltas on many decoder-only models when calibrated on task-relevant samples. | ||
|
||
### Implementation notes | ||
|
||
* 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. | ||
* 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. | ||
* Per-channel scaling is the default for weights where supported, because it materially improves accuracy at negligible overhead. | ||
|
||
--- | ||
|
||
## Quantizing Keras Models | ||
|
||
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. | ||
|
||
Typical workflow: | ||
|
||
1. **Build / load your FP model.** Train if needed. Ensure `build()` or a forward pass has materialized weights. | ||
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. | ||
3. **Invoke quantization.** Call `model.quantize("<mode>")` or `layer.quantize("<mode>")` with `"int8"`, `"int4"`, `"float8"`, or `"gptq"` (weight-only). | ||
4. **Use or save.** Run inference, or `model.save(...)`. Quantization state (packed weights, scales, metadata) is preserved on save/load. | ||
|
||
### Model Quantization | ||
|
||
```python | ||
import keras | ||
import numpy as np | ||
|
||
# Sample training data | ||
x_train = keras.ops.array(np.random.rand(100, 10)) | ||
y_train = keras.ops.array(np.random.rand(100, 1)) | ||
|
||
# Build the model | ||
model = keras.Sequential([ | ||
keras.layers.Dense(32, activation="relu", input_shape=(10,)), | ||
keras.layers.Dense(1) | ||
]) | ||
|
||
# Compile and fit the model | ||
model.compile(optimizer="adam", loss="mean_squared_error") | ||
model.fit(x_train, y_train, epochs=1, verbose=0) | ||
|
||
# Quantize the model | ||
model.quantize("int8") | ||
``` | ||
|
||
**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. | ||
|
||
**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. | ||
|
||
### Layer-wise Quantization | ||
|
||
The Keras quantization framework allows you to quantize each layer separately, without having to quantize the entire model using the same unified API. | ||
|
||
```python | ||
from keras import layers | ||
|
||
input_shape = (10,) | ||
layer = layers.Dense(32, activation="relu", input_shape=input_shape) | ||
layer.build(input_shape) | ||
|
||
layer.quantize("int4") # or "int8", "float8", etc. | ||
JyotinderSingh marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
``` | ||
|
||
### When to use layer-wise quantization | ||
|
||
* To keep numerically sensitive blocks (e.g., small residual paths, logits) at higher precision while quantizing large projection layers. | ||
* To mix modes (e.g., attention projections in int4, feed-forward in int8) and measure trade-offs incrementally. | ||
* Always validate on a small eval set after each step; mixing precisions across residual connections can shift distributions. | ||
|
||
--- | ||
|
||
## Layer & model coverage | ||
|
||
Keras supports the following core layers in its quantization framework: | ||
|
||
* `Dense` | ||
* `EinsumDense` | ||
* `Embedding` (available in KerasHub) | ||
* `ReversibleEmbedding` (available in KerasHub) | ||
|
||
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. | ||
|
||
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. | ||
|
||
## Practical guidance | ||
|
||
* 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). | ||
* Measure both **VRAM** and **throughput/latency**: memory savings are immediate; speedups depend on the availability of fused low-precision kernels on your device. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.