Skip to content

Layer skipping (SWIFT, Draft & Verify)

At a glance

Self-speculative whole-layer greedy skip: draft tokens run the model without a fixed set of whole layers.

Registered name Family Saves Lossless Trainable Configuration
layer_skip drafting latency yes no LayerSkipConfig

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

Self-speculative decoding by layer skipping drafts with the model itself minus a set of its layers. A draft step runs every layer outside the skip set on the last token and reads the next token from the model's own norm and LM head, so a draft costs the remaining layers and needs no extra parameters. Skipped layers write no K/V for the drafted positions, and the next exact pass recomputes these positions with all layers while it verifies the drafts. Greedy decoding is therefore lossless. Draft & Verify (Zhang et al., 2024) chooses the skip set offline by Bayesian optimization, SWIFT (Xia et al., 2025) searches it on the fly during decoding, and CLaSp (Chen et al., 2025) by dynamic programming. economize takes a given skip set or searches one once, when the technique attaches, on calibration data: the greedy search adds one layer at a time, the one whose removal changes the model's next-token distribution least. None of the three papers' own searches is implemented, and nothing is trained.

Setup

Every tutorial starts from the same model and prompt:

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)

Quick start

A fixed skip set attaches without data. Layers are 1-indexed, so this skips five of the middle layers of the 24:

from economize.techniques.layer_skip import LayerSkipConfig

model = economize.apply(base, LayerSkipConfig(skip_layers=(10, 12, 14, 16, 18)),
                        decoding=economize.DecodeConfig(cycle_length=4))

result = model.decode(ids[0], 64)
print(tokenizer.decode(result.tokens))
print(result.mean_accepted)            # accepted drafts per verification
print(result.cost_summary())           # exact passes, draft steps and layer-tokens of both

cycle_length=4 drafts three tokens per verification. The output is the model's greedy output whatever the skip set, since every token is verified. A larger skip set makes drafts cheaper and less often accepted.

Calibration

With num_skip instead of skip_layers the technique searches the set on the calibration rows passed to economize.apply. A few short rows are enough, since the search only runs forward passes:

model.detach()
model = economize.apply(base, LayerSkipConfig(num_skip=8, search="greedy", metric="kl"),
                        calibration=calibration[:8, :256], decoding=economize.DecodeConfig(cycle_length=4))
print(model.techniques["layer_skip"].skip_layers)

metric="kl" scores a candidate set by KL(full || skipped) of the next-token distributions and "mismatch" by the share of positions where the greedy token changes. keep_first and keep_last (1 each by default) protect the outermost layers from the search. search="uniform" spreads num_skip layers evenly between them and reads no data:

model.detach()
model = economize.apply(base, LayerSkipConfig(num_skip=8, search="uniform"),
                        decoding=economize.DecodeConfig(cycle_length=4))

Saving and loading

The checkpoint holds the skip set, so loading it does not search again:

model.save_pretrained("layer_skip")
model.detach()

model = economize.load(base, "layer_skip", decoding=economize.DecodeConfig(cycle_length=4))

Decoding options

min_confidence ends a cycle early when the drafter's top probability falls below the threshold. Sampling stays lossless with the rejection verifier:

model.decode(ids[0], 64, decoding=economize.DecodeConfig(cycle_length=8, min_confidence=0.6))

sampling = economize.DecodeConfig(cycle_length=4, verifier="rejection")
sampled = model.generate(ids, max_new_tokens=64, do_sample=True, temperature=0.7, top_p=0.9, decoding=sampling)

Combining with other techniques

Layer skipping composes with techniques that are not drafters, for example int8 weights:

from economize.techniques.quant import QuantConfig

print(economize.compatible("layer_skip", "quant"))  # True

model.detach()
model = economize.apply(
    AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda"),
    QuantConfig(format="int8"),
    LayerSkipConfig(skip_layers=(10, 12, 14, 16, 18)),
    decoding=economize.DecodeConfig(cycle_length=4),
)

KnapSpec skips attention and MLP sublayers separately and searches again during decoding.

Serving

vLLM and SGLang serve the drafter through economize's plugins:

from economize.backends.vllm import serving

plan = serving.to_vllm(model, "out/qwen-layer-skip", num_speculative_tokens=3)
llm = plan.llm()

Configuration

LayerSkipConfig dataclass

LayerSkipConfig(skip_layers: tuple[int, ...] = (), num_skip: int | None = None, search: str = 'greedy', metric: str = 'kl', keep_first: int = 1, keep_last: int = 1)

Hyperparameters of a whole-layer greedy-skip self-drafter.

A draft step runs every layer of the model except the skip set and reads the next-token logits with the model's own head. The skip set is given (skip_layers) or searched when the technique attaches, on the calibration data passed to :func:economize.apply (num_skip layers, chosen by the registered search search).

Attributes:

Name Type Description
skip_layers tuple[int, ...]

Layers (1-indexed) the draft path skips. Empty means: search num_skip layers.

num_skip int | None

Size of the searched skip set.

search str

Name of a registered skip-set search (:data:SKIP_SEARCHES): "greedy" adds, one at a time, the layer whose skipping hurts the metric least; "uniform" spreads the skipped layers evenly and needs no data.

metric str

Name of a registered score minimized by data-driven searches (:data:SKIP_METRICS): "kl" is KL(full || skipped) of the next-token distributions, "mismatch" the share of positions where the skipped model's greedy token differs from the full model's.

keep_first int

The first keep_first layers are never skipped by a search.

keep_last int

The last keep_last layers are never skipped by a search.

size property

size: int

Number of skipped layers.

candidates

candidates(num_layers: int) -> tuple[int, ...]

Layers a search may skip.

References

  • Chen, L., Shan, R., Wang, H., Wang, L., Liu, Z., Luo, R., Wang, J., Alinejad-Rokny, H., & Yang, M. (2025). CLaSp: In-context layer skip for self-speculative decoding. In Annual Meeting of the Association for Computational Linguistics. https://doi.org/10.48550/arXiv.2505.24196
  • Xia, H., Li, Y., Zhang, J., Du, C., & Li, W. (2025). SWIFT: On-the-fly self-speculative decoding for LLM inference acceleration. In International Conference on Learning Representations. https://doi.org/10.48550/arXiv.2410.06916
  • Zhang, J., Wang, J., Li, H., Shou, L., Chen, K., Chen, G., & Mehrotra, S. (2024). Draft & Verify: Lossless large language model acceleration via self-speculative decoding. In Annual Meeting of the Association for Computational Linguistics. https://doi.org/10.48550/arXiv.2309.08168