Skip to content
ImagineWorld

Advanced quantization techniques

node_idnode-book_build-small-language-model_chapter-09-advanced-quantization-techniques
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleAdvanced quantization techniques
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 9 — Advanced quantization techniques

Section titled “Chapter 9 — Advanced quantization techniques”

Part 4

Advanced concepts

T his last part of the book covers the most advanced concepts. Chapters 9 and 10 explain advanced quantization techniques for larger SLMs and one way of implementing friendly model profiling insights. Chapters 11 and 12 showcase multiple ways to deploy and serve SLMs in hardware-constrained environments, laptops, and devices (specifically presenting options for the Android OS). Chapters 13 and 14 cover the integration of SLMs with RAG and agentic AI. Finally, chapter 15 talks about test-time compute and SLMs, and it concludes the book with an end-to-end example of tuning an SLM for reasoning on a specific domain through GRPO.

This chapter covers

  • Using the FlexGen technique to offload part of an LLM to memory or disk
  • Using SmoothQuant, an advanced post-training quantization technique, to reduce memory footprint and accelerate inference
  • Using BitNet, a scalable 1-bit Transformer architecture, to reduce memory footprint and energy consumption

Typically, domain-specific language models are small: in my professional experience, they’re usually no more than 7 or 8 billion parameters (excluding the additional parameters from LoRA or QLoRA partial tuning, which are small anyway). The techniques explained in previous chapters make such models practical to deploy and use in computationally constrained environments. Still, a larger pool of specialized training data, unstructured training data with representations larger than natural language, or a larger baseline model that better fits the task may result in a final model size that exceeds the available inference hardware capacity, even after quantization.

This chapter introduces advanced LLM quantization techniques that can help you run such specialized models efficiently in target environments, balancing quality and speed. The sections that follow describe these strategies and compare their pros and cons. You’ll also find detailed code examples and benchmarks.

NOTE This chapter covers advanced LMM quantization techniques for cases where the methods in chapter 6 can’t meet performance or compute constraints. Before continuing, make sure you understand chapter 6.

FlexGen is a high-throughput inference engine for running LLMs in situations where GPU memory is limited. Introduced in the 2023 paper “FlexGen: High-Throughput Generative Inference of Large Language Models with a Single GPU” (https://arxiv .org/abs/2303.06865), FlexGen can be configured for different hardware constraints by pooling memory and compute across the GPU, CPU, and disk. It searches for efficient ways to store and access tensors by solving a linear programming problem, and it further compresses the weights and attention cache to 4 bits with negligible accuracy loss. This expands the feasible batch-size range and increases the maximum throughput for a model. The paper reports substantially higher throughput than with traditional offloading methods.

To give you an idea of what FlexGen enables, consider a GPT-3–sized model with 175 billion parameters. Using the formula in section 4.2, the VRAM required to load it is 840 GB in FP32 or 420 GB in FP16. This means that to load the model and make it available for inference, you’d need, for example, six NVIDIA A100 Tensor Core GPUs (see figure 9.1).

Required_memory=(4×P)(32÷F)×1.2=840 GB (fp32) or 420 GB (fp16)\text{Required\_memory} = \frac{(4 \times P)}{(32 \div F)} \times 1.2 = 840 \text{ GB (fp32)} \text{ or } 420 \text{ GB (fp16)}

dslm-fig-9.1-hardware-for-175b-model.png

[!visual-conversion] Figure 9.1 — The hardware needed to load a 175 billion–parameter language model into memory (p. 176) 6 NVIDIA A100 Tensor Core GPU!

Given the price of the hardware, running a single model this way can be very expensive—often beyond the budget of small and mid-sized organizations and even some large non-tech ones. Assume a node with one consumer GPU (16 GB DRAM) but more RAM and disk space, which are cheaper and more available than GPUs. The FlexGen linear programming optimizer finds the best way to store and access the model’s weights, activations, and attention KV cache across the GPU, CPU, and disk. As a result, parts of the model are offloaded, as shown in figure 9.2 (assuming the model is loaded in FP16 format). This approach is definitely cheaper than buying or renting six NVIDIA A100 GPUs.

175B model: 420 GB VRAM → 16 GB VRAM + 200 GB DRAM + 204 GB disk

dslm-fig-9.2-three-images-a-graphics-card.png

[!visual-conversion] Figure 9.2 — Loading a 175 billion-parameter language model with FlexGen across GPU, CPU, and disk (p. 177)

This kind of offloading lets us deploy a very large model in a hardware-constrained environment, but it increases latency and reduces throughput. That’s expected: CPUs and disks are slower than GPUs, and offloading adds extra I/O.

FlexGen goes beyond basic offloading: during generative inference, it decides which tensors (weights, activations, and KV cache) to offload, where to place them, and when to move them to improve throughput while keeping I/O efficient. It further boosts inference performance by compressing both weights and the KV cache to 4 bits with negligible accuracy loss. This is an extreme example using a very large model—when you fine-tune a model for domain-specific tasks, you typically won’t reach this size—but it illustrates the benefits of the FlexGen approach in simple terms.

NOTE FlexGen supports only NVIDIA GPUs via CUDA and has no plans to support other vendors’ hardware acceleration.

Let’s look at how FlexGen works in practice and see whether it delivers on the paper’s claims. A companion Colab notebook includes the code for this section.

FlexGen is open source and available on GitHub (the repository is named FlexLLMGen; https://github.com/FMInference/FlexLLMGen/tree/main), and you can install it from PyPI without building from source. It includes prebuilt implementations for Facebook’s OPT (https://arxiv.org/abs/2205.01068) and Galactica (https://arxiv.org/pdf/2211.09085) models and BigScience’s BLOOM (https://arxiv.org/abs/2211.05100), plus models fine-tuned from these baselines. In this section , we focus on OPT, a suite of decoder-only pretrained transformers ranging from 125M to 175B parameters. The paper reports that OPT-175B is comparable to GPT-3 while requiring only one-seventh the carbon footprint to develop. All OPT models are hosted on the Hugging Face Hub.

This example, in the accompanying notebook, requires hardware acceleration and runs on Colab’s free-tier GPU VM. We’ll start with the OPT-1.3B model to get a sense of FlexGen. After installing the FlexGen code package (as shown in the notebook), you can evaluate FlexGen on one of the supported models from the CLI by running the flex_opt Python script as follows:

Terminal window
python -m flexgen.flex_opt --model facebook/opt-1.3b

In its simplest form, flex_opt expects the model argument, which is the ID of the target model on the Hugging Face Hub. After downloading the model, the script converts the weights to FlexGen based on the selected model’s configuration, then loads or offloads its weights, attention cache, and activations to the destination storage (by default, if you don’t specify otherwise at runtime, everything is loaded to the GPU). Finally, it runs a small benchmark. The output of the command looks like this:

TorchDevice: cuda:0
cur_mem: 2.6505 GB, peak_mem: 3.2478 GB
TorchDevice: cpu
cur_mem: 0.0000 GB, peak_mem: 0.0000 GB
model size: 2.443 GB cache size: 0.398 GB hidden size (p): 0.008 GB peak gpu mem: 3.248 GB projected: False prefill latency: 0.350 s prefill throughput: 5846.976 token/s decode latency: 0.932 s decode throughput: 132.989 token/s total latency: 1.283 s total throughput: 99.791 token/s

As you can see, everything runs on the GPU because the model fits in the device available in our execution environment. Now let’s try a larger model that won’t fit on our GPU, such as OPT-6.7B. Another key argument for the flex_opt script is percent. It lets us specify what percentage of weights, attention cache, and activations to load onto the GPUs and what percentage to offload to the CPU. It expects a string of six integers:

  • The percentage of weights on GPU
  • The percentage of weights on CPU
  • The percentage of attention cache on GPU
  • The percentage of attention cache on CPU
  • The percentage of activations on GPU
  • The percentage of activations on CPU

The default values are 100 0 100 0 100 0, which keeps everything on the GPU. If larger model doesn’t fit on your GPU, you can run the script and specify the following offloading policy:

Terminal window
python -m flexgen.flex_opt --model facebook/opt-6.7b
--percent 50 50 50 50 50

The CLI is a quick way to evaluate FlexGen. For models that run inference as part of a larger ecosystem, however, it’s usually better to call the FlexGen API programmatically alongside the Hugging Face Transformers API. For example, to run a text completion task with a model that doesn’t fit on your GPU, start by importing the required FlexGen classes (which will be discussed as we use them):

from flexgen.flex_opt import (Policy, OptLM, ExecutionEnv,
CompressionConfig, str2bool)

Next, download the target model’s tokenizer from the Hugging Face Hub:

from transformers import AutoTokenizer
model_id = "facebook/opt-6.7b"
tokenizer = AutoTokenizer.from_pretrained(model_id, padding_side="left")
tokenizer.add_bos_token = False
stop = tokenizer("\n").input_ids[0]

Before we initialize the model with FlexGen, we need to set up a few things. First, create the execution environment for the converted model using the ExecutionEnv class and its create method. This method takes the name of the directory where FlexGen can offload data that shouldn’t go in GPU memory or RAM:

offload_dir = './flexgen_offload'
env = ExecutionEnv.create(offload_dir)

We also need to set up FlexGen offloading and compression policies. The Policy class handles both. Here’s how to use it to set up everything we need:

policy = Policy(len(prompts), 1,
50, 50, 50, 50, 100, 0,
overlap=True, sep_layer=True, pin_weight=True,
cpu_cache_compute=True, attn_sparsity=1.0,
compress_weight=True,
comp_weight_config=CompressionConfig(
num_bits=4, group_size=64,
group_dim=0, symmetric=False),
compress_cache=True,
comp_cache_config=CompressionConfig(
num_bits=4, group_size=64,
group_dim=2, symmetric=False)
)

When creating an instance of the Policy class, we pass the offloading percentages (as with the CLI command) and specify whether to compress weights and the weight compression settings, whether to compress the cache, and the cache compression settings.

Next, we’ll create an OptLM instance for the target model by passing the Hugging Face Hub model ID, the execution-environment instance, the local cache path (after it’s downloaded from the hub), and the configured policies. The OptLM class takes care of any steps required to download and convert the target model:

path = '~/opt_weights'
model = OptLM(model_id, env, path, policy)

The FlexGen-prepared model is now ready for few-shot text-completion tasks. After you set up a list of example prompts, you can run completion as follows:

inputs = tokenizer(prompts, padding="max_length", max_length=128)
output_ids = model.generate(
inputs.input_ids,
do_sample=True,
temperature=0.7,
max_new_tokens=32,
stop=stop)
outputs = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
print("Outputs:\n" + 70 * '-')
for i in [0, len(outputs)-1]:
print(f"{i}: {outputs[i]}")
print("-" * 70)

LLMs prepared for FlexGen are fully supported by the Hugging Face’s Transformers library. When you’re done generating text completions, you can shut down the execution environment:

env.close_copy_threads()

FlexGen also supports multiple GPUs, which helps when the model you need to run might not fit in VRAM on your available hardware.

To support other families of open source LLMs, you can create a new Python script that follows the structure of flexgen.opt_config.py. In it, specify the target model architecture configuration, and implement utilities to download its weights from the Hub.

FlexGen provides advanced offloading and compression out of the box, and it delivers higher throughput on large batches than other approaches covered so far in this book, such as Accelerate and DeepSpeed. But it’s optimized for throughput-focused scenarios (LLM applications running inference on millions of tokens per batch). If latency is your main KPI, FlexGen isn’t the best way to run a larger model on budget hardware; you’ll need to consider other optimization options instead.

SmoothQuant is a post-training quantization method that improves LLM efficiency while preserving accuracy. Traditional quantization methods often focus on weights and can struggle with activation outliers, especially in larger models. These outliers can hurt performance after quantization. SmoothQuant (introduced in the paper of the same name; https://arxiv.org/abs/2211.10438) addresses this by enabling 8-bit weight and activation quantization without additional training. It does so by smoothing activation outliers via a mathematical transformation, effectively shifting quantization difficulties from activations to weights. This makes it possible to quantize a range of LLM architectures successfully. According to experiments in the paper, SmoothQuant can deliver up to 1.56 times speed increases and a 50% reduction in memory usage with minimal accuracy loss. This can enable the deployment of extremely large models, potentially even on a single node, depending on the node’s hardware specs. SmoothQuant is compatible with the PyTorch framework.

Before going hands-on with SmoothQuant, let’s look at the main quantization challenge it addresses. The techniques described in chapter 6 work well for LLMs up to about 6 or 7 billion parameters. Beyond that threshold, systematic activation outliers often appear, which can degrade accuracy after quantization. In section 6.2.2, I introduced the LLM.int8() technique, which mitigates this problem with a mixed-precision decomposition (it keeps outliers in FP16 while using INT8 for the remaining activations). This technique is already integrated into popular Python libraries, including some we use throughout this book. But for larger models, this decomposition is difficult to implement efficiently on hardware accelerators. In those cases, it’s better to use a different training-free quantization scheme that uses INT8 for all compute-intensive operations. SmoothQuant migrates the quantization difficulty from activations to weights by applying a mathematically equivalent, per-channel scaling transformation that smooths magnitudes across channels and makes the model more quantization-friendly. Figure 9.3, taken from the original SmoothQuant paper, illustrates the idea.

Figure 9.3 (top) shows activation (left) and weight (right) distributions for an LLM with a large activation outlier. This outlier stretches the quantization range, making quantization difficult. Figure 9.3 (bottom) shows the same model after SmoothQuant shifts scale variance from activations to weights offline (before inference). The activations are smoothed and the

dslm-fig-9.3-a-high-level-explanation-of.png

[!visual-conversion] Figure 9.3 — A high-level explanation of SmoothQuant (p. 181)

weights adjusted, making both easier to quantize. SmoothQuant can preserve accuracy after quantization while reducing serving costs.

Let’s look at an example; the complete code is available in a companion Colab notebook. We’ll see that, for a given LLM, SmoothQuant can use INT8 for both activations and weights while achieving accuracy comparable to FP16 on the same model. SmoothQuant has been tested on diverse LLM families, including Llama, OPT, Mistral, Mixtral, and Falcon. For PyTorch, SmoothQuant provides INT8 inference with CUTLASS INT8 GEMM kernels, wrapped as PyTorch modules in the torch-int (https://github.com/Guangxuan-Xiao/torch-int) Python package. SmoothQuant has also been integrated into inference engines such as Intel’s Neural Compressor, NVIDIA’s TensorRT-LLM, and Amazon SageMaker (we’ll cover LLM inference engines in chapter 11). To keep the focus on how SmoothQuant works in code, we’ll simulate 8-bit dynamic per-tensor quantization of weights and activations using FP16. All examples in this section require hardware acceleration.

Our first target model is Facebook’s OPT-2.7b (https://huggingface.co/facebook/opt-2.7b). We’ll start with a model that has fewer than 6 billion parameters to see whether the SmoothQuant strategy benefits smaller models.

Let’s first install SmoothQuant from the source code:

Terminal window
pip install git+https://github.com/mit-han-lab/smoothquant.git

Next, download the model’s FP16 weights and its tokenizer from the Hugging Face Hub:

import torch
from transformers.models.opt.modeling_opt import OPTForCausalLM
from transformers import GPT2Tokenizer
model_id = 'facebook/opt-2.7b'
tokenizer = GPT2Tokenizer.from_pretrained(model_id)
model_fp16 = OPTForCausalLM.from_pretrained(model_id,
torch_dtype=torch.float16,
device_map='auto',
)

Now we’ll load a dataset to evaluate different versions of the target model:

from datasets import load_dataset
dataset = load_dataset('cimec/lambada', split='validation[:1000]')

In this example, we use the first 1,000 samples from the LAMBADA dataset (https://huggingface.co/datasets/cimec/lambada), available on the Hugging Face Hub. LAMBADA is a collection of narrative passages used to evaluate text understanding via a word-prediction task. The dataset has two columns: text, the narrative passage, and domain, a label for the narrative genre. After evaluating the FP16 model on this dataset

(for example, using LM-Eval, introduced in section 4.1.4, or another tool), we can determine the model accuracy:

Original model (fp16) accuracy: 0.759

Let’s quantize this model. We’ll use a custom function adapted from the SmoothQuant repo.

Listing 9.1 A custom function to quantize an LLM’s weights and activations to INT8

from transformers.models.opt.modeling_opt import OPTAttention, OPTDecoderLayer, OPTForCausalLM
from smoothquant.fake_quant import W8A8Linear
def quantize_model(model, weight_quant='per_tensor', act_quant='per_tensor', quantize_bmm_input=True):
for name, m in model.model.named_modules():
if isinstance(m, OPTDecoderLayer):
m.fc1 = W8A8Linear.from_float(m.fc1, weight_quant=weight_quant, act_quant=act_quant)
m.fc2 = W8A8Linear.from_float(m.fc2, weight_quant=weight_quant, act_quant=act_quant)
elif isinstance(m, OPTAttention):
m.q_proj = W8A8Linear.from_float(
m.q_proj, weight_quant=weight_quant, act_quant=act_quant, quantize_output=quantize_bmm_input)
m.k_proj = W8A8Linear.from_float(
m.k_proj, weight_quant=weight_quant, act_quant=act_quant, quantize_output=quantize_bmm_input)
m.v_proj = W8A8Linear.from_float(
m.v_proj, weight_quant=weight_quant, act_quant=act_quant, quantize_output=quantize_bmm_input)
m.out_proj = W8A8Linear.from_float(m.out_proj, weight_quant=weight_quant, act_quant=act_quant)
return model

This function replaces the linear layers in self-attention and activation with SmoothQuant’s W8A8 (8-bit weight, 8-bit activation) implementation.

We can now apply the preceding function to the original model:

model_w8a8 = quantize_model(model_fp16)

Compare the original FP16 model structure, shown here

OPTForCausalLM(
(model): OPTModel(
(decoder): OPTDecoder(
(embed_tokens): Embedding(50272, 2560, padding_idx=1)
(embed_positions): OPTLearnedPositionalEmbedding(2050, 2560)
(final_layer_norm): LayerNorm((2560,), eps=1e-05,
elementwise_affine=True)
(layers): ModuleList(
(0-31): 32 x OPTDecoderLayer(
(self_attn): OPTSdpaAttention(
(k_proj): Linear(in_features=2560, out_features=2560, bias=True)
(v_proj): Linear(in_features=2560, out_features=2560, bias=True)
(q_proj): Linear(in_features=2560, out_features=2560, bias=True)
(out_proj): Linear(in_features=2560, out_features=2560,
bias=True)
)
(activation_fn): ReLU()
(self_attn_layer_norm): LayerNorm((2560,), eps=1e-05,
elementwise_affine=True)
(fc1): Linear(in_features=2560, out_features=10240, bias=True)
(fc2): Linear(in_features=10240, out_features=2560, bias=True)
(final_layer_norm): LayerNorm((2560,), eps=1e-05,
elementwise_affine=True)
)
)
(lm_head): Linear(in_features=2560, out_features=50272, bias=False)
)
with the 8-bit quantized version to verify that the self-attention and activation layers
were replaced correctly:
OPTForCausalLM(
(model): OPTModel(
(decoder): OPTDecoder(
(embed_tokens): Embedding(50272, 2560, padding_idx=1)
(embed_positions): OPTLearnedPositionalEmbedding(2050, 2560)
(final_layer_norm): LayerNorm((2560,), eps=1e-05,
elementwise_affine=True)
(layers): ModuleList(
(0-31): 32 x OPTDecoderLayer(
(self_attn): OPTSdpaAttention(
(k_proj): W8A8Linear(2560, 2560, bias=True,
weight_quant=per_tensor, act_quant=per_tensor,
output_quant=per_tensor)
(v_proj): W8A8Linear(2560, 2560, bias=True,
weight_quant=per_tensor, act_quant=per_tensor,
voutput_quant=per_tensor)
(q_proj): W8A8Linear(2560, 2560, bias=True,
weight_quant=per_tensor, act_quant=per_tensor,
output_quant=per_tensor)
(out_proj): W8A8Linear(2560, 2560, bias=True,
weight_quant=per_tensor, act_quant=per_tensor,
voutput_quant=None)
)
(activation_fn): ReLU()
(self_attn_layer_norm): LayerNorm((2560,), eps=1e-05,
elementwise_affine=True)
(fc1): W8A8Linear(2560, 10240, bias=True,
weight_quant=per_tensor, act_quant=per_tensor,
output_quant=None)
(fc2): W8A8Linear(10240, 2560, bias=True,
weight_quant=per_tensor, act_quant=per_tensor,
output_quant=None)
(final_layer_norm): LayerNorm(2560,), eps=1e-05,
elementwise_affine=True)
)
)
(lm_head): Linear(in_features=2560, out_features=50272, bias=False)

If we repeat the evaluation on the same 1,000 LAMBADA samples for the quantized model, we can see that the accuracy remains comparable to the original FP16 version:

Naive W8A8 quantized model accuracy: 0.758

This is expected: the model is large enough that its activations don’t contain large outliers. So far, we’ve quantized without smoothing the model’s activations. Now let’s apply smoothing before quantization:

act_scales = torch.load('./act_scales/opt-2.7b.pt')
smooth_lm(model_fp16, act_scales, 0.5)
model_smoothquant_w8a8 = quantize_model(model_fp16)

The smooth_lm function takes as input the original model, the model scales (available for this and many other models on the Hugging Face Hub; https://huggingface.co/mit-han-lab/smoothquant-scales/tree/main), and alpha, a hyperparameter that controls the migration strength, that is, how much quantization difficulty is shifted from activations to weights. The SmoothQuant paper defines the smoothing factor s_j for a given activation X_j and weight W_j as a function of alpha:

sj=max⁡(∣Xj∣)αmax⁡(∣Wj∣)1−αs_j = \frac{\max(|X_j|)^\alpha}{\max(|W_j|)^{1-\alpha}}

For this example—and for models under 100 billion parameters in general—we can keep alpha = 0.5. If we re-evaluate this model on the same dataset as in the previous versions, we can see that the accuracy is unchanged and is comparable to the original FP16 model:

SmoothQuant W8A8 quantized model accuracy: 0.759

Let’s see how things change with a larger model—let’s try OPT-6.7B. Repeating the same evaluation on its FP16 version, we can observe the following accuracy:

Original model (fp16) accuracy: 0.798

After 8-bit quantization with no smoothing, the model’s accuracy on the same evaluation dataset drops sharply:

Naive W8A8 quantized model accuracy: 0.423

This confirms the presence of at least one large outlier in the model’s activations. With activation smoothing applied before quantization, accuracy under the same evaluation is comparable to FP16:

SmoothQuant W8A8 quantized model accuracy: 0.799

As you’ve seen, SmoothQuant is a powerful strategy for reducing compute costs without affecting model performance, especially once specialized models exceed 6 to 7 billion parameters. As mentioned earlier, several LLM families are supported out of the box; others require some code customization to adapt the smoothing and quantization steps to the architecture.

BitNet is a scalable 1-bit Transformer architecture designed to reduce the cost and energy use of large language models. It replaces traditional linear layers with a component called BitLinear, which allows the training of 1-bit weights from scratch. Experimental findings indicate that BitNet, proposed for the first time in “BitNet: Scaling 1-bit Transformers for Large Language Models” (https://arxiv.org/abs/2310.11453), shows competitive language-modeling performance with much lower memory use and energy consumption than leading 8-bit quantization methods and FP16 transformer benchmarks. BitNet preserves high precision for optimizer states and gradients to maintain training stability, and it scales to larger models, adhering to a scaling law like full-precision transformers. The paper also describes group quantization for model parallelism, improving efficiency without additional communication overhead. Overall, BitNet has the potential to lower inference costs and improve performance, making it a promising alternative to other quantization methods.

Figure 9.4, from the original BitNet paper, shows the BitLinear component (left) and the BitNet architecture (right), which uses BitLinear in the attention layers. As you can see, the BitNet architecture has the same layout as a transformer. The main difference is that it uses BitLinear in the attention layers instead of matrix multiplication. This binarizes the attention weights (1-bit), while the rest of the model uses higher precision (8-bit). This reduces computational costs while preserving precision for the input/output embeddings, since the model still uses high-precision probabilities for sampling.

The BitNet paper also reports on several comparison experiments. Figure 9.5 compares the scaling curves of BitNet and FP16 transformers.

For smaller models, traditional FP16 transformers achieve lower loss than BitNet. As model size increases, the gap narrows: the loss delta is already small at around 30 billion parameters and drops to 0.09 near 100 billion.

BitLinear BitNet
┌── L-Layer ────────────┐
Output Output │ Output │
▲ ▲ │ ▲ │
┌────┴──────────┐ β ┌─────┴─────┐ │ ┌─────┴──────────┐ │
│ Dequantization │◄──────┐ │ BitLinear │ │ │ Feed-Forward │ │
└────▲──────────┘ │ └─────▲─────┘ │ │ Network │ │
│ │ │ │ └─────▲──────────┘ │
(⊗)◄─────────┬───────┤ ┌──┴───┐ │ │ │
▲ │ ┌────┴──────┐ │ GELU │ │ ┌─────┴──────────┐ │
│ γ └──│ 1-bit │ └──▲───┘ │ │ Multi-Head │ │
┌────┴──────────┐ │ Weights │ │ │ │ Attention │ │
│ Absmax │ └───────────┘ ┌────┴─────┐ │ └─────▲──────────┘ │
│ Quantization │ │ BitLinear│ │ │ │
└────▲──────────┘ └────▲─────┘ │ Input │
│ │ └───────────────────────┘
┌────┴──────────┐ Input
│ LayerNorm │
└────▲──────────┘ Attention detail (h Heads)
│ Output ▲
Input ┌────────┴────────┐
│ BitLinear │
└────────▲────────┘
┌────────┴────────┐
│ Attention │──► h Heads
└──▲─────▲─────▲──┘
Q K V
┌─────┐┌─────┐┌─────┐
│BitLi││BitLi││BitLi│
│near ││near ││near │
└──▲──┘└──▲──┘└──▲──┘
└───── Input ─┘

[!visual-conversion] Figure 9.4 — The BitLinear component (left) and the BitNet architecture (right) (p. 187) dslm-fig-9.5-comparing-the-scaling-curves-for.png

[!visual-conversion] Figure 9.5 — Comparing the scaling curves for BitNet and FP16 transformers (p. 187)

The biggest challenge in training low-bit transformers is optimization stability. The paper’s authors tested both BitNet and an FP16 baseline by training a series of models with varying peak learning rates. Figure 9.6 shows the results.

On the left of figure 9.6, BitNet converges with a high learning rate, whereas FP16 transformers fail to converge, indicating better training stability. On the right, BitNet converges when training with different learning rates—its perplexity improves as the learning rate increases.

The BitNet paper also compares this architecture with other post-training quantization (PTQ) methods, including Absmax, SmoothQuant, GPTQ, and QuIP (a 2-bit method described in “QuIP: 2-Bit Quantization of Large Language Models With Guarantees,” https://arxiv.org/abs/2307.13304). Figure 9.7, from the BitNet paper, compares the accuracy of an FP16 transformer with the same model after PTQ using different techniques, including BitNet, on zero-shot (left) and few-shot (right) downstream tasks.

dslm-fig-9.6-two-graphs-showing-ppl-perplexity.png

[!visual-conversion] Figure 9.6 — The results of the stability tests for BitNet and FP16 transformers (p. 188)

dslm-fig-9.7-two-graphs-showing-accuracy-vs.png

[!visual-conversion] Figure 9.7 — Average accuracy on downstream tasks in zero-shot (a) and few-shot (b) settings for vanilla FP16 transformers, BitNet, and various PTQ methods (p. 188)

The different techniques have been evaluated on multiple datasets; the table in figure 9.8 (from the BitNet paper) summarizes the zero-shot results.

The graphs and table in figures 9.7 and 9.8 show that BitNet’s average performance (accuracy and perplexity) is slightly lower than the FP16 Transformer baseline, but it’s much better than any other PTQ scenario.

WBitsMethodsPTQPPL↓WG↑WGe↑HS↑SC↑Avg↑
-Random✗-50.050.025.050.043.8
16Transformer✗15.1966.754.342.967.457.8
8Absmax✓21.4360.452.038.362.753.4
SmoothQuant✓15.6765.353.140.967.656.7
4GPTQ✓16.0557.251.239.963.452.9
Absmax✓4.8e455.850.925.053.146.2
SmoothQuant✓1.6e653.748.324.853.645.1
2GPTQ✓103251.650.125.853.445.2
QuIP✓70.4356.151.230.358.449.0
1Absmax✓3.5e2349.850.024.853.644.6
SmoothQuant✓3.3e2150.549.524.653.144.4
1BitNet✗17.0766.351.438.966.955.9

Figure 9.8 Zero-shot results for BitNet and a baseline Transformer (FP16), plus results after applying various quantization techniques

The BitNet framework is based on llama.cpp (introduced in chapter 6), and its core is implemented in C++. It provides optimized kernels for fast, energy-efficient, lossless inference for 1-bit models on CPUs. It doesn’t yet support GPUs, but that’s planned. You can install BitNet from source; follow the instructions for your OS in the official Microsoft GitHub repository (https://github.com/microsoft/BitNet).

BitNet also provides Python bindings, so you can run inference in Python on BitNet-quantized models hosted on the Hugging Face Hub. The main Python script, run_inference.py, uses the following syntax:

Terminal window
python run_inference.py -m models/
Falcon3-7B-Instruct-1.58bit/ggml-model-i2_s.gguf -p "You are a helpful
assistant" -cnv

In its basic form, it takes as arguments the ID of the target model in the Hugging Face Hub, a prompt, and a flag to enable or disable chat mode (valid for instructed models only). You can also pass other arguments to set the temperature, the maximum number of tokens to generate, the number of threads to use, and the prompt context size. At the time of writing, BitNet supports its native models (0.7B and 3.3B parameters) and the Llama and Falcon families. If you’d rather not use C++ and port pretrained models yourself, you can use a full Python alternative: a PyTorch port with CUDA support. The source code is available on GitHub: https://github.com/kyegomez/BitNet. It’s also available on PyPI and can be installed from there:

Terminal window
pip install bitnet

This package provides PyTorch implementations of BitLinear, the BitNet Transformer, and BitNet Attention and FeedForward.

With this API, you can create a simple BitNet Transformer as follows:

from bitnet import BitNetTransformer
bitnet = BitNetTransformer(
num_tokens=20000,
dim=1024,
depth=6,
heads=8,
ff_mult=4,
)

We use the BitNetTransformer class and specify the number of unique input tokens, the embedding dimension, the number of layers and attention heads, and the feedforward hidden-dimension multiplier. The resulting model architecture follows:

BitNetTransformer(
(emb): Embedding(20000, 1024)
(transformer): Transformer(
(layers): ModuleList(
(0-5): 6 x BitMGQA(
(q_proj): BitLinear(in_features=1024, out_features=1024, bias=True)
(k_proj): BitLinear(in_features=1024, out_features=512, bias=True)
(v_proj): BitLinear(in_features=1024, out_features=512, bias=True)
(norm): LayerNorm((512,), eps=1e-05, elementwise_affine=True)
(out_proj): BitLinear(in_features=512, out_features=1024, bias=True)
)
)
(ffn_layers): ModuleList(
(0-5): 6 x BitFeedForward(
(ff): Sequential(
(0): Sequential(
(0): BitLinear(in_features=1024, out_features=4096, bias=True)
(1): SiLU()
)
(1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)
(2): Dropout(p=0.1, inplace=False)
(3): BitLinear(in_features=4096, out_features=1024, bias=True)
)
)
)
(to_logits): Sequential(
(0): RMSNorm()
(1): Linear(in_features=1024, out_features=20000, bias=True)
)
)
)

We can easily identify all the PyTorch implementations provided by this package. This package integrates with the Hugging Face Transformers library and supports pretrained LLMs hosted on the Hugging Face Hub, not just the few model famili supported by the original BitNet framework. Let’s try it with ProtGPT2, a model discussed in section 8.2. You can download the pretrained model and tokenizer t the Hugging Face Hub using the Transformers API:

from transformers import AutoTokenizer, AutoModelForCausalLM
model_id = 'nferruz/ProtGPT2'
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)

Next, we’ll use the BitNet API to replace linear layers that have BitNet implementation

from bitnet import replace_linears_in_hf
replace_linears_in_hf(model)

Regardless of the pretrained LLM architecture, when a model is used through the Transformers API, we always call replace_linears_in_hf. As you’ll see next, the head linear layers have been replaced:

GPT2LMHeadModel(
(transformer): GPT2Model(
(wte): Embedding(50257, 1280)
(wpe): Embedding(1024, 1280)
(drop): Dropout(p=0.1, inplace=False)
(h): ModuleList(
(0-35): 36 x GPT2Block(
(ln_1): LayerNorm((1280,), eps=1e-05, elementwise_affine=True)
(atttn): GPT2SdpaAttention(
(c_attn): Conv1D()
(c_proj): Conv1D()
(atttn_dropout): Dropout(p=0.1, inplace=False)
(resid_dropout): Dropout(p=0.1, inplace=False)
)
(ln_2): LayerNorm((1280,), eps=1e-05, elementwise_affine=True)
(mlp): GPT2MLP(
(c_fc): Conv1D()
(c_proj): Conv1D()
(act): NewGELUActivation()
(dropout): Dropout(p=0.1, inplace=False)
)
)
(ln_f): LayerNorm((1280,), eps=1e-05, elementwise_affine=True)
(lm_head): BitLinear(in_features=1280, out_features=50257, bias=False)
)

We can now run inference as usual with the Transformers API, including using a pipeline:

from transformers import pipeline
pipe = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
)
sequences = pipe("<|endoftext|>",
max_length=100,
do_sample=True,
top_k=950,
repetition_penalty=1.2,
num_return_sequences=10,
eos_token_id=0)

The Python BitNet package also provides a drop-in replacement for PyTorch models:

import torch
from torch import nn
from bitnet import replace_linears_in_pytorch_model
model = nn.Sequential(
nn.Linear(10, 20),
nn.ReLU(),
nn.Linear(20, 30),
)
replace_linears_in_pytorch_model(model)

In the preceding example, all the PyTorch linear layers have been replaced with BitNet linear layers.

It is also possible to run inference with existing PyTorch checkpoints:

from bitnet import BitNetInference
bitnet = BitNetInference()
bitnet.load_model("../model_checkpoint.pth")
output_str = bitnet.generate("The dog jumped over the ", 512)

BitNet could be a viable alternative to other quantization strategies when there are computational or sustainability constraints.

This concludes our look at advanced model-quantization techniques. For many production use cases with local small language models, traditional quantization methods are a good fit. But for niche tasks involving more complex, unstructured content, you may want to use one of these advanced strategies.

Summary

  • FlexGen distributes model weights, activations, and the attention cache across the GPU, CPU, and disk, enabling large-model inference on limited hardware.
  • FlexGen uses linear programming to find efficient patterns for storing and accessing tensors across different storage types.
  • FlexGen compresses weights and the attention cache to 4 bits, increasing throughput with minimal accuracy loss.
  • In FlexGen, the Policy class sets offloading percentages and compression for weights, cache, and activations.
  • FlexGen prioritizes throughput over latency, making it best for batch processing with millions of tokens.
  • SmoothQuant addresses activation outliers in large language models by shifting the hard part of quantization from activations to weights.
  • SmoothQuant uses mathematical transformations to smooth activation magnitudes across channels before quantization.
  • Models larger than 6 to 7 billion parameters develop systematic activation outliers that degrade quantization performance.
  • SmoothQuant preserves accuracy when 8-bit quantizing weights and activations in large models.
  • SmoothQuant replaces standard linear layers to enable 8-bit weight and activation quantization.
  • BitNet introduces BitLinear components that replace traditional linear layers with 1-bit weights.
  • BitNet keeps optimizer states and gradients in high precision while using 1-bit weights in its attention layers.
  • BitLinear components cut computational costs while preserving precision for input/output embeddings.
  • BitNet trains more stably and converges more reliably than traditional FP16 transformers at high learning rates.
  • BitNet achieves competitive performance while using far less memory and energy than 8-bit quantization.
  • Python BitNet implementations offer PyTorch-compatible replacements for linear layers in existing models.