File size: 1,662 Bytes
643267a | 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 | """Sampling respects the public vocabulary and explicit sampling settings."""
from types import SimpleNamespace
import pytest
import torch
from pat.generate import generate, sample
from pat.tokenizer import EOD_ID
def test_internal_ids_cannot_win_greedy_selection():
logits = torch.zeros(50304)
logits[EOD_ID + 1:] = 1000
logits[17] = 10
assert sample(logits, 0, 0.95, None) == 17
logits[EOD_ID] = 20
assert sample(logits, 0, 0.95, None) == EOD_ID
def test_small_nucleus_keeps_highest_probability_token():
logits = torch.tensor([3., 2., 1.])
generator = torch.Generator().manual_seed(42)
for _ in range(10):
assert sample(logits, 1, 0.1, generator) == 0
@pytest.mark.parametrize("temperature,top_p", [(-1, .9), (float('nan'), .9), (1, 0), (1, 2)])
def test_invalid_sampling_settings_are_rejected(temperature, top_p):
with pytest.raises(ValueError):
sample(torch.zeros(3), temperature, top_p, None)
def test_nonfinite_logits_are_rejected():
with pytest.raises(FloatingPointError):
sample(torch.tensor([0., float('nan')]), 0, .9, None)
def test_generation_requires_a_nonempty_text_prompt():
tokenizer = SimpleNamespace(encode=lambda _: [])
with pytest.raises(ValueError, match="at least one text token"):
generate(None, "", tokenizer=tokenizer)
def test_generation_context_budget_includes_bos():
tokenizer = SimpleNamespace(encode=lambda _: [1, 2, 3])
model = SimpleNamespace(config=SimpleNamespace(context_length=4))
with pytest.raises(ValueError, match="context length"):
generate(model, "three tokens", tokenizer=tokenizer, max_new_tokens=1)
|