FREE¶
At a glance
FREE: a shallow exit model emits confident tokens, and the deep layers catch up on them in one parallel pass.
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
free |
drafting | latency | no | readout | FreeConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: real · trtllm: no · vllm: real
FREE (Bae et al., 2023) splits the model into a shallow model, its first L_S layers with an exit, and the deep model,
all L layers. A token is emitted by the shallow model when its confidence, the gap between the two largest
probabilities of the exit's distribution, reaches the threshold lambda. Exited tokens stack up until one does not
exit, and then the deep layers run once, in parallel, over the stacked tokens and that token (synchronized parallel
decoding). The stacked tokens get their deep-layer K/V from this pass, so no hidden state is copied. A shallow token
costs L_S of the L layers. The method is lossy: every shallow token is kept, and the output differs from the base
model's greedy output wherever the exit is confident and wrong.
economize decodes FREE through its drafting cycle. The shallow model is an early-exit drafter whose drafts are kept
(lossless=False), and the draft-length policy softmax_gap ends the cycle at the first token below lambda. The
exact pass that follows is the synchronized pass and emits that token from the deep model. With head="shared" (the
paper) nothing is added to the model, and the free objective fine-tunes the model itself. With head="readout" a
small readout adapter is trained on the frozen model instead.
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¶
FreeConfig attaches the shallow exit, and decode_config builds FREE's decoding options from its threshold:
from economize.techniques.dynamic_depth import FreeConfig
model = economize.apply(base, FreeConfig(exit_layer=8, threshold=0.9))
free = model.techniques["free"]
result = model.decode(ids[0], 64, decoding=free.decode_config())
print(tokenizer.decode(result.tokens))
print(free.cost_summary(result)) # layer-tokens with the shallow layers the deep pass reuses
free.cost_summary reports FREE's own cost. economize's exact pass recomputes the shallow layers of the stacked
tokens, which FREE reuses since they are the same layers, and the summary subtracts them (reused_layer_tokens).
threshold=1.0 never exits, which reproduces the base model's greedy output. max_exits (31 by default) bounds the
number of consecutive shallow tokens before a deep pass runs anyway; the paper has no such bound.
Adaptive threshold¶
The paper sets lambda with a two-component Beta mixture over the confidences of tokens on which the shallow and the
deep prediction agree and disagree, and picks the smallest lambda whose posterior probability of agreement reaches
zeta (posterior, 0.4 by default). free_calibration_pairs collects the pairs in one teacher-forced pass and
bmm_threshold fits the mixture. economize sets the threshold once, offline, where the paper updates it while
decoding:
from economize.techniques.dynamic_depth import bmm_threshold, free_calibration_pairs
confidence, agree = free_calibration_pairs(model, calibration[:8, :512])
lam = bmm_threshold(confidence, agree, posterior=free.config.posterior)
result = model.decode(ids[0], 64, decoding=free.decode_config(threshold=lam))
The paper collects the pairs on sequences the model generates itself, so text generated by the base model matches it more closely than the training data.
Training¶
The default objective free fine-tunes the model with the weighted cross-entropies of both exits,
alpha_S = L_S / (L + L_S) and alpha_L = L / (L + L_S), plus a distillation term that matches each shallow layer
to a deep layer by MSE. kd_mapping chooses the layer mapping: "dynamic" (the paper's KD-dyna, a monotone map
searched per batch), "last", "uniform" or "none":
from economize.techniques.dynamic_depth import FreeObjective
from economize.train import fit
fit(model, "train.bin", FreeObjective(kd_mapping="dynamic", kd_weight=1.0), steps=2000, batch_size=8,
seq_len=1024, output_dir="runs/free")
result = model.decode(ids[0], 64, decoding=free.decode_config())
The objective trains the base weights in place (or the PEFT adapters of a PEFT model). The run writes them to
runs/free/final/base_parameters.safetensors and a plain transformers copy to runs/free/final/base/, as described
in Training. The paper trains encoder-decoder models with AdaFactor, while economize trains
decoder-only models with the trainer's optimizer.
To keep the model frozen, attach the exit with a readout and train it with the early-exit KL objective:
from economize.techniques.early_exit import EarlyExitKL
model.detach()
model = economize.apply(base, FreeConfig(exit_layer=8, head="readout"))
fit(model, "train.bin", EarlyExitKL(technique="free"), steps=2000, batch_size=8, seq_len=1024)
model.save_pretrained("free_readout")
Lossless decoding¶
An ordinary DecodeConfig verifies the shallow tokens instead of keeping them, which turns FREE's exit into a
self-speculative drafter with the base model's greedy output:
model.decode(ids[0], 64, decoding=economize.DecodeConfig(cycle_length=4, min_confidence=0.9,
draft_policy="softmax_gap"))
Serving¶
vLLM and SGLang serve the shallow exit through economize's plugins as an early-exit drafter. Served drafts are always verified, so the served output is lossless:
from economize.backends.vllm import serving
plan = serving.to_vllm(model, "out/qwen-free", num_speculative_tokens=3)
llm = plan.llm()
Configuration¶
FreeConfig
dataclass
¶
FreeConfig(exit_layer: int, head: str = 'shared', adaptation: str = 'frozen', lora_rank: int = 16, lora_alpha: float | None = None, copy_dtype: str = 'float32', threshold: float = 0.9, posterior: float = 0.4, max_exits: int = 31)
Hyperparameters of FREE.
Attributes:
| Name | Type | Description |
|---|---|---|
exit_layer |
int
|
|
head |
str
|
|
adaptation |
str
|
Must be |
threshold |
float
|
|
posterior |
float
|
|
max_exits |
int
|
Most consecutive shallow exits before a deep pass runs anyway (a bound of economize's cycle; the paper has none). |
References¶
- Bae, S., Ko, J., Song, H., & Yun, S.-Y. (2023). Fast and robust early-exiting framework for autoregressive language models with synchronized parallel decoding. In Conference on Empirical Methods in Natural Language Processing. https://doi.org/10.48550/arXiv.2310.05424