Model Pruning
local graph
Chapter 11 — Model Pruning
Section titled “Chapter 11 — Model Pruning”In this chapter, we’ll explore model pruning techniques designed to reduce model size while maintaining performance.
Model pruning refers to the systematic elimination of unnecessary parameters from a neural network while maintaining performance. For LLMs, this typically involves identifying and removing redundant or less important weights, neurons, or attention heads based on criteria such as magnitude, sensitivity analysis, or gradient-based importance.
You’ll learn how to implement various pruning methods, from magnitude-based pruning to iterative techniques, and the trade-offs involved in size reduction versus performance. Additionally, this chapter will help you decide whether to prune during or after training, ensuring your LLMs remain efficient and effective.
In this chapter, we’ll be covering the following topics:
- Magnitude-based pruning
- Structured versus unstructured pruning
- Iterative pruning techniques
- Pruning during training versus post-training pruning
- Balancing pruning and model performance
- Combining pruning with other compression techniques
Magnitude-based pruning
Section titled “Magnitude-based pruning”Magnitude-based pruning is one of the simplest and most widely used pruning techniques. The idea behind this method is to remove weights in the neural network that contribute least to the model’s overall function, typically, these are weights with the smallest magnitude (absolute value). By pruning such weights, the model becomes more compact and faster, with minimal impact on accuracy:
import torchimport torch.nn.utils.prune as prune# Assume model is an instance of a pre-trained LLMmodel = ... # Load or define your LLM model# Prune 30% of the lowest magnitude weights in all Linear layersfor name, module in model.named_modules(): if isinstance(module, torch.nn.Linear): prune.l1_unstructured(module, name='weight', amount=0.3)# Remove the pruning reparameterizationfor name, module in model.named_modules(): if isinstance(module, torch.nn.Linear): prune.remove(module, 'weight')In this code example, magnitude-based pruning removes 30% of the lowest-magnitude weights in all linear layers of an LLM. The prune.l1_unstructured function specifies that weights with the smallest L1 norm will be pruned.
The following code snippet implements the prune.l1_unstructured function for unstructured L1-norm-based pruning on a given parameter tensor within a PyTorch module by zeroing out weights with the smallest absolute values:
def prune.l1_unstructured(module, name, amount):"""Prunes weights with lowest L1 norm magnitude in a module's tensor"""# Get the parameter to prunetensor = getattr(module, name)# Calculate number of parameters to prunen_params_to_prune = int(amount * tensor.numel())# Get magnitude threshold (kth smallest absolute value)threshold = torch.kthvalue( tensor.abs().view(-1), n_params_to_prune).values# Create and apply mask (zeros out weights below threshold)mask = tensor.abs() > thresholdpruned_tensor = tensor.clone() * mask# Update parameter and register masksetattr(module, name, torch.nn.Parameter(pruned_tensor))module.register_buffer(f'{name}_mask', mask)# Add hook to maintain pruning during updatesmodule.register_forward_pre_hook( lambda m, _: setattr( m, name, torch.nn.Parameter( getattr(m, name) * getattr(m, f'{name}_mask') ) ))return maskHere, the function begins by extracting the target tensor from the module and determining how many of its elements should be pruned based on the specified proportion amount. It identifies a pruning threshold by computing the k -th smallest absolute value in the tensor, where k corresponds to the number of parameters to prune. A binary mask is then created, where values above the threshold are retained while those below the threshold are set to zero. This mask is applied to produce a pruned version of the tensor, which replaces the original parameter in the module. The mask is stored as a buffer to persist across model operations, and a forward pre-hook is registered to ensure that pruning is enforced before every forward pass, preserving the sparsity pattern even if the underlying weights are updated during training.
In model pruning, the L1 norm is used to evaluate the importance of weights or parameters in a model by summing the absolute values of their components, with lower L1 norm values often indicating less significant parameters that can be removed to reduce model size while maintaining performance.
After pruning, the prune.remove method is called to remove the pruning reparameterization and make the changes permanent.
Magnitude-based pruning is particularly effective for models with many small weights that contribute little to overall performance, but it may not be sufficient when applied alone for large-scale pruning.
Structured versus unstructured pruning
Section titled “Structured versus unstructured pruning”When pruning LLMs, you can either prune weights individually (unstructured pruning) or remove entire structures, such as filters, channels, or attention heads (structured pruning):
- Unstructured pruning: This involves removing individual weights based on magnitude or other criteria. It provides more granularity but can result in sparse matrices, which are harder to optimize on standard hardware, as demonstrated in the
prune.l1_unstructuredfunction described earlier. - Structured pruning: Entire sections of the model, such as neurons, channels, or layers, are pruned. This approach is easier to implement on modern hardware and often leads to better speedups in inference time, even though it may have a larger immediate effect on model performance.
Structured pruning in LLMs can be implemented using PyTorch’s built-in utilities, as shown in the following code. Here, we apply L2-norm structured pruning to remove 30% of neurons across linear layers, targeting entire rows of weight matrices to effectively eliminate complete neurons rather than just individual connections:
import torch.nn.utils.prune as prune# Structured pruning of entire neurons in a layerfor name, module in model.named_modules(): if isinstance(module, torch.nn.Linear): prune.ln_structured( module, name='weight', amount=0.3, n=2, dim=0 )In this structured pruning example, the ln_structured function removes entire neurons from the linear layer based on the L2 norm across all weights in a given dimension. The choice of structured pruning can significantly reduce computational complexity while also making the model more suitable for deployment on standard hardware architectures.
Next, we’ll see how to prune a small fraction of weights at a time over multiple training steps instead of pruning large portions of the model in a single pass.
Iterative pruning techniques
Section titled “Iterative pruning techniques”Here, we’ll talk about iterative pruning, which allows you to prune a small fraction of weights at a time over multiple training steps. This method reduces the risk of drastic performance drops and provides more opportunities for the model to recover and adjust to the pruning.
The iterative approach also allows for fine-tuning after each pruning step, enabling the model to “heal” from the weight reduction:
# Iteratively prune 10% of the model after every 10 epochsfor epoch in range(1, num_epochs+1): train(model, train_loader, optimizer) # Regular training step if epoch % 10 == 0: for name, module in model.named_modules(): if isinstance(module, torch.nn.Linear): prune.l1_unstructured(module, name='weight', amount=0.1) prune.remove(module, 'weight') # Remove pruning mask after each step validate(model, val_loader)In this example, 10% of the weights are pruned after every 10 epochs. The gradual removal of weights ensures that the model has enough time to adjust between each pruning step. Iterative pruning, combined with validation steps, can help find a more optimal balance between model size and performance.
Pruning during training versus post-training pruning
Section titled “Pruning during training versus post-training pruning”A key decision in applying pruning is whether to prune the model during training or after training is complete:
- Pruning during training: This approach allows the model to adjust to the pruned structure over time by iteratively pruning weights as it learns. The model can compensate for pruned weights, potentially resulting in better final performance. However, it requires more computational resources and
Here’s an example of this approach:
import torchimport torch.nn.utils.prune as prune# Assuming model is a pre-trained LLMmodel = ... # Load or define your LLM modeloptimizer = torch.optim.Adam(model.parameters(), lr=0.001)criterion = torch.nn.CrossEntropyLoss()def train(model, train_loader, optimizer):model.train()for batch in train_loader:inputs, targets = batchoptimizer.zero_grad()outputs = model(inputs)loss = criterion(outputs, targets)loss.backward()optimizer.step()# Prune 20% of the weights every 5 epochs during trainingfor epoch in range(1, 20):train(model, train_loader, optimizer)# Apply pruning every 5 epochsif epoch % 5 == 0:for name, module in model.named_modules():if isinstance(module, torch.nn.Linear):prune.l1_unstructured(module, name='weight',amount=0.2)prune.remove(module, 'weight') # Remove reparameterization after each pruning
- Post-training pruning: In this approach, pruning is performed after the model has been fully trained. This method is computationally efficient since it doesn’t require modifications during the training process, and you can optionally fine-tune the model afterward. However, it may result in a larger accuracy drop compared to pruning
Let’s take a look at an example of post-training pruning:
# Assuming the model has already been fully trainedmodel = ... # Load or define your trained LLM model# Prune 30% of the weights in all Linear layers after trainingfor name, module in model.named_modules():if isinstance(module, torch.nn.Linear):prune.l1_unstructured(module, name='weight', amount=0.3)# Optionally, fine-tune the model after pruningfine_tune_epochs = 3for epoch in range(fine_tune_epochs):train(model, train_loader, optimizer) # Fine-tuning the pruned model
The choice between these two depends on your performance constraints and available resources. Pruning during training often leads to more stable models, while post-training pruning is faster and more resource-efficient.
Balancing pruning and model performance
Section titled “Balancing pruning and model performance”Finding the right balance between pruning and model performance is critical. Aggressive pruning can lead to significant performance degradation, while too little pruning may not yield enough benefits. The key is to identify which parts of the model can be pruned with minimal impact on accuracy. This requires careful validation after each pruning step and close monitoring of key performance metrics. These metrics include parameter reduction rates, inference speed gains, memory footprint reduction, changes in perplexity, and task-specific performance. Throughout the process, it’s crucial to balance the accuracy-efficiency trade-off to ensure the pruned model retains acceptable performance despite having fewer parameters
A common strategy is to apply fine-tuning after pruning to restore some of the lost performance. Fine-tuning allows the model to adjust to the pruned structure and recover its original capabilities:
import torch.nn.utils.prune as prune# Assuming model has been trained and prunedmodel = ... # Pruned LLM model# Apply fine-tuning to restore performance after pruningoptimizer = torch.optim.Adam(model.parameters(), lr=1e-5) # Lower learning rate for fine-tuningfine_tune_epochs = 5for epoch in range(fine_tune_epochs): train(model, train_loader, optimizer) # Reuse the train function from earlier validate(model, val_loader) # Validation step to monitor performanceIn this example, after pruning a portion of the weights, the model is fine-tuned with a lower learning rate to restore performance. A lower learning rate allows the model to adjust gradually to the new pruned structure, preventing the destabilization of learned features. Validation is performed after each fine-tuning step to monitor the model’s progress and ensure that pruning has not significantly degraded performance.
Let’s see how we can combine pruning with other model compression techniques.
Combining pruning with other compression techniques
Section titled “Combining pruning with other compression techniques”Pruning can be combined with other model compression techniques, such as quantization or distillation, to achieve even greater reductions in model size and complexity. Combining these techniques often results in more compact models that maintain high performance.
Pruning and quantization
Section titled “Pruning and quantization”Pruning followed by quantization can lead to significant reductions in model size and faster inference speeds, especially for resource-constrained environments:
import torchimport torch.nn.utils.prune as pruneimport torch.quantization as quant# Prune the model firstmodel = ... # Pre-trained LLMfor name, module in model.named_modules(): if isinstance(module, torch.nn.Linear): prune.l1_unstructured(module, name='weight', amount=0.4) prune.remove(module, 'weight')# Apply dynamic quantization after pruningquantized_model = quant.quantize_dynamic( model, {torch.nn.Linear}, dtype=torch.qint8)# Check the size reductionprint("Original model size:", torch.cuda.memory_allocated())print("Quantized model size:", torch.cuda.memory_allocated())Pruning and knowledge distillation
Section titled “Pruning and knowledge distillation”You can also combine pruning with knowledge distillation, where a smaller, pruned student model is trained to mimic the behavior of a larger, well-trained teacher model:
# Teacher and student models for knowledge distillationteacher_model = ... # Larger, fully trained modelstudent_model = ... # Smaller model to be distilled and pruneddef distillation_loss(student_outputs, teacher_outputs, temperature): return torch.nn.KLDivLoss()( torch.nn.functional.log_softmax( student_outputs / temperature ), torch.nn.functional.softmax( teacher_outputs / temperature ) )# Train the smaller, pruned model using knowledge distillationtemperature = 2.0optimizer = torch.optim.Adam(student_model.parameters(), lr=1e-4)for batch in train_loader: inputs, _ = batch teacher_outputs = teacher_model(inputs) student_outputs = student_model(inputs) loss = distillation_loss( student_outputs, teacher_outputs, temperature ) loss.backward() optimizer.step()This approach allows the student model to achieve high performance with fewer parameters. Knowledge distillation helps compensate for accuracy loss caused by pruning by transferring high-level representations from the unpruned teacher model.
These examples illustrate how pruning can be applied during or after training, balanced with performance requirements, and combined with other compression techniques such as quantization and knowledge distillation to create more efficient LLMs.
Summary
Section titled “Summary”In this chapter, we explored various model pruning techniques for LLMs, including magnitude-based pruning, structured versus unstructured pruning, and iterative pruning methods. We discussed the trade-offs involved in pruning during training versus post-training, and the importance of fine-tuning after pruning to recover lost performance. By combining pruning with other compression techniques, such as quantization and distillation, you can create more efficient LLMs suitable for deployment in resource-constrained environments.
In the next chapter, we’ll explore quantization techniques for LLMs, focusing on reducing numerical precision to improve model efficiency while maintaining performance. You’ll learn how to apply post-training and quantization-aware training to optimize your LLMs further.