Download code/tt_glmocr/tests/test_host_frontend.py from changh95/GLM-OCR: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/changh95/GLM-OCR/resolve/main/code/tt_glmocr/tests/test_host_frontend.py
- Command line
-
hf download hf://changh95/GLM-OCR/code/tt_glmocr/tests/test_host_frontend.py
-
curl -L -o test_host_frontend.py https://huggingface.co/changh95/GLM-OCR/resolve/main/code/tt_glmocr/tests/test_host_frontend.py
10.9 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Host tests of the front end (no device): smart_resize, patches, prompt ids, 3D positions, messages. | |
| TT_VISIBLE_DEVICES=none python -m pytest bundles/glm-ocr/code/tt_glmocr/tests/test_host_frontend.py | |
| Tests that need the checkpoint's tokenizer or the workspace goldens skip when they are absent. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| import os | |
| import sys | |
| import numpy as np | |
| import pytest | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) | |
| from tt_glmocr import config as C # noqa: E402 | |
| from tt_glmocr import frontend as FE # noqa: E402 | |
| from tt_glmocr.api import ByteTokenizer # noqa: E402 | |
| MODEL = os.environ.get("GLMOCR_MODEL_DIR") or os.environ.get("GLMOCR_MODEL") or "" # a local checkpoint dir (optional) | |
| HAVE_TOK = os.path.isfile(os.path.join(MODEL, "tokenizer.json")) | |
| ASSETS = os.environ.get("GLMOCR_ASSETS") or "" # the development golden set (optional) | |
| SAMPLES = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "samples") | |
| # ---------------------------------------------------------------------------------------------- smart_resize | |
| def test_smart_resize_invariants(H, W): | |
| h, w = FE.smart_resize(H, W) | |
| assert h % 28 == 0 and w % 28 == 0 and h >= 28 and w >= 28 | |
| assert 2 * h * w <= C.OFFICIAL_MAX_PIXELS, (h, w) | |
| assert 2 * h * w >= C.OFFICIAL_MIN_PIXELS, (h, w) | |
| tokens = (h // 28) * (w // 28) | |
| assert 8 <= tokens <= C.HARD_MAX_IMAGE_TOKENS | |
| # aspect ratio preserved up to the rounding to 28 px | |
| if min(H, W) >= 28 and 2 * H * W <= C.OFFICIAL_MAX_PIXELS and 2 * H * W >= 4 * C.OFFICIAL_MIN_PIXELS: | |
| assert abs(h - H) <= 14 and abs(w - W) <= 14 | |
| def test_smart_resize_known_values(): | |
| assert FE.smart_resize(64, 709) == (56, 700) # the line_en sample: 2 x 25 = 50 tokens | |
| assert FE.image_tokens_for(1754, 1240) == 2772 # an A4 page at 150 dpi | |
| assert FE.image_tokens_for(10000, 10000) <= 6144 | |
| # the official smart_resize keeps the short side at >= 28 px: a very elongated image at a tiny budget may exceed | |
| # it (64 x 709 at 8 tokens -> 1 x 9 tokens); never at the compiled caps (>= 256 tokens, aspect < 200) | |
| assert FE.smart_resize(64, 709, max_pixels=C.tokens_to_max_pixels(8)) == (28, 252) | |
| h, w = FE.smart_resize(56, 56) # below min_pixels: scaled up (ceil) | |
| assert 2 * h * w >= C.OFFICIAL_MIN_PIXELS and (h, w) == (84, 84) | |
| def test_smart_resize_respects_max_pixels(tokens): | |
| mp = C.tokens_to_max_pixels(tokens) | |
| for H, W in ((4000, 3000), (1754, 1240), (500, 9000), (9000, 500), (100, 19000), (28, 28 * 199)): | |
| n = FE.image_tokens_for(H, W, max_pixels=mp) | |
| if math.sqrt(tokens * 784 * min(H, W) / max(H, W)) >= 28: # the short side does not clamp at 28 px | |
| assert n <= tokens, (H, W, tokens, n) | |
| else: | |
| assert min(FE.smart_resize(H, W, max_pixels=mp)) == 28 | |
| if tokens >= 256: | |
| assert n <= tokens, (H, W, tokens, n) | |
| def test_smart_resize_aspect_ratio_limit(): | |
| with pytest.raises(ValueError): | |
| FE.smart_resize(28, 28 * 201) | |
| FE.smart_resize(28, 28 * 199) | |
| # ---------------------------------------------------------------------------------------------- patches | |
| def _synthetic(h=60, w=90, seed=0): | |
| return np.random.default_rng(seed).integers(0, 256, (h, w, 3), dtype=np.uint8) | |
| def test_preprocess_patch_layout(): | |
| rgb = _synthetic(60, 90) | |
| img = FE.preprocess(rgb) | |
| h, w = img.resized | |
| assert img.original == (60, 90) and (h, w) == FE.smart_resize(60, 90) | |
| assert img.grid_h == h // 14 and img.grid_w == w // 14 and img.grid_h % 2 == 0 and img.grid_w % 2 == 0 | |
| assert img.patches.shape == (img.n_patches, 588) and img.patches.dtype == np.float32 | |
| assert img.n_tokens == img.n_patches // 4 and img.llm_grid == (img.grid_h // 2, img.grid_w // 2) | |
| # recompute the normalized resized image and check the official patch order (2 x 2 merge blocks in raster | |
| # order, raster inside a block; each row (c, py, px)) | |
| chw = FE.resize_uint8(np.transpose(rgb, (2, 0, 1)), h, w).astype(np.float32) | |
| mean = np.array(FE.MEAN, np.float32)[:, None, None] * 255.0 | |
| std = np.array(FE.STD, np.float32)[:, None, None] * 255.0 | |
| x = (chw - mean) / std | |
| def patch(r, c): | |
| return x[:, 14 * r:14 * r + 14, 14 * c:14 * c + 14].reshape(-1) | |
| order = [(0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (0, 3), (1, 2), (1, 3)] | |
| for i, (r, c) in enumerate(order): | |
| np.testing.assert_allclose(img.patches[i], patch(r, c), rtol=1e-5, atol=1e-5) | |
| gw2 = img.grid_w // 2 # the first patch of the second block row | |
| np.testing.assert_allclose(img.patches[4 * gw2], patch(2, 0), rtol=1e-5, atol=1e-5) | |
| def test_preprocess_resize_identity_and_range(): | |
| rgb = _synthetic(56, 112) # already a multiple of 28 and inside the pixel limits: no resampling | |
| img = FE.preprocess(rgb) | |
| assert img.resized == (56, 112) | |
| lo = (0 - max(FE.MEAN)) / min(FE.STD) | |
| hi = (1 - min(FE.MEAN)) / min(FE.STD) | |
| assert img.patches.min() >= lo - 1e-4 and img.patches.max() <= hi + 1e-4 | |
| official = FE.official_pixel_values(img) | |
| assert official.shape == (img.n_patches, 1176) | |
| np.testing.assert_array_equal(official.reshape(-1, 3, 2, 196)[:, :, 0], official.reshape(-1, 3, 2, 196)[:, :, 1]) | |
| def test_preprocess_sample_png(): | |
| img = FE.preprocess(os.path.join(SAMPLES, "line_en", "sample.png")) | |
| assert img.original == (64, 709) and img.resized == (56, 700) and img.n_tokens == 50 | |
| # ---------------------------------------------------------------------------------------------- prompt | |
| def _check_prompt(tok, text, img): | |
| pr = FE.build_prompt(tok, text, img) | |
| enc = tok.encode(text) | |
| if img is None: | |
| assert pr.ids == [FE.GMASK, FE.SOP, FE.USER, FE.NL] + enc + [FE.ASSISTANT, FE.NL] | |
| assert pr.n_image == 0 and pr.rope_delta == 0 | |
| np.testing.assert_array_equal(pr.pos3d, np.tile(np.arange(pr.L), (3, 1))) | |
| return pr | |
| n = img.n_tokens | |
| assert pr.ids == [FE.GMASK, FE.SOP, FE.USER, FE.NL, FE.BOI] + [FE.IMAGE] * n + [FE.EOI] + enc + [FE.ASSISTANT, | |
| FE.NL] | |
| s = pr.image_start | |
| assert s == 5 and pr.n_image == n and pr.L == len(pr.ids) == C.TEMPLATE_TOKENS + n + len(enc) | |
| pos = pr.pos3d | |
| assert pos.shape == (3, pr.L) and pos.dtype == np.int64 | |
| np.testing.assert_array_equal(pos[:, :s], np.tile(np.arange(s), (3, 1))) # text before: t = h = w | |
| gh, gw = img.llm_grid | |
| blk = pos[:, s:s + n] | |
| assert (blk[0] == s).all() # t constant in the image | |
| np.testing.assert_array_equal(blk[1].reshape(gh, gw), s + np.arange(gh)[:, None].repeat(gw, 1)) | |
| np.testing.assert_array_equal(blk[2].reshape(gh, gw), s + np.arange(gw)[None, :].repeat(gh, 0)) | |
| after = pos[:, s + n:] | |
| np.testing.assert_array_equal(after, np.tile(s + max(gh, gw) + np.arange(pr.L - s - n), (3, 1))) | |
| assert pr.rope_delta == int(pos.max()) + 1 - pr.L and pr.rope_delta <= 0 | |
| # the first decoded token (cache index L) continues the text positions: L + delta = max + 1 | |
| assert pr.L + pr.rope_delta == int(pos[0, -1]) + 1 | |
| return pr | |
| def test_prompt_byte_tokenizer(): | |
| tok = ByteTokenizer() | |
| img = FE.preprocess(_synthetic(60, 300)) | |
| for text in ("Text Recognition:", "Table Recognition:", "请按下列JSON格式输出图中信息:\n{}"): | |
| _check_prompt(tok, text, img) | |
| _check_prompt(tok, "Hello", None) | |
| def test_prompt_real_tokenizer(): | |
| tok = FE.Tokenizer(MODEL) | |
| assert tok.encode("Text Recognition:") and tok.decode(tok.encode("Text Recognition:")) == "Text Recognition:" | |
| img = FE.preprocess(os.path.join(SAMPLES, "line_en", "sample.png")) | |
| pr = _check_prompt(tok, FE.TASK_PROMPTS["text"], img) | |
| assert pr.L == 62 and pr.rope_delta == -25 # the official processor's input_ids / rope_deltas of this image | |
| for t in FE.TASK_PROMPTS.values(): | |
| _check_prompt(tok, t, img) | |
| # special tokens are skipped by decode (the stop token <|user|> included) | |
| assert tok.decode([FE.USER, FE.ENDOFTEXT] + tok.encode("abc")) == "abc" | |
| assert tok.decode(tok.encode("café 你好 🙂")) == "café 你好 🙂" | |
| def test_prompt_matches_the_official_processor(): | |
| tok = FE.Tokenizer(MODEL) | |
| entries = {e["name"]: e for e in json.load(open(os.path.join(ASSETS, "images.json")))} | |
| for name in ("line_en", "formula_quad", "para_en", "formula_sum"): | |
| p = os.path.join(ASSETS, "golden", name, "gen_fp32.json") | |
| if not os.path.isfile(p): | |
| continue | |
| g = json.load(open(p)) | |
| img = FE.preprocess(os.path.join(ASSETS, entries[name]["file"])) | |
| pr = FE.build_prompt(tok, entries[name]["prompt"], img) | |
| assert pr.ids == g["input_ids"] and pr.rope_delta == g["rope_delta"], name | |
| assert tok.decode(g["tokens"]) == g["text"], name | |
| # ---------------------------------------------------------------------------------------------- messages | |
| def test_messages_to_request(): | |
| img, text = FE.messages_to_request([{"role": "user", "content": "Text Recognition:"}]) | |
| assert img is None and text == "Text Recognition:" | |
| msgs = [{"role": "system", "content": "ignored"}, | |
| {"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}, | |
| {"type": "text", "text": "Table "}, {"type": "text", "text": "Recognition:"}]}] | |
| img, text = FE.messages_to_request(msgs) | |
| assert img == "data:image/png;base64,AAAA" and text == "Table Recognition:" | |
| img, _ = FE.messages_to_request([{"role": "user", "content": [{"type": "image_url", "image_url": "data:x"}]}]) | |
| assert img == "data:x" | |
| with pytest.raises(ValueError): | |
| FE.messages_to_request([{"role": "system", "content": "x"}]) | |
| def test_task_prompts_are_the_cards(): | |
| assert FE.TASK_PROMPTS == {"text": "Text Recognition:", "table": "Table Recognition:", | |
| "formula": "Formula Recognition:"} | |
| assert FE.EOS_IDS == (59246, 59253) | |
| assert math.isclose(C.tokens_to_max_pixels(6144), C.OFFICIAL_MAX_PIXELS) | |