File size: 10,288 Bytes
aa204f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""GLM-OCR host front-end (CPU, numpy / torch only; no ttnn): image preprocessing bit-exact with transformers'
``Glm46VImageProcessor`` (torchvision backend), the chat-template prompt for one image + one text, tokenization
(``tokenizers`` + tokenizer.json), the 3D (M-RoPE) positions of ``GlmOcrModel.get_rope_index`` and detokenization.

Written for this bundle from the transformers 5.24.1 sources (Apache-2.0): ``glm46v/image_processing_glm46v.py``
(``smart_resize``, ``patchify``), ``image_processing_backends.py`` (fused rescale + normalize), ``glm_ocr`` (rope index).

Patch layout: the official ``pixel_values`` row of a patch is (c, t, py, px) with the frame repeated (t = 0, 1); the
device folds the temporal axis into the weights, so :func:`preprocess` returns the (c, py, px) rows ([N, 588]) in the
official patch order (2 x 2 merge blocks in raster order, row-major inside a block) plus the grid.
"""

from __future__ import annotations

import io
import json
import math
import os
from dataclasses import dataclass, field
from typing import Iterable, List, Optional, Sequence, Tuple

import numpy as np

PATCH = 14
MERGE = 2
FACTOR = PATCH * MERGE  # 28
T_PATCH = 2
MEAN = (0.48145466, 0.4578275, 0.40821073)
STD = (0.26862954, 0.26130258, 0.27577711)
RESCALE = 0.00392156862745098
#: processor_config.json "size" (pixels counted x T_PATCH = 2 frames, as the official smart_resize does)
MIN_PIXELS = 12544
MAX_PIXELS = 9633792

# special tokens (tokenizer.json / config.json)
GMASK, SOP, USER, ASSISTANT, NL = 59248, 59250, 59253, 59254, 10
BOI, EOI, IMAGE = 59256, 59257, 59280
ENDOFTEXT = 59246
EOS_IDS = (59246, 59253)  # generation_config.json: <|endoftext|>, <|user|>

TASK_PROMPTS = {
    "text": "Text Recognition:",
    "table": "Table Recognition:",
    "formula": "Formula Recognition:",
}


def smart_resize(height: int, width: int, min_pixels: int = MIN_PIXELS, max_pixels: int = MAX_PIXELS,
                 factor: int = FACTOR, num_frames: int = T_PATCH, temporal_factor: int = T_PATCH) -> Tuple[int, int]:
    """The official ``smart_resize`` (glm46v), called by the processor with num_frames = temporal_factor = 2."""
    if height < factor or width < factor:
        scale = max(factor / height, factor / width)
        height = int(height * scale)
        width = int(width * scale)
    if max(height, width) / min(height, width) > 200:
        raise ValueError(f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}")
    h_bar = round(height / factor) * factor
    w_bar = round(width / factor) * factor
    t_bar = round(num_frames / temporal_factor) * temporal_factor
    if t_bar * h_bar * w_bar > max_pixels:
        beta = math.sqrt((num_frames * height * width) / max_pixels)
        h_bar = max(factor, math.floor(height / beta / factor) * factor)
        w_bar = max(factor, math.floor(width / beta / factor) * factor)
    elif t_bar * h_bar * w_bar < min_pixels:
        beta = math.sqrt(min_pixels / (num_frames * height * width))
        h_bar = math.ceil(height * beta / factor) * factor
        w_bar = math.ceil(width * beta / factor) * factor
    return h_bar, w_bar


def image_tokens_for(height: int, width: int, min_pixels: int = MIN_PIXELS, max_pixels: int = MAX_PIXELS) -> int:
    h, w = smart_resize(height, width, min_pixels, max_pixels)
    return (h // FACTOR) * (w // FACTOR)


def load_rgb(src) -> np.ndarray:
    """PIL image / path / bytes -> [H, W, 3] uint8 (``convert("RGB")`` as the processor's do_convert_rgb)."""
    from PIL import Image

    if isinstance(src, np.ndarray):
        a = src
        if a.ndim == 2:
            a = np.repeat(a[..., None], 3, axis=2)
        return np.ascontiguousarray(a[..., :3].astype(np.uint8))
    if isinstance(src, (bytes, bytearray)):
        im = Image.open(io.BytesIO(src))
    elif isinstance(src, str):
        im = Image.open(src)
    else:
        im = src
    im.load()
    if "A" in im.getbands() or im.info.get("transparency") is not None:
        # transparency composited onto white (as transformers' convert_rgb), not dropped to black
        from PIL import Image as PILImage

        rgba = im.convert("RGBA")
        bg = PILImage.new("RGBA", rgba.size, (255, 255, 255, 255))
        im = PILImage.alpha_composite(bg, rgba)
    return np.asarray(im.convert("RGB"), dtype=np.uint8)


def resize_uint8(chw: np.ndarray, h: int, w: int) -> np.ndarray:
    """[C, H, W] uint8 -> [C, h, w] uint8: bicubic + antialias, torch's native uint8 kernel (the path torchvision's
    ``resize`` takes on CPU for uint8 tensors)."""
    import torch
    import torch.nn.functional as F

    if chw.shape[1:] == (h, w):
        return chw
    t = torch.from_numpy(np.ascontiguousarray(chw))[None]
    out = F.interpolate(t, size=[h, w], mode="bicubic", align_corners=False, antialias=True)
    return out[0].numpy()


@dataclass
class Image:
    patches: np.ndarray  # [N, 588] float32 (c, py, px), official patch order
    grid_h: int  # patch grid (multiples of 2)
    grid_w: int
    resized: Tuple[int, int]  # (h, w) pixels after smart_resize
    original: Tuple[int, int]

    @property
    def n_patches(self) -> int:
        return self.grid_h * self.grid_w

    @property
    def n_tokens(self) -> int:  # LLM image tokens
        return self.n_patches // (MERGE * MERGE)

    @property
    def llm_grid(self) -> Tuple[int, int]:
        return self.grid_h // MERGE, self.grid_w // MERGE


def preprocess(src, min_pixels: int = MIN_PIXELS, max_pixels: int = MAX_PIXELS) -> Image:
    """Official preprocessing: RGB -> smart_resize -> bicubic AA (uint8) -> (x - 255 mean) / (255 std) -> patches."""
    import torch

    rgb = load_rgb(src)
    H, W = rgb.shape[:2]
    h, w = smart_resize(H, W, min_pixels, max_pixels)
    chw = resize_uint8(np.transpose(rgb, (2, 0, 1)), h, w)
    x = torch.from_numpy(np.ascontiguousarray(chw)).to(torch.float32)
    mean = torch.tensor(MEAN) * (1.0 / RESCALE)
    std = torch.tensor(STD) * (1.0 / RESCALE)
    x = (x - mean[:, None, None]) / std[:, None, None]
    gh, gw = h // PATCH, w // PATCH
    p = x.reshape(3, gh // MERGE, MERGE, PATCH, gw // MERGE, MERGE, PATCH)
    p = p.permute(1, 4, 2, 5, 0, 3, 6).reshape(gh * gw, 3 * PATCH * PATCH)
    return Image(p.numpy(), gh, gw, (h, w), (H, W))


def official_pixel_values(img: Image) -> np.ndarray:
    """[N, 1176] = the processor's pixel_values (temporal frame repeated): for comparisons with goldens."""
    p = img.patches.reshape(-1, 3, 1, PATCH * PATCH)
    return np.repeat(p, T_PATCH, axis=2).reshape(-1, 3 * T_PATCH * PATCH * PATCH)


# ---------------------------------------------------------------------------------------------- tokenizer / prompt
class Tokenizer:
    def __init__(self, path: str):
        from tokenizers import Tokenizer as T

        f = os.path.join(path, "tokenizer.json") if os.path.isdir(path) else path
        self.tok = T.from_file(f)
        self.special = set()
        cfgp = os.path.join(os.path.dirname(f), "tokenizer_config.json")
        if os.path.exists(cfgp):
            for s in json.load(open(cfgp)).get("extra_special_tokens", []):
                i = self.tok.token_to_id(s)
                if i is not None:
                    self.special.add(i)
        for i in (GMASK, SOP, USER, ASSISTANT, BOI, EOI, IMAGE, ENDOFTEXT, 59249, 59251, 59252, 59255):
            self.special.add(i)

    def encode(self, text: str) -> List[int]:
        return self.tok.encode(text, add_special_tokens=False).ids

    def decode(self, ids: Sequence[int], skip_special: bool = True) -> str:
        ids = [int(i) for i in ids]
        if skip_special:
            ids = [i for i in ids if i not in self.special]
        return self.tok.decode(ids, skip_special_tokens=False)


@dataclass
class Prompt:
    ids: List[int]  # full prompt token ids (image tokens as IMAGE)
    image_start: int  # index of the first image token
    n_image: int
    pos3d: np.ndarray  # [3, L] int64 (t, h, w) positions
    rope_delta: int  # decode position of the token at cache index p = p + rope_delta

    @property
    def L(self) -> int:
        return len(self.ids)


def build_prompt(tok: Tokenizer, text: str, img: Optional[Image]) -> Prompt:
    """The chat template for one user turn [image, text] + generation prompt (no thinking flag), as rendered by
    ``chat_template.jinja``: ``[gMASK]<sop><|user|>\\n<|begin_of_image|><|image|>*n<|end_of_image|>{text}<|assistant|>\\n``.
    Without an image: ``[gMASK]<sop><|user|>\\n{text}<|assistant|>\\n``."""
    pre = [GMASK, SOP, USER, NL]
    post = tok.encode(text) + [ASSISTANT, NL]
    if img is None:
        ids = pre + post
        L = len(ids)
        pos = np.tile(np.arange(L, dtype=np.int64), (3, 1))
        return Prompt(ids, len(pre), 0, pos, 0)
    n = img.n_tokens
    ids = pre + [BOI] + [IMAGE] * n + [EOI] + post
    s = len(pre) + 1
    gh, gw = img.llm_grid
    pos = np.zeros((3, len(ids)), np.int64)
    pos[:, :s] = np.arange(s)
    hh, ww = np.meshgrid(np.arange(gh), np.arange(gw), indexing="ij")
    pos[0, s:s + n] = s
    pos[1, s:s + n] = s + hh.reshape(-1)
    pos[2, s:s + n] = s + ww.reshape(-1)
    cur = s + max(gh, gw)
    rest = len(ids) - (s + n)
    pos[:, s + n:] = cur + np.arange(rest)
    delta = int(pos.max()) + 1 - len(ids)
    return Prompt(ids, s, n, pos, delta)


def messages_to_request(messages: Iterable[dict]) -> Tuple[Optional[object], str]:
    """OpenAI-style messages -> (image source, text). GLM-OCR is single-turn OCR: the LAST user message's first image
    and its text parts (joined) are used; system / earlier turns are not supported by the model's prompt format."""
    img, texts = None, []
    users = [m for m in messages if m.get("role") == "user"]
    if not users:
        raise ValueError("no user message")
    c = users[-1].get("content")
    if isinstance(c, str):
        return None, c
    for part in c or []:
        t = part.get("type")
        if t == "text":
            texts.append(part.get("text", ""))
        elif t in ("image_url", "image", "input_image") and img is None:
            img = part.get("image_url", part.get("image"))
            if isinstance(img, dict):
                img = img.get("url")
    return img, "".join(texts)