schift-ocr-1-beta / code /tt_dsocr /tests /test_host_device_sampling.py
changh95's picture
tt-model push schift-ocr-1-beta (container)
ca1a504 verified
Raw History Blame Contribute Delete
4.44 kB
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the device engine's host-side token choice (tt/model.py ``_pick``, the tt-nn decode path of
``DsocrDevice.generate``; no device): the repetition penalty is applied (as backends.pick_token, the HF order),
sampling draws from at most DSOCR_K_MAX candidates (as the megakernel's sampler), greedy output is unchanged, and the
decode timings (tokens / s) are recorded also when the caller closes the generator early (EOS / max tokens / cancel).
"""
from __future__ import annotations
import os
import sys
import types
import torch
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
from tt_dsocr import backends as B # noqa: E402
from tt_dsocr import frontend as FE # noqa: E402
from tt_dsocr.reference import model as R # noqa: E402
from tt_dsocr.tt import model as M # noqa: E402
V = 300
def test_pick_matches_pick_token():
g = torch.Generator().manual_seed(0)
for trial in range(30):
lg = torch.randn(V, generator=g) * 3
seen = torch.randint(0, V, (40,), generator=g).tolist()
banned = torch.randint(0, V, (5,), generator=g).tolist()
for sp in (M.Sampling(), M.Sampling(repetition_penalty=1.7), M.Sampling(repetition_penalty=1.2)):
assert M._pick(lg, seen, banned, sp, None) == B.pick_token(lg, seen, banned, sp, None), (trial, sp)
# the penalty changes the greedy choice when the best token was seen
lg = torch.zeros(V)
lg[5], lg[6] = 2.0, 1.5
assert M._pick(lg, [5], [], M.Sampling(), None) == 5
assert M._pick(lg, [5], [], M.Sampling(repetition_penalty=2.0), None) == 6
lg[5] = -1.0 # a negative logit is multiplied, not divided
assert M._pick(lg, [5, 6], [6], M.Sampling(repetition_penalty=2.0), None) not in (5, 6)
def test_sampling_is_capped_at_k_max():
lg = torch.arange(V, dtype=torch.float32) / 10.0 # every token has a non-zero probability at temperature 50
sp = M.Sampling(temperature=50.0, seed=1)
g = torch.Generator().manual_seed(1)
got = {M._pick(lg, [], [], sp, g, k_max=64) for _ in range(3000)}
assert got <= set(range(V - 64, V)) and len(got) > 50
got = {M._pick(lg, [], [], M.Sampling(temperature=50.0, top_k=8), g, k_max=64) for _ in range(500)}
assert got <= set(range(V - 8, V))
got = {M._pick(lg, [], [], M.Sampling(temperature=50.0, top_k=1000), g, k_max=64) for _ in range(2000)}
assert got <= set(range(V - 64, V)) # top_k above DSOCR_K_MAX is capped
class FakeTtnnDec:
"""A scripted tt-nn decoder: after token t the next logits prefer (t + 1) % V; token 1 (EOS) after 30 steps."""
def __init__(self):
self.last = None
self.n = 0
def prefill(self, rows, L):
self.last = 10
def logits_host(self):
lg = torch.full((V,), -5.0)
lg[(self.last + 5) % V] = 1.0
lg[(self.last + 2) % V] = 2.0
lg[(self.last + 1) % V] = 3.0
lg[FE.EOS_ID] = 4.0 if self.n >= 30 else -9.0
return lg
def step(self, token, pos):
self.last = token
self.n += 1
def _device():
dev = M.DsocrDevice.__new__(M.DsocrDevice)
dev.cfg = M.DeviceConfig(engine_dec="ttnn", max_context=4096)
dev.dec = FakeTtnnDec()
dev.dash = False
dev.prompt_rows = lambda prep: torch.zeros(len(prep.ids), R.D)
dev.buckets = [4096]
dev._t = {}
return dev
def test_timings_recorded_when_closed_early():
prep = types.SimpleNamespace(ids=[0, 3, 4], image_pos=(1, 1))
dev = _device()
g = dev.generate(prep, 100, M.Sampling(), M.NGram(0))
got = [next(g) for _ in range(10)]
g.close() # the API stops at max_new_tokens / EOS / cancel
assert got == list(range(11, 21)) and dev.timings()["tokens"] == 10 and "tokens_per_s" in dev.timings()
dev = _device()
out = list(dev.generate(prep, 100, M.Sampling(), M.NGram(0))) # runs to EOS: the same accounting
assert out[-1] == FE.EOS_ID and dev.timings()["tokens"] == len(out)
def test_penalty_reaches_the_decode_path():
prep = types.SimpleNamespace(ids=[0, 12, 13], image_pos=(1, 1))
plain = list(_device().generate(prep, 6, M.Sampling(), M.NGram(0)))
pen = list(_device().generate(prep, 6, M.Sampling(repetition_penalty=1e6), M.NGram(0)))
assert plain[:3] == [11, 12, 13] and pen[:2] == [11, 16], (plain, pen) # 12 and 13 were in the prompt