File size: 12,517 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# SPDX-License-Identifier: Apache-2.0
"""Clean-room CPU reference of GLM-OCR (torch only; written for this bundle from the architecture in
research/glmocr/ARCH.md, checked against the official transformers goldens).

* :class:`Weights`: the checkpoint tensors (safetensors, any dtype -> ``dtype``), the MTP layer 16 skipped.
* :func:`vision`: patches [N, 588] (temporal frame folded) -> image embeddings [N / 4, 1536] (+ stage dict).
* :class:`Decoder`: embeddings / KV cache / one forward over rows at given 3D positions; logits.
* :func:`generate`: greedy or sampled generation with the official stop tokens and repetition penalty.

Numerics: everything in ``dtype`` (fp32 by default) with fp32 RMSNorm statistics, as the official modules.
"""

from __future__ import annotations

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

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

V_DEPTH, V_D, V_HEADS, V_HD, V_I = 24, 1024, 16, 64, 4096
T_LAYERS, T_D, T_HEADS, T_KV, T_HD, T_I, VOCAB = 16, 1536, 16, 8, 128, 4608, 59392
EPS = 1e-5
V_THETA = 10000.0
T_THETA = 10000.0
MROPE = (16, 24, 24)


class Weights:
    def __init__(self, path: str, dtype=torch.float32):
        from safetensors import safe_open

        p = os.path.join(path, "model.safetensors") if os.path.isdir(path) else path
        self.t: Dict[str, torch.Tensor] = {}
        with safe_open(p, framework="pt") as f:
            for k in f.keys():
                if ".layers.16." in k:  # the MTP (next-n prediction) layer: unused by generation
                    continue
                self.t[k] = f.get_tensor(k).to(dtype)
        self.dtype = dtype

    def __getitem__(self, k: str) -> torch.Tensor:
        return self.t[k]


#: bf16 emulation for drift studies: weights already bf16-rounded, activations rounded to bf16 at every op boundary
#: (the official bf16 model's storage precision) while computing in fp32 (fast on CPUs without bf16 units)
EMULATE_BF16 = False


def _r(t: torch.Tensor) -> torch.Tensor:
    return t.to(torch.bfloat16).float() if EMULATE_BF16 else t


def rms(x: torch.Tensor, w: torch.Tensor, eps: float = EPS) -> torch.Tensor:
    dt = x.dtype
    x32 = x.float()
    y = x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + eps)
    return w * y.to(dt)


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


# ---------------------------------------------------------------------------------------------- vision
def vision_rope(grid_h: int, grid_w: int, n: Optional[int] = None) -> Tuple[torch.Tensor, torch.Tensor]:
    """cos / sin [N, 64] of the 2D axial rope for patches in the official order (2 x 2 blocks, raster)."""
    hh, ww = np.meshgrid(np.arange(grid_h), np.arange(grid_w), indexing="ij")
    blk = (grid_h // 2, 2, grid_w // 2, 2)
    hp = torch.from_numpy(hh.reshape(blk).transpose(0, 2, 1, 3).reshape(-1).copy())
    wp = torch.from_numpy(ww.reshape(blk).transpose(0, 2, 1, 3).reshape(-1).copy())
    inv = 1.0 / (V_THETA ** (torch.arange(0, V_HD // 2, 2, dtype=torch.float) / (V_HD // 2)))  # 16
    fh = hp[:, None].float() * inv
    fw = wp[:, None].float() * inv
    f = torch.cat([fh, fw], -1)
    f = torch.cat([f, f], -1)  # [N, 64]
    return f.cos(), f.sin()


def vision(W: Weights, patches: torch.Tensor, grid_h: int, grid_w: int, stages: Optional[dict] = None):
    """patches [N, 588] (c, py, px) -> image embeddings [N/4, 1536]."""
    dt = W.dtype
    pfx = "model.visual."
    w = W[pfx + "patch_embed.proj.weight"]  # [1024, 3, 2, 14, 14]
    w = (w[:, :, 0] + w[:, :, 1]).reshape(V_D, -1)  # temporal frames identical: fold
    x = _r(patches.to(dt) @ w.T + W[pfx + "patch_embed.proj.bias"])
    if stages is not None:
        stages["v_patch"] = x.float().clone()
    cos, sin = vision_rope(grid_h, grid_w)
    N = x.shape[0]
    for li in range(V_DEPTH):
        p = pfx + f"blocks.{li}."
        h = _r(rms(x, W[p + "norm1.weight"]))
        qkv = _r(h @ W[p + "attn.qkv.weight"].T + W[p + "attn.qkv.bias"]).reshape(N, 3, V_HEADS, V_HD)
        q, k, v = qkv.unbind(1)
        q = _r(rms(q, W[p + "attn.q_norm.weight"]))
        k = _r(rms(k, W[p + "attn.k_norm.weight"]))
        c, s = cos[:, None, :], sin[:, None, :]
        q = _r((q.float() * c + rotate_half(q.float()) * s).to(dt))
        k = _r((k.float() * c + rotate_half(k.float()) * s).to(dt))
        a = F.scaled_dot_product_attention(q.transpose(0, 1)[None], k.transpose(0, 1)[None], v.transpose(0, 1)[None],
                                           scale=V_HD ** -0.5)
        a = _r(a[0].transpose(0, 1).reshape(N, V_D))
        x = _r(x + _r(a @ W[p + "attn.proj.weight"].T + W[p + "attn.proj.bias"]))
        h = _r(rms(x, W[p + "norm2.weight"]))
        g = _r(h @ W[p + "mlp.gate_proj.weight"].T + W[p + "mlp.gate_proj.bias"])
        u = _r(h @ W[p + "mlp.up_proj.weight"].T + W[p + "mlp.up_proj.bias"])
        x = _r(x + _r(_r(F.silu(g) * u) @ W[p + "mlp.down_proj.weight"].T + W[p + "mlp.down_proj.bias"]))
        if stages is not None and li in (0, 11, 23):
            stages[f"v_blk{li}"] = x.float().clone()
    x = _r(rms(x, W[pfx + "post_layernorm.weight"]))
    if stages is not None:
        stages["v_postln"] = x.float().clone()
    wd = W[pfx + "downsample.weight"]  # [1536, 1024, 2, 2] -> [(kh kw c), 1536]
    wd = wd.permute(2, 3, 1, 0).reshape(4 * V_D, T_D)
    x = _r(x.reshape(N // 4, 4 * V_D) @ wd + W[pfx + "downsample.bias"])
    if stages is not None:
        stages["v_down"] = x.float().clone()
    m = pfx + "merger."
    x = _r(x @ W[m + "proj.weight"].T)
    x = _r(F.gelu(_r(F.layer_norm(x, (T_D,), W[m + "post_projection_norm.weight"],
                                  W[m + "post_projection_norm.bias"]))))
    x = _r(_r(_r(F.silu(_r(x @ W[m + "gate_proj.weight"].T))) * _r(x @ W[m + "up_proj.weight"].T))
           @ W[m + "down_proj.weight"].T)
    if stages is not None:
        stages["v_merger"] = x.float().clone()
    return x


# ---------------------------------------------------------------------------------------------- text decoder
def mrope_cos_sin(pos3d: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
    """pos3d [3, L] -> cos / sin [L, 128] in the official interleaved layout (pair j = dims 2j, 2j+1)."""
    inv = 1.0 / (T_THETA ** (torch.arange(0, T_HD, 2, dtype=torch.float) / T_HD))  # 64
    f = pos3d[..., None].float() * inv  # [3, L, 64]
    parts, o = [], 0
    for i, n in enumerate(MROPE):
        parts.append(f[i, :, o:o + n])
        o += n
    f = torch.cat(parts, -1)  # [L, 64]
    f = f.repeat_interleave(2, dim=-1)
    return f.cos(), f.sin()


def rotate_pairs(x):
    x1, x2 = x[..., 0::2], x[..., 1::2]
    return torch.stack((-x2, x1), dim=-1).flatten(-2)


class Decoder:
    def __init__(self, W: Weights, max_len: int = 16384):
        self.W = W
        self.dt = W.dtype
        self.pfx = "model.language_model."
        self.embed = W[self.pfx + "embed_tokens.weight"]
        self.head = W["lm_head.weight"]
        self.k: List[Optional[torch.Tensor]] = [None] * T_LAYERS
        self.v: List[Optional[torch.Tensor]] = [None] * T_LAYERS
        self.n = 0

    def reset(self):
        self.k = [None] * T_LAYERS
        self.v = [None] * T_LAYERS
        self.n = 0

    def forward(self, x: torch.Tensor, pos3d: torch.Tensor, stages: Optional[dict] = None,
                all_logits: bool = False) -> torch.Tensor:
        """x [T, 1536] rows appended at cache positions n .. n+T-1, pos3d [3, T]; returns logits of the last row
        (or of every row)."""
        W, dt, p0 = self.W, self.dt, self.pfx
        T = x.shape[0]
        cos, sin = mrope_cos_sin(pos3d)
        cos, sin = cos[:, None, :], sin[:, None, :]
        x = x.to(dt)
        for li in range(T_LAYERS):
            p = p0 + f"layers.{li}."
            h = _r(rms(x, W[p + "input_layernorm.weight"]))
            q = _r(h @ W[p + "self_attn.q_proj.weight"].T).reshape(T, T_HEADS, T_HD)
            k = _r(h @ W[p + "self_attn.k_proj.weight"].T).reshape(T, T_KV, T_HD)
            v = _r(h @ W[p + "self_attn.v_proj.weight"].T).reshape(T, T_KV, T_HD)
            cr, sr = _r(cos.to(dt)), _r(sin.to(dt))
            q = _r((q * cr) + rotate_pairs(q) * sr)
            k = _r((k * cr) + rotate_pairs(k) * sr)
            kc = k.transpose(0, 1) if self.k[li] is None else torch.cat([self.k[li], k.transpose(0, 1)], 1)
            vc = v.transpose(0, 1) if self.v[li] is None else torch.cat([self.v[li], v.transpose(0, 1)], 1)
            self.k[li], self.v[li] = kc, vc
            S = kc.shape[1]
            mask = torch.ones(T, S, dtype=torch.bool).tril(S - T)
            kr = kc.repeat_interleave(T_HEADS // T_KV, 0)
            vr = vc.repeat_interleave(T_HEADS // T_KV, 0)
            a = F.scaled_dot_product_attention(q.transpose(0, 1)[None], kr[None], vr[None], attn_mask=mask[None, None],
                                               scale=T_HD ** -0.5)
            a = _r(a[0].transpose(0, 1).reshape(T, T_HEADS * T_HD))
            a = _r(a @ W[p + "self_attn.o_proj.weight"].T)
            x = _r(x + _r(rms(a, W[p + "post_self_attn_layernorm.weight"])))
            h = _r(rms(x, W[p + "post_attention_layernorm.weight"]))
            gu = _r(h @ W[p + "mlp.gate_up_proj.weight"].T)
            g, u = gu.chunk(2, -1)
            m = _r(_r(u * _r(F.silu(g))) @ W[p + "mlp.down_proj.weight"].T)
            x = _r(x + _r(rms(m, W[p + "post_mlp_layernorm.weight"])))
            if stages is not None and li in (0, 7, 15):
                stages[f"t_layer{li}"] = x.float().clone()
        self.n += T
        h = _r(rms(x if all_logits else x[-1:], W[p0 + "norm.weight"]))
        if stages is not None:
            stages["t_norm"] = h.float().clone()
        return (h @ self.head.T).float()


def prompt_rows(W: Weights, ids: Sequence[int], image_start: int, img_emb: Optional[torch.Tensor]) -> torch.Tensor:
    x = W["model.language_model.embed_tokens.weight"][torch.tensor(list(ids), dtype=torch.long)].clone()
    if img_emb is not None:
        x[image_start:image_start + img_emb.shape[0]] = img_emb.to(x.dtype)
    return x


@dataclass
class SampleParams:
    temperature: float = 0.0  # 0 = greedy
    top_k: int = 0
    top_p: float = 1.0
    repetition_penalty: float = 1.0
    seed: Optional[int] = None


def process_logits(lg: torch.Tensor, seen: Sequence[int], sp: SampleParams) -> torch.Tensor:
    """transformers' RepetitionPenaltyLogitsProcessor -> temperature -> top-k -> top-p (on fp32 logits)."""
    lg = lg.clone().float()
    if sp.repetition_penalty != 1.0 and len(seen):
        idx = torch.tensor(sorted(set(int(i) for i in seen)), dtype=torch.long)
        s = lg[idx]
        lg[idx] = torch.where(s < 0, s * sp.repetition_penalty, s / sp.repetition_penalty)
    return lg


def generate(W: Weights, ids: Sequence[int], image_start: int, img_emb: Optional[torch.Tensor], pos3d: np.ndarray,
             rope_delta: int, max_new: int = 1024, sp: Optional[SampleParams] = None,
             eos: Sequence[int] = (59246, 59253), logits_out: Optional[list] = None) -> List[int]:
    sp = sp or SampleParams()
    dec = Decoder(W)
    x = prompt_rows(W, ids, image_start, img_emb)
    lg = dec.forward(x, torch.from_numpy(np.asarray(pos3d)))[0]
    L = len(ids)
    out: List[int] = []
    gen = torch.Generator().manual_seed(int(sp.seed)) if sp.seed is not None else None
    seen = list(ids)  # transformers' penalty covers the whole input_ids (prompt + generated)
    while True:
        if logits_out is not None:
            logits_out.append(lg.clone())
        z = process_logits(lg, seen, sp)
        if sp.temperature <= 0:
            t = int(torch.argmax(z))
        else:
            z = z / sp.temperature
            if sp.top_k > 0:
                kth = torch.topk(z, sp.top_k).values[-1]
                z[z < kth] = -float("inf")
            if sp.top_p < 1.0:
                sz, si = torch.sort(z, descending=True)
                cp = torch.softmax(sz, -1).cumsum(-1)
                rm = cp - torch.softmax(sz, -1) > sp.top_p
                z[si[rm]] = -float("inf")
            t = int(torch.multinomial(torch.softmax(z, -1), 1, generator=gen))
        out.append(t)
        seen.append(t)
        if t in eos or len(out) >= max_new:
            return out
        p = L + len(out) - 1 + rope_delta
        e = W["model.language_model.embed_tokens.weight"][t][None]
        lg = dec.forward(e, torch.full((3, 1), p, dtype=torch.long))[0]