Skip to content

DFlash

At a glance

DFlash: block drafting with a small decoder conditioned on the model's features.

Registered name Family Saves Lossless Trainable Configuration
dflash drafting latency yes fc, hidden_norm, layers, norm DFlashConfig

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

DFlash (Chen et al., 2026) drafts a whole block of tokens with one forward pass of a few small decoder layers. Every committed token t gets a context vector c_t = hidden_norm(fc([h^{l_1}_t; ...; h^{l_n}_t])) from the base model's hidden states at a few layers spread over the depth. Each draft layer projects keys and values from these vectors once, when the base model commits the token, and keeps them in a cache of its own. To draft after the last committed token x_p, the layers run once over the block [E[x_p], E[mask], ..., E[mask]] of block_size entries, attending to the context before p and to the block itself. The output at block index i >= 1, read through the drafter's norm and the base model's LM head, drafts token p + i. The drafter has no embedding and no LM head of its own.

The base model verifies the block as a chain in one forward pass, so greedy decoding returns its own tokens. Because the full-attention layers see the whole block in both directions, the block always runs at full width. A shorter draft only shortens the verification.

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)

Quick start

An untrained drafter attaches to any supported model. mask_token_id names the token that fills the block, here an unused special token of Qwen2.5. The draft layers take their geometry from the base model unless you set it:

from economize.techniques.dflash import DFlashConfig

mask = tokenizer.convert_tokens_to_ids("<|fim_pad|>")
model = economize.apply(base, DFlashConfig(block_size=8, num_layers=2, mask_token_id=mask),
                        decoding=economize.DecodeConfig(cycle_length=8))

result = model.decode(ids[0], 64)
print(tokenizer.decode(result.tokens))
print(result.mean_accepted)            # accepted drafts per verification
print(result.cost_summary())

A cycle of length g + 1 drafts min(g, block_size - 1) tokens, so cycle_length=8 uses all seven masks of the block. An untrained drafter accepts almost nothing, and the output is still the base model's greedy output. target_layers picks the layers whose states form the context vector (five layers spread over the depth by default).

Training

economize has no training objective for DFlash, and fit on a DFlash model raises a ConfigError that names the missing default objective. Use the authors' checkpoints, or train the drafter with the reference code and load the result.

Saving and loading

model.save_pretrained("dflash_drafter")
model.detach()

model = economize.load(base, "dflash_drafter", decoding=economize.DecodeConfig(cycle_length=8))

The official drafters for Gemma 4 31B load from their repository folders. The z-lab layout is detected. The RedHatAI speculators folder also matches the EAGLE-3 reader, so it needs format="speculators_dflash":

from huggingface_hub import snapshot_download

gemma = AutoModelForCausalLM.from_pretrained("google/gemma-4-31B-it", dtype=torch.bfloat16, device_map="cuda")
model = economize.load(gemma, snapshot_download("z-lab/gemma-4-31B-it-DFlash"),
                       decoding=economize.DecodeConfig(cycle_length=16))
model.detach()
model = economize.load(gemma, snapshot_download("RedHatAI/gemma-4-31B-it-speculator.dflash"),
                       format="speculators_dflash", decoding=economize.DecodeConfig(cycle_length=8))

Variants economize does not implement, such as a restricted draft vocabulary or a drafter with its own LM head, raise CheckpointFormatError on load. DFlash block drafting lists the checkpoint details.

Combining with other techniques

The drafter composes with techniques that are not drafters, for example int8 weights on the base model:

from economize.techniques.quant import QuantConfig

model.detach()
model = economize.apply(
    AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map="cuda"),
    QuantConfig(format="int8"),
    DFlashConfig(block_size=8, num_layers=2, mask_token_id=mask),
    decoding=economize.DecodeConfig(cycle_length=8),
)
model.decode(ids[0], 64)

Serving

vLLM serves the drafter with its own DFlash proposer (method="dflash"), and SGLang with its DFLASH algorithm. to_vllm writes the drafter in the z-lab layout. vLLM drafts at most block_size - 1 tokens from a block of 1 + num_speculative_tokens slots, so with fewer drafts the masks see fewer neighbours than in economize. The output stays lossless.

from economize.backends.vllm import serving

plan = serving.to_vllm(model, "out/qwen-dflash", num_speculative_tokens=7)
llm = plan.llm()

Configuration

DFlashConfig dataclass

DFlashConfig(target_layers: tuple[int, ...] | None = None, block_size: int = 16, num_layers: int = 5, mask_token_id: int = 0, intermediate_size: int | None = None, num_heads: int | None = None, num_kv_heads: int | None = None, head_dim: int | None = None, layer_types: tuple[str, ...] | None = None, sliding_window: int = 2048, sliding_causal: bool = True, rope_theta: float = 1000000.0, rope_scaling: JSONObject | None = None, partial_rotary_factor: float = 1.0, max_position_embeddings: int | None = None, rms_norm_eps: float = 1e-06, attention_bias: bool = False, embed_scale: float = 1.0, logit_softcap: float | None = None, param_dtype: str = 'float32')

Hyperparameters of a DFlash block drafter (Chen et al., 2026, arXiv 2602.06036).

The drafter fuses the model's hidden states at target_layers (outputs of those 1-indexed blocks) of every committed token with fc and hidden_norm into a context vector, which each draft layer projects into keys and values of its own. One forward over the block [x_p, mask, ..., mask] (block_size tokens at the positions p .. p + block_size - 1, x_p the last token the model emitted) attends to the context of the positions before p and, inside the block, bidirectionally (full layers) or causally (sliding layers by default). The output at the i-th mask, through the drafter's norm and the model's LM head, drafts the token at p + i, so one forward drafts block_size - 1 tokens.

Attributes:

Name Type Description
target_layers tuple[int, ...] | None

Blocks whose outputs are fused (None: :func:default_target_layers with 5 layers).

block_size int

Tokens of the drafted block, the anchor included (16 for z-lab's Gemma-4 drafter, 8 for RedHat's). A cycle drafts at most block_size - 1 tokens.

num_layers int

Draft decoder layers.

mask_token_id int

Token id of the masks of the block (4 for Gemma-4's official drafters).

intermediate_size int | None

Width of the draft layers' MLPs (None: the model's).

num_heads int | None

Attention heads of the draft layers (None: the model's).

num_kv_heads int | None

Key/value heads of the draft layers (None: the model's).

head_dim int | None

Head width of the draft layers (None: the model's).

layer_types tuple[str, ...] | None

"sliding_attention" or "full_attention" per draft layer (None: all sliding but the last).

sliding_window int

Window of the sliding layers, on absolute positions.

sliding_causal bool

Sliding layers attend causally inside the block (z-lab and the speculators default); full layers always attend bidirectionally inside the block.

rope_theta float

Base of the draft layers' rotary table.

rope_scaling JSONObject | None

Scaling of the rotary table, a Hugging Face rope_scaling dict. None: unscaled.

partial_rotary_factor float

Fraction of each head the rotary table rotates.

max_position_embeddings int | None

The max_position_embeddings the table's scaling refers to.

rms_norm_eps float

Epsilon of the drafter's RMS norms.

attention_bias bool

Biases on the q/k/v/o projections.

embed_scale float

Factor on the model's raw token embeddings (the reference's input_embedding_scale; the official Gemma-4 drafters read unscaled embeddings, without Gemma's sqrt(d)).

logit_softcap float | None

Final logit soft cap of the drafter: None applies the model's own logit transform (Gemma's soft cap), 0 none, a positive value c the cap c * tanh(z / c). Greedy drafts do not depend on it.

param_dtype str

Storage and compute dtype of the drafter's parameters: "float32" (default) or "model" (the model's dtype, as the official checkpoints are stored). Softmaxes and norms run in float32 and logits are returned in float32.

layers

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

The fused layers for a model with num_layers blocks.

types

types() -> tuple[str, ...]

The attention kind of every draft layer.

References