wang2226's picture
Beyond Tokens decoding playground: contrastive, guided and parallel decoding
371d90c verified
Raw History Blame Contribute Delete
2.72 kB
"""Test fixtures: tiny randomly initialized models that share the SmolLM2 tokenizer."""
from __future__ import annotations
import os
import sys
from pathlib import Path
os.environ.setdefault("HF_HUB_OFFLINE", "1")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import pytest # noqa: E402
import torch # noqa: E402
from transformers import AutoModelForCausalLM, AutoTokenizer, Gemma3TextConfig, LlamaConfig, Qwen3Config # noqa: E402
from models import FamilySpec, make_family # noqa: E402
TOKENIZER_ID = "HuggingFaceTB/SmolLM2-135M-Instruct"
ARCHS = ("llama", "qwen3", "gemma3")
def tiny_config(arch: str, vocab: int, layers: int = 4):
common = dict(
vocab_size=vocab,
hidden_size=64,
intermediate_size=128,
num_hidden_layers=layers,
num_attention_heads=4,
num_key_value_heads=2,
max_position_embeddings=1024,
initializer_range=0.2, # peaky logits, so greedy ties are rare
bos_token_id=1,
eos_token_id=2,
pad_token_id=2,
)
if arch == "llama":
return LlamaConfig(**common, tie_word_embeddings=False)
if arch == "qwen3":
return Qwen3Config(**common, head_dim=16, tie_word_embeddings=True)
if arch == "gemma3":
return Gemma3TextConfig(**common, head_dim=16, sliding_window=8)
raise ValueError(arch)
def tiny_model(arch: str, vocab: int, seed: int = 0, layers: int = 4):
torch.manual_seed(seed)
model = AutoModelForCausalLM.from_config(tiny_config(arch, vocab, layers), dtype=torch.float32)
return model.eval()
def perturbed_copy(model, scale: float, seed: int = 1):
"""A draft model that agrees with ``model`` often but not always."""
import copy
torch.manual_seed(seed)
draft = copy.deepcopy(model)
with torch.no_grad():
for p in draft.parameters():
p.add_(scale * torch.randn_like(p) * p.std().clamp_min(1e-3))
return draft
@pytest.fixture(scope="session")
def tok():
return AutoTokenizer.from_pretrained(TOKENIZER_ID)
@pytest.fixture(scope="session")
def tiny_family(tok):
"""A Family whose helper is a perturbed copy of the main model (moderate agreement)."""
def build(arch: str = "llama", scale: float = 0.05, seed: int = 0):
main = tiny_model(arch, len(tok), seed=seed)
helper = perturbed_copy(main, scale, seed=seed + 1)
spec = FamilySpec(f"tiny-{arch}", f"Tiny {arch}", f"tiny/{arch}", f"tiny/{arch}-helper")
return make_family(spec, tok, main, helper)
return build
def pytest_configure(config):
config.addinivalue_line("markers", "slow: uses real cached models (minutes)")