File size: 10,352 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
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
# SPDX-License-Identifier: Apache-2.0
"""Host pre-processing of PaddleOCR-VL (clean-room re-implementation of the repos' image processor, processor and
chat template; numpy + PIL only, no torch):

* ``smart_resize`` / ``preprocess``: RGB -> bicubic resize to a 28-multiple grid inside [min_pixels, max_pixels] ->
  x / 255 -> (x - 0.5) / 0.5 -> 14 x 14 patches [N, 3 * 14 * 14] (channel, row, col inside a patch).
* patch order: the official order is row-major over the (gh, gw) patch grid. ``merge_order(gh, gw)`` is the
  permutation (h, w, p1, p2) that puts the 4 patches of each 2 x 2 merged token next to each other; the vision
  encoder is permutation-equivariant (full attention, per-patch position inputs), so the device runs it in that
  order and the projector's 2 x 2 merge becomes a plain reshape.
* ``build_prompt``: the chat template for one image + one task prompt, expanded image placeholders.
* ``rope_index``: the decoder's 3-D (t, h, w) M-RoPE position ids and the decode offset ``delta``.
"""

from __future__ import annotations

import math
import os
from dataclasses import dataclass
from typing import List, Optional, Sequence, Tuple

import numpy as np

from .config import (CLS, IMAGE_END, IMAGE_PLACEHOLDER, IMAGE_START, SPOTTING_MAX_PIXELS,
                     SPOTTING_UPSCALE_THRESHOLD, TASKS, ProfileConfig)

PATCH, MERGE = 14, 2
FACTOR = PATCH * MERGE  # 28
MEAN = STD = 0.5


def smart_resize(height: int, width: int, factor: int = FACTOR, min_pixels: int = 28 * 28 * 130,
                 max_pixels: int = 28 * 28 * 1280) -> Tuple[int, int]:
    """Exactly the repos' ``smart_resize`` (incl. the tiny-side rescue and the aspect-ratio limit)."""
    if height < factor:
        width = round((width * factor) / height)
        height = factor
    if width < factor:
        height = round((height * factor) / width)
        width = factor
    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
    if h_bar * w_bar > max_pixels:
        beta = math.sqrt((height * width) / max_pixels)
        h_bar = math.floor(height / beta / factor) * factor
        w_bar = math.floor(width / beta / factor) * factor
    elif h_bar * w_bar < min_pixels:
        beta = math.sqrt(min_pixels / (height * width))
        h_bar = math.ceil(height * beta / factor) * factor
        w_bar = math.ceil(width * beta / factor) * factor
    return h_bar, w_bar


@dataclass
class ImageInput:
    patches: np.ndarray  # [N, 588] float32, official (row-major grid) order
    gh: int
    gw: int
    resized: Tuple[int, int]  # (h, w) after smart_resize
    source_size: Tuple[int, int]  # (w, h) of the image given to the processor (after a spotting upscale)

    @property
    def n_patches(self) -> int:
        return self.gh * self.gw

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


def task_image(image, task: str):
    """The model cards' task-specific image preparation (spotting: 2x LANCZOS when both sides < 1500)."""
    from PIL import Image

    image = image.convert("RGB")
    if task == "spotting":
        w, h = image.size
        if w < SPOTTING_UPSCALE_THRESHOLD and h < SPOTTING_UPSCALE_THRESHOLD:
            image = image.resize((w * 2, h * 2), Image.Resampling.LANCZOS)
    return image


def task_max_pixels(task: str, prof: ProfileConfig, override: Optional[int] = None) -> int:
    if override:
        return int(override)
    return SPOTTING_MAX_PIXELS if task == "spotting" else prof.max_pixels


def preprocess(image, min_pixels: int, max_pixels: int) -> ImageInput:
    """PIL image (any mode) -> normalized patches, as the official image processor (PIL bicubic resize of the uint8
    RGB image, float64 rescale -> float32, float32 normalize)."""
    from PIL import Image

    image = image.convert("RGB")
    w, h = image.size
    rh, rw = smart_resize(h, w, FACTOR, min_pixels, max_pixels)
    if (rh, rw) != (h, w):
        image = image.resize((rw, rh), resample=Image.Resampling.BICUBIC)
    x = (np.asarray(image, dtype=np.uint8).astype(np.float64) * (1.0 / 255.0)).astype(np.float32)
    x = (x - np.float32(MEAN)) / np.float32(STD)
    gh, gw = rh // PATCH, rw // PATCH
    # [gh, 14, gw, 14, 3] -> [gh, gw, 3, 14, 14]
    p = x.reshape(gh, PATCH, gw, PATCH, 3).transpose(0, 2, 4, 1, 3).reshape(gh * gw, 3 * PATCH * PATCH)
    return ImageInput(np.ascontiguousarray(p, dtype=np.float32), gh, gw, (rh, rw), (w, h))


def merge_order(gh: int, gw: int) -> np.ndarray:
    """Permutation of the official patch order such that rows 4k .. 4k + 3 are the (p1, p2) = (0,0), (0,1), (1,0),
    (1,1) patches of merged token k (merged tokens in row-major (h, w) order, as the projector's rearrange)."""
    hh, ww = gh // MERGE, gw // MERGE
    h = np.arange(hh)[:, None, None, None]
    w = np.arange(ww)[None, :, None, None]
    p1 = np.arange(MERGE)[None, None, :, None]
    p2 = np.arange(MERGE)[None, None, None, :]
    idx = (h * MERGE + p1) * gw + (w * MERGE + p2)
    return idx.reshape(-1).astype(np.int64)


def vision_rope_tables(gh: int, gw: int, head_dim: int = 72, theta: float = 10000.0,
                       order: Optional[np.ndarray] = None) -> Tuple[np.ndarray, np.ndarray]:
    """2-D RoPE of the vision encoder: per patch [head_dim] cos / sin = (freqs(h) | freqs(w)) repeated twice
    (rotate-half pairing over the full head_dim); ``order`` permutes the rows like the patches."""
    dim = head_dim // 2  # 36 = rotary width of each axis pair
    inv = 1.0 / (theta ** (np.arange(0, dim, 2, dtype=np.float32) / np.float32(dim)))  # 18 (float32 as torch)
    pid = np.arange(gh * gw)
    hid, wid = pid // gw, pid % gw
    if order is not None:
        hid, wid = hid[order], wid[order]
    fr_h = hid[:, None].astype(np.float32) * inv[None]
    fr_w = wid[:, None].astype(np.float32) * inv[None]
    emb = np.concatenate([fr_h, fr_w], 1)  # [N, 36]
    emb = np.concatenate([emb, emb], 1)  # [N, 72]
    return np.cos(emb).astype(np.float32), np.sin(emb).astype(np.float32)


class PromptBuilder:
    """Token ids of the chat template for one image + one task prompt (``tokenizers`` fast tokenizer)."""

    def __init__(self, tokenizer_json: str, prof: ProfileConfig):
        from tokenizers import Tokenizer

        self.tok = Tokenizer.from_file(tokenizer_json)
        self.prof = prof
        for name, tid in (("<|begin_of_sentence|>", CLS), ("<|IMAGE_START|>", IMAGE_START),
                          ("<|IMAGE_PLACEHOLDER|>", IMAGE_PLACEHOLDER), ("<|IMAGE_END|>", IMAGE_END)):
            got = self.tok.token_to_id(name)
            if got != tid:
                raise ValueError(f"{tokenizer_json}: {name} = {got}, expected {tid}")
        self._cache = {}

    @classmethod
    def from_dir(cls, path: str, prof: ProfileConfig) -> "PromptBuilder":
        return cls(os.path.join(path, "tokenizer.json"), prof)

    def text(self, prompt: str) -> str:
        return ("<|begin_of_sentence|>User: <|IMAGE_START|><|IMAGE_PLACEHOLDER|><|IMAGE_END|>" + prompt + "\n"
                + self.prof.assistant)

    def ids(self, prompt: str, n_image_tokens: int) -> List[int]:
        base = self._cache.get(prompt)
        if base is None:
            base = self._cache[prompt] = self.tok.encode(self.text(prompt), add_special_tokens=False).ids
        k = base.index(IMAGE_PLACEHOLDER)
        return base[:k] + [IMAGE_PLACEHOLDER] * int(n_image_tokens) + base[k + 1:]

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


def task_prompt(task: Optional[str], prompt: Optional[str]) -> str:
    if prompt:
        return prompt
    if task not in TASKS:
        raise ValueError(f"unknown task {task!r}; known {tuple(TASKS)}")
    return TASKS[task]


def rope_index(ids: Sequence[int], gh: int, gw: int, merge: int = MERGE) -> Tuple[np.ndarray, int]:
    """3-D position ids [3, L] (t, h, w) and delta (decode position of KV index p = p + delta), as the official
    get_rope_index for one image: text before the image counts 0.., the image tokens get (s, s + h, s + w) with s
    the next text index, the text after it continues from max + 1."""
    ids = list(ids)
    L = len(ids)
    k = ids.index(IMAGE_PLACEHOLDER)
    hh, ww = gh // merge, gw // merge
    n = hh * ww
    assert ids[k:k + n] == [IMAGE_PLACEHOLDER] * n and (k + n == L or ids[k + n] != IMAGE_PLACEHOLDER)
    pos = np.zeros((3, L), dtype=np.int64)
    pos[:, :k] = np.arange(k)[None]
    hi = np.repeat(np.arange(hh), ww)
    wi = np.tile(np.arange(ww), hh)
    pos[0, k:k + n] = k
    pos[1, k:k + n] = k + hi
    pos[2, k:k + n] = k + wi
    st = int(pos[:, :k + n].max()) + 1 if k + n > 0 else 0
    rest = L - (k + n)
    pos[:, k + n:] = st + np.arange(rest)[None]
    delta = int(pos.max()) + 1 - L
    return pos, delta


def mrope_cos_sin(pos: np.ndarray, head_dim: int = 128, theta: float = 500000.0,
                  section: Sequence[int] = (16, 24, 24)) -> Tuple[np.ndarray, np.ndarray]:
    """Decoder M-RoPE tables [L, head_dim] (float32): frequency i of the rotate-half pairs uses the position of axis
    t / h / w by mrope_section (16 / 24 / 24 frequencies), both halves alike."""
    inv = 1.0 / (theta ** (np.arange(0, head_dim, 2, dtype=np.int64).astype(np.float32) / np.float32(head_dim)))
    axis = np.concatenate([np.full(s, a) for a, s in enumerate(section)])  # [64]
    p = pos[axis, :].T.astype(np.float32)  # [L, 64]
    fr = p * inv[None]
    emb = np.concatenate([fr, fr], 1)
    return np.cos(emb).astype(np.float32), np.sin(emb).astype(np.float32)


def interp_matrix(n_out: int, n_in: int) -> np.ndarray:
    """Bilinear (align_corners=False, no antialias) 1-D interpolation weights [n_out, n_in] as torch's
    F.interpolate(mode='bilinear')."""
    m = np.zeros((n_out, n_in), dtype=np.float64)
    scale = n_in / n_out
    for i in range(n_out):
        src = (i + 0.5) * scale - 0.5
        src = max(src, 0.0)
        i0 = min(int(math.floor(src)), n_in - 1)
        i1 = min(i0 + 1, n_in - 1)
        l1 = src - i0
        m[i, i0] += 1.0 - l1
        m[i, i1] += l1
    return m