"""Speculative decoding that also works for hybrid (linear-attention + attention) models. This is mlx_lm's `speculative_generate_step` (mlx_lm 0.31.x) with one change. mlx_lm rewinds rejected draft tokens by trimming the KV cache, so it refuses any model whose cache cannot be trimmed. Qwen3.5/3.6 Gated DeltaNet layers keep a recurrent state (ArraysCache), which cannot be trimmed. Here each non-trimmable layer is rolled back by restoring a snapshot of its state: * draft model: it runs one token per step, so we keep a snapshot after every step (free: MLX arrays are immutable, a snapshot is just a list of references) and restore the right one. * target model: it verifies k+1 tokens in a single forward pass, so there is no intermediate state to restore. After a rejection we restore the pre-verify state and re-run the n+1 accepted tokens through the target (logits are never evaluated, so MLX skips the lm_head). This re-forward is the extra cost hybrid models pay for speculation. Acceptance rule is mlx_lm's: a draft token is accepted iff it equals the target's own (greedy or sampled) token at that position, so the output distribution is the target's. Only `mlx.core` is imported, so the logic can be tested with a numpy stand-in. """ from contextlib import nullcontext import mlx.core as mx def is_trimmable(cache): return all(c.is_trimmable() for c in cache) def snapshot(cache): """References to the state of every non-trimmable layer (None for trimmable layers).""" return [None if c.is_trimmable() else list(c.state) for c in cache] def rewind(cache, snap, n_trim): """Trim trimmable layers by n_trim tokens and restore the others from `snap`.""" for c, s in zip(cache, snap): if s is None: c.trim(n_trim) else: c.state = list(s) def prefill(model, cache, y, step_size=2048): """Process all but the last prompt token; return the remaining token(s).""" while y.size > 1: n = min(step_size, y.size - 1) model(y[:n][None], cache=cache) mx.eval([c.state for c in cache]) y = y[n:] return y def speculative_generate(prompt, model, draft_model, model_cache, draft_cache, *, num_draft_tokens, max_tokens, sampler, stats, stream=None): """Yield (token, from_draft) for `max_tokens` tokens. Fills `stats` with counters.""" ctx = (lambda: mx.stream(stream)) if stream is not None else nullcontext target_hybrid = not is_trimmable(model_cache) stats.update(cycles=0, proposed=0, accepted=0, rejections=0, target_reforwards=0, reforward_tokens=0, target_hybrid=target_hybrid, draft_hybrid=not is_trimmable(draft_cache)) def step(m, cache, y, n_predict=1): with ctx(): logits = m(y[None], cache=cache)[:, -n_predict:, :] logprobs = logits - mx.logsumexp(logits, axis=-1, keepdims=True) return sampler(logprobs.squeeze(0)) y = prompt.astype(mx.uint32) with ctx(): draft_y = prefill(draft_model, draft_cache, y) y = prefill(model, model_cache, y) ntoks = 0 while True: num_draft = min(max_tokens - ntoks, num_draft_tokens) # 1) draft num_draft tokens, snapshotting the draft state after every step draft_snaps, ys, dy = [], [], draft_y for _ in range(num_draft): dy = step(draft_model, draft_cache, dy) mx.async_eval(dy) ys.append(dy) draft_snaps.append(snapshot(draft_cache)) draft_tokens = mx.concatenate(ys) # 2) verify all drafts with one target forward pass over [y, d1..dk] target_snap = snapshot(model_cache) if target_hybrid else None verify_in = mx.concatenate([y, draft_tokens]) tokens = step(model, model_cache, verify_in, num_draft + 1) mx.eval(tokens, draft_tokens) draft_list, tok_list = draft_tokens.tolist(), tokens.tolist() # 3) accept the longest matching prefix, then emit the target's own next token n = 0 while n < num_draft and tok_list[n] == draft_list[n]: n += 1 ntoks += 1 yield tok_list[n - 1], True if ntoks == max_tokens: break stats["cycles"] += 1 stats["proposed"] += num_draft stats["accepted"] += n if n < num_draft: stats["rejections"] += 1 if ntoks < max_tokens: ntoks += 1 yield tok_list[n], False if ntoks == max_tokens: return # 4) roll both caches back to "prompt + accepted tokens" if n < num_draft: if target_hybrid: rewind(model_cache, target_snap, num_draft + 1) with ctx(): model(verify_in[: n + 1][None], cache=model_cache) stats["target_reforwards"] += 1 stats["reforward_tokens"] += n + 1 else: rewind(model_cache, [None] * len(model_cache), num_draft - n) # draft state after step n+1 covers [.., y, d1..dn]; its KV trims num_draft-n-1 rewind(draft_cache, draft_snaps[n], num_draft - n - 1) y = mx.array([tok_list[n]], mx.uint32) draft_y = y if n == num_draft: # the last draft token was never fed to the draft model: feed it next time draft_y = mx.concatenate([mx.array(draft_list[-1:], mx.uint32), draft_y])