Skip to content

FlexiDepth

At a glance

FlexiDepth: a router per layer sends low-scoring tokens through a light adapter instead of the layer.

Registered name Family Saves Lossless Trainable Configuration
flexidepth dynamic-depth compute or latency no routers, adapters FlexiDepthConfig

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

FlexiDepth (Luo et al., 2025) gives each flexible layer a router and a light adapter. At layer l the router scores every token with g = sigmoid(router(x)) of the layer's input x. A token with g > threshold runs the layer and leaves it as x + g (layer(x) - x). Any other token leaves it as x + (1 - g) adapter(x), where the adapter is a SwiGLU MLP whose width is the layer's FFN width divided by adapter_reduction. Skipped tokens still write their K/V, as in the paper, so later tokens attend to every position at every layer. The flexible layers default to the second half of the model, which keeps the first layers dense. The saving is the layer applications that the adapter replaces, minus the adapter's own cost.

FlexiDepth is lossy, and economize implements a layer-level variant. In the paper's model the router acts on the two branches of a layer separately, while here g scales the whole layer update. Training updates the routers and the adapters, with the base model frozen, which is also how the paper trains them.

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

The base model's greedy output is the reference for quality, so generate it before the technique is applied:

reference = base.generate(ids, max_new_tokens=64, do_sample=False)[0, ids.shape[1]:]

The router bias starts at 5, so every score starts near 1 and every token runs every layer. The adapters start as the identity. Training teaches the routers which tokens can take the adapter:

from economize.techniques.dynamic_depth import FlexiDepthConfig, token_mismatch
from economize.train import fit

model = economize.apply(base, FlexiDepthConfig())
fit(model, "train.bin", steps=2000, batch_size=8, seq_len=1024, seed=0)

result = model.decode(ids[0], 64)
print(tokenizer.decode(result.tokens))
summary = model.techniques["flexidepth"].cost_summary(result)
print(token_mismatch(result.tokens, reference))      # fraction of positions that differ from the base model
print(summary["relative_effective_layer_tokens"])    # layer applications relative to plain decoding
print(summary["executed_fraction_per_layer"])        # fraction of the tokens that ran each layer

Measuring quality and saving

token_mismatch is CALM's token-level consistency loss: the fraction of the positions of the longer generation at which the two generations differ, with a missing token counted as a difference. Greedy decoding compounds every early difference, so it is worth averaging it over prompts from the target workload. relative_effective_layer_tokens divides the layer applications that ran by those of plain decoding of the same output, prompt included, and phases["decode"] holds the counts of the decoding steps alone. kv_fill_layer_tokens counts the skipped layers that computed K/V, which is part of the remaining cost.

Training

fit without an objective uses FlexiDepthObjective(): the language-model loss plus layer_penalty * mean((sum_l g_l)^2) over tokens, which penalizes the squared number of layers a token uses, as in the paper. A larger penalty skips more. kl_weight adds a KL divergence to the base model's distribution, and ce_weight scales the language-model loss:

from economize.techniques.dynamic_depth import FlexiDepthObjective

model.detach()
model = economize.apply(base, FlexiDepthConfig(layers=tuple(range(9, 25)), router="bottleneck", adapter_reduction=32))
fit(model, "train.bin", objective=FlexiDepthObjective(layer_penalty=1e-2, kl_weight=1.0),
    steps=2000, batch_size=8, seq_len=1024, seed=0)

router="paper" (the default) is the router of the reference code, a bottleneck of width hidden_size / router_reduction with an RMSNorm inside. router="bottleneck" is a smaller MLP. adapter_reduction sets the width of the adapters, here 1/32 of the FFN width.

Saving and loading

save_pretrained writes the configuration and the weights of the routers and adapters:

model.save_pretrained("flexidepth_model")
model.detach()

model = economize.load(base, "flexidepth_model")

Decoding options

threshold is the router score above which a token runs a layer (0.5 in the reference code), and a higher threshold sends more tokens to the adapters. skip_prompt=False runs the prompt through every layer. Trained routers can be decoded with other inference settings by changing the configuration in the checkpoint:

import dataclasses

checkpoint = economize.read_checkpoint("flexidepth_model")
checkpoint.configs[0] = dataclasses.replace(checkpoint.configs[0], threshold=0.7, skip_prompt=False)
model.detach()
model = economize.attach(base, checkpoint)
result = model.decode(ids[0], 64)
print(token_mismatch(result.tokens, reference))

Combining with other techniques

Only one dynamic-depth technique is used per model. FlexiDepth composes with drafters and with KV-cache techniques. The exact pass that verifies a draft follows the routers, so greedy verification reproduces the output of FlexiDepth alone. Here the drafter is an untrained EAGLE-3 head (train it as in EAGLE-3 before use) and the cache is quantized to 4 bits:

from economize.techniques.eagle3 import Eagle3Config
from economize.techniques.kv_quant.kivi import KIVIConfig

model.detach()
model = economize.apply(base, FlexiDepthConfig(), KIVIConfig(bits=4), Eagle3Config(),
                        decoding=economize.DecodeConfig(cycle_length=6))
combined = model.decode(ids[0], 64)

Serving

FlexiDepth runs on the Hugging Face path only, and a model with it decodes without CUDA graphs:

print(economize.backend_support(FlexiDepthConfig()))

Configuration

FlexiDepthConfig dataclass

FlexiDepthConfig(layers: tuple[int, ...] = (), skip_prompt: bool = True, decision_group: int = 1, threshold: float = 0.5, router: str = 'paper', router_reduction: int = 16, adapter_reduction: int = 16, router_bias: float = 5.0)

FlexiDepth.

Attributes:

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

Flexible layers (empty: the second half of the model, as in the paper, which keeps the first layers dense).

threshold float

Tokens whose router score exceeds it run the layer (0.5 in the reference code).

router str

Router architecture, a name in :data:FLEXI_ROUTERS.

router_reduction int

Router bottleneck width hidden_size // router_reduction.

adapter_reduction int

Adapter width intermediate_size // adapter_reduction (hidden_size // adapter_reduction when the model config has no intermediate_size).

router_bias float

Initial bias of the router output. At >= 100 every score is exactly 1 and the model is unchanged.

skip_prompt bool

Route the prompt too (False: the prompt runs every layer).

flexible_layers

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

The flexible layers (:meth:layer_set).

References