An AI model can be accurate yet too slow or expensive for the intended product. Inference optimization aims to deliver required quality with acceptable latency, throughput, memory use, and cost. One common technique is quantization, which represents some model values with lower-precision numbers.
1. What happens during inference?
The system preprocesses an input, runs mathematical operations using trained weights, and postprocesses the output. Costs depend on model size, operation types, data shapes, execution hardware, and runtime implementation.
Improving performance is not simply “making the model smaller.” An optimization that reduces memory may slow a particular device, and a faster model may become less accurate on important cases.
2. Precision and quantization
Weights are often stored using floating-point formats such as FP32, FP16, or BF16. Quantization can map some values to low-bit representations such as INT8 or 4-bit formats, usually with scales and sometimes zero points that approximate the original numbers.
A simplified symmetric quantizer uses:
where is a real value, is a scale, and is a signed integer. Approximate reconstruction is .
This formula illustrates one scheme; practical inference frameworks use different granularity, zero-point conventions, and hardware kernels.
3. A numeric example
Let . The value maps to and reconstructs as . The error is . Rounding errors accumulate differently across layers, so accuracy must be measured on the actual task.
For weights alone, changing from 32 bits to 8 bits suggests a theoretical 4× reduction in their raw storage. Real memory savings are lower or higher depending on metadata, activations, caches, other buffers, and implementation.
4. Common strategies
- Post-training quantization: Quantize a pretrained model, possibly using calibration data.
- Quantization-aware training: Simulate quantization effects during training so the model adapts.
- Pruning: Remove selected parameters or structures, potentially reducing work if the runtime exploits the sparsity.
- Distillation: Train a smaller student model using outputs or representations from a larger teacher.
- Kernel and graph optimization: Fuse operations and choose efficient implementations for target hardware.
- Batching and caching: Reuse computation or process compatible requests together when beneficial.
These techniques have distinct accuracy and deployment costs. Quantization is not a substitute for improving the algorithm or fixing unnecessary requests.
5. Python demonstration of quantization error
import numpy as np
values = np.array([-1.24, -0.11, 0.07, 1.26], dtype=np.float32)
scale = 0.1
integers = np.clip(np.rint(values / scale), -127, 127).astype(np.int8)
reconstructed = integers.astype(np.float32) * scale
print('quantized:', integers)
print('reconstructed:', reconstructed)
print('maximum absolute error:', np.max(np.abs(values - reconstructed)))
This illustrates rounding and reconstruction, not a full framework-level quantization of a neural network.
6. Benchmark correctly
Measure after warmup and with representative input lengths, batch sizes, and request patterns. Record p50/p95 latency, throughput, peak memory, cold-start time, and task quality. A microbenchmark of one tensor operation does not necessarily predict end-to-end service performance.
For generative models, distinguish prompt processing from token generation. Quantization may affect both differently. Measure hallucination-related failure modes and high-impact classes as well as average accuracy.
7. When optimization backfires
Small batch sizes can underutilize a GPU; large batches may cause memory pressure or queueing. Low-bit arithmetic requires suitable kernels. Aggressive pruning may add overhead when sparsity is not supported. A model that fits in memory may still violate response-time requirements.
Choose a target metric first, change one factor at a time, and retain a reproducible baseline and rollback path.
Related concepts
- Model Serving and Deployment
- GPU Compute, Latency, and Throughput
- LLM Inference, Decoding, and Sampling
- Evaluating Machine Learning Models
References
Related articles in
- Clustering and K-Means — Learn how unsupervised clustering discovers groups in data, how K-Means optimizes cluster centroids, and how to evaluate and use its results responsibly.
- Data, Model, and Experiment Versioning — Learn to trace ML results to exact datasets, code revisions, configurations, and artifacts.
- Decision Trees, Random Forests, and Boosting — Learn how decision trees partition data, how random forests reduce variance through bagging, and how boosting combines sequential learners to improve predictions.