#!/usr/bin/env python3 """Reference Python implementation of DWarp-v1 speculative drafting & lossless verification. Demonstrates: 1. Loading `dwarp_config.json` + `dwarp.safetensors` from a local folder or Hugging Face Hub. 2. Pre-folding the Markov output projection through the target unembedding matrix: fold_w = W_U @ W_out ([V, 256]), fold_b = W_U @ b_out ([V]) 3. 1-Pass B=16 parallel block forward with optional plausibility-gated Carry-Over Edit. 4. L1-sized Top-64 shortlisted autoregressive Markov loop (64 x 256 x 2B = 32 KB per step). 5. Mathematically lossless speculative rejection sampling + exact sparse residual `(p - q_S)+` over the full vocabulary (Leviathan et al., 2023; Chen et al., 2023). 6. Plausibility gate (`q_acc(x*) >= 0.05`) deciding whether to carry over the rejected tail to the next round. Usage: # Self-contained synthetic smoke test (no target model download required): python3 reference/inference_example.py --synthetic-smoke # Inspect & run against a local Inkling-2-Mini + DWarp-v1 checkpoint: python3 reference/inference_example.py \\ --target-dir /path/to/Inkling-2-Mini \\ --dwarp-dir /path/to/Inkling-2-Mini-DotH-DWarp-v1 \\ --prompt "Write a concise explanation of speculative decoding:" """ import argparse import json from pathlib import Path from typing import Optional import torch import torch.nn.functional as F from safetensors.torch import load_file from dwarp_model import DWarpConfig, DWarpV1 def load_dwarp_v1( dwarp_dir: str | Path, device: torch.device | str = "cuda", dtype: torch.dtype = torch.bfloat16, ) -> DWarpV1: """Load DWarp-v1 BF16 weights + config from a local directory or Hugging Face repo ID.""" path = Path(dwarp_dir) if not path.exists(): from huggingface_hub import snapshot_download path = Path( snapshot_download( repo_id=str(dwarp_dir), allow_patterns=["dwarp.safetensors", "dwarp_config.json"], ) ) cfg_dict = json.loads((path / "dwarp_config.json").read_text()) cfg_dict["local_layer_ids"] = tuple(cfg_dict["local_layer_ids"]) cfg_dict["target_layer_ids"] = tuple(cfg_dict["target_layer_ids"]) cfg = DWarpConfig(**cfg_dict) model = DWarpV1(cfg).to(device=device, dtype=dtype) sd = load_file(str(path / "dwarp.safetensors"), device=str(device)) model.load_state_dict(sd, strict=True) model.eval() return model @torch.no_grad() def prefold_markov_head( dwarp: DWarpV1, lm_head_weight: torch.Tensor, # [V, D] ) -> tuple[torch.Tensor, torch.Tensor]: """Fold DWarpHead.hidden_out through target W_U once at startup: fold_w = W_U @ W_out^T -> [V, R] (R=256) fold_b = W_U @ b_out -> [V] """ w_out = dwarp.markov_head.hidden_out.weight.float() # [D, R] b_out = dwarp.markov_head.hidden_out.bias.float() # [D] wu = lm_head_weight.float() # [V, D] fold_w = (wu @ w_out).to(lm_head_weight.dtype) # [V, R] fold_b = (wu @ b_out).to(lm_head_weight.dtype) # [V] return fold_w, fold_b @torch.no_grad() def dwarp_draft_block_top64( dwarp: DWarpV1, taps5: torch.Tensor, # [L_ctx, 5, D] committed target taps [5, 17, 29, 41, 48] anchor_pos: int, # current position P (>= 1, <= L_ctx) anchor_tok: int, # last committed token ID x_P embed_fn, # callable(token_ids: LongTensor) -> [..., D] (target embed_norm'd) lm_head_weight: torch.Tensor, # [V, D] target unembedding matrix W_U fold_w: torch.Tensor, # [V, R] pre-folded W_U @ W_out fold_b: torch.Tensor, # [V] pre-folded W_U @ b_out num_drafts: int = 15, # K in 1..15 (B = K + 1 <= 16) shortlist_k: int = 64, # S = 64 -> 64 * 256 * 2B = 32 KB L1-resident per slot temperature: float = 0.0, top_p: float = 0.95, carry_toks: Optional[list[int]] = None, # plausibility-gated rejected tail from previous round ) -> dict: """Single-round 1-pass DWarp-v1 block draft with L1-resident Top-64 folded Markov head. Returns: draft_tokens: list[int] length K (proposed tokens for positions P+1 .. P+K) short_ids: [K, S] LongTensor of shortlisted candidate token IDs per step short_probs: [K, S] FloatTensor of exact draft probabilities q_S(v) per step pivot_probs: [K] FloatTensor of calibrated acceptance probabilities sigmoid(pivot_logits) """ dev = taps5.device dtype = taps5.dtype cfg = dwarp.cfg M = num_drafts + 1 assert 2 <= M <= cfg.block_size ap = torch.tensor([anchor_pos], device=dev, dtype=torch.long) depths = torch.arange(M, device=dev, dtype=torch.long).unsqueeze(0) # [1, M] pos_blk = ap.unsqueeze(1) + depths # [1, M] parent_idx = depths - 1 # [1, M] (-1 at slot 0) blk_mask = torch.ones(1, M, M, device=dev, dtype=torch.bool) # full block attention temp_t = torch.tensor([temperature], device=dev, dtype=torch.float32) topp_t = torch.tensor([top_p], device=dev, dtype=torch.float32) anchor_emb = embed_fn(torch.tensor([anchor_tok], device=dev, dtype=torch.long)).to(dtype) # [1, D] # Optional Warm-Start Carry-Over Edit (Mode 2) when previous round passed plausibility gate carry_emb, is_carry = None, None if carry_toks: n_carry = min(len(carry_toks), num_drafts) c_ids = torch.zeros(1, M, device=dev, dtype=torch.long) is_carry = torch.zeros(1, M, device=dev, dtype=torch.bool) c_ids[0, 1 : 1 + n_carry] = torch.tensor(carry_toks[:n_carry], device=dev, dtype=torch.long) is_carry[0, 1 : 1 + n_carry] = True carry_emb = embed_fn(c_ids).to(dtype) # 1) Single parallel 4-layer backbone forward over all M <= 16 rows out = dwarp.forward_sequence( taps=taps5, anchor_pos=ap, anchor_emb=anchor_emb, pos_blk=pos_blk, depths=depths, parent_idx=parent_idx, blk_internal_mask=blk_mask, temp=temp_t, top_p=topp_t, prev_toks=None, carry_emb=carry_emb, is_carry=is_carry, ) base_h = out["base_hidden"][0] # [K, D] f_rnn = out["f_rnn"][0] # [D] pivot_probs = torch.sigmoid(out["pivot_logits"][0].float()) # [K] # 2) Single base LM-head matmul + Top-64 shortlist extraction per draft slot V = lm_head_weight.shape[0] S = min(shortlist_k, V) base_logits = F.linear(base_h.float(), lm_head_weight.float()) # [K, V] top_vals, short_ids = torch.topk(base_logits, S, dim=-1) # [K, S] # 3) Autoregressive L1-resident Markov loop over ONLY the S=64 shortlisted rows! mh = dwarp.markov_head state = torch.zeros(1, cfg.markov_rank, device=dev, dtype=dtype) prev_tok = torch.tensor([anchor_tok], device=dev, dtype=torch.long) draft_tokens: list[int] = [] short_probs = torch.zeros(num_drafts, S, device=dev, dtype=torch.float32) for j in range(num_drafts): state, z, _ = mh.step_rnn(state, prev_tok, base_h[j : j + 1], f_rnn.unsqueeze(0)) idx_j = short_ids[j] # [S] # Gather ONLY 64 rows of fold_w ([64, 256] = 32 KB in BF16!) and fold_b ([64]) fw_j = fold_w[idx_j].float() # [S, R] fb_j = fold_b[idx_j].float() # [S] raw_j = top_vals[j] + fb_j + (fw_j @ z[0].float()) # [S] logits_j = cfg.logit_softcap * torch.tanh(raw_j / cfg.logit_softcap) if temperature <= 1e-4: local_pick = int(logits_j.argmax().item()) p_j = F.softmax(logits_j, dim=-1) # stored for plausibility gate check else: p_j = F.softmax(logits_j / temperature, dim=-1) local_pick = int(torch.multinomial(p_j, 1).item()) tok_j = int(idx_j[local_pick].item()) draft_tokens.append(tok_j) short_probs[j] = p_j prev_tok = torch.tensor([tok_j], device=dev, dtype=torch.long) return { "draft_tokens": draft_tokens, "short_ids": short_ids, "short_probs": short_probs, "pivot_probs": pivot_probs, } @torch.no_grad() def verify_shortlist_lossless( target_logits: torch.Tensor, # [K + 1, V] target logits at positions P .. P+K (post-softcap) draft_tokens: list[int], # length K short_ids: torch.Tensor, # [K, S] short_probs: torch.Tensor, # [K, S] temperature: float = 0.0, top_p: float = 0.95, top_k: int = 128, carry_plausibility_thresh: float = 0.05, ) -> tuple[list[int], Optional[list[int]]]: """Exact mathematically lossless speculative verification over a Top-S shortlist. Because the shortlist defines an explicit valid draft distribution q_S (with q_S(v) = 0 for v not in short_ids), standard rejection sampling + residual `(p - q_S)+` emits the EXACT target distribution p with zero approximation bias. Also applies DWarp's plausibility gate (`q_acc(x*) >= 0.05`) to return an optional `next_carry_toks` tail for the next round's Warm-Start Carry-Over Edit. """ K = len(draft_tokens) dev = target_logits.device V = target_logits.shape[-1] def target_dist(row_logits: torch.Tensor) -> torch.Tensor: if temperature <= 1e-4: p = torch.zeros(V, device=dev, dtype=torch.float32) p[int(row_logits.argmax().item())] = 1.0 return p scaled = row_logits.float() / temperature k_eff = min(top_k, V) vals, idx = torch.topk(scaled, k_eff) probs_k = F.softmax(vals, dim=-1) if top_p < 1.0: csum = torch.cumsum(probs_k, dim=-1) keep = (csum - probs_k) < top_p keep[0] = True probs_k = probs_k * keep probs_k = probs_k / probs_k.sum().clamp(min=1e-12) p = torch.zeros(V, device=dev, dtype=torch.float32) p.scatter_(0, idx, probs_k) return p emitted: list[int] = [] next_carry: Optional[list[int]] = None for j in range(K): p_j = target_dist(target_logits[j]) d_j = draft_tokens[j] if temperature <= 1e-4: t_pick = int(target_logits[j].argmax().item()) accepted = (d_j == t_pick) correction = t_pick else: # Look up q_S(d_j) inside step j's shortlist matches = (short_ids[j] == d_j).nonzero(as_tuple=False) q_d = float(short_probs[j, matches[0, 0]].item()) if matches.numel() > 0 else 0.0 p_d = float(p_j[d_j].item()) alpha = min(1.0, p_d / max(q_d, 1e-12)) if q_d > 0.0 else 0.0 accepted = bool(torch.rand(1, device=dev).item() < alpha) correction = -1 if accepted: emitted.append(d_j) continue # Rejected at slot j: sample correction token x* from exact residual (p_j - q_S)+ if temperature > 1e-4: q_full = torch.zeros(V, device=dev, dtype=torch.float32) q_full.scatter_(0, short_ids[j], short_probs[j]) res = (p_j - q_full).clamp(min=0.0) res_sum = float(res.sum().item()) probs_corr = (res / res_sum) if res_sum > 1e-12 else p_j correction = int(torch.multinomial(probs_corr, 1).item()) emitted.append(correction) # Plausibility-gated Carry-Over Edit: only feed unused tail draft[j+1:] if # correction x* had probability >= 0.05 under DWarp's step-j shortlist distribution! if j + 1 < K: m_corr = (short_ids[j] == correction).nonzero(as_tuple=False) q_corr = float(short_probs[j, m_corr[0, 0]].item()) if m_corr.numel() > 0 else 0.0 if q_corr >= carry_plausibility_thresh: next_carry = draft_tokens[j + 1 :] return emitted, next_carry # All K drafts accepted -> sample bonus token from row K p_bonus = target_dist(target_logits[K]) bonus = int(target_logits[K].argmax().item()) if temperature <= 1e-4 else int(torch.multinomial(p_bonus, 1).item()) emitted.append(bonus) return emitted, None def run_synthetic_smoke(): """Fast self-contained test exercising DWarpV1 + Top-64 fold_w + Carry-Over Edit + verification.""" dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") dtype = torch.bfloat16 if dev.type == "cuda" else torch.float32 cfg = DWarpConfig( hidden_size=128, num_hidden_layers=2, num_attention_heads=4, num_key_value_heads=2, head_dim=32, intermediate_size=256, vocab_size=512, unpadded_vocab_size=512, local_layer_ids=(0,), markov_rank=32, dynconv_group_size=16, ) dwarp = DWarpV1(cfg).to(device=dev, dtype=dtype).eval() emb = torch.nn.Embedding(cfg.vocab_size, cfg.hidden_size).to(device=dev, dtype=dtype) lm_head_w = torch.randn(cfg.vocab_size, cfg.hidden_size, device=dev, dtype=dtype) * 0.02 fold_w, fold_b = prefold_markov_head(dwarp, lm_head_w) taps5 = torch.randn(24, 5, cfg.hidden_size, device=dev, dtype=dtype) res1 = dwarp_draft_block_top64( dwarp, taps5, anchor_pos=24, anchor_tok=42, embed_fn=emb, lm_head_weight=lm_head_w, fold_w=fold_w, fold_b=fold_b, num_drafts=15, shortlist_k=64, temperature=0.85, top_p=0.95, ) fake_tgt = torch.randn(16, cfg.vocab_size, device=dev) emitted, carry = verify_shortlist_lossless( fake_tgt, res1["draft_tokens"], res1["short_ids"], res1["short_probs"], temperature=0.85, top_p=0.95, ) # Run Round 2 explicitly exercising Warm-Start Carry-Over Edit res2 = dwarp_draft_block_top64( dwarp, taps5, anchor_pos=24, anchor_tok=emitted[-1], embed_fn=emb, lm_head_weight=lm_head_w, fold_w=fold_w, fold_b=fold_b, num_drafts=15, shortlist_k=64, temperature=0.85, top_p=0.95, carry_toks=res1["draft_tokens"][1:8], ) print( f"[Synthetic Smoke PASS] device={dev}, drafted={len(res1['draft_tokens'])}, " f"emitted={len(emitted)}, carry_triggered={carry is not None}, " f"round2_edit_drafted={len(res2['draft_tokens'])}, " f"pivot_probs[0..3]={[round(x, 3) for x in res2['pivot_probs'][:4].tolist()]}" ) def main(): ap = argparse.ArgumentParser(description="DWarp-v1 reference Python drafting & verification example.") ap.add_argument("--synthetic-smoke", action="store_true", help="Run fast synthetic shape & math verification.") ap.add_argument("--target-dir", type=str, default="", help="Path or HF ID for thinkingmachines/Inkling-2-Mini.") ap.add_argument("--dwarp-dir", type=str, default="doth4580/Inkling-2-Mini-DotH-DWarp-v1", help="Path or HF ID for DWarp-v1.") ap.add_argument("--prompt", type=str, default="Write a concise explanation of speculative decoding:") ap.add_argument("--temperature", type=float, default=0.0) ap.add_argument("--top-p", type=float, default=0.95) ap.add_argument("--num-drafts", type=int, default=15) args = ap.parse_args() if args.synthetic_smoke or not args.target_dir: run_synthetic_smoke() return from transformers import AutoTokenizer from eval_dwarp import InklingTeacher dev = torch.device("cuda" if torch.cuda.is_available() else "cpu") tok = AutoTokenizer.from_pretrained(args.target_dir) teacher = InklingTeacher(args.target_dir, dev) dwarp = load_dwarp_v1(args.dwarp_dir, device=dev, dtype=torch.bfloat16) lm_w = teacher.model.lm_head.weight.detach() fold_w, fold_b = prefold_markov_head(dwarp, lm_w) input_ids = tok.encode(args.prompt, return_tensors="pt").to(dev) L = input_ids.shape[1] taps5, _, tgt_logits = teacher.forward_taps_and_logits(input_ids, torch.tensor([L - 1], device=dev)) first_tok = int(tgt_logits[0].argmax().item()) # Append first generated token and draft next K tokens with DWarp-v1 full_ids = torch.cat([input_ids, torch.tensor([[first_tok]], device=dev)], dim=1) taps5_next, _, _ = teacher.forward_taps_and_logits(full_ids, torch.tensor([L], device=dev)) res = dwarp_draft_block_top64( dwarp=dwarp, taps5=taps5_next, anchor_pos=L, anchor_tok=first_tok, embed_fn=teacher.embed_normed, lm_head_weight=lm_w, fold_w=fold_w, fold_b=fold_b, num_drafts=args.num_drafts, shortlist_k=64, temperature=args.temperature, top_p=args.top_p, ) print("Prompt:", args.prompt) print("Anchor token:", repr(tok.decode([first_tok]))) print("DWarp-v1 Top-64 draft block:", repr(tok.decode(res["draft_tokens"]))) print("Predicted slot survival probs:", [round(x, 3) for x in res["pivot_probs"].tolist()]) if __name__ == "__main__": main()