|
| 1 | +"""Torch/CUDA ``RestorationDraftEngine`` (ADR 0009 §4 F3, host B on a GPU). |
| 2 | +
|
| 3 | +The pure-torch twin of ``inference_engine.backends.mlx.dflash_distributed |
| 4 | +.MLXRestorationDraftEngine``: a remote DFlash drafter + f_θ projection that runs |
| 5 | +on a CUDA host (no MLX), feeding a gemma-4 MLX verifier on another host. Reuses |
| 6 | +the CUDA fused-engine machinery (``CrossModelDLMRestoredVerifier.project_drafter_kv``, |
| 7 | +``DFlashDrafter`` context K/V, the Gap-B torch embed/lm_head). |
| 8 | +
|
| 9 | +Imports torch + transformers + the v04 stack, so it lives in v04 (not coverage- |
| 10 | +gated) and is validated on-device. |
| 11 | +""" |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +from dataclasses import dataclass |
| 15 | +from typing import Any, Dict, List, Sequence, Tuple |
| 16 | + |
| 17 | +from inference_engine.distributed.dflash_service import DraftResult, RestoreResult |
| 18 | +from inference_engine.distributed.tensor_codec import ( |
| 19 | + WireTensor, |
| 20 | + torch_to_wire, |
| 21 | + wire_to_torch, |
| 22 | +) |
| 23 | + |
| 24 | + |
| 25 | +def build_torch_embed_lm_head(verifier_model, softcap): |
| 26 | + """Gap-B torch embed/lm_head over the verifier's tied embedding (no |
| 27 | + ×sqrt(hidden) on embed; tied head + final-logit softcap). Mirrors |
| 28 | + scripts/research/k3_specdecode_gpu_bench._build_embed_lm_head.""" |
| 29 | + import torch |
| 30 | + import torch.nn.functional as F |
| 31 | + |
| 32 | + emb_w = verifier_model.get_input_embeddings().weight.detach() |
| 33 | + head_w = verifier_model.get_output_embeddings().weight.detach() |
| 34 | + |
| 35 | + def embed_fn(ids: torch.Tensor) -> torch.Tensor: |
| 36 | + return F.embedding(ids, emb_w).float() |
| 37 | + |
| 38 | + def lm_head_fn(h: torch.Tensor) -> torch.Tensor: |
| 39 | + logits = (h.to(head_w.dtype) @ head_w.t()).float() |
| 40 | + if softcap: |
| 41 | + logits = softcap * torch.tanh(logits / softcap) |
| 42 | + return logits |
| 43 | + |
| 44 | + return embed_fn, lm_head_fn |
| 45 | + |
| 46 | + |
| 47 | +@dataclass |
| 48 | +class _Session: |
| 49 | + ctx_kv: Any = None |
| 50 | + |
| 51 | + |
| 52 | +class TorchRestorationDraftEngine: |
| 53 | + """``RestorationDraftEngine`` on a CUDA host: torch DFlash + f_θ + a gemma-4 |
| 54 | + verifier (used only for its embedding / drafter-KV capture).""" |
| 55 | + |
| 56 | + def __init__( |
| 57 | + self, *, verifier_model: Any, drafter: Any, f_theta: Any, device: Any, |
| 58 | + sink: int, window: int, force_f_theta: bool = True, |
| 59 | + ) -> None: |
| 60 | + import torch |
| 61 | + |
| 62 | + from inference_engine.v04.cross_model_dlm_verifier import ( |
| 63 | + CrossModelDLMRestoredVerifier, |
| 64 | + full_attention_layer_indices, |
| 65 | + ) |
| 66 | + |
| 67 | + self._torch = torch |
| 68 | + self.device = device |
| 69 | + self.sink = int(sink) |
| 70 | + self.window = int(window) |
| 71 | + self.force_f_theta = bool(force_f_theta) |
| 72 | + self.drafter = drafter |
| 73 | + self.exact_set = set(full_attention_layer_indices(verifier_model)) |
| 74 | + self._restored = CrossModelDLMRestoredVerifier( |
| 75 | + verifier_model=verifier_model, drafter=drafter, f_theta=f_theta, |
| 76 | + sink_size=sink, window_size=window, |
| 77 | + exact_layer_indices=self.exact_set) |
| 78 | + softcap = None |
| 79 | + vcfg = getattr(verifier_model, "config", None) |
| 80 | + for attr in ("final_logit_softcapping",): |
| 81 | + cap = getattr(vcfg, attr, None) if vcfg is not None else None |
| 82 | + if cap is None and vcfg is not None: |
| 83 | + cap = getattr(getattr(vcfg, "text_config", None), attr, None) |
| 84 | + if cap: |
| 85 | + softcap = float(cap) |
| 86 | + self._embed_fn, self._lm_head_fn = build_torch_embed_lm_head( |
| 87 | + verifier_model, softcap) |
| 88 | + self._sessions: Dict[str, _Session] = {} |
| 89 | + |
| 90 | + def restore( |
| 91 | + self, session_id: str, prompt_ids: Sequence[int], *, |
| 92 | + sink: int, window: int, s5_exact_full_attn: bool, model_id: str, |
| 93 | + ) -> RestoreResult: |
| 94 | + from inference_engine.v04.kv_merge import compute_evicted_positions |
| 95 | + |
| 96 | + torch = self._torch |
| 97 | + self._sessions[session_id] = _Session() |
| 98 | + prompt_ids = list(prompt_ids) |
| 99 | + T = len(prompt_ids) |
| 100 | + evicted = compute_evicted_positions(T, self.sink, self.window) |
| 101 | + restored: List[Tuple[int, WireTensor, WireTensor]] = [] |
| 102 | + if not (s5_exact_full_attn and not self.force_f_theta): |
| 103 | + ids = torch.tensor([prompt_ids], dtype=torch.long, device=self.device) |
| 104 | + with torch.no_grad(): |
| 105 | + vk, vv = self._restored.project_drafter_kv(ids) |
| 106 | + for li in range(len(vk)): |
| 107 | + if s5_exact_full_attn and li in self.exact_set: |
| 108 | + continue # native cache owns exact (full-attn) layers |
| 109 | + restored.append((li, torch_to_wire(vk[li]), torch_to_wire(vv[li]))) |
| 110 | + return RestoreResult(restored=restored, evicted_positions=list(evicted), |
| 111 | + prompt_len=T) |
| 112 | + |
| 113 | + def seed_context( |
| 114 | + self, session_id: str, aux: Sequence[WireTensor], positions: Sequence[int], |
| 115 | + ) -> int: |
| 116 | + torch = self._torch |
| 117 | + aux_t = [wire_to_torch(w).to(self.device) for w in aux] |
| 118 | + pos = torch.tensor(list(positions), device=self.device) |
| 119 | + self._sessions[session_id].ctx_kv = self.drafter.make_context_kv(aux_t, pos) |
| 120 | + return len(positions) |
| 121 | + |
| 122 | + def draft_block( |
| 123 | + self, session_id: str, *, bonus_token_id: int, context_len: int, |
| 124 | + block_size: int, |
| 125 | + ) -> DraftResult: |
| 126 | + if block_size <= 0: |
| 127 | + raise ValueError("block_size must be positive") |
| 128 | + sess = self._sessions[session_id] |
| 129 | + drafts = self.drafter.draft_block_cached( |
| 130 | + sess.ctx_kv, int(bonus_token_id), self._embed_fn, self._lm_head_fn, |
| 131 | + block_size=block_size, context_len=int(context_len)) |
| 132 | + return DraftResult(draft_token_ids=[int(t) for t in drafts], |
| 133 | + forward_passes=1, peak_activation_bytes=0) |
| 134 | + |
| 135 | + def extend_context( |
| 136 | + self, session_id: str, aux: Sequence[WireTensor], positions: Sequence[int], |
| 137 | + ) -> int: |
| 138 | + torch = self._torch |
| 139 | + sess = self._sessions[session_id] |
| 140 | + aux_t = [wire_to_torch(w).to(self.device) for w in aux] |
| 141 | + pos = torch.tensor(list(positions), device=self.device) |
| 142 | + new_kv = self.drafter.make_context_kv(aux_t, pos) |
| 143 | + sess.ctx_kv = self.drafter.extend_context_kv(sess.ctx_kv, new_kv) |
| 144 | + return int(positions[-1]) + 1 if len(positions) else 0 |
| 145 | + |
| 146 | + def close_session(self, session_id: str) -> None: |
| 147 | + self._sessions.pop(session_id, None) |
0 commit comments