Tuesday, December 1, 2026
Mobile Offer

🎁 You've Got 1 Reward Left

Check if your device is eligible for instant bonuses.

Unlock Now
Survey Cash

🧠 Discover the Simple Money Trick

This quick task could pay you today — no joke.

See It Now
Top Deals

📦 Top Freebies Available Near You

Get hot mobile rewards now. Limited time offers.

Get Started
Game Offer

🎮 Unlock Premium Game Packs

Boost your favorite game with hidden bonuses.

Claim Now
Money Offers

💸 Earn Instantly With This Task

No fees, no waiting — your earnings could be 1 click away.

Start Earning
Crypto Airdrop

🚀 Claim Free Crypto in Seconds

Register & grab real tokens now. Zero investment needed.

Get Tokens
Food Offers

🍔 Get Free Food Coupons

Claim your free fast food deals instantly.

Grab Coupons
VIP Offers

🎉 Join Our VIP Club

Access secret deals and daily giveaways.

Join Now
Mystery Offer

🎁 Mystery Gift Waiting for You

Click to reveal your surprise prize now!

Reveal Gift
App Bonus

📱 Download & Get Bonus

New apps giving out free rewards daily.

Download Now
Exclusive Deals

💎 Exclusive Offers Just for You

Unlock hidden discounts and perks.

Unlock Deals
Movie Offer

🎬 Watch Paid Movies Free

Stream your favorite flicks with no cost.

Watch Now
Prize Offer

🏆 Enter to Win Big Prizes

Join contests and win amazing rewards.

Enter Now
Life Hack

💡 Simple Life Hack to Save Cash

Try this now and watch your savings grow.

Learn More
Top Apps

📲 Top Apps Giving Gifts

Download & get rewards instantly.

Get Gifts
Summer Drinks

🍹 Summer Cocktails Recipes

Make refreshing drinks at home easily.

Get Recipes

Latest Posts

Model Compression Beyond Quantization – MachineLearningMastery.com


Quantization changes how model values are represented. Other compression methods reduce the number of values or the size of model structures. Pruning removes weights or structures, while knowledge distillation trains a smaller student to reproduce a teacher’s behavior.

Serving a smaller model is often an effective inference optimization. It reads fewer weights and may use less cache, depending on its layer count, KV heads, and head dimension. It may also allow larger batches or cheaper hardware. The difficult part is preserving the behavior the application needs and ensuring that the compressed structure is supported efficiently by the runtime.

In this post, you will learn about:

  • How pruning removes weights and when sparsity can improve execution
  • How structured pruning changes model shapes and compute
  • How distillation trains a smaller model for serving

Let’s get started.

Model Compression Beyond Quantization.
Photo by Kutan Ural. Some rights reserved.

Overview

This post is divided into three parts; they are:

  • Pruning and Sparsity
  • Structured Pruning
  • Knowledge Distillation

Pruning and Sparsity

Pruning sets selected model parameters to zero or removes larger structures. Magnitude pruning starts with a simple assumption: weights with small absolute values may have less effect on the output.

Sparse and dense matrix multiplication can accumulate terms in a different order, so the script compares their outputs with a numerical tolerance. The sparsity argument represents the fraction of weights intended for removal. Setting sparsity=0.0 retains all weights. The upper bound excludes sparsity=1.0, which would remove every weight and make the layer unusable. After pruning, zeros can appear anywhere in pruned_weight, but that tensor is still stored densely. Calling to_sparse_csr() creates a compressed sparse row tensor that stores the nonzero values together with row and column metadata. The function torch.sparse.mm() then multiplies that sparse matrix by a dense matrix. A sparse representation saves space only when its metadata costs less than the removed data, and it improves speed only when the matrix shape, sparsity level, dtype, and hardware have an efficient sparse kernel.

Structured Pruning

Structured pruning removes complete units such as attention heads, MLP channels, layers, or blocks. The result can often be represented as a smaller dense model, which makes it easier to accelerate across hardware.

A transformer MLP uses one projection to expand each hidden vector into an intermediate representation and another to project it back to the model’s hidden size:
$$
\mathbf{y} = \mathbf{W}_{\text{down}} \phi(\mathbf{W}_{\text{up}} \mathbf{x})
$$
Each intermediate channel is produced by one row of $\mathbf{W}_{\text{up}}$ and consumed by the matching column of $\mathbf{W}_{\text{down}}$. Removing a row from the up projection therefore requires removing the corresponding column from the down projection. The following small example removes intermediate channels according to the norms of the first projection’s rows:

The parameter keep_channels is the number of intermediate MLP channels retained after pruning; it is a count, not a sparsity fraction. It must be an integer from 1 through up_proj.out_features, and the original projections must satisfy up_proj.out_features == down_proj.in_features. The code ranks the rows of up_proj.weight by their norms and keeps the keep_channels highest-scoring rows. It then keeps the matching columns of down_proj.weight, so the reduced output of smaller_up remains a valid input to smaller_down. For example, setting keep_channels=2048 reduces an original intermediate width of 8192 to 2048 channels.

This code preserves compatible tensor shapes but does not determine whether the chosen channels are truly unimportant. A real pruning method evaluates layer outputs, interactions, and recovery fine-tuning.

Removing attention heads requires similar coordinated edits to query, key, value, and output projections. With GQA, query heads share KV heads, so arbitrary head removal can break grouping. Removing transformer layers changes residual depth and may require learning mappings between the retained layers. These changes require coordinated edits and quality checks.

Structured pruning can reduce parameter count and dense compute, but awkward hidden sizes may perform worse than slightly larger hardware-friendly sizes. Align channel counts with the tile requirements of the target matrix multiplication kernels.

Knowledge Distillation

A smaller model can run faster and use less memory. Knowledge distillation trains a smaller student model using signals from a larger teacher. The student may learn from the teacher’s output distribution (not just the highest-scoring token), intermediate representations, generated data, or a combination of them.

For logits $\mathbf{z}_t$ and $\mathbf{z}_s$ from teacher and student, a common distillation loss function uses a temperature $T$:
$$
\mathcal{L}_{KD} = T^2\operatorname{KL}\Big(
\operatorname{softmax}\big(\frac{\mathbf{z}_t}{T}\big)\;\big\Vert \;\operatorname{softmax}\big(\frac{\mathbf{z}_s}{T}\big)
\Big)
$$
Here, $\operatorname{KL}(\mathbf{P}\Vert \mathbf{Q})$ is the Kullback-Leibler divergence from the teacher distribution $\mathbf{P}$ to the student distribution $\mathbf{Q}$; it is zero when they match and grows as their probabilities differ. The corresponding PyTorch code is:

For padded batches, replace .mean() with a masked average over valid token positions. This loss assumes teacher and student logits refer to the same vocabulary and token positions. The teacher runs without gradients, but producing its targets still costs time. The next example defines the same loss so it can run independently.

The following local example uses two small, randomly initialized GPT-2 style models. It demonstrates one training step; it does not produce a useful language model. A real distillation experiment needs a pretrained teacher and representative text.

For a real comparison, train on a representative data split and report held-out task quality, parameter bytes, peak memory, prefill latency, and decode throughput for the same prompts and hardware. Pruning or distillation can change behavior even when parameter count falls substantially.

Further Reading

Below are some resources you may find useful:

Summary

In this post, you learned that compression can change model structure, not only number formats. Unstructured pruning needs sparse storage and kernels to improve runtime, while structured pruning can produce smaller dense shapes. Distillation transfers behavior into a smaller student model.



Source link

Mobile Offer

🎁 You've Got 1 Reward Left

Check if your device is eligible for instant bonuses.

Unlock Now
Survey Cash

🧠 Discover the Simple Money Trick

This quick task could pay you today — no joke.

See It Now
Top Deals

📦 Top Freebies Available Near You

Get hot mobile rewards now. Limited time offers.

Get Started
Game Offer

🎮 Unlock Premium Game Packs

Boost your favorite game with hidden bonuses.

Claim Now
Money Offers

💸 Earn Instantly With This Task

No fees, no waiting — your earnings could be 1 click away.

Start Earning
Crypto Airdrop

🚀 Claim Free Crypto in Seconds

Register & grab real tokens now. Zero investment needed.

Get Tokens
Food Offers

🍔 Get Free Food Coupons

Claim your free fast food deals instantly.

Grab Coupons
VIP Offers

🎉 Join Our VIP Club

Access secret deals and daily giveaways.

Join Now
Mystery Offer

🎁 Mystery Gift Waiting for You

Click to reveal your surprise prize now!

Reveal Gift
App Bonus

📱 Download & Get Bonus

New apps giving out free rewards daily.

Download Now
Exclusive Deals

💎 Exclusive Offers Just for You

Unlock hidden discounts and perks.

Unlock Deals
Movie Offer

🎬 Watch Paid Movies Free

Stream your favorite flicks with no cost.

Watch Now
Prize Offer

🏆 Enter to Win Big Prizes

Join contests and win amazing rewards.

Enter Now
Life Hack

💡 Simple Life Hack to Save Cash

Try this now and watch your savings grow.

Learn More
Top Apps

📲 Top Apps Giving Gifts

Download & get rewards instantly.

Get Gifts
Summer Drinks

🍹 Summer Cocktails Recipes

Make refreshing drinks at home easily.

Get Recipes

Latest Posts

Don't Miss

Stay in touch

To be updated with all the latest news, offers and special announcements.