File size: 2,543 Bytes
c60a316 | 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 | # SPDX-License-Identifier: Apache-2.0
"""DsocrDevice.image_rows row layout per variant with a stub vision engine (no ttnn): DeepSeek-OCR (newline after
every token row; tiles, global, separator) and DeepSeek-OCR-2 (no newline; tiles, global, separator)."""
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
class Vis:
def __init__(self, n_of):
self.n_of = n_of
def run(self, px):
px = torch.as_tensor(px)
B, S = px.shape[0], px.shape[-1]
return torch.arange(B, dtype=torch.float32)[:, None, None].expand(B, self.n_of[S], R.D) + 10.0 * (S == 1024)
def _dev(variant, n_of, has_newline):
d = M.DsocrDevice.__new__(M.DsocrDevice)
d.variant = variant
d.vis = Vis(n_of)
d.cfg = M.DeviceConfig(tile_chunk=2)
t = {R.PFX + "view_seperator": torch.full((R.D,), -1.0)}
if has_newline:
t[R.PFX + "image_newline"] = torch.full((R.D,), -2.0)
d.W = types.SimpleNamespace(get=lambda k, cache=True: t[k]) # KeyError for a missing parameter
return d
def _prep(variant, tiles, grid, gsize):
return types.SimpleNamespace(global_px=np.zeros((3, gsize, gsize), np.float32),
tiles_px=None if tiles == 0 else np.zeros((tiles, 3, variant.tile, variant.tile),
np.float32),
grid=grid)
def test_ocr2_rows_without_newline():
d = _dev(FE.OCR2, {1024: 256, 768: 144}, has_newline=False)
rows = d.image_rows(_prep(FE.OCR2, 3, (3, 1), 1024))
assert rows.shape[0] == FE.image_token_count(FE.OCR2, 1024, 768, True, (3, 1)) == 3 * 144 + 256 + 1
assert torch.all(rows[:144] == 0) and torch.all(rows[144:288] == 1) and torch.all(rows[432:688] == 10)
assert torch.all(rows[-1] == -1)
def test_ocr1_rows_with_newline():
d = _dev(FE.OCR1, {1024: 256, 640: 100}, has_newline=True)
rows = d.image_rows(_prep(FE.OCR1, 2, (2, 1), 1024))
assert rows.shape[0] == FE.image_token_count(FE.OCR1, 1024, 640, True, (2, 1))
loc = rows[:10 * 21].view(10, 21, R.D)
assert torch.all(loc[:, 20] == -2) and torch.all(loc[:, :10] == 0) and torch.all(loc[:, 10:20] == 1)
assert torch.all(rows[-1] == -1)
|