As Large Language Models (LLMs) continue to scale into tens and hundreds of billions of parameters, deploying them efficiently at scale remains one of the most critical engineering challenges in modern artificial intelligence. While weight-only quantization techniques—such as AWQ and GPTQ—have successfully slashed memory footprints by compressing model weights ahead of deployment, they leave runtime activations untouched in higher-precision formats (typically FP16 or BF16).
The next frontier in LLM optimization is Activation and Floating-Point Quantization (specifically W8A8 and FP8 workflows). Unlike static model weights, which are finalized during training and remain invariant across inference requests, activations are dynamic tensors generated on-the-fly. They fluctuate wildly based on input tokens, sequence positions, and previous layers, frequently harboring persistent numerical outliers.
This comprehensive guide explores the complexities of activation quantization, examines advanced mathematical workarounds like SmoothQuant, unpacks the nuances of FP8 floating-point formats, and provides a production-grade blueprint for building and deploying compressed checkpoints using llmcompressor and vLLM.
Detailed Chronology & Technical Evolution
To understand where modern activation quantization stands today, it is helpful to examine the evolutionary path hardware and software optimizations have taken over recent years:
- The Pre-Quantization Era: Early LLM deployments relied heavily on native FP16 or BF16 arithmetic. While straightforward, memory bandwidth bottlenecks severely restricted token generation speeds, making large-scale serving economically unviable.
- The Rise of Weight-Only Quantization: Techniques like GPTQ and AWQ emerged to compress weights down to 4 bits or 8 bits. This dramatically reduced the GPU VRAM footprint required to load massive models, allowing multi-billion parameter networks to fit onto fewer enterprise accelerators. However, because activations remained in FP16, computing matrix multiplications still required high-precision accumulator paths and failed to fully unlock the integer arithmetic throughput of modern tensor cores.
- The Introduction of INT8 W8A8 & SmoothQuant (2022–2023): Researchers identified that shifting the numerical burden from unruly activations back to static weights via mathematical equivalence (SmoothQuant) could clear the path for true W8A8 (8-bit weights, 8-bit activations) execution. This unlocked efficient integer matrix multiplication primitives on hardware architectures like NVIDIA Turing, Ampere, and Hopper.
- The Standardization of FP8 Formats (2023–Present): With the release of NVIDIA Ada Lovelace, Hopper, and subsequent architectures, native hardware support for 8-bit floating-point types (FP8)—specifically E4M3 and E5M2 variants—gained prominence. This shift provided a superior balance of dynamic range and precision compared to affine INT8, minimizing the accuracy degradation seen in sensitive generative models.
Why Activations Are Hard to Quantize
The fundamental difficulty in quantizing activation tensors stems from their dynamic, request-dependent nature. While a weight matrix is fixed once training concludes, an activation tensor entering a linear layer is born at runtime. Its range of values depends entirely on user prompts, context lengths, and preceding architectural blocks.
Static vs. Dynamic Activation Quantizers
Engineers generally approach activation quantization using one of two paradigms:
- Static Activation Quantization: Relies on calibration data gathered prior to deployment to predict the expected ranges of runtime tensors. While computationally fast because quantization scales are pre-calculated, it risks catastrophic clipping if a user input generates values outside the calibration boundary.
- Dynamic Activation Quantization: Measures the tensor at runtime, adapting the scale factor instantly to every incoming token.
Below is a standard PyTorch implementation of a dynamic per-token activation quantizer operating on a signed symmetric INT8 scheme:
import torch
def quantize_activation_per_token(x):
qmax = 127
scale = x.abs().amax(dim=-1, keepdim=True) / qmax
scale = scale.clamp_min(torch.finfo(x.dtype).eps)
q = torch.round(x / scale).clamp(-qmax, qmax)
return q.to(torch.int8), scale
x = torch.randn(2, 32, 1024)
q, scale = quantize_activation_per_token(x)
x_hat = q.float() * scale
print("mean absolute error:", (x - x_hat).abs().mean().item())
For an activation tensor shaped [batch, sequence, hidden], reducing over the final dimension yields a scale shaped [batch, sequence, 1]. This means a single scale is shared across all hidden features for a given token—a strategy frequently referred to as per-row quantization.
The Outlier Dilemma
Transformer architectures are notoriously plagued by persistent outlier channels—specific dimensions across the hidden state that exhibit activation magnitudes orders of magnitude larger than their neighbors.
- If a quantization scheme attempts to cover the entire absolute maximum of these outliers, the resulting step size becomes too coarse for ordinary values, degrading the model’s overall representational quality.
- Conversely, clipping the outliers to preserve resolution for ordinary values destroys critical signals, often leading to gibberish output during generation.
W8A8 Inference and SmoothQuant
To resolve the outlier problem without sacrificing performance, researchers developed SmoothQuant. SmoothQuant mathematically migrates the quantization difficulty from activations over to the weights, transforming a mathematically equivalent linear layer operation:
$$mathbfy = mathbfxmathbfW^top = (mathbfx operatornamediag(mathbfs)^-1)(mathbfW operatornamediag(mathbfs))^top$$
By dividing large activation channels by a carefully tuned scale vector $mathbfs$ and multiplying the corresponding weight columns by those same scales, the activation range is successfully smoothed out. Because weights are static, they absorb this uneven range adjustment seamlessly via per-channel quantization.
The mathematical equivalence of this transformation can be validated in PyTorch:
import torch
import torch.nn.functional as F
x = torch.randn(4, 128)
weight = torch.randn(256, 128)
smooth_scale = torch.rand(128) + 0.5
reference = F.linear(x, weight)
smoothed_x = x / smooth_scale
smoothed_weight = weight * smooth_scale
transformed = F.linear(smoothed_x, smoothed_weight)
torch.testing.assert_close(transformed, reference, rtol=1e-5, atol=1e-5)
Building W8A8 Checkpoints with LLM Compressor
Modern toolchains such as llmcompressor (integrated within the vLLM ecosystem) simplify the creation of reusable INT8 checkpoints. The script below loads a baseline model, applies a SmoothQuant recipe combined with a GPTQ modifier, and saves an optimized W8A8 artifact:
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from llmcompressor import oneshot
from llmcompressor.modifiers.gptq import GPTQModifier
from llmcompressor.modifiers.transform.smoothquant import SmoothQuantModifier
model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
output_dir = "models/tinyllama-w8a8"
num_calibration_samples = 128
max_sequence_length = 512
model = AutoModelForCausalLM.from_pretrained(
model_id,
device_map="auto",
dtype="auto",
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset(
"HuggingFaceH4/ultrachat_200k",
split="train_sft",
)
dataset = dataset.shuffle(seed=42).select(range(num_calibration_samples))
def preprocess(example):
text = tokenizer.apply_chat_template(example["messages"], tokenize=False)
return "text": text
def tokenize(example):
return tokenizer(
example["text"],
max_length=max_sequence_length,
truncation=True,
add_special_tokens=False,
)
dataset = dataset.map(preprocess)
dataset = dataset.map(tokenize, remove_columns=dataset.column_names)
recipe = [
SmoothQuantModifier(smoothing_strength=0.8),
GPTQModifier(targets="Linear", scheme="W8A8", ignore=["lm_head"]),
]
oneshot(
model=model,
dataset=dataset,
recipe=recipe,
max_seq_length=max_sequence_length,
num_calibration_samples=num_calibration_samples,
)
model.save_pretrained(output_dir, save_compressed=True)
tokenizer.save_pretrained(output_dir)
print(f"Saved the INT8 checkpoint to output_dir")
Once saved, the local checkpoint can be loaded directly into vLLM for high-throughput serving:
from vllm import LLM, SamplingParams
model = LLM(model="models/tinyllama-w8a8")
sampling_params = SamplingParams(temperature=0, min_tokens=16, max_tokens=64)
outputs = model.generate(
["Explain activation quantization in one paragraph."],
sampling_params,
)
print(outputs[0].outputs[0].text)
Floating-Point Quantization (FP8 Workflow)
As hardware accelerators have evolved to support native 8-bit floating-point math, FP8 has emerged as a compelling alternative to affine INT8. Unlike fixed-point integer representations, FP8 formats utilize an exponent-mantissa structure (such as E4M3 for higher precision or E5M2 for wider dynamic range), providing nonuniform spacing that naturally handles broad value distributions without requiring complex zero-point shifts.
The scaling mechanism for FP8 can be expressed as:
$$q = operatornamecasttextFP8(x/s)$$
$$hatx = soperatornamecasttextFP16 or FP32(q)$$
Dynamic FP8 Conversion
For scenarios where calibration data is unavailable or unnecessary, dynamic FP8 schemes compute weight scales on the fly from the static parameters, while letting the inference engine measure activation tensors dynamically per token.
from transformers import AutoModelForCausalLM, AutoTokenizer
from llmcompressor import oneshot
from llmcompressor.modifiers.quantization import QuantizationModifier
model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
output_dir = "models/tinyllama-w8a8-fp8"
model = AutoModelForCausalLM.from_pretrained(model_id, dtype="auto")
tokenizer = AutoTokenizer.from_pretrained(model_id)
recipe = QuantizationModifier(
targets="Linear",
scheme="FP8_DYNAMIC",
ignore=["lm_head"],
)
oneshot(model=model, recipe=recipe)
model.save_pretrained(output_dir, save_compressed=True)
tokenizer.save_pretrained(output_dir)
print(f"Saved the FP8 checkpoint to output_dir")
For models suffering from severe activation outliers, SmoothQuant can be cleanly paired with FP8 quantization using calibration datasets, ensuring optimal performance across target hardware architectures like NVIDIA Ada Lovelace, Hopper, and Blackwell.
Future Outlook & Architectural Considerations
As the machine learning ecosystem matures, the choice between W4A16, W8A8, and FP8 quantization will depend heavily on specific operational constraints:
- Prefill vs. Decode Bottlenecks: Activation quantization primarily accelerates compute-bound, matrix-heavy operations like the prompt prefill phase. However, during small-batch token generation (decoding), memory bandwidth remains the primary bottleneck, meaning that weight-only compression (W4A16) may still offer competitive or superior tail latency.
- Hardware Co-Design: Future accelerators are expected to incorporate increasingly sophisticated native data-type switching and hardware-accelerated dynamic scaling, reducing the runtime overhead associated with per-token reduction steps.
- Comprehensive Benchmarking: Engineering teams must avoid evaluating quantized models solely on static perplexity scores. End-to-end latency, throughput (tokens per second), memory utilization, and task-specific accuracy must be thoroughly profiled under realistic production workloads before enterprise deployment.