Skip to content

Depth pruning: ShortGPT and SLEB

At a glance

ShortGPT and SLEB: removal of the decoder layers that change the hidden state least.

Registered name Family Saves Lossless Trainable Configuration
depth_prune weight-compression weight memory, compute or latency no no DepthPruneConfig

Backends (default configuration): transformers: real · gguf: real · mlx: untested · onnx: real · sglang: real · trtllm: untested · vllm: real

depth_prune removes whole decoder layers from the model once. ShortGPT (Men et al., 2024) ranks the layers by their Block Influence, BI_i = 1 - E[cos(h_{i-1}, h_i)], the mean cosine distance between a layer's input and output hidden states over the calibration tokens, and removes the num_blocks layers with the lowest score in one pass. SLEB (Song et al., 2024) removes one layer at a time, each time the one whose removal raises the calibration perplexity least, and scores the remaining layers again after every removal. A third criterion, minitron, removes the contiguous window of layers whose removal gives the lowest calibration loss. Nothing is trained, and the result is lossy.

The layers are deleted from the module list, and the model's layer count and every remaining attention layer's layer_idx are renumbered, so generate and the KV cache work unchanged. The saving is real on every backend: the pruned model is a plain checkpoint with fewer layers, and its FLOPs, weight bytes and KV cache shrink by the removed fraction. Removing layers rewrites the base model in place, so the technique cannot be detached.

Setup

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

import economize

device = "cuda" if torch.cuda.is_available() else "cpu"
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map=device)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
ids = tokenizer("Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. "
                "How many clips did Natalia sell altogether?", return_tensors="pt").input_ids.to(device)

Training data is a flat file of uint32 token ids, the format of nanoGPT-style pretraining shards, and calibration data is a [N, S] tensor of token ids. Both are made here from GSM8K:

import numpy as np
from datasets import load_dataset

texts = [f"{row['question']}\n{row['answer']}" for row in load_dataset("openai/gsm8k", "main", split="train")]
tokens = np.concatenate([tokenizer(t + tokenizer.eos_token).input_ids for t in texts]).astype(np.uint32)
tokens[: len(tokens) * 9 // 10].tofile("train.bin")
tokens[len(tokens) * 9 // 10 :].tofile("val.bin")

calibration = torch.from_numpy(tokens[: 128 * 2048].astype(np.int64)).view(128, 2048)

Depth pruning changes the base model, so measure the perplexity and the parameter count of the full model first:

from economize.train import fixed_windows

windows = fixed_windows("val.bin", 64, 1024).cuda()


@torch.no_grad()
def perplexity(model, windows):
    return torch.stack([model(w[None], labels=w[None]).loss for w in windows]).float().mean().exp().item()


dense_ppl, dense_params = perplexity(base, windows), base.num_parameters()

Quick start

ShortGPT removes the four layers with the lowest Block Influence on the calibration tokens:

from economize.techniques.prune import DepthPruneConfig

model = economize.apply(base, DepthPruneConfig(method="shortgpt", num_blocks=4), calibration=calibration)

summary = model.techniques["depth_prune"].summary
print(summary["removed_layers"], summary["num_layers"])            # 1-indexed layers removed, layers left
print(dense_params, model.unwrap().num_parameters())
print(dense_ppl, perplexity(model, windows))
print(tokenizer.decode(model.generate(ids, max_new_tokens=32)[0]))

model.simulations() is empty: the model is smaller, and nothing is emulated.

Criteria

SLEB runs one calibration pass per removed layer, so it costs num_blocks times as much as ShortGPT. keep_first and keep_last protect the leading and trailing layers. Their defaults follow the papers' code: no protected layer for ShortGPT, the first and the last layer for SLEB:

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, DepthPruneConfig(method="sleb", num_blocks=4, keep_first=2), calibration=calibration)
print(model.techniques["depth_prune"].summary["removed_layers"], perplexity(model, windows))

When the layers to remove are known, layers names them (1-indexed) and no calibration data is read:

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, DepthPruneConfig(num_blocks=2, layers=(20, 21)))

Saving and loading

The technique records the removed layers in its configuration, so a checkpoint removes the same layers from an unmodified base model without calibration:

model.save_pretrained("qwen-shortgpt")

base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.load(base, "qwen-shortgpt")
print(model.techniques["depth_prune"].summary["removed_layers"])

Combining with other techniques

Depth pruning runs first among the weight transforms. The remaining layers can then be pruned or quantized, and a drafter or an early-exit head attaches to the shorter model:

from economize.techniques.quant import QuantConfig

print(economize.compatible("depth_prune", "quant"))
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda")
model = economize.apply(base, DepthPruneConfig(num_blocks=4), QuantConfig(format="int4", method="gptq"),
                        calibration=calibration)
print(perplexity(model, windows))

Serving

The pruned base model is a plain transformers checkpoint with fewer layers, so vLLM, SGLang and the GGUF, MLX, ONNX and TensorRT-LLM exporters serve it as they serve the original architecture:

from economize.backends.vllm import serving

plan = serving.to_vllm(model, "out/qwen-shortgpt")
llm = plan.llm()

Configuration

DepthPruneConfig dataclass

DepthPruneConfig(method: str = 'shortgpt', num_blocks: int = 1, keep_first: int | None = None, keep_last: int | None = None, layers: tuple[int, ...] = ())

Remove whole decoder layers once, before any other weight transform.

Parameters:

Name Type Description Default
method str

Registered criterion: "shortgpt" (Block Influence, one pass), "sleb" (iterative, lowest calibration perplexity after each removal) or "minitron" (the contiguous window whose removal gives the lowest calibration NLL, registered by :mod:economize.techniques.width_prune).

'shortgpt'
num_blocks int

Number of layers to remove.

1
keep_first int | None

Leading layers that are never removed (None: the criterion's default, 0 for ShortGPT and 1 for SLEB, as in the papers' code).

None
keep_last int | None

Trailing layers that are never removed (None: the criterion's default, 0 for ShortGPT and 1 for SLEB).

None
layers tuple[int, ...]

The 1-indexed layers to remove, chosen beforehand (num_blocks of them). When given, the criterion is not run and no calibration data is read; method then only records which criterion chose them. The technique fills this field with the layers it removed, so a saved checkpoint reproduces the removal without recalibrating.

()

candidates

candidates(num_layers: int) -> list[int]

The 1-indexed layers the criterion may remove from a model of num_layers layers.

References

  • Men, X., Xu, M., Zhang, Q., Wang, B., Lin, H., Lu, Y., Han, X., & Chen, W. (2024). ShortGPT: Layers in large language models are more redundant than you expect (arXiv:2403.03853). arXiv. https://doi.org/10.48550/arXiv.2403.03853
  • Song, J., Oh, K., Kim, T., Kim, H., Kim, Y., & Kim, J.-J. (2024). SLEB: Streamlining LLMs through redundancy verification and elimination of transformer blocks. In International Conference on Machine Learning. https://doi.org/10.48550/arXiv.2402.09025