File size: 19,701 Bytes
9b1a077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
# SPDX-License-Identifier: Apache-2.0
# Adapted from this workspace's GLM-OCR bundle (tt_glmocr/tests/test_host_api.py, Apache-2.0).
"""Host tests of the Python API on the fake backend (no device, no weights): task presets, modes, formats, the
n-gram / sampling / crop validation, streaming detokenization, image decoding:

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

``DSOCR_TEST_CPU=1`` also runs the CPU reference backend on one sample (needs the checkpoint; minutes).
"""

from __future__ import annotations

import base64
import io
import os
import subprocess
import sys
import threading

import numpy as np
import pytest

CODE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, CODE)

from tt_dsocr import config as C  # noqa: E402
from tt_dsocr import postprocess as PP  # noqa: E402
from tt_dsocr.api import (ByteTokenizer, DeepSeekOcr, Detokenizer, InputError, load_image,  # noqa: E402
                          parse_messages)
from tt_dsocr.backends import FakeBackend  # noqa: E402
from tt_dsocr.tests._paths import MODELS  # noqa: E402

MODEL = os.environ.get("DSOCR_MODEL_DIR") or MODELS["deepseek-ocr"]
HAVE_TOK = os.path.isfile(os.path.join(MODEL, "tokenizer.json"))
SAMPLES = os.path.join(CODE, "tt_dsocr", "samples")
LINE = os.path.join(SAMPLES, "line_en", "sample.png")        # 709 x 64: Gundam 9 x 1 tiles
FORMULA = os.path.join(SAMPLES, "formula_quad", "sample.png")  # 500 x 130: Gundam without tiles


def _png(arr) -> bytes:
    from PIL import Image

    b = io.BytesIO()
    Image.fromarray(arr).save(b, format="PNG")
    return b.getvalue()


@pytest.fixture(scope="module")
def model():
    m = DeepSeekOcr.from_config(C.resolve_config({"DSOCR_BACKEND": "fake"}))
    yield m
    m.close()


@pytest.fixture(scope="module")
def small():
    """A small compiled configuration: Tiny / Small only, 64 prompt tokens, 1024 KV positions."""
    m = DeepSeekOcr.from_config(C.resolve_config({"DSOCR_BACKEND": "fake", "DSOCR_MODES": "tiny,small",
                                                  "DSOCR_MAX_PROMPT_TOKENS": "64", "DSOCR_MAX_CONTEXT": "1024",
                                                  "DSOCR_MAX_NEW_TOKENS": "2048",
                                                  "DSOCR_DEFAULT_MAX_NEW_TOKENS": "512"}))
    yield m
    m.close()


# ---------------------------------------------------------------------------------------------- tasks / formats
def test_markdown_default(model):
    r = model.ocr(LINE)
    assert (r.task, r.mode, r.output_format, r.finish_reason) == ("markdown", "gundam", "markdown", "stop")
    assert r.raw_text == FakeBackend.MARKDOWN and r.text == PP.to_markdown(FakeBackend.MARKDOWN)
    assert "<|ref|>" not in r.text and "![](images/0.jpg)" in r.text and ":= b" in r.text
    assert [x["label"] for x in r.refs] == ["title", "text", "image", "table"]
    assert r.refs[2]["boxes"] == [[int(100 / 999 * 709), int(400 / 999 * 64), int(500 / 999 * 709),
                                   int(800 / 999 * 64)]]
    assert r.image == {"width": 709, "height": 64, "mode": "gundam", "base_size": 1024, "image_size": 640,
                       "crop": True, "grid": [9, 1], "tiles": 9, "image_tokens": 1183, "min_crops": 2,
                       "max_crops": 9}
    assert r.usage["image_tokens"] == 1183 and r.usage["completion_tokens"] == len(r.tokens) + 1
    assert r.usage["total_tokens"] == r.usage["prompt_tokens"] + r.usage["completion_tokens"]
    assert r.sampling["no_repeat_ngram_size"] == 20 and r.sampling["ngram_window"] == 0
    for k in ("preprocess_ms", "first_token_ms", "generate_ms", "total_ms", "vision_ms", "prefill_ms", "ttft_ms",
              "decode_ms", "tokens", "prompt_tokens", "image_tokens"):
        assert k in r.timings, k
    assert model.last_timings == r.timings


def test_task_presets(model):
    assert model.ocr(LINE, task="free").text == FakeBackend.TEXT
    r = model.ocr(LINE, task="free", output_format="markdown")
    assert r.text == FakeBackend.TEXT and r.output_format == "markdown"
    assert model.ocr(LINE, task="figure").text == FakeBackend.FIGURE
    assert model.ocr(LINE, task="describe").text == FakeBackend.DESCRIBE
    r = model.ocr(LINE, task="ocr")
    assert r.raw_text == FakeBackend.OCR and r.text == FakeBackend.TEXT      # labels kept for grounded OCR
    assert r.refs[0]["label"] == FakeBackend.TEXT
    r = model.ocr(LINE, task="markdown", output_format="raw")
    assert r.text == FakeBackend.MARKDOWN
    r = model.ocr(LINE, prompt="Free OCR.")
    assert r.task == "free" and r.text == FakeBackend.TEXT
    r = model.ocr(LINE, prompt="What is written here?")
    assert r.task == "prompt" and r.output_format == "raw" and r.text == "Fake reply to: What is written here?"


def test_locate(model):
    r = model.ocr(LINE, task="locate", ref="the date")
    assert r.task == "locate" and r.output_format == "json" and r.json["text"] == ""
    assert r.json["refs"] == [{"label": "the date", "boxes": [[int(100 / 999 * 709), int(200 / 999 * 64),
                                                               int(300 / 999 * 709), int(400 / 999 * 64)]],
                               "boxes_norm": [[100, 200, 300, 400]]}]
    assert model.ocr(LINE, ref="the date").task == "locate"
    for bad in ({"task": "locate"}, {"task": "locate", "ref": "  "}, {"task": "free", "ref": "x"},
                {"task": "locate", "ref": "<|ref|>x"}, {"task": "locate", "ref": "x" * 600},
                {"ref": "x", "prompt": "y"}, {"task": "ocr2"}, {"prompt": 5}, {"ref": 5}):
        with pytest.raises(InputError):
            model.prepare(LINE, **bad)


def test_json_format(model):
    r = model.ocr(LINE, output_format="json")
    assert r.json["text"] == PP.to_markdown(FakeBackend.MARKDOWN) and len(r.json["refs"]) == 4
    assert r.json["image"] == {"width": 709, "height": 64}
    with pytest.raises(InputError):
        model.ocr(LINE, output_format="xml")


# ---------------------------------------------------------------------------------------------- modes / crops
def test_modes(model):
    want = {"tiny": (73, 512), "small": (111, 640), "base": (273, 1024), "large": (421, 1280)}
    for mode, (n, s) in want.items():
        r = model.ocr(LINE, task="free", mode=mode)
        assert r.mode == mode and r.image["image_tokens"] == n and r.image["image_size"] == s and not r.image["crop"]
        assert r.image["tiles"] == 0
    r = model.ocr(FORMULA, task="free", mode="gundam")
    assert r.image["tiles"] == 0 and r.image["image_tokens"] == 273
    r = model.ocr(LINE, task="free", mode="GUNDAM", max_crops=4)
    assert r.image["grid"] == [4, 1] and r.image["image_tokens"] == 273 + 41 * 10 and r.image["max_crops"] == 4
    r = model.ocr(LINE, task="free", max_crops=1)
    assert r.image["grid"] == [1, 1] and r.image["tiles"] == 0 and r.image["min_crops"] == 1
    for bad in ({"mode": "huge"}, {"mode": 3}, {"max_crops": 10}, {"min_crops": 0}, {"min_crops": 5, "max_crops": 4},
                {"max_crops": "x"}):
        with pytest.raises(InputError):
            model.prepare(LINE, **bad)


def test_disabled_mode(small):
    assert small.ocr(LINE, task="free").mode == "tiny"            # the default falls back to the first enabled mode
    with pytest.raises(InputError, match="DSOCR_MODES"):
        small.prepare(LINE, mode="gundam")


# ---------------------------------------------------------------------------------------------- streaming
def _check_stream(m, **kw):
    s = m.ocr_stream(LINE, **kw)
    deltas = list(s)
    assert s.result is not None and "".join(deltas) == s.result.raw_text
    assert all(d and "�" not in d for d in deltas), deltas
    return deltas, s.result


def test_stream_utf8_byte_tokens(model):
    deltas, r = _check_stream(model, task="free")
    assert r.text == FakeBackend.TEXT
    assert "é" in deltas and "你" in deltas and "🙂" in deltas  # multi-byte characters arrive whole
    got = []
    r2 = model.ocr(LINE, task="free", on_delta=got.append)
    assert got == deltas and r2.text == r.text


@pytest.mark.skipif(not HAVE_TOK, reason="the DeepSeek-OCR tokenizer is not available")
def test_stream_real_tokenizer():
    m = DeepSeekOcr.from_config(C.resolve_config({"DSOCR_BACKEND": "fake", "DSOCR_MODEL_DIR": MODEL}))
    deltas, r = _check_stream(m)                                  # markdown: special tokens in the output
    assert r.raw_text == FakeBackend.MARKDOWN and r.text == PP.to_markdown(FakeBackend.MARKDOWN)
    assert "<|ref|>" in deltas and 128816 in r.tokens            # <|ref|> is one token
    assert r.usage["prompt_tokens"] == 1 + 1183 + len(m.tok.encode("\n<|grounding|>Convert the document to markdown."))
    deltas, r = _check_stream(m, task="free", mode="tiny")
    assert r.text == FakeBackend.TEXT and r.usage["prompt_tokens"] == 78    # the formula_quad golden's prompt length


def test_detokenizer_units():
    tok = ByteTokenizer()
    for text in ("a🙂b", "你好", "plain", "é\nü", "🙂🙂", "<|ref|>x<|/ref|>"):
        d = Detokenizer(tok)
        out = [d.push(t) for t in tok.encode(text)]
        out.append(d.flush())
        assert "".join(out) == text and all("�" not in x for x in out)
    d = Detokenizer(tok)
    assert d.push(0xF0 + 3) == "" and d.push(0x9F + 3) == ""     # an incomplete character is held back
    assert d.flush() == "�"                                  # and emitted as the full decode gives it
    assert tok.decode([0, 72 + 3, 1]) == "<|begin▁of▁sentence|>H" + PP.EOS_TEXT
    assert tok.decode([0, 72 + 3, 1], skip_special_tokens=True) == "H"


def test_cancel(model):
    ev = threading.Event()
    ev.set()
    r = model.ocr(LINE, cancel=ev)
    assert r.finish_reason == "cancelled" and len(r.tokens) == 1


def test_max_new_tokens(model, small):
    r = model.ocr(LINE, task="free", max_new_tokens=5)
    assert r.finish_reason == "length" and r.raw_text == FakeBackend.TEXT[:5] and r.usage["completion_tokens"] == 5
    for bad in (0, -1, 8193, "x", 1.5, True):
        with pytest.raises(InputError):
            model.ocr(LINE, max_new_tokens=bad)
    p = small.prepare(LINE)
    assert p.max_new_tokens == 512                                     # DSOCR_DEFAULT_MAX_NEW_TOKENS
    p = small.prepare(LINE, max_new_tokens=2048)
    L = len(p.fe.ids)
    assert p.max_new_tokens == 1024 - L                                # clipped to the KV room
    assert small.ocr(LINE, max_new_tokens=2048).sampling["max_new_tokens"] == 1024 - L


# ---------------------------------------------------------------------------------------------- caps
def test_sampling_validation(model):
    sp = model.sampling()
    assert (sp.temperature, sp.top_k, sp.top_p, sp.repetition_penalty, sp.seed) == (0.0, 0, 1.0, 1.0, None)
    sp = model.sampling(temperature=0.7, top_k=64, top_p=0.9, repetition_penalty=1.1)
    assert sp.seed is not None and 0 <= sp.seed < 2 ** 63
    assert model.sampling(temperature=0.5, seed=7).seed == 7
    for bad in ({"temperature": 3}, {"temperature": -0.1}, {"temperature": float("nan")}, {"top_k": 65},
                {"top_k": -1}, {"top_p": 0}, {"top_p": 1.5}, {"repetition_penalty": 0.5},
                {"repetition_penalty": 2.5}, {"seed": -1}, {"seed": 2 ** 64}, {"temperature": "hot"}):
        with pytest.raises(InputError):
            model.sampling(**bad)


def test_ngram_validation(model):
    g = model.ngram()
    assert (g.size, g.window, g.whitelist) == (20, 0, ())
    g = model.ngram(preset="vllm")
    assert (g.size, g.window, g.whitelist) == (30, 90, (128821, 128822))
    assert model.ngram(preset="off").size == 0 and model.ngram(size=0).size == 0
    g = model.ngram(size=35, preset="VLLM", whitelist="[5, 3, 5]")
    assert (g.size, g.window, g.whitelist) == (35, 90, (3, 5))
    assert model.ngram(whitelist="7, 9").whitelist == (7, 9) and model.ngram(whitelist=[]).whitelist == ()
    assert model.ngram(size=4, window=4).window == 4
    for bad in ({"size": 1}, {"size": 65}, {"size": -1}, {"window": -1}, {"size": 10, "window": 5},
                {"window": 100000}, {"whitelist": [129280]}, {"whitelist": "[1, 2"}, {"whitelist": "a,b"},
                {"whitelist": list(range(65))}, {"whitelist": 5}, {"preset": "gpu"}, {"size": "x"}):
        with pytest.raises(InputError):
            model.ngram(**bad)
    model.ocr(LINE, task="free", ngram_preset="vllm", no_repeat_ngram_size=25)
    assert model.backend.last_ngram.size == 25 and model.backend.last_ngram.window == 90


def test_prompt_validation(model, small):
    with pytest.raises(InputError, match="DSOCR_MAX_PROMPT_TOKENS"):
        small.ocr(LINE, prompt="x" * 70)                  # byte tokenizer: one token per character (+ BOS, \n)
    assert small.ocr(LINE, prompt="x" * 60).finish_reason == "stop"
    with pytest.raises(InputError, match="exactly one"):
        model.ocr(LINE, prompt="<image> and <image>")
    with pytest.raises(InputError, match="image is required"):
        model.ocr(None, task="free")
    r = model.ocr(LINE, prompt="Read it.<image>")         # the placeholder may be anywhere
    assert r.text == "Fake reply to: Read it."


# ---------------------------------------------------------------------------------------------- image decoding
def test_load_image_sources(tmp_path):
    rgb = np.random.default_rng(0).integers(0, 256, (40, 60, 3), dtype=np.uint8)
    data = _png(rgb)
    for src in (data, bytearray(data), "data:image/png;base64," + base64.b64encode(data).decode(),
                base64.b64encode(data).decode(), rgb):
        im = load_image(src)
        assert im.mode == "RGB" and im.size == (60, 40)
        np.testing.assert_array_equal(np.asarray(im), rgb)
    p = tmp_path / "x.png"
    p.write_bytes(data)
    assert load_image(str(p)).size == (60, 40) and load_image(p).size == (60, 40)
    with pytest.raises(InputError):
        load_image(str(p), allow_paths=False)            # the server never reads paths: base64 decoding fails
    gray = load_image(rgb[..., 0])
    assert gray.mode == "RGB" and np.asarray(gray)[0, 0, 0] == rgb[0, 0, 0]


def test_load_image_alpha_exif():
    from PIL import Image

    rgba = np.zeros((20, 30, 4), np.uint8)              # a transparent image: the official convert("RGB") keeps RGB
    rgba[..., :3] = 200
    rgba[5:10, 5:20, :3] = 0
    rgba[5:10, 5:20, 3] = 255
    im = np.asarray(load_image(_png(rgba)))
    assert (im[0, 0] == 200).all() and (im[6, 6] == 0).all()
    b = io.BytesIO()                                    # EXIF orientation 6: a 30 x 20 stored image is shown 20 x 30
    exif = Image.Exif()
    exif[0x0112] = 6
    Image.fromarray(np.zeros((20, 30, 3), np.uint8)).save(b, format="JPEG", exif=exif.tobytes())
    assert load_image(b.getvalue()).size == (20, 30)


def test_load_image_errors():
    for bad in (b"not an image", b"", "data:image/png;base64,@@@", "data:image/png,raw", "http://example.com/x.png",
                12, np.zeros((4, 4, 3), np.float32)):
        with pytest.raises(InputError) as e:
            load_image(bad)
        assert e.value.status == 400
    big = _png(np.zeros((1200, 1000, 3), np.uint8))
    with pytest.raises(InputError) as e:
        load_image(big, max_pixels=1e6)
    assert e.value.status == 413
    trunc = _png(np.random.default_rng(1).integers(0, 256, (200, 200, 3), dtype=np.uint8))[:500]
    with pytest.raises(InputError):
        load_image(trunc)


# ---------------------------------------------------------------------------------------------- messages / info
def test_parse_messages():
    img, text = parse_messages([{"role": "system", "content": "x"}, {"role": "user", "content": [
        {"type": "text", "text": "Free OCR."}, {"type": "image_url", "image_url": {"url": "data:abc"}}]}])
    assert img == "data:abc" and text == "Free OCR."
    assert parse_messages([{"role": "user", "content": "hello"}]) == (None, "hello")
    img, text = parse_messages([{"role": "user", "content": [{"type": "image_url", "image_url": "b64"},
                                                             {"type": "text", "text": "a"},
                                                             {"type": "text", "text": "b"}]}])
    assert img == "b64" and text == "a\nb"
    for bad in (None, [], "hi", [{"role": "assistant", "content": "x"}], ["x"],
                [{"role": "user", "content": [{"type": "image_url", "image_url": "a"},
                                              {"type": "image_url", "image_url": "b"}]}],
                [{"role": "user", "content": [{"type": "audio", "audio": "a"}]}],
                [{"role": "user", "content": [{"type": "text", "text": 5}]}],
                [{"role": "user", "content": 5}]):
        with pytest.raises(InputError):
            parse_messages(bad)


def test_info(model):
    i = model.info
    assert i["model"] == "deepseek-ocr" and i["variant"] == "deepseek-ocr" and i["backend"] == "fake"
    assert i["weights"] == {"repo": "deepseek-ai/DeepSeek-OCR", "revision": C.VARIANTS["deepseek-ocr"].revision,
                            "license": "MIT"}
    assert list(i["modes"]) == ["tiny", "small", "base", "large", "gundam"] and i["default_mode"] == "gundam"
    assert i["modes"]["gundam"] == {"base_size": 1024, "image_size": 640, "crop": True, "tile": 640,
                                    "image_tokens": [273, 1263]}
    assert i["limits"]["max_image_tokens"] == 1263 and i["defaults"]["max_new_tokens"] == 8192
    assert i["defaults"]["format"]["locate"] == "json" and i["ngram_presets"]["vllm"]["ngram_window"] == 90
    assert set(i["tasks"]) == {"markdown", "ocr", "free", "figure", "describe", "locate"}
    assert i["formats"] == ["raw", "markdown", "json"] and i["stop_token_ids"] == [1]
    assert "model card" in i["performance"] and "PENDING" not in i["performance"]


def test_other_variant_host_path():
    m = DeepSeekOcr.from_config(C.resolve_config({"DSOCR_BACKEND": "fake", "DSOCR_VARIANT": "deepseek-ocr-2"}))
    r = m.ocr(LINE, task="free")
    assert r.text == FakeBackend.TEXT and r.image["image_size"] == 768 and m.info["weights"]["license"] == "Apache-2.0"
    assert r.image["image_tokens"] == 257 + 144 * r.image["tiles"]
    with pytest.raises(InputError):
        m.prepare(LINE, mode="tiny")                  # not a DeepSeek-OCR-2 mode


def test_no_heavy_imports_for_the_fake_backend():
    code = ("import sys; from tt_dsocr import config as C; from tt_dsocr.api import DeepSeekOcr; "
            "m = DeepSeekOcr.from_config(C.resolve_config({'DSOCR_BACKEND': 'fake'})); "
            f"r = m.ocr({LINE!r}, task='free'); assert r.finish_reason == 'stop'; "
            "assert 'ttnn' not in sys.modules and 'torch' not in sys.modules, 'heavy imports'")
    env = dict(os.environ, PYTHONPATH=os.pathsep.join([CODE] + [p for p in sys.path if p]))
    subprocess.check_call([sys.executable, "-c", code], env=env)


@pytest.mark.skipif(os.environ.get("DSOCR_TEST_CPU") != "1" or not HAVE_TOK,
                    reason="DSOCR_TEST_CPU=1 and the checkpoint run the CPU reference backend")
def test_cpu_backend_formula_tiny():
    m = DeepSeekOcr.from_config(C.resolve_config({"DSOCR_BACKEND": "cpu", "DSOCR_MODEL_DIR": MODEL,
                                                  "DSOCR_MAX_CONTEXT": "2048", "DSOCR_MODES": "tiny"}))
    s = m.ocr_stream(FORMULA, task="free", max_new_tokens=40)
    deltas = list(s)
    r = s.result
    assert r.finish_reason == "stop" and "".join(deltas) == r.raw_text
    assert r.text == "\\[ X = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a} \\]"   # the official fp32 output of this image
    assert r.usage["prompt_tokens"] == 78 and r.timings["tokens"] == r.usage["completion_tokens"]