code-switch-mtp / tests /test_phase4_speculative.py
Anupam-Rawat-IITB's picture
Add code, result files and documentation
3bbd5dd verified
Raw History Blame Contribute Delete
3.41 kB
"""Tests for the verified speculative-decoding loop used by the Phase 4 pilot."""
import importlib.util
from pathlib import Path
from types import SimpleNamespace
import torch
import torch.nn.functional as F
VOCAB = 64
_SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "phase4_speculative_eval.py"
_spec = importlib.util.spec_from_file_location("phase4_speculative_eval", _SCRIPT)
phase4_spec = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(phase4_spec)
class _CountingBackbone:
"""Base model whose greedy next token is always (last token + 1); hidden state = one-hot token."""
def __init__(self) -> None:
self.drafting_inputs = []
self.model = _ModelProxy(self)
def _hidden(self, input_ids):
self.drafting_inputs.append(input_ids[0].tolist())
return SimpleNamespace(last_hidden_state=F.one_hot(input_ids, VOCAB).float())
def __call__(self, input_ids):
return SimpleNamespace(logits=F.one_hot((input_ids + 1) % VOCAB, VOCAB).float())
class _ModelProxy:
def __init__(self, backbone: _CountingBackbone) -> None:
self._backbone = backbone
def __call__(self, input_ids):
return self._backbone._hidden(input_ids)
class _ShiftStack:
"""Head k drafts (token + k + 1), i.e. agrees with the base model, unless listed in wrong_heads."""
def __init__(self, n_heads: int, wrong_heads: tuple = ()) -> None:
self.n_heads = n_heads
self.wrong_heads = wrong_heads
def trunk_states(self, hidden):
return hidden
def head_logits(self, trunk, k):
shift = k + 1 + (7 if k in self.wrong_heads else 0)
return torch.roll(trunk, shifts=shift, dims=-1)
class _IntTokenizer:
def __call__(self, text, add_special_tokens=False, truncation=True, max_length=None):
return SimpleNamespace(input_ids=[int(x) for x in text.split()][:max_length])
def decode(self, ids):
return str(ids[0])
def test_all_drafts_accepted_commits_a_verified_bonus_token():
"""Every draft matches, so each pass commits 4 drafts plus the base model's
token after them -- and the next round must start from a duplicate-free
sequence (the original loop re-committed the last draft instead)."""
backbone = _CountingBackbone()
stats = phase4_spec.speculative_decode_verified(
backbone, _ShiftStack(4), _IntTokenizer(), ["0 1 2 3 4 5 6 7"], "cpu", prompt_tokens=8, completion_tokens=10
)
assert stats.n_rounds == 2
assert stats.mean_accepted_per_forward == 5.0
assert backbone.drafting_inputs[1] == list(range(13))
def test_rejection_commits_accepted_prefix_plus_correction():
"""Head 3 is always wrong: two drafts accepted plus the base token, 3 per pass;
position 3 is reached and rejected, position 4 never reached."""
opens = torch.zeros(VOCAB, dtype=torch.bool)
closes = torch.zeros(VOCAB, dtype=torch.bool)
stats = phase4_spec.speculative_decode_verified(
_CountingBackbone(), _ShiftStack(4, wrong_heads=(2,)), _IntTokenizer(), ["0 1 2 3 4 5 6 7"], "cpu",
prompt_tokens=8, completion_tokens=9, opens=opens, closes=closes,
)
assert stats.mean_accepted_per_forward == 3.0
rounds = stats.n_rounds
assert stats.reached_inner == [rounds, rounds, rounds, 0]
assert stats.accepted_inner == [rounds, rounds, 0, 0]
assert stats.reached_start == [0, 0, 0, 0]