File size: 16,987 Bytes
e349bd8 adc84bd e349bd8 adc84bd e349bd8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | #!/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()
|