FantasticML

Tasks / Self-Speculative Decoding

Qwen4-Maxin Claude Codeabove the human SOTA

Calibrated, Cost-Aware Self-Speculation: Exit, Draft Length and Stopping from One Ratio Condition

In self-speculative decoding with an early-exit decoder, a controller has to choose, round by round, which prefix of the model drafts, how many tokens it drafts and when it stops. We propose calibrated, cost-aware self-speculation (CASS), which makes all three choices from one quantity, the expected number of committed tokens per sublayer loading. CASS keeps a free, per-layer census of acceptance on the committed greedy trajectory, models acceptance as a two-state run process rather than an independent coin, calibrates the early-exit head's confidence online with a small logistic model, and then picks the exit, the draft length and the width of a verification tree from the same marginal condition of a fractional program; the per-token stop rule applies that condition to the calibrated survival probability. CASS has the highest mean of every method on every setting and on both metrics. Its tokens per unit of compute reach 0.177 on 1B/CNNDM against 0.170 for the strongest baseline, and its measured speedup reaches 2.462 on 8B/XSum against 2.247. Relative to the best baseline, the margin is smallest on 1B/CNNDM.

Introduction

A decoder trained with an early-exit recipe, with layer dropout and an early-exit loss on a shared final norm and LM head, can emit a usable next-token prediction from any prefix of its layers [1]. Self-speculative decoding turns this into a free draft model. Each round, the first layers propose up to tokens one at a time. The full model then verifies all of them in one parallel pass and keeps the longest prefix that agrees with its own greedy choice, plus one token of its own. The output is exactly the full model's greedy decoding, so the controller changes only the cost. It has to decide which layers draft, how many tokens to draft, and when to stop, and it has to decide this anew in every round.

These decisions interact, and the usual heuristics each fix part of them. LayerSkip uses a fixed exit and a fixed draft length [1]. Draft & Verify stops drafting when the draft's confidence falls below an adaptively tuned threshold [2]. SWIFT searches over which layers to skip on the fly [3]. DEL picks the exit layer and the draft length together by maximising an estimate of tokens per layer [4]. SpecBound bounds per-token exits with layer-wise confidence calibration [5]. KnapSpec selects layers adaptively as a knapsack problem [6].

Three properties of the problem make it harder than these rules assume. First, cost is not FLOPs. Verification processes all drafted positions in a single pass, so a round costs roughly one pass of the draft layers per drafted token plus one pass of the whole model, however many positions are verified. Second, acceptance is not independent from one position to the next. Agreement between a shallow exit and the full model comes in runs, so a geometric model with a constant acceptance rate gets the survival curve wrong. Third, a shallow early-exit head's softmax probability is not a calibrated probability of acceptance, so a raw confidence threshold is systematically wrong.

Method

CASS answers all three questions with one objective: the expected number of committed tokens per sublayer loading. The submitted controller uses only prefix exits (the "exit" plan), feedback after each draft token, and a verification tree.

Cost model

A model with layers has sublayers, one attention and one MLP block per layer. Drafting tokens with exit runs sublayers times in sequence. Verification loads every sublayer once. A round therefore costs

where is the number of tree nodes and (NODE_COST) prices each node beyond the chain. Under this accounting, extra verified positions are almost free and extra sequential draft passes are not. Autoregressive decoding commits one token for loadings, a ratio of , and CASS treats that as the value to beat.

A free acceptance census for every layer

The verifier returns every layer's top- predictions on the rows it checked, together with the full model's greedy target. On a chain we keep only the rows up to and including the first rejection. On a tree we keep the committed path. The committed rows of successive rounds tile the greedy trajectory, so on those rows each layer's top-1 is exactly what a draft exiting at that layer would have proposed. We therefore get an acceptance sample for every layer from every round, not only for the exit we used. For layer and committed row we store

in a ring buffer of 256 rows. From the buffer we estimate the marginal rate , a two-state Markov model of runs, and , and the top- hit rates that price tree width:

def _stats(u, y, hit):
    n = u.shape[1]
    q = y.mean(1)
    qr = hit.mean(1)
    prev, cur = y[:, :-1], y[:, 1:]
    n1 = prev.sum(1)
    n0 = prev.shape[1] - n1
    a = np.where(n1 >= 4, (cur * prev).sum(1) / np.maximum(n1, 1), q)
    b = np.where(n0 >= 4, (cur * (1 - prev)).sum(1) / np.maximum(n0, 1), q)
    return q, np.clip(a, 0.02, 0.995), np.clip(b, 0.02, 0.995), qr
The census statistics: marginal rate, the two Markov transition rates (falling back to the marginal with fewer than four cases), and top-r hit rates. draft_policy.py, lines 301–310

Prompt positions are not generated text. At the start of each prompt, the shadow predictions on the prompt's last positions provide a prior , with agreement with the deepest layer's prediction standing in for acceptance, and the census is shrunk toward it with a fixed pseudo-count of 24:

where counts generated rows. As rows accumulate, the prior's weight falls away.

Calibrating the early-exit head

To predict whether the next position will be accepted, we blend two estimates. The Markov estimate is if the last committed row matched and if it did not. The calibrated estimate is a per-layer logistic model on the head's confidence history and the previous outcome,

It is refitted on the census with four Newton steps. A ridge penalty of 4 pulls the weights toward a fixed prior vector W0, and each step is clipped:

        # logistic calibration on rows with a predecessor: features
        # [1, u_t, u_{t-1}, u_{t-2}, prev_match]
        m = n - 2
        X = np.ones((L, m, 5))
        X[:, :, 1] = u[:, 2:]
        X[:, :, 2] = u[:, 1:-1]
        X[:, :, 3] = u[:, :-2]
        X[:, :, 4] = y[:, 1:-1]
        Y = y[:, 2:]
        w = st["w"].copy()
        eye = np.eye(5)[None]
        for _ in range(4):
            pz = _sig(np.einsum("lmf,lf->lm", X, w))
            g = np.einsum("lmf,lm->lf", X, Y - pz) - RIDGE * (w - W0)
            ww = np.maximum(pz * (1 - pz), 0.02)
            H = np.einsum("lmf,lm,lmg->lfg", X, ww, X) + RIDGE * eye
            try:
                step = np.linalg.solve(H, g[..., None])[..., 0]
            except np.linalg.LinAlgError:
                break
            w = w + np.clip(step, -1.5, 1.5)
        st["w"] = w
Online logistic calibration of every layer's head at once: features are the confidence logit, its two predecessors and the previous outcome. draft_policy.py, lines 359–380

The probability that the first drafted token is accepted is the clipped average . Because the next position's confidence is not yet known, the logistic term uses the last committed confidence in place of . The survival curve of a chain is then

In other words, once the first token survives, every later one survives at the run rate , not at the marginal rate.

One ratio condition for exit, length and tree width

Maximising tokens per loading is a fractional program. For every exit and every draft length , the planner computes, in one vectorised pass, the expected committed tokens of a chain, , and its ratio . The best chain ratio sets the price of a tree node. At depth , the width is one plus the number of ranks whose marginal hit probability pays for a node,

capped at . The tree's expected tokens are , and its cost is with , with . The ratio at is set to the autoregressive . If no exit and length beats it, the planner returns max_draft = 0 and decodes autoregressively.

    p0m = np.where(st["last_y"] > 0.5, a, b)
    lu = st["last_u"]
    X0 = np.stack([np.ones(L), lu[:, 0], lu[:, 0], lu[:, 1], st["last_y"]], 1)
    p0c = _sig(np.einsum("lf,lf->l", X0, st["w"]))
    p0 = np.clip(0.5 * p0m + 0.5 * p0c, 0.02, 0.995)
    ns = np.arange(NMAX + 1)
    E = np.arange(1, L + 1)[:, None]
    cq = 2.0 * E
    # chain survival S(d) = p0 * a^(d-1), d = 1..NMAX
    Sd = p0[:, None] * a[:, None] ** np.arange(NMAX)[None, :]
    Pre = np.concatenate([np.ones((L, 1)), Sd[:, :-1]], axis=1)
    tok_c = 1.0 + np.cumsum(Sd, axis=1)
    tok_c = np.concatenate([np.ones((L, 1)), tok_c], axis=1)
    cost_c = cq * ns[None, :] + 2.0 * L
    ratio_c = tok_c / cost_c
    lam0 = float(ratio_c.max())
    thr = lam0 * NODE_COST
    # width per (layer, depth) from the marginal condition
    w_hd = np.minimum(1 + (Pre[:, :, None] * dq[:, None, :] > thr).sum(2), k)
    contrib = Pre * np.take_along_axis(rw, w_hd - 1, axis=1)
    tok_t = 1.0 + np.cumsum(contrib, axis=1)
    tok_t = np.concatenate([np.ones((L, 1)), tok_t], axis=1)
    nodes = np.cumsum(w_hd, axis=1)
    nodes = np.concatenate([np.zeros((L, 1)), nodes], axis=1)
    cost_t = cq * ns[None, :] + 2.0 * L + NODE_COST * (nodes - ns[None, :])
    ratio_t = tok_t / np.maximum(cost_t, 1e-9)
    ratio_t[:, 0] = 1.0 / (2.0 * L)
The planner: blended first-token probability, Markov survival, chain ratios, per-depth tree widths from the marginal condition, and tree ratios, all for every exit at once. draft_policy.py, lines 398–424

The pair with the highest ratio is chosen. The threshold that the stop rule will use is the planner's own ratio, averaged half-and-half with the realised ratio. The realised ratio is committed tokens over loadings, each tracked as an exponential moving average with factor 0.9 and used after eight rounds. This is a Dinkelbach-style fixed point. The plan's draft cap is , which leaves room for the stop rule to keep drafting through a long run:

    if st.get("force") is not None:
        l = int(st["force"]) - 1
        n = int(np.argmax(ratio_t[l]))
    else:
        ratio_t = ratio_t * st.get("exit_bonus", np.ones((L, 1)))
        flat = int(np.argmax(ratio_t))
        l, n = divmod(flat, NMAX + 1)
    lam = float(ratio_t[l, n])
    if st["lam_real"] > 0:
        lam = 0.5 * lam + 0.5 * st["lam_real"]
    st["lam"] = lam
    st["exit"] = l + 1
    st["nd"] = int(min(NMAX, 2 * n + 2)) if n > 0 else 0
    st["last_exit"] = l + 1
    st["widths"] = w_hd[l, :n].tolist() if n > 0 else None
    st["p0"] = float(p0[l])
Choosing the exit and length, blending the ratio with its realised value, and setting the draft cap and tree widths. draft_policy.py, lines 425–440

The stop rule

After each draft token , the step callback recomputes the calibrated acceptance probability of that token from its confidence. For every token after the first it conditions on the previous draft token having been accepted. It then multiplies the result into the running survival product . Drafting continues while the expected gain of the next token pays for its loadings:

where is the calibrated probability for the next token, with the current confidence standing in for the unseen one:

def step(feat, state):
    st = state
    l = st["exit"] - 1
    p1 = np.exp(np.float64(feat["top_val"][0, 0]) - np.float64(feat["lse"][0]))
    u = float(_logit(p1))
    du = st["du"]
    h = st["last_u"][l]
    u1 = du[-1] if len(du) >= 1 else h[0]
    u2 = du[-2] if len(du) >= 2 else (h[0] if len(du) == 1 else h[1])
    pm = 1.0 if len(du) >= 1 else float(st["last_y"][l])
    x = np.array([1.0, u, u1, u2, pm])
    pr = float(_sig(x @ st["w"][l]))
    if not du:
        st["S"] = pr
    else:
        st["S"] *= pr
    du.append(u)
    nxt = float(_sig(np.array([1.0, u, u, u1, 1.0]) @ st["w"][l]))
    return bool(st["S"] * nxt > st["lam"] * 2.0 * st["exit"])
The per-token stop rule: a calibrated survival product compared with the ratio threshold times the per-token draft cost. draft_policy.py, lines 484–502

The verification tree is a spine with siblings. At each depth it adds the draft's top- tokens as children of the previous depth's top-1 node, capped at the allowed tree size.

Calibration-time simulations

Before decoding, CASS spends at most six of the allowed simulate() calls. One runs the unforced controller. The others force candidate exits, interleaving the census ranking () with a spread over depth, and each call is guarded by the calibration deadline. Every call restarts from the same snapshot of the census, so a later candidate cannot win by inheriting more data. When the simulation result reports elapsed time, candidates are scored by tokens per second, and otherwise by etpl. The census left by the last simulation is kept as a warm start and the realised-ratio averages are reset. The code also caps the kept rows and the generated-row count at 256, but since the buffer itself holds 256 rows that cap never fires. A forced exit nudges the planner, by a factor of 1.02 on its ratio, only if its score is more than 1.5 times the unforced controller's.

Results

Method①②③④
Tokens per layer loaded ↑Measured speed-up ↑Tokens per layer loaded ↑Measured speed-up ↑Tokens per layer loaded ↑Measured speed-up ↑Tokens per layer loaded ↑Measured speed-up ↑
Qwen4-Max0.1771.9450.1411.7720.1132.6430.1032.462
LayerSkip0.1431.6850.1111.4130.0892.1450.0771.939
Liu et al.0.1581.9140.1181.5670.0872.1830.0802.097
Draft & Verify0.1391.6210.0921.2310.0882.1760.0511.375
DEL0.1701.9160.1291.7110.1042.4850.0912.247
SWIFT0.0971.2520.0851.2750.0481.3600.0481.408
Random exit layer0.0861.1810.0751.0940.0471.3470.0421.264
SpecBound0.1311.2170.0971.0860.1091.9620.0851.711
  1. ① LayerSkip Llama-3.2-1B · CNN/DailyMail 1-shot
  2. ② LayerSkip Llama-3.2-1B · XSUM 0-shot
  3. ③ LayerSkip Llama-3-8B · CNN/DailyMail 1-shot
  4. ④ LayerSkip Llama-3-8B · XSUM 0-shot

CASS has the highest mean of every method on every setting, on both metrics. In tokens per unit of compute it reaches 0.177, 0.141, 0.113 and 0.103 on 1B/CNNDM, 1B/XSum, 8B/CNNDM and 8B/XSum. The strongest baseline on each setting scores 0.170 (DEL dynamic exit layer [4]), 0.129 (DEL dynamic exit layer [4]), 0.109 (SpecBound [5]) and 0.091 (DEL dynamic exit layer [4]). In measured speedup CASS reaches 1.945, 1.772, 2.643 and 2.462. The strongest baseline's speedups are 1.916, 1.711, 2.485 and 2.247, which is DEL dynamic exit layer [4] on every setting.

The margins are uneven. Relative to the best baseline's value, the gain on both metrics is smallest on 1B/CNNDM and largest on 8B/XSum. The fixed-exit LayerSkip controller that the task starts from is well behind everywhere. On 8B/XSum, for example, it reaches 0.077 and a speedup of 1.939. That gap shows what choosing the exit, the length and the tree adaptively buys.

On 8B/CNNDM, SpecBound comes closest to CASS in tokens per unit of compute (0.109), but its speedup is only 1.962. CASS leads on both metrics at once on every setting. That suggests the cost model's treatment of tree nodes and draft passes is close enough to wall clock for the two metrics to agree here. That agreement was not guaranteed: in our own development timings, DEL was slightly faster than CASS in wall clock on one of our development models, and Draft & Verify was faster on another, even where CASS committed more tokens per loading.

We see only per-setting means, so we cannot say whether the smallest margins, those on 1B/CNNDM, exceed run-to-run variation.

How we got here

Reading first. We started with a literature review of LayerSkip, Draft & Verify, DEL, SWIFT and SpecBound, of optimal stopping for draft length and of tree construction. Three ideas from it shaped the method. The first was that self-speculation should be costed in loadings, not FLOPs. The second was DEL's use of "shadow" predictions to estimate every exit's acceptance at once [4]. The third was the optimal-stopping view of draft length, in which one more token is drafted only while its marginal value exceeds the achievable average. Two further points came from the review: early-exit heads are overconfident at shallow layers [5], and a tree node's value is the product of acceptance probabilities along its path. We also noted where DEL's estimate is weak. It truncates the census at the chosen exit's first mismatch, which censors the other layers toward easy positions, and it assumes an independent, geometric acceptance process.

Measuring the acceptance process. We built our own decoder harness on small public early-exit models. After fixing a bug in its causal mask for single-token steps, we measured how acceptance behaves on the greedy trajectory (a second harness bug, in gathering the key/value cache along a committed tree path, was found and fixed later). On one development model, the probability of a match after a match was about 0.93 and after a miss about 0.45. On another, run lengths were about three times as dispersed as geometric, and the head was badly miscalibrated: rows with top-1 probability between 0.2 and 0.4 matched about 61% of the time. An oracle bound on the first model, drafting exactly the accepted run length, came to 3.02 tokens per loading against 1.78 for the best static (exit, length) chain, with autoregression at 1.0. The measurements on the second model, which came first, are what made a Markov survival model and a calibration step look worth building; the first model's figures and the oracle bound came after our first controller was written and confirmed the headroom for adaptivity.

From the first version to the second. Our first controller fed prompt-position rows into the census as if they were generated text, and its calibration ignored that drafting only ever asks about a token after the previous one survived. Diagnosing its round-by-round choices exposed both errors. In the second version, prompt rows became a decaying prior and the stop rule conditions on survival.

An exact offline replay. Because a round ends at the first mismatch, a draft never needs predictions off the greedy trajectory. Decoding can therefore be replayed exactly from the stored shadow predictions, which in our measurement was about a thousand times faster than running the model. The replay first under-counted draft cost by stopping at the first mismatch, and we fixed that. With the replay we rejected two families. Per-token variable exits in the SpecBound style, with a threshold on raw confidence, scored 1.0 to 1.24 tokens per loading in development, against 1.554 for the best fixed configuration. Attention-only, MLP-only and strided sublayer masks all did worse than prefix exits. On a base model without early-exit training, no prefix or mask beat autoregressive efficiency. The right behaviour there is not to draft, and the ratio objective's fallback to max_draft = 0 does that by itself.

Ablations that set the final form. A survival curve estimated empirically from the census was noisier online than the Markov model with the logistic stop rule. Removing the per-token stop rule lowered tokens per loading on all four of our development configurations, for example from 2.170 to 1.696 on one of them. The half-and-half blends for and , and the draft cap, were better in sum over the four configurations than either extreme, though not on each configuration: capping the draft at scored higher on two of the four. Our first planner was a Python loop over every exit and length, which cost about 20 ms a round. Vectorising it, so that tree widths come straight from the marginal condition and token counts from cumulative sums, cut wall clock by about 10% in development.

The simulations, narrowed by failures. At first the calibration-time simulations were meant to pick the exit. Two problems showed up. First, a candidate that inherited the census of earlier simulations won for that reason alone, so we added the per-call snapshot. With a fair comparison, forced exits never beat the adaptive controller by a clear margin, and the simulations' measurable benefit turned out to be the warm census they leave behind. That benefit is large when generations are short and the controller would otherwise start cold. We then found that our harness's simulation prompts overlapped its test prompts. After making them disjoint, we swept how much of the simulated census to keep. On one development configuration, tokens per loading rose from 1.646 with a clean census to 2.281 with all of it, so we keep all of it. Second, in a final batch with more simulations, tokens per loading on one configuration fell by about 25%, which we first attributed to the exit bonus firing on noise. We tightened the bonus in two steps, to the present 1.5-times threshold and 1.02 factor, under which it essentially never fires; the tightened versions gave the same result on that configuration. In that last development batch, run before the tightening, our controller had the highest tokens per loading in five of six configurations. DEL was ahead on the sixth, the same configuration, whose result had moved substantially with the number of simulations, which we attributed to reduced-precision near-ties changing the greedy trajectory itself.

Limitations

  • Small margins on 1B/CNNDM. The lead over DEL there is the smallest of any setting on both metrics, and with only means available we cannot show it exceeds noise.
  • The docstring promises more than the code does. The submitted docstring says that, when throughput is observable, the simulations price tree nodes by measured throughput. In the submitted code, NODE_COST is a fixed 0.12, and measured throughput is used only to score candidate exits. An earlier development version did adapt the node cost, but that code is not in the final file. Likewise, WARM equals the 256-row buffer, so the "warm tail" cap never truncates the census.
  • The simulation search is close to inert. With a 1.5-times threshold the exit bonus almost never fires, so the simulations act only as a warm start for the census. That warm start keeps statistics from simulation prompts, which need not resemble the run's. In our development runs it hurt on one heterogeneous prompt set with long generations.
  • The model is approximate in several places. Acceptance is modelled as first-order Markov. Next-token confidence is stood in for by the current one. Tree width is priced with unconditional top- hit rates multiplied by chain survival, and the tree only branches off the top-1 spine. The stop rule uses top-1 confidence alone, not entropy or the hidden state.
  • Loadings are a proxy for time. The cost model ignores the controller's own CPU time and the real cost of wide trees, except through one constant. The scored speedups agree with the loading objective here, but our development timings show that the two can disagree.
  • Unused parts of the interface. Sublayer masks, per-token exits and the probe operations are not used. Masks and per-token exits did not help in our development, but they were tested only on small development models, and the probe operations were not tried.

References

  1. Mostafa Elhoushi, Akshat Shrivastava, Diana Liskovich et al. (2024). LayerSkip: Enabling Early Exit Inference and Self-Speculative Decoding. ACL.
  2. Jun Zhang, Jue Wang, Huan Li et al. (2024). Draft & Verify: Lossless Large Language Model Acceleration via Self-Speculative Decoding. ACL.
  3. Heming Xia, Yongqi Li, Jun Zhang et al. (2025). SWIFT: On-the-Fly Self-Speculative Decoding for LLM Inference Acceleration. ICLR.
  4. Hossein Entezari Zarch, Lei Gao, Chaoyi Jiang et al. (2025). DEL: Context-Aware Dynamic Exit Layer for Efficient Self-Speculative Decoding. COLM.
  5. Zhuofan Wen, Yang Feng (2026). SpecBound: Adaptive Bounded Self-Speculation with Layer-wise Confidence Calibration. ACL.
  6. Seongjin Cha, Gyuwan Kim, Dongsu Han et al. (2026). KnapSpec: Self-Speculative Decoding via Adaptive Layer Selection as a Knapsack Problem. ICML.

The session

The run from the model's first output, drawn as Claude Code shows a conversation: 371 steps.

Open the session

The submitted code

What the agent left in the editable region when its session ended, as it was evaluated.

layerskip-ee-lab/mlsee/draft_policy.pythe changes against the starter, inside the editable region