File size: 4,652 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 | # SPDX-License-Identifier: Apache-2.0
"""Host tests of the pre-processing core (no device, no weights; the tokenizer test reads a repo tokenizer.json when
present): smart_resize, patch layout, merge order, 2-D RoPE tables, M-RoPE ids, bilinear matrices, the mk virtual
kv-head expansion and the DEC STATE layout."""
import os
import numpy as np
import pytest
from tt_paddleocr import frontend as FE
from tt_paddleocr.config import PROFILE_CONFIGS
from tt_paddleocr.tests._weights import repo_file # noqa: E402
TOK = repo_file("tokenizer.json") or ""
def test_smart_resize_limits():
for h, w in [(21, 50), (66, 917), (1400, 1000), (420, 64), (5000, 300)]:
rh, rw = FE.smart_resize(h, w, 28, 112896, 1003520)
assert rh % 28 == 0 and rw % 28 == 0
assert 112896 <= rh * rw <= 1003520 or (rh * rw < 112896 and False)
# the 1.6 golden grids (official processor): 917 x 66 -> 8 x 90 patches, 644 x 75 -> 10 x 72
assert FE.smart_resize(66, 917, 28, 112896, 1003520) == (112, 1260)
assert FE.smart_resize(75, 644, 28, 112896, 1003520) == (140, 1008)
with pytest.raises(ValueError):
FE.smart_resize(10, 3000, 28, 112896, 1003520)
def test_preprocess_layout():
from PIL import Image
rng = np.random.default_rng(0)
arr = rng.integers(0, 255, (56, 84, 3), dtype=np.uint8)
img = FE.preprocess(Image.fromarray(arr), 28 * 28, 56 * 84)
assert (img.gh, img.gw) == (4, 6) and img.patches.shape == (24, 588)
x = (arr.astype(np.float64) / 255.0).astype(np.float32)
x = (x - 0.5) / 0.5
# patch (1, 2): rows 14..27, cols 28..41, channel-major
ref = x[14:28, 28:42].transpose(2, 0, 1).reshape(-1)
assert np.array_equal(img.patches[1 * 6 + 2], ref)
def test_merge_order_is_projector_rearrange():
gh, gw, d = 6, 8, 3
x = np.arange(gh * gw * d).reshape(gh * gw, d)
o = FE.merge_order(gh, gw)
merged = x[o].reshape(-1, 4 * d)
ref = x.reshape(gh // 2, 2, gw // 2, 2, d).transpose(0, 2, 1, 3, 4).reshape(-1, 4 * d)
assert np.array_equal(merged, ref)
assert sorted(o.tolist()) == list(range(gh * gw))
def test_vision_rope_tables_order():
c, s = FE.vision_rope_tables(4, 6)
o = FE.merge_order(4, 6)
c2, s2 = FE.vision_rope_tables(4, 6, order=o)
assert np.allclose(c[o], c2) and np.allclose(s[o], s2)
assert c.shape == (24, 72) and np.allclose(c[:, :36], c[:, 36:])
def test_rope_index_and_mrope():
ids = [100273, 2969, 93963, 93919, 101305] + [100295] * 12 + [101306, 93972, 2497, 93963, 23]
pos, delta = FE.rope_index(ids, 6, 8) # 3 x 4 merged tokens
assert pos.shape == (3, len(ids))
assert (pos[:, :5] == np.arange(5)).all()
assert pos[0, 5] == 5 and pos[1, 5:9].tolist() == [5] * 4 and pos[2, 5:9].tolist() == [5, 6, 7, 8]
assert pos[1, -6] == 5 + 2 and pos[2, -6] == 5 + 3
assert (pos[:, 17:] == np.arange(9, 9 + 5)).all() # text after the image starts at max + 1 = 9
assert delta == int(pos.max()) + 1 - len(ids)
cos, sin = FE.mrope_cos_sin(np.full((3, 1), 7))
from tt_paddleocr.tt.mk_dec.weights import rope_tables
import torch
c1, s1 = rope_tables(torch.tensor([7]))
assert np.allclose(cos, c1.numpy(), atol=1e-6) and np.allclose(sin, s1.numpy(), atol=1e-6)
def test_interp_matrix_matches_torch():
import torch
t = torch.randn(1, 5, 27, 27, dtype=torch.float64)
r = torch.nn.functional.interpolate(t, size=(10, 44), mode="bilinear", align_corners=False)
mh, mw = FE.interp_matrix(10, 27), FE.interp_matrix(44, 27)
r2 = np.einsum("hi,cij,wj->chw", mh, t[0].numpy(), mw)
assert np.allclose(r[0].numpy(), r2, atol=1e-10)
def test_kv_expansion_matches_repeat_kv():
import torch
from tt_paddleocr.tt.mk_dec.weights import KV_REP, NKV, expand_kv
w = torch.randn(2 * 128, 16)
e = expand_kv(w).reshape(NKV, 128, 16)
for g in range(NKV): # virtual group g serves q heads 2g, 2g + 1 -> real head (2g) // 8 = g // KV_REP
assert torch.equal(e[g], w.reshape(2, 128, 16)[g // KV_REP])
assert (2 * g) // 8 == g // KV_REP
def test_state_words_and_ring():
from tt_paddleocr.tt.mk_dec import geometry as G
assert G.S_ROPE not in range(0, 18) and G.S_ROPE < G.S_NTOK
assert G.N_LAYERS_FULL == 18 and G.VOCAB == 103424 and G.dims_of(1024).hc == 101
@pytest.mark.skipif(not TOK or not os.path.exists(TOK), reason="tokenizer.json not available")
def test_prompt_ids():
pb = FE.PromptBuilder(TOK, PROFILE_CONFIGS["1.6"])
ids = pb.ids("OCR:", 3)
assert ids == [100273, 2969, 93963, 93919, 101305, 100295, 100295, 100295, 101306, 93972, 2497, 93963, 23,
92267, 93963, 23]
|