File size: 7,568 Bytes
b8b3105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the schift-ocr-1-beta variant (no device, no ttnn; the official CPU goldens are optional):

- configuration: 2..32 tiles, the 128-token decode window (KV rows = largest prompt bucket + 128, positions up to
  DSOCR_MAX_CONTEXT 32768), the prefill buckets, the task preset ``<image>document parsing.``;
- the decode window bookkeeping of the tt-nn decoder (``TtnnDecoder.kv_slots``) against the official ring
  (``SlidingWindowLlamaAttention``: prompt rows + the last 128 generated rows, the current one included);
- the reference decoder's window mask against that rule;
- the det-only block format ``<|det|>label [x1, y1, x2, y2]<|/det|>content`` (Markdown / JSON);
- with goldens (``DSOCR_WORKSPACE``): the prompt ids and views equal the official ``infer`` inputs.
"""

from __future__ import annotations

import json
import os
import sys
import types

import pytest

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(HERE)))
from tt_dsocr import api as A  # noqa: E402
from tt_dsocr import config as C  # noqa: E402
from tt_dsocr import postprocess as PP  # noqa: E402
from tt_dsocr.tests._paths import ASSETS, GOLDEN, MODELS  # noqa: E402

V = "schift-ocr-1-beta"


def test_config():
    v = C.VARIANTS[V]
    assert (v.weights_repo, v.revision, v.license) == ("schift-io/schift-ocr-1-beta",
                                                       "8fc26dce9ef6c0307a9067ee39a97ae15ccd1cbf", "MIT")
    assert (v.tile, v.crop_min, v.crop_max, v.newline, v.window) == (640, 2, 32, True, 128)
    assert not [f for f in v.weight_files if f.endswith(".py")]
    c = C.resolve_config({"DSOCR_VARIANT": V})
    assert c.modes == ("gundam", "base") and c.default_mode == "gundam" and c.max_crops == 32
    assert c.engine["dec"] == v.dec_engines[0] and C.TASK_PROMPTS[V] == {"parse": "<image>document parsing."}
    # 32 tiles in a 1 x 32 grid: 273 global rows + 11 x 320 tile rows = 3793 image tokens
    assert C.mode_image_tokens(v, "gundam", 32) == (273, 3793) and c.max_prompt == 3793 + 512
    assert c.pre_buckets == (384, 896, 1024, 1536, 2048, 2560, 3072, 3584, 3840, 4096, 4352)
    assert c.kv_positions == 4352 + 128 and c.max_context == 32768 and c.max_new_tokens == 16384
    kw = c.device_kwargs()
    assert (kw["max_context"], kw["window"], kw["max_positions"]) == (4480, 128, 32768)
    for bad in ({"DSOCR_MAX_CROPS": "33"}, {"DSOCR_MAX_CONTEXT": "40000"}, {"DSOCR_MODES": "tiny"},
                {"DSOCR_MAX_PAGES": "2"}):
        with pytest.raises(ValueError):
            C.resolve_config(dict(bad, DSOCR_VARIANT=V))
    # the other variants keep their buckets and full-context KV
    assert C.resolve_config({}).kv_positions == 8192 and C.VARIANTS["deepseek-ocr"].window == 0


def test_device_buckets_mirror_config():
    pytest.importorskip("torch")
    from tt_dsocr import frontend as FE
    from tt_dsocr.tt import model as TM

    c = C.resolve_config({"DSOCR_VARIANT": V})
    dc = TM.DeviceConfig(variant=V, modes=c.modes, max_crops=c.max_crops, max_prompt_text=c.max_prompt_tokens)
    assert tuple(TM.default_prefill_buckets(dc, FE.VARIANTS[V])) == c.pre_buckets


def _official_visible(L, p, W):
    """Rows a decode query at position p sees in SlidingWindowLlamaAttention (prompt L rows, ring W)."""
    return set(range(L)) | {j for j in range(L, p + 1) if p - j < W}


def test_window_slots_match_the_official_ring():
    pytest.importorskip("torch")
    from tt_dsocr.tt.ttnn_decoder import TtnnDecoder

    for L, W in ((10, 4), (300, 128), (257, 128)):
        d = types.SimpleNamespace(window=W, win_base=L)
        ring = {}  # KV row -> the position whose K / V it holds
        for p in range(L, L + 5 * W + 3):
            wrow, ext = TtnnDecoder.kv_slots(d, p)
            assert L <= wrow < L + W and ext == min(p, L + W - 1)
            ring[wrow] = p
            seen = set(range(L)) | {ring[r] for r in range(L, ext + 1)}
            assert seen == _official_visible(L, p, W), (L, W, p)
    d = types.SimpleNamespace(window=0, win_base=100)
    assert TtnnDecoder.kv_slots(d, 5000) == (5000, 5000)


def test_reference_window_mask():
    torch = pytest.importorskip("torch")
    from tt_dsocr.reference import model as R

    # the mask rule of Decoder.layer: hide = (ki > qi) | (ki >= L0 & qi - ki >= window)
    L, W = 7, 3
    for qi in range(L, L + 10):
        vis = {k for k in range(qi + 1) if not (k >= L and qi - k >= W)}
        assert vis == _official_visible(L, qi, W)
    assert "window" in R.Decoder.__init__.__code__.co_varnames
    del torch


RAW = ("<|det|>title [132, 68, 310, 86]<|/det|>3. ์กฐํšŒ์— ๊ด€ํ•œ ์‚ฌํ•ญ\n"
       "<|det|>table [80, 94, 938, 382]<|/det|><table><tr><td>์กฐํšŒ ๋Œ€์ƒ ๊ธฐ๊ด€</td></tr></table>\n"
       "<|det|>image [10, 400, 500, 600]<|/det|>\n<|det|>text [80, 700, 900, 720]<|/det|>๋ณธ ์‹ ์ฒญ์„œ๋Š” ์ ‘์ˆ˜ ํ›„ ์ฒ˜๋ฆฌ๋ฉ๋‹ˆ๋‹ค."
       "<๏ฝœendโ–ofโ–sentence๏ฝœ>")


def test_det_blocks_formats():
    md, _o, refs = PP.apply_format(RAW, "parse", "markdown", (1000, 2000))
    assert md.startswith("3. ์กฐํšŒ์— ๊ด€ํ•œ ์‚ฌํ•ญ\n<table>") and "![](images/0.jpg)" in md and "<|det|>" not in md
    assert md.rstrip().endswith("๋ณธ ์‹ ์ฒญ์„œ๋Š” ์ ‘์ˆ˜ ํ›„ ์ฒ˜๋ฆฌ๋ฉ๋‹ˆ๋‹ค.")
    assert [r["label"] for r in refs] == ["title", "table", "image", "text"]
    assert refs[0]["boxes_norm"] == [[132, 68, 310, 86]] and refs[0]["boxes"] == [[132, 136, 310, 172]]
    _t, obj, _r = PP.apply_format(RAW, "parse", "json", (1000, 2000))
    assert [b["text"] for b in obj["blocks"]] == ["3. ์กฐํšŒ์— ๊ด€ํ•œ ์‚ฌํ•ญ", "<table><tr><td>์กฐํšŒ ๋Œ€์ƒ ๊ธฐ๊ด€</td></tr></table>",
                                                "", "๋ณธ ์‹ ์ฒญ์„œ๋Š” ์ ‘์ˆ˜ ํ›„ ์ฒ˜๋ฆฌ๋ฉ๋‹ˆ๋‹ค."]
    raw, _o, _r = PP.apply_format(RAW, "parse", "raw", (1000, 2000))
    assert raw == RAW
    # strict elsewhere: a flat box is a det-only block's box, not a DeepSeek-OCR box list
    assert PP.parse_boxes("[1, 2, 3, 4]") is None and PP.parse_boxes("[1, 2, 3, 4]", single_ok=True) == [[1, 2, 3, 4]]
    assert PP.det_blocks("<|det|>x [1, 2, 3]<|/det|>a", 10, 10)[0]["boxes"] == []


def test_task_preset_is_recognised():
    assert A.infer_task("<image>document parsing.", V) == "parse"
    assert A.infer_task("  <image>document parsing.  ", V) == "parse"
    assert A.infer_task("<image>\nFree OCR.", V) == "prompt"
    assert A.infer_task("<image>\nFree OCR.", "deepseek-ocr") == "free"


def _goldens():
    g = GOLDEN.get(V) or ""
    if not g or not os.path.isdir(g):
        return []
    return sorted(d for d in os.listdir(g) if os.path.isfile(os.path.join(g, d, "meta.json")))


@pytest.mark.parametrize("case", _goldens() or ["(no goldens)"])
def test_golden_prompt_ids(case):
    if case == "(no goldens)":
        pytest.skip("no schift-ocr-1-beta goldens (DSOCR_WORKSPACE / assets/dsocr/golden/schift-ocr-1-beta)")
    pytest.importorskip("torch")
    from tt_dsocr import frontend as FE

    if not MODELS.get(V) or not os.path.isdir(MODELS[V]):
        pytest.skip("no checkpoint (DSOCR_MODELS_ROOT)")
    meta = json.load(open(os.path.join(GOLDEN[V], case, "meta.json")))
    imgs = {e["name"]: e for e in json.load(open(os.path.join(ASSETS, "images_ko.json")))}
    name, mode = case.split("__")
    tok = FE.Tokenizer(MODELS[V])
    prep = FE.prepare(FE.VARIANTS[V], tok, os.path.join(ASSETS, imgs[name]["file"]), meta["prompt_text"], mode)
    assert prep.ids == meta["input_ids"]
    assert list(prep.grid) == meta["spatial_crop"][0] and meta["window"] == 128 and meta["ngram"] == 0