File size: 5,229 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# SPDX-License-Identifier: Apache-2.0
"""Host test of the exact no-repeat n-gram rule on the megakernel decode path (tt/model.py DsocrDevice.generate):
a fake MkDecoder replays a scripted greedy model; a token the rule bans must roll the request back to that step and
replay it with the step's banned ids, so the output equals the HF NoRepeatNGram decode of the same model."""

from __future__ import annotations

import os
import sys
import types

import numpy as np
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 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
from tt_dsocr.tt.mk_moe import geometry as G  # noqa: E402

V = 50


def scripted_logits(seq):
    """A deterministic 'model': prefers repeating the token 4 positions back, else (last + 1) % V."""
    lg = torch.full((V,), -10.0)
    if len(seq) >= 4:
        lg[seq[-4]] = 5.0
    lg[(seq[-1] + 1) % V] = 4.0
    lg[FE.EOS_ID] = 3.0 if len(seq) > 60 else -20.0
    return lg


class FakeEng:
    """Mimics MkDecoder: STATE ring, ban list for one step, batch launches."""

    def __init__(self, prompt, batch):
        self.prompt = list(prompt)
        self.batch = batch
        self.ring = np.zeros(G.S_TOKENS_MAX, np.uint32)
        self.restarts = 0

    def prefill(self, rows, L):
        return scripted_logits(self.prompt)

    def start(self, L, token0, max_new, ntok=1, ban_step=0, bans=(), **kw):
        self.restarts += int(ntok > 1)
        self.n = ntok
        self.ring[(ntok - 1) % G.S_TOKENS_MAX] = token0
        self.max_new = max_new
        self.ban_step, self.bans = ban_step, set(bans)
        self.done = token0 == FE.EOS_ID or max_new <= 1

    def run_batch(self):
        for _ in range(self.batch):
            if self.done:
                return
            seq = self.prompt + [int(self.ring[i % G.S_TOKENS_MAX]) for i in range(self.n)]
            lg = scripted_logits(seq)
            if self.n == self.ban_step:
                for b in self.bans:
                    lg[b] = float("-inf")
            t = int(lg.argmax())
            self.ring[self.n % G.S_TOKENS_MAX] = t
            self.n += 1
            if t == FE.EOS_ID or self.n >= self.max_new:
                self.done = True

    def poll(self):
        return self.n, self.done, 0, self.ring.copy()


def reference(prompt, n, max_new):
    seq, out = list(prompt), []
    for _ in range(max_new):
        lg = scripted_logits(seq)
        for b in R.banned_ngram_tokens(seq, n):
            lg[b] = float("-inf")
        t = int(lg.argmax())
        out.append(t)
        seq.append(t)
        if t == FE.EOS_ID:
            break
    return out


def run_device(prompt, n, max_new, batch):
    dev = M.DsocrDevice.__new__(M.DsocrDevice)
    dev.cfg = M.DeviceConfig(engine_dec="mk", max_context=4096)
    dev.dec = FakeEng(prompt, batch)
    dev.image_rows = lambda prep: torch.zeros(0, R.D)
    dev.prompt_rows = lambda prep: torch.zeros(len(prep.ids), R.D)
    dev.buckets = [4096]
    dev._t = {}
    prep = types.SimpleNamespace(ids=list(prompt), image_pos=(1, 1))
    out = list(dev.generate(prep, max_new, M.Sampling(), M.NGram(size=n)))
    return out, dev.dec.restarts


def test_rollback_matches_hf_rule():
    prompt = [0, 7, 8, 9]
    for n in (3, 5, 8):
        for batch in (1, 3, 8):
            ref = reference(prompt, n, 200)
            got, restarts = run_device(prompt, n, 200, batch)
            assert got == ref, (n, batch, got[:30], ref[:30])
    # the rule fires in this script (otherwise the test proves nothing)
    assert run_device(prompt, 3, 200, 8)[1] > 0


class AbortingEng(FakeEng):
    """FakeEng whose launches abort (no commit, STATE S_ABORTS + 1) at the given steps, ``times`` times each."""

    def __init__(self, prompt, batch, abort_at=(), times=1):
        super().__init__(prompt, batch)
        self.pending = {s: times for s in abort_at}
        self.last_aborts = 0

    def start(self, *a, **k):
        super().start(*a, **k)
        self.last_aborts = 0

    def run_batch(self):
        if not self.done and self.pending.get(self.n, 0) > 0:
            self.pending[self.n] -= 1
            self.last_aborts += 1
            return
        super().run_batch()


def test_aborted_launches_are_retried_or_fail_cleanly():
    import pytest

    prompt = [0, 7, 8, 9]
    ref = reference(prompt, 5, 120)
    dev = M.DsocrDevice.__new__(M.DsocrDevice)
    dev.cfg = M.DeviceConfig(engine_dec="mk", max_context=4096)
    dev.image_rows = lambda prep: torch.zeros(0, R.D)
    dev.prompt_rows = lambda prep: torch.zeros(len(prep.ids), R.D)
    dev.buckets = [4096]
    dev._t = {}
    prep = types.SimpleNamespace(ids=list(prompt), image_pos=(1, 1))
    dev.dec = AbortingEng(prompt, 1, abort_at=(5, 17), times=2)
    got = list(dev.generate(prep, 120, M.Sampling(), M.NGram(size=5)))
    assert got == ref and dev._t["mk_aborts"] == 4
    dev.dec = AbortingEng(prompt, 1, abort_at=(9,), times=10)
    dev._t = {}
    with pytest.raises(RuntimeError, match="aborted"):
        list(dev.generate(prep, 120, M.Sampling(), M.NGram(size=5)))