Efficient ML
NN tolerate approximation -> efficiency opportunities. Bit-level (quantisation), tensor-level (pruning), operator-level (efficient operators), architecture-level (Neural Architecture Search).
1. Quantization
We can represent weights / activations with lower-precision data types (e.g. int8, fp16, fp4) instead of fp32. Weights are simply stored in lower precision, while activations are computed in lower precision and then converted back to higher precision for the next layer.
This reduces both memory footprint and energy consumption while increasing throughput and compute density.
1.1 Floating Point
FP32 consists of
Where NaN is given by
A subnormal (denormalized) number is
We may wanna repurpose some underused bits here (e.g. sign bit) in a kind of quantisation.
| Format | Precision | |||
|---|---|---|---|---|
| FP64 | 11 | 52 | 1023 | 15-16 digits |
| FP32 | 8 | 23 | 127 | 6-7 digits |
| FP16 | 5 | 10 | 15 | 3-4 digits |
| FP8 | 4 | 3 | 7 | 2-3 digits |
| FP4 | 2 | 1 | 1 | 1 digit |
1.2 Integer
Unsigned integers are simply
Signed integers are usually represented in two's complement with range
1.3 Emerging Data Types
Block Floating Point: keep the exponent shared across a block of numbers, while each number has its own mantissa and sign bit. This allows for a more efficient representation of numbers with similar magnitudes. This saves memory and potentially improves performance as fixed-point arithmetic can be used within a block.
Microscaling (MX): use a block of
1.4 Quantisation Paradigms
- Post Training Quantization (PTQ) - Train model in heihg precision, then calibrate quantization hyperparameters, apply quantization. No retraining required & fast deployment, but may lead to accuracy loss. Extra memory cost for fine-grained quantization.
- Quantization-Aware Training (QAT) - start full-precision training, and incorporate quantization during finetuning. Models learn to be robust to quantization noise. Then export quantized model. Better at maintaining accuracy, & enable low bit widths (e.g. FP4), but is more time consuming during training, and extra training data is required.
Fake Quantization: simulates quantization during QAT by injecting quantization noise (while still learning at high precision). Useful when no hardware support for low-precision computation.
1.5 Linear Quantization
An affine mapping of integers
is the scale factor, an arbitrary postive real number that determines the step size between quantized values. is the zero-point, an integer that determines the quantized value that corresponds to the real value of zero.
So, for tensor
Multiple layers can be chained together. Quantize initial input tensor, then for each layer:
- Perform matmul in integer.
- Accumulate results in high bit-width (e.g. INT32).
- Apply scaling rounding and zero-point to get quantized output tensor.
- Map results back to low-bit integer for next layer.
1.6 Symmetric vs Asymmetric
- Symmetrics: zero-centered: equal negative & postive ranges. Simpler implementation, but wastes representational capacity if data is not zero-centered.
- Assymetric: range shifted to cover non-zero-centered data. Better representational capacity, but more complex implementation. (
).
1.7 Non-linear Quantization
Linear quantisation is suboptimal for heavy-tailed or highly-skewed distributions.
An example of non-linear quantisation is logarithmic quantisation where:
K-means quantization clusters weight values into a limited number of centroids:
- Apply K-means to group weights into
-clusters. - Store cluster centroids in a lookup table (codebook).
- Use an index, replacing each weight by its centroid index.
- During inference, weights are reconstructed from the lookup table.
1.8 Block / Group Size
There are granularity trade-offs:
- Large blocks: less metadata, but higher quantization error.
- Small blocks: more metadata, but lower quantization error.
Addionally, we can have:
- Per-layer quantization: one scale/zero point for the whole layer. Low metadata, easy alignment but high quantization error.
- Per-group quantization: one scale/zero point for each group of channels. A balance between metadata and quantization error.
- Per-channel quantization: one scale/zero point for each channel. Low quantization error, but high metadata and alignment complexity.
1.9 Dynamic vs Static
- Static: Optimize quantization configuration ahead of time, keep fixed during inference. High accuracy loss when data drifts during runtime.
- Dynamic: Determine and adjust quantization configuration on-the-fly during inference. Better accuracy, but more complex implementation and higher runtime overhead.
2. Pruning
Reduce model size by removing redundant weights.
- Learn connectivity via normal training.
- Prune low-weight connections (e.g. below a threshold).
- Retain network with sparse connections.
Iterative pruning: repeats step 2 and 3, until satisfactory performance is achieved. Compression rate is
This reduces computation and memory cost. Pruning can be:
- Point-wise pruning: removes individual weights based on their values. High sparsity and given accuracies, but harder to accelerate without structured sparsity.
- Channel-wise pruning: removes entire channels from the network. Easier to accelerate with structured sparsity, but may result in lower accuracy.
- Layer-wise pruning: remove whole layers from the network. Significantly reduces latency but requires distillation or re-training to recover accuracy loss.
- Expert-wise pruning: removes redundant or low-utility experts during inference.
Structured pruning enforces regular sparsity patterns for hardware efficiency. This depends on the memory access patterns and accelerator support. Modern AI accelerators integrate sparisty-aware computation.
NVIDIA supports
-sparse matrix multiplication, where is the number of non-zero elements per row and is the number of non-zero elements per column. This allows for efficient computation on sparse matrices.
- Static pruning uses a fixed sparsity pattern during runtime. Easy for hardware explotation, no runtime overhead. But, accuracy loss if data distribution drifts.
- Dynamic pruning adaptively adjusts sparsity patterns during runtime based on heuristics. This adapts to different data distributions and streaming inputs, but has runtime overhead and harder hardware scheduling.
3. Efficient Operators
We want to convert dense operations to sparse operations, and reduce the number of operations required for a given task.
In multi-head attention, seperate
Instead, grouped query attention (GQA) makes the number of shared
4. Neural Architecture Search (AutoML)
Neural architecture is manually designed, constrained by hardware and requires time consuming hyperparameter tuning.
Using Reinforcement Learning for NAS: adopts an RNN to predict neural architecture configuration, train the architecture, and use the validation accuracy as a reward signal to update the RNN. This is repeated until convergence. However, this is very computationally expensive. Search cost depends on:
- Sampling / Evaluation cost: time taken to obtain a reward signal (training time). This can be reduced by using proxy loss (training on a smaller dataset or fewer epochs).
- Search Efficiency could be: genetic / evolutionary algorithm, bayesian optimisation or a gradient based approach.
4.1 DARTS
Differentiable Architecture Search (DARTS) relaxes the discrete search space to a continuous one, allowing for gradient-based optimization. It represents the NAS problem as a DAG, where each node
For an operation pool
- Each operation is parameterized by a continuous variable
, where . This represents the importance of each operation in the search space. - Relax the choice of operations to a softmax over all possible operations:
. - Apply gradient descent to iteratively update
and the network weights . - Final architecture is obtained by selecting
for each edge.
This reduces NAS search cost with comparable results, but has high memory consumption and no hardware awareness. To fix this, we can add a expected latency loss to the loss function, which penalizes architectures with high latency. This encourages the search to find architectures that are both accurate and efficient.