File size: 4,278 Bytes
ca1a504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the no-repeat n-gram rule (no device, no ttnn): the device engine's incremental index
(``tt.model.NGramIndex``) against the reference rule (``reference.model.banned_ngram_tokens``, the HF
``NoRepeatNGramLogitsProcessor`` / the vLLM windowed variant) on random sequences, its rollback (``pop``), and the host
sampler's handling of banned ids.

    TT_VISIBLE_DEVICES=none python -m pytest -q code/tt_dsocr/tests/test_host_ngram.py
"""

from __future__ import annotations

import os
import random
import sys

import pytest

torch = pytest.importorskip("torch")
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from tt_dsocr.backends import NGRAM_PRESETS, Sampling, pick_token  # noqa: E402
from tt_dsocr.reference.model import banned_ngram_tokens  # noqa: E402
from tt_dsocr.tt.model import NGram, NGramIndex  # noqa: E402


def test_tt_model_imports_without_ttnn():
    assert "ttnn" not in sys.modules


@pytest.mark.parametrize("n,window,whitelist,vocab", [
    (2, 0, (), 3), (3, 0, (), 4), (5, 0, (1,), 3), (20, 0, (), 2), (2, 6, (), 3), (3, 10, (0,), 3),
    (30, 90, (128821, 128822), 3), (4, 4, (), 2)])
def test_index_matches_the_reference(n, window, whitelist, vocab):
    rng = random.Random(1000 * n + window + vocab)
    for trial in range(6):
        prompt = [rng.randrange(vocab) for _ in range(rng.randrange(0, 3 * n + 5))]
        if vocab >= 3 and whitelist:
            prompt = [whitelist[0] if t == 0 and rng.random() < 0.5 else t for t in prompt]
        ng = NGramIndex(NGram(n, window, tuple(whitelist)), prompt)
        seq = list(prompt)
        for step in range(4 * n + 30):
            want = banned_ngram_tokens(seq, n, window, whitelist)
            assert ng.banned() == want, (trial, step, seq)
            if want and rng.random() < 0.3:       # a token the rule bans: the device rolls back and replays
                t = want[0]
                ng.push(t)
                ng.pop()
                assert ng.banned() == want and ng.seq == seq
            allowed = [t for t in range(vocab) if t not in want] or [vocab]
            t = rng.choice(allowed)
            ng.push(t)
            seq.append(t)
        assert ng.seq == seq


def test_hf_rule_examples():
    # the 3-gram (1, 2, 3) exists: after (..., 1, 2) the token 3 is banned (whole sequence, prompt included)
    assert banned_ngram_tokens([1, 2, 3, 4, 1, 2], 3) == [3]
    ng = NGramIndex(NGram(3, 0, ()), [1, 2, 3, 4, 1, 2])
    assert ng.banned() == [3]
    ng = NGramIndex(NGram(3, 0, (3,)), [1, 2, 3, 4, 1, 2])
    assert ng.banned() == []                                     # whitelisted
    assert NGramIndex(NGram(0, 0, ()), [1, 2, 1]).banned() == []  # off
    assert NGramIndex(NGram(20, 0, ()), [1] * 10).banned() == []  # shorter than the n-gram
    assert banned_ngram_tokens([1, 2, 3, 9, 9, 9, 1, 2], 3, window=4) == []   # outside the window (vLLM)


def test_presets():
    assert (NGRAM_PRESETS["hf"].size, NGRAM_PRESETS["hf"].window, NGRAM_PRESETS["hf"].whitelist) == (20, 0, ())
    assert (NGRAM_PRESETS["vllm"].size, NGRAM_PRESETS["vllm"].window,
            NGRAM_PRESETS["vllm"].whitelist) == (30, 90, (128821, 128822))
    assert NGRAM_PRESETS["off"].size == 0


def test_pick_token_respects_bans_and_penalty():
    lg = torch.tensor([0.0, 5.0, 4.0, -1.0, 3.0])
    assert pick_token(lg, [], [], Sampling(), None) == 1
    assert pick_token(lg, [], [1], Sampling(), None) == 2
    assert pick_token(lg, [], [1, 2], Sampling(), None) == 4
    # repetition penalty 2: logit 5 of the seen token 1 -> 2.5 < 4
    assert pick_token(lg, [1], [], Sampling(repetition_penalty=2.0), None) == 2
    g = torch.Generator().manual_seed(0)
    for _ in range(50):     # sampling never draws a banned token, top_k 2 keeps {1, 2} minus the bans
        assert pick_token(lg, [], [1], Sampling(temperature=1.5, top_k=2, seed=0), g) in (2, 4)
    g1, g2 = torch.Generator().manual_seed(7), torch.Generator().manual_seed(7)
    a = [pick_token(lg, [], [], Sampling(temperature=1.0, top_p=0.9, seed=7), g1) for _ in range(20)]
    b = [pick_token(lg, [], [], Sampling(temperature=1.0, top_p=0.9, seed=7), g2) for _ in range(20)]
    assert a == b and set(a) <= {1, 2, 4}