File size: 11,488 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
# SPDX-License-Identifier: Apache-2.0
"""Clean-room CPU reference of PaddleOCR-VL 0.9B (torch only; written from the architecture description in
research/paddleocr/ARCH.md, checked against the official goldens). fp32 by default (``dtype`` selectable).

    ref = Reference.load(weights_dir, profile)
    out = ref.generate(image, task="ocr", max_new_tokens=512)   # greedy, like model.generate(do_sample=False)
    ve = ref.vision(img_input)                                   # [N, 1152] encoder output (post-LN, official order)
    pe = ref.project(ve, gh, gw)                                 # [N / 4, 1024]
"""

from __future__ import annotations

import os
from dataclasses import dataclass
from typing import Dict, List, Optional

import numpy as np
import torch
import torch.nn.functional as F

from ..config import EOS, IMAGE_PLACEHOLDER, ModelConfig
from ..frontend import (ImageInput, PromptBuilder, interp_matrix, mrope_cos_sin, preprocess, rope_index,
                        task_image, task_max_pixels, task_prompt, vision_rope_tables)

VP = "visual.vision_model."


def load_state(path: str, dtype=torch.float32) -> Dict[str, torch.Tensor]:
    from safetensors import safe_open

    p = os.path.join(path, "model.safetensors") if os.path.isdir(path) else path
    out = {}
    with safe_open(p, framework="pt") as f:
        for k in f.keys():
            if k.startswith(VP + "head.") or "packing_position_embedding" in k:
                continue  # unused at inference (pooling head, packing table)
            out[k] = f.get_tensor(k).to(dtype)
    return out


def rotate_half(x):
    h = x.shape[-1] // 2
    return torch.cat([-x[..., h:], x[..., :h]], -1)


def gelu_tanh(x):
    return F.gelu(x, approximate="tanh")


@dataclass
class GenOut:
    ids: List[int]  # generated ids (incl. the final EOS if produced)
    text: str
    prompt_len: int
    eos: bool


class Reference:
    def __init__(self, W: Dict[str, torch.Tensor], cfg: ModelConfig, prompts: Optional[PromptBuilder] = None,
                 dtype=torch.float32):
        self.W, self.cfg, self.prompts, self.dtype = W, cfg, prompts, dtype
        v = cfg.vision
        self.pos_table = W[VP + "embeddings.position_embedding.weight"].reshape(v.pos_grid, v.pos_grid, v.d)
        self.patch_w = W[VP + "embeddings.patch_embedding.weight"].reshape(v.d, -1)  # [1152, 588]
        self.patch_b = W[VP + "embeddings.patch_embedding.bias"]

    @classmethod
    def load(cls, path: str, profile: str, dtype=torch.float32) -> "Reference":
        cfg = ModelConfig.from_dir(path, profile)
        return cls(load_state(path, dtype), cfg, PromptBuilder.from_dir(path, cfg.prof), dtype)

    # ------------------------------------------------------------------ vision
    def pos_embed(self, gh: int, gw: int) -> torch.Tensor:
        """Bilinear resize of the 27 x 27 table to (gh, gw) (align_corners False): [gh * gw, D]."""
        t = self.pos_table.permute(2, 0, 1)[None].float()  # [1, D, 27, 27]
        r = F.interpolate(t, size=(gh, gw), mode="bilinear", align_corners=False)
        return r[0].permute(1, 2, 0).reshape(gh * gw, -1).to(self.dtype)

    def pos_embed_matrix(self, gh: int, gw: int) -> torch.Tensor:
        """The same as separable matrices (host-side alternative, float64 weights)."""
        mh = torch.from_numpy(interp_matrix(gh, self.cfg.vision.pos_grid))
        mw = torch.from_numpy(interp_matrix(gw, self.cfg.vision.pos_grid))
        t = self.pos_table.double()
        r = torch.einsum("hi,ijd,wj->hwd", mh, t, mw)
        return r.reshape(gh * gw, -1).to(self.dtype)

    def vision(self, img: ImageInput, taps: Optional[dict] = None) -> torch.Tensor:
        v, W = self.cfg.vision, self.W
        x = torch.from_numpy(img.patches).to(self.dtype)
        x = x @ self.patch_w.T + self.patch_b
        x = x + self.pos_embed(img.gh, img.gw)
        if taps is not None:
            taps["vis_embed"] = x.clone()
        cos, sin = vision_rope_tables(img.gh, img.gw, v.head_dim, v.rope_theta)
        cos = torch.from_numpy(cos).to(self.dtype)[:, None, :]  # [N, 1, 72]
        sin = torch.from_numpy(sin).to(self.dtype)[:, None, :]
        N, H, hd = x.shape[0], v.heads, v.head_dim
        for l in range(v.layers):
            p = VP + f"encoder.layers.{l}."
            h = F.layer_norm(x, (v.d,), W[p + "layer_norm1.weight"], W[p + "layer_norm1.bias"], v.eps)
            q = (h @ W[p + "self_attn.q_proj.weight"].T + W[p + "self_attn.q_proj.bias"]).view(N, H, hd)
            k = (h @ W[p + "self_attn.k_proj.weight"].T + W[p + "self_attn.k_proj.bias"]).view(N, H, hd)
            vv = (h @ W[p + "self_attn.v_proj.weight"].T + W[p + "self_attn.v_proj.bias"]).view(N, H, hd)
            q = q * cos + rotate_half(q) * sin
            k = k * cos + rotate_half(k) * sin
            a = F.scaled_dot_product_attention(q.transpose(0, 1), k.transpose(0, 1), vv.transpose(0, 1),
                                               scale=hd ** -0.5)  # [H, N, hd]
            a = a.transpose(0, 1).reshape(N, v.d)
            x = x + a @ W[p + "self_attn.out_proj.weight"].T + W[p + "self_attn.out_proj.bias"]
            h = F.layer_norm(x, (v.d,), W[p + "layer_norm2.weight"], W[p + "layer_norm2.bias"], v.eps)
            h = gelu_tanh(h @ W[p + "mlp.fc1.weight"].T + W[p + "mlp.fc1.bias"])
            x = x + h @ W[p + "mlp.fc2.weight"].T + W[p + "mlp.fc2.bias"]
        return F.layer_norm(x, (v.d,), W[VP + "post_layernorm.weight"], W[VP + "post_layernorm.bias"], v.eps)

    def project(self, ve: torch.Tensor, gh: int, gw: int) -> torch.Tensor:
        """Projector (mlp_AR): LayerNorm(1e-5) per patch, 2 x 2 merge (row-major merged grid, (p1, p2) inside),
        Linear 4608 -> 4608, GELU (erf), Linear 4608 -> 1024."""
        v, W = self.cfg.vision, self.W
        x = F.layer_norm(ve, (v.d,), W["mlp_AR.pre_norm.weight"], W["mlp_AR.pre_norm.bias"], v.proj_eps)
        hh, ww = gh // 2, gw // 2
        x = x.view(hh, 2, ww, 2, v.d).permute(0, 2, 1, 3, 4).reshape(hh * ww, 4 * v.d)
        x = F.gelu(x @ W["mlp_AR.linear_1.weight"].T + W["mlp_AR.linear_1.bias"])
        return x @ W["mlp_AR.linear_2.weight"].T + W["mlp_AR.linear_2.bias"]

    # ------------------------------------------------------------------ decoder
    def embed(self, ids: List[int], image_embeds: Optional[torch.Tensor]) -> torch.Tensor:
        e = self.W["model.embed_tokens.weight"][torch.tensor(ids)]
        if image_embeds is not None:
            m = torch.tensor(ids) == IMAGE_PLACEHOLDER
            e = e.clone()
            e[m] = image_embeds.to(e.dtype)
        return e

    def _rms(self, x, w):
        xf = x.float()
        y = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.cfg.dec.eps)
        return w * y.to(x.dtype)

    def decoder(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, cache: Optional[list] = None,
                taps: Optional[dict] = None) -> torch.Tensor:
        """x [S, D] rows at KV indices [P, P + S) (P = cache length), cos / sin [S, 128]: final-norm hidden [S, D].
        ``cache``: list of per-layer (K [kv, T, hd], V) extended in place."""
        c, W = self.cfg.dec, self.W
        S = x.shape[0]
        P = 0 if not cache or cache[0] is None else cache[0][0].shape[1]
        rep = c.heads // c.kv_heads
        mask = torch.full((S, P + S), float("-inf"), dtype=x.dtype).triu(P + 1)
        cs, sn = cos[None].to(x.dtype), sin[None].to(x.dtype)
        for l in range(c.layers):
            p = f"model.layers.{l}."
            h = self._rms(x, W[p + "input_layernorm.weight"])
            q = (h @ W[p + "self_attn.q_proj.weight"].T).view(S, c.heads, c.head_dim).transpose(0, 1)
            k = (h @ W[p + "self_attn.k_proj.weight"].T).view(S, c.kv_heads, c.head_dim).transpose(0, 1)
            v = (h @ W[p + "self_attn.v_proj.weight"].T).view(S, c.kv_heads, c.head_dim).transpose(0, 1)
            q = q * cs + rotate_half(q) * sn
            k = k * cs + rotate_half(k) * sn
            if cache is not None:
                if cache[l] is not None:
                    k = torch.cat([cache[l][0], k], 1)
                    v = torch.cat([cache[l][1], v], 1)
                cache[l] = (k, v)
            kk = k.repeat_interleave(rep, 0)
            vv = v.repeat_interleave(rep, 0)
            att = (q @ kk.transpose(1, 2)) * c.head_dim ** -0.5 + mask
            att = torch.softmax(att.float(), -1).to(x.dtype)
            o = (att @ vv).transpose(0, 1).reshape(S, c.heads * c.head_dim)
            x = x + o @ W[p + "self_attn.o_proj.weight"].T
            h = self._rms(x, W[p + "post_attention_layernorm.weight"])
            g = F.silu(h @ W[p + "mlp.gate_proj.weight"].T) * (h @ W[p + "mlp.up_proj.weight"].T)
            x = x + g @ W[p + "mlp.down_proj.weight"].T
            if taps is not None and l == 0:
                taps["dec_l0"] = x.clone()
        return self._rms(x, W["model.norm.weight"])

    def logits(self, h: torch.Tensor) -> torch.Tensor:
        return h @ self.W["lm_head.weight"].T

    # ------------------------------------------------------------------ end to end
    def prepare(self, image, task: str = "ocr", prompt: Optional[str] = None, max_pixels: Optional[int] = None,
                min_pixels: Optional[int] = None):
        prof = self.cfg.prof
        img = preprocess(task_image(image, task), min_pixels or prof.min_pixels,
                         task_max_pixels(task, prof, max_pixels))
        ids = self.prompts.ids(task_prompt(task, prompt), img.n_tokens)
        return img, ids

    @torch.no_grad()
    def generate(self, image, task: str = "ocr", prompt: Optional[str] = None, max_new_tokens: int = 512,
                 max_pixels: Optional[int] = None, taps: Optional[dict] = None, forced: Optional[List[int]] = None,
                 logits_out: Optional[list] = None) -> GenOut:
        """Greedy generation (``forced``: teacher-forced token sequence; logits of every step to ``logits_out``)."""
        img, ids = self.prepare(image, task, prompt, max_pixels)
        ve = self.vision(img, taps)
        pe = self.project(ve, img.gh, img.gw)
        if taps is not None:
            taps["vis_out"], taps["proj_out"] = ve, pe
        pos, delta = rope_index(ids, img.gh, img.gw)
        c = self.cfg.dec
        cos, sin = mrope_cos_sin(pos, c.head_dim, c.theta, c.mrope_section)
        cache = [None] * c.layers
        h = self.decoder(self.embed(ids, pe), torch.from_numpy(cos).to(self.dtype),
                         torch.from_numpy(sin).to(self.dtype), cache)
        lg = self.logits(h[-1:])[0].float()
        L = len(ids)
        out = []
        n = len(forced) if forced is not None else max_new_tokens
        for s in range(n):
            if logits_out is not None:
                logits_out.append(lg.clone())
            t = int(forced[s]) if forced is not None else int(lg.argmax())
            out.append(t)
            if (forced is None and t == EOS) or s == n - 1:
                break
            p = L + s + delta
            cs, sn = mrope_cos_sin(np.full((3, 1), p), c.head_dim, c.theta, c.mrope_section)
            h = self.decoder(self.W["model.embed_tokens.weight"][t][None], torch.from_numpy(cs).to(self.dtype),
                             torch.from_numpy(sn).to(self.dtype), cache)
            lg = self.logits(h)[0].float()
        eos = bool(out and out[-1] == EOS)
        text = self.prompts.decode(out, skip_special_tokens=True) if self.prompts else ""
        return GenOut(out, text, L, eos)