File size: 13,176 Bytes
22e0325
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# SPDX-License-Identifier: Apache-2.0
"""Host tests (no device, no weights): configuration knobs, post-processing, the tokenizer stub, incremental
detokenization and the Python API on the fake backend.

    TT_VISIBLE_DEVICES=none python -m pytest code/tt_paddleocr/tests/test_host_api.py
"""
import os

import numpy as np
import pytest
from PIL import Image

from tt_paddleocr import config as C
from tt_paddleocr import postprocess as PP
from tt_paddleocr import serve_config as S
from tt_paddleocr.api import (DeltaStream, InputError, PaddleOCRVL, StubTokenizer, decode_image, sample_next,
                              stub_prompts)
from tt_paddleocr.tt.model_types import GenParams

HERE = os.path.dirname(os.path.abspath(__file__))
SAMPLES = os.path.join(os.path.dirname(HERE), "samples")
from tt_paddleocr.tests._weights import repo_file  # noqa: E402

REAL_TOK = repo_file("tokenizer.json") or ""


def fake(profile="1.6", **env):
    e = {"PADDLEOCR_PROFILE": profile, "PADDLEOCR_BACKEND": "fake"}
    e.update(env)
    return PaddleOCRVL.from_config(S.resolve_config(e))


# ------------------------------------------------------------------------------------------ configuration
def test_defaults_per_profile():
    c = S.resolve_config({})
    assert c.profile == "1.6" and c.backend == "tt" and c.dispatch == "eth"
    assert c.engine == {"vis": "ttnn", "pre": "ttnn", "dec": "mk"}
    assert c.max_pixels == C.SPOTTING_MAX_PIXELS == 1605632  # 1.6 serves the spotting preset
    assert c.vis_buckets == (640, 768, 1024, 1536, 2048, 3072, 4096, 5120, 6144, 8192)  # min 576 patches
    assert c.pre_buckets == (192, 256, 384, 512, 768, 1024, 1280, 1536, 2112)  # config.derive_pre_buckets
    assert c.max_positions == 2112 + 4096 and c.default_max_new_tokens == 512
    v = S.resolve_config({"PADDLEOCR_PROFILE": "vl"})
    assert v.max_pixels == 2822400 and v.vis_buckets[-1] == 14464 and v.tasks == ("ocr", "table", "formula", "chart")
    assert v.default_max_new_tokens == 1024 and v.min_pixels == 147384
    assert S.resolve_config({"PADDLEOCR_PROFILE": "1.5"}).tasks == tuple(C.TASKS)


def test_weights_pins_from_tt_model():
    c = S.resolve_config({"PADDLEOCR_PROFILE": "1.5",
                          "TT_AUXILIARY_WEIGHTS": "PaddlePaddle/PaddleOCR-VL@abc,PaddlePaddle/PaddleOCR-VL-1.5@def"})
    assert c.revision == "def"
    c = S.resolve_config({"TT_MODEL_WEIGHTS_REVISION": "x" * 40})
    assert c.revision == "x" * 40
    assert S.resolve_config({"PADDLEOCR_PROFILE": "vl"}).revision == C.WEIGHTS["vl"][1]


@pytest.mark.parametrize("bad", [
    {"PADDLEOCR_PROFILE": "2.0"}, {"PADDLEOCR_BACKEND": "gpu"}, {"PADDLEOCR_DISPATCH": "pcie"},
    {"PADDLEOCR_ENGINE": "dec=gpu"}, {"PADDLEOCR_ENGINE": "vis=mk"}, {"PADDLEOCR_PRECISION": "vis=fp8"}, {"PADDLEOCR_PRECISION": "attn=bf16"}, {"PADDLEOCR_TTNN_FALLBACK": "x"},
    {"PADDLEOCR_VIS_BUCKETS": "1000"}, {"PADDLEOCR_VIS_BUCKETS": "1024"}, {"PADDLEOCR_PRE_BUCKETS": "100"},
    {"PADDLEOCR_MAX_NEW_TOKENS": "5"}, {"PADDLEOCR_MAX_PIXELS": "100"}, {"PADDLEOCR_TRACE": "maybe"},
    {"PADDLEOCR_MAX_POSITIONS": "512"}, {"PADDLEOCR_WARMUP": "some"}, {"PADDLEOCR_K_MAX": "65"},
])
def test_bad_config_refused(bad):
    with pytest.raises(ValueError):
        S.resolve_config(bad)


def test_overrides_and_settings():
    c = S.resolve_config({"PADDLEOCR_MAX_PIXELS": str(1280 * 28 * 28), "PADDLEOCR_ENGINE": "ttnn",
                          "PADDLEOCR_PRECISION": "vis=bfp8,mk=bf16,pre_mlp=bf16", "PADDLEOCR_WARMUP": "2048,1024",
                          "PADDLEOCR_TTNN_FALLBACK": "1", "PADDLEOCR_POLL_TOKENS": "4",
                          "PADDLEOCR_MAX_NEW_TOKENS": "1024"})
    assert c.engine["dec"] == "ttnn" and c.vis_buckets[-1] == 5120 and c.precision["vis"] == "bfp8"
    d = c.device_settings()
    assert d["engine"]["dec"] == "ttnn" and d["vis_buckets"][-1] == 5120 and d["warmup_buckets"] == [1024, 2048]
    assert d["ttnn_fallback"] is True and d["mk_batch"] == 4 and d["precision"]["pre_mlp"] == "bf16"
    assert S.resolve_config({}).device_settings()["ttnn_fallback"] is None
    assert d["max_positions"] == c.max_positions == S.ceil_to(c.pre_buckets[-1] + 1024, 64)
    assert set(c.as_env()) >= {"PADDLEOCR_PROFILE", "PADDLEOCR_ENGINE", "PADDLEOCR_VIS_BUCKETS"}


def test_default_vis_buckets_match_ttnn_vision():
    src = open(os.path.join(os.path.dirname(HERE), "tt", "ttnn_vision.py")).read()
    assert "VIS_BUCKET_BASE = " + repr(S.VIS_BUCKET_BASE) in src  # mirrored in serve_config (no torch import there)


# ------------------------------------------------------------------------------------------ post-processing
def test_otsl_to_html_spans():
    t = "<fcel>A<lcel><fcel>C<nl><fcel>D<fcel>E<ucel><nl><ucel><ecel><fcel>F<nl>"
    h = PP.otsl_to_html(t)
    assert h == ('<table><tr><td colspan="2">A</td><td rowspan="2">C</td></tr>'
                 '<tr><td rowspan="2">D</td><td>E</td></tr><tr><td></td><td>F</td></tr></table>'), h
    assert PP.otsl_grid("<fcel>x<fcel>y")[0] == [("fcel", "x"), ("fcel", "y")]
    assert "&lt;b&gt;" in PP.otsl_to_html("<fcel><b><nl>")
    two = PP.otsl_to_html("<fcel>a<lcel><nl><ucel><xcel><nl>")
    assert two == '<table><tr><td colspan="2" rowspan="2">a</td></tr><tr></tr></table>', two


def test_golden_table_format():
    t = ("<fcel>Model<fcel>Params<fcel>Latency (ms)<fcel>Score<nl><fcel>Alpha<fcel>0.9B<fcel>12.5<fcel>94.5<nl>"
         "<fcel>Beta<fcel>1.7B<fcel>20.1<fcel>95.2<nl>")
    r = PP.structured("table", t)
    assert r["rows"][0] == ["Model", "Params", "Latency (ms)", "Score"] and len(r["rows"]) == 3
    assert r["html"].count("<tr>") == 3 and r["html"].count("<td>") == 12


def test_spotting_both_orders():
    a = PP.parse_spotting("Hi<|LOC_0|><|LOC_0|><|LOC_500|><|LOC_500|>Yo<|LOC_500|><|LOC_500|><|LOC_1000|><|LOC_1000|>",
                          200, 100)
    assert [i["text"] for i in a] == ["Hi", "Yo"] and a[0]["box"] == [0.0, 0.0, 100.0, 50.0]
    b = PP.parse_spotting("<|LOC_0|><|LOC_0|><|LOC_500|><|LOC_500|>Hi<|LOC_500|><|LOC_500|><|LOC_1000|><|LOC_1000|>Yo")
    assert [i["text"] for i in b] == ["Hi", "Yo"] and b[1]["norm"] == [[500, 500], [1000, 1000]] and "box" not in b[0]
    assert PP.parse_spotting("") == []


def test_latex_and_chart():
    assert PP.strip_latex("\\[E=m c^{2}\\]") == "E=m c^{2}"
    assert PP.strip_latex("$$x$$") == "x" and PP.strip_latex("x") == "x"
    assert PP.parse_pipe_table("A | B\n--- | ---\n1 | 2") == [["A", "B"], ["1", "2"]]
    assert PP.parse_pipe_table("plain text") is None
    golden_chart = "Quarter | Revenue\nQ1 | 120\nQ2 | 135\nQ3 | 98\nQ4 | 160"  # 1.6 official output, chart_bar.png
    assert PP.structured("chart", golden_chart)["rows"][4] == ["Q4", "160"]
    assert PP.structured("seal", "测试印章专用有限公司\n财务专用章") == {}


# ------------------------------------------------------------------------------------------ tokenizer / streaming
def test_stub_tokenizer_roundtrip():
    t = StubTokenizer()
    s = "Héllo 你好<fcel>x<nl><|LOC_12|>"
    ids = t.encode(s).ids
    assert t.decode(ids) == s and C.LOC0 + 12 in ids and 101309 in ids
    pb = stub_prompts(C.PROFILE_CONFIGS["1.6"])
    ids = pb.ids("OCR:", 5)
    assert ids[0] == C.CLS and ids.count(C.IMAGE_PLACEHOLDER) == 5 and C.IMAGE_START in ids and C.IMAGE_END in ids
    assert pb.decode(ids).endswith("OCR:\nAssistant:\n")
    assert stub_prompts(C.PROFILE_CONFIGS["vl"]).decode(ids[:0] + pb.tok.encode("Assistant: ").ids) == "Assistant: "


def _stream_all(pb, ids, skip=True):
    ds = DeltaStream(pb, skip)
    out = "".join(ds.push(t) for t in ids) + ds.finish()
    return out, pb.decode([i for i in ids if i != C.EOS], skip)


def test_delta_stream_utf8_bytes():
    pb = stub_prompts(C.PROFILE_CONFIGS["1.6"])
    ids = pb.tok.encode("abc 你好 é <fcel>x").ids + [C.EOS]
    got, want = _stream_all(pb, ids)
    assert got == want
    ds = DeltaStream(pb)
    b = pb.tok.encode("你").ids  # 3 byte tokens: nothing until the character is complete
    assert ds.push(b[0]) == "" and ds.push(b[1]) == "" and ds.push(b[2]) == "你"


@pytest.mark.skipif(not os.path.isfile(REAL_TOK), reason="the checkpoint's tokenizer.json is not available")
def test_delta_stream_real_tokenizer():
    from tt_paddleocr.frontend import PromptBuilder

    pb = PromptBuilder(REAL_TOK, C.PROFILE_CONFIGS["1.6"])
    for s in ("The quick brown fox jumps over the lazy dog 0123456789.", "飞桨文字识别模型支持一百零九种语言。",
              "<fcel>Model<fcel>Params<nl><fcel>α β γ<nl>", "\\[E=m c^{2}\\]  x\n y", "Hi<|LOC_12|><|LOC_999|>"):
        ids = pb.tok.encode(s, add_special_tokens=False).ids + [C.EOS]
        got, want = _stream_all(pb, ids)
        assert got == want, (s, got, want)
    assert pb.ids("OCR:", 3) == [100273, 2969, 93963, 93919, 101305, 100295, 100295, 100295, 101306, 93972, 2497,
                                 93963, 23, 92267, 93963, 23]


# ------------------------------------------------------------------------------------------ host sampling
def test_sample_next():
    import torch

    lg = torch.tensor([0.0, 5.0, 1.0, 4.9])
    g = torch.Generator().manual_seed(0)
    assert sample_next(lg, GenParams(), [], g) == 1
    assert sample_next(lg, GenParams(repetition_penalty=2.0), [1], g) == 3  # 5 / 2 < 4.9
    draws = {sample_next(lg, GenParams(temperature=1.0, top_k=2), [], g) for _ in range(50)}
    assert draws <= {1, 3} and len(draws) == 2
    assert {sample_next(lg, GenParams(temperature=1.0, top_p=0.3), [], g) for _ in range(20)} == {1}
    a = [sample_next(lg, GenParams(temperature=1.0), [], torch.Generator().manual_seed(7)) for _ in range(3)]
    assert len(set(a)) == 1


# ------------------------------------------------------------------------------------------ the API (fake backend)
def test_recognize_tasks_fake():
    m = fake()
    img = os.path.join(SAMPLES, "table_simple.png")
    r = m.recognize(img, task="table")
    assert r["stop"] == "eos" and r["text"].startswith("<fcel>") and r["result"]["html"].startswith("<table>")
    assert r["usage"]["image_tokens"] == r["image"]["patches"] // 4 and r["usage"]["completion_tokens"] > 0
    assert r["image"]["grid"][0] * 14 == r["image"]["resized"][0]
    r = m.recognize(img, task="formula")
    assert r["result"]["latex"] == "E=m c^{2}"
    r = m.recognize(img, task="spotting")
    assert len(r["result"]["items"]) == 2 and r["image"]["model_input_size"] == [1100, 424]  # 2x upscale preset
    r = m.recognize(img, prompt="Describe:")
    assert r["task"] == "custom" and r["prompt"] == "Describe:"
    r = m.recognize(img, max_new_tokens=3, return_tokens=True)
    assert r["stop"] == "length" and len(r["tokens"]) == 3


def test_stream_equals_text():
    m = fake()
    img = Image.open(os.path.join(SAMPLES, "text_zh_line.png"))
    deltas = list(m.stream(img, task="ocr"))
    assert "".join(deltas) == m.last_result["text"] and len(deltas) > 3


def test_recognize_refusals():
    m = fake()
    img = os.path.join(SAMPLES, "text_en_line.png")
    for kw in (dict(task="layout"), dict(temperature=3.0), dict(top_k=100), dict(top_p=0.0), dict(seed=-1),
               dict(max_new_tokens=0), dict(max_new_tokens=10 ** 6), dict(repetition_penalty=0.5),
               dict(max_pixels=10), dict(max_pixels=10 ** 9), dict(min_pixels=10), dict(task="custom"),
               dict(prompt="x " * 200), dict(prompt="OCR \ud800 lone surrogate")):
        with pytest.raises(InputError):
            m.recognize(img, **kw)
    with pytest.raises(InputError):
        fake("vl").recognize(img, task="spotting")
    with pytest.raises(InputError):
        m.recognize(b"not an image")
    with pytest.raises(InputError):
        decode_image(np.zeros((10, 2500), np.uint8))  # aspect ratio > 200


def test_decode_image_bomb_guard(tmp_path):
    big = Image.new("L", (3000, 3000))
    p = tmp_path / "big.png"
    big.save(p)
    with pytest.raises(InputError):
        decode_image(p.read_bytes(), max_mpix=1.0)
    assert decode_image(p.read_bytes(), max_mpix=10.0).size == (3000, 3000)


def test_min_pixels_upscale_tiny():
    m = fake()
    r = m.recognize(Image.new("RGB", (50, 21), "white"))
    assert r["image"]["patches"] * 196 >= C.PROFILE_CONFIGS["1.6"].min_pixels


def test_info_fake():
    i = fake().info
    assert i["backend"] == "fake" and i["limits"]["max_patches"] == 8192 and "spotting" in i["tasks"]


def test_backend_value_error_is_input_error():
    m = fake()
    lim = m.backend.limits()

    class B:
        def run(self, *a, **k):
            raise ValueError("this request needs the ttnn decode engine")

        def limits(self):
            return lim

    m.backend = B()
    with pytest.raises(InputError):
        m.recognize(os.path.join(SAMPLES, "text_en_line.png"))


def test_string_timings_pass_through():
    m = fake()
    run = m.backend.run

    def run2(*a, **k):
        r = run(*a, **k)
        r.timings["engine_dec"] = "mk"
        r.timings["ms_per_token"] = 1.25
        return r

    m.backend.run = run2
    r = m.recognize(os.path.join(SAMPLES, "text_en_line.png"))
    assert r["timings"]["engine_dec"] == "mk" and r["timings"]["ms_per_token"] == 1.25