File size: 15,596 Bytes
ca1a504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# SPDX-License-Identifier: Apache-2.0
"""Clean-room CPU reference of the Unlimited-OCR-2 decoder attention (torch only; no transformers, no remote code).

Written from research/dsocr/UOCR2_NOTES.md (a read-only analysis of the official remote code: modeling_deepseekv2.py
DASH overlay, _sparse_base_impl.py, dash_attention.py, modeling_unlimitedocr.py). Everything else of the model (the
DeepEncoder, the MoE decoder layers, norms, lm_head) is DeepSeek-OCR's and comes from reference/model.py.

Per layer the attention of a query at flat position P is
    softmax over {local keys P-127..P (bias 0)} U {keys of the selected remote blocks, j <= P-128 (bias_b)} of
    q.k / sqrt(128) + bias,
with the remote blocks chosen per query by the layer's router ("dash", stage0 = head_cls):
    iq = rope2d(GemmaRMS(x Wrq^T)), ik = rope2d(GemmaRMS(x Wrk^T))            (index dim 128, fp32)
    kbar[b] = sum_t softmax_t(ik_t . head_cls / sqrt(128)) ik_t over the 32 tokens of block b
    score[i, b] = iq_i . kbar_b / sqrt(128) for blocks b <= P_i // 32 - 4 (complete, remote), else none
    candidates = remote blocks holding the query's page's image tokens (falls back to every remote block)
    top-16 of the candidates' scores x idx_scale (128 / sqrt(128), so x = iq . kbar), entmax-1.5 prior over the 16,
    first 12 kept; bias = log(max(prior, 1e-4)) - mean over the valid kept.
RoPE ("page2d"): 63 token frequencies 10000^(-i / 63) on the token count inside the token's page bucket, one pair on
the page parity (page mod 2); the same cos / sin for the main attention and the router.
"""

from __future__ import annotations

import math
from typing import Dict, List, Optional, Sequence, Tuple

import torch
import torch.nn.functional as F

from . import model as R

BLOCK = 32
LOCAL_BLOCKS = 4
LOCAL_WINDOW = BLOCK * LOCAL_BLOCKS  # 128
TOPM, TOPK = 16, 12
FLOOR, SIGMA = 1e-4, 1.0
IDX_D = 128
IDX_SCALE = 128.0 / math.sqrt(IDX_D)  # dash_scale_per_layer / sqrt(index_dim)
SCORE_NEG, ENTMAX_NEG, MASK_NEG, ACT_CLAMP = -1.0e9, -1.0e4, -1.0e9, 1.0e4
PAGE_ID, IMAGE_ID = 128827, 128815


# ------------------------------------------------------------------------------------------------ rope (page2d)
def rope2d_inv():
    n_tok = 64 - 1
    inv_tok = 1.0 / (10000.0 ** (torch.arange(0, n_tok, dtype=torch.int64).float() / n_tok))
    inv_page = torch.ones(1)  # 256 ** 0
    return inv_tok, inv_page


def rope2d(tok: torch.Tensor, page: torch.Tensor):
    """cos / sin [n, 128] for (tok, page) int coordinates."""
    inv_tok, inv_page = rope2d_inv()
    t = tok.float()[:, None]
    p = torch.remainder(page.long(), 2).float()[:, None]
    ang = torch.cat([t * inv_tok[None], p * inv_page[None]], -1)
    emb = torch.cat([ang, ang], -1)
    return emb.cos(), emb.sin()


def page_coords(ids: Sequence[int]):
    """Prefill (tok, page) of every prompt position + the decode state (pf_cnt per page, n_pages)."""
    ids = torch.as_tensor(list(ids))
    S = ids.numel()
    ar = torch.arange(S)
    img = ids == IMAGE_ID
    mk = ids == PAGE_ID
    if not bool(img.any()) or not bool(mk.any()):
        raise ValueError("non-marker prompt (no <PAGE>): the YaRN fallback is not implemented")
    cum = torch.cumsum(mk.long(), 0)
    last_img = int((img.long() * (ar + 1)).max()) - 1
    n_pages = int(cum[last_img])
    in_prefill = ar <= last_img
    page = torch.where(in_prefill, cum, cum - n_pages).clamp(min=0)
    n_pg = int(page.max()) + 1
    onehot = F.one_hot(page, num_classes=n_pg)
    run = onehot.cumsum(0)
    tok = run.gather(1, page[:, None]).squeeze(1) - 1
    pf_cnt = (onehot * in_prefill[:, None].long()).sum(0)
    return tok, page, {"pf_cnt": pf_cnt, "n_pg": n_pg, "page": int(page[-1]), "tok": int(tok[-1]),
                       "n_pages": n_pages, "last_img": last_img}


def decode_coord(state: dict, token_in: int) -> Tuple[int, int]:
    """Advance the decode state machine with the step's input token; returns its (tok, page)."""
    if token_in == PAGE_ID:
        state["page"] = min(state["page"] + 1, state["n_pg"] - 1)
        state["tok"] = int(state["pf_cnt"][state["page"]])
    else:
        state["tok"] += 1
    return state["tok"], state["page"]


def prefill_page_ids(ids: Sequence[int], n_pages: int, last_img: int):
    """ipage (image page of a key, -1 = none) and qpage (the query's page, -1 = unconstrained)."""
    ids = torch.as_tensor(list(ids))
    S = ids.numel()
    img = ids == IMAGE_ID
    cum = torch.cumsum((ids == PAGE_ID).long(), 0)
    ipage = torch.where(img, cum - 1, torch.full_like(cum, -1))
    ar = torch.arange(S)
    qpage = torch.where(ar <= last_img, cum - 1, cum - 1 - n_pages)
    qpage = torch.where(qpage < 0, torch.full_like(qpage, -1), qpage)
    return ipage, qpage


def block_candidates(ipage: torch.Tensor, qpage: torch.Tensor, nblk: int) -> torch.Tensor:
    """[S, nblk]: block b holds an image token of the query's page (rows without any such block: all True)."""
    pad = nblk * BLOCK - ipage.numel()
    ip = F.pad(ipage, (0, pad), value=-1).view(nblk, BLOCK)
    pages = torch.unique(qpage[qpage >= 0])
    cand = torch.ones(qpage.numel(), nblk, dtype=torch.bool)
    for pg in pages.tolist():  # one row pattern per page
        c = (ip == pg).any(-1)
        if bool(c.any()):
            cand[qpage == pg] = c
    return cand


# ------------------------------------------------------------------------------------------------ router
def entmax15(X: torch.Tensor) -> torch.Tensor:
    X = (X - X.max(-1, keepdim=True).values) / 2
    Xs, _ = torch.sort(X, descending=True, dim=-1)
    rho = torch.arange(1, X.shape[-1] + 1, dtype=X.dtype)
    mean = Xs.cumsum(-1) / rho
    mean_sq = (Xs ** 2).cumsum(-1) / rho
    ss = rho * (mean_sq - mean ** 2)
    delta = ((1 - ss) / rho).clamp(min=0)
    tau = mean - torch.sqrt(delta)
    support = (tau <= Xs).sum(-1, keepdim=True).clamp(min=1)
    tau_star = tau.gather(-1, support - 1)
    return (X - tau_star).clamp(min=0) ** 2


def gemma_rms(x: torch.Tensor, w: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
    x32 = torch.nan_to_num(x.float())
    x32 = (x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + eps)).clamp(-ACT_CLAMP, ACT_CLAMP)
    return (x32 * (1.0 + w.float())).clamp(-ACT_CLAMP, ACT_CLAMP)


def rotate(x, cos, sin):
    return x * cos + R.rotate_half(x) * sin


def router_qk(W, l: int, h: torch.Tensor, cos, sin):
    p = R.PFX + f"layers.{l}.self_attn.dash_router."
    iq = gemma_rms(F.linear(h, W.get(p + "q_proj.weight")), W.get(p + "q_norm.weight"))
    ik = gemma_rms(F.linear(h, W.get(p + "k_proj.weight")), W.get(p + "k_norm.weight"))
    return rotate(iq, cos, sin).float(), rotate(ik, cos, sin).float()


def block_summaries(ik: torch.Tensor, head_cls: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
    """kbar [nblk, 128] and block-nonempty [nblk] over keys ik [S, 128]."""
    S = ik.shape[0]
    nblk = -(-S // BLOCK)
    kk = F.pad(ik, (0, 0, 0, nblk * BLOCK - S)).view(nblk, BLOCK, IDX_D)
    real = F.pad(torch.ones(S, dtype=torch.bool), (0, nblk * BLOCK - S)).view(nblk, BLOCK)
    aw = ((kk * head_cls.float()).sum(-1) / math.sqrt(IDX_D)).clamp(-ACT_CLAMP, ACT_CLAMP)
    neg = torch.finfo(aw.dtype).min
    rmax = torch.where(real, aw, torch.full_like(aw, neg)).amax(-1, keepdim=True)
    rmax = torch.where(real.any(-1, keepdim=True), rmax, torch.zeros_like(rmax))
    e = torch.exp(aw - rmax) * real.float()
    w = e / e.sum(-1, keepdim=True).clamp_min(1e-6)
    return (w[..., None] * kk).sum(1), real.any(-1)


def route(iq: torch.Tensor, kbar: torch.Tensor, nonempty: torch.Tensor, q_pos: torch.Tensor,
          cand: Optional[torch.Tensor]):
    """-> per query: selected block ids [n, K], bias [n, K], valid [n, K]."""
    nblk = kbar.shape[0]
    z = ((iq @ kbar.t()) / math.sqrt(IDX_D)).clamp(-ACT_CLAMP, ACT_CLAMP)
    qblk = q_pos // BLOCK
    keep = (torch.arange(nblk)[None, :] <= (qblk[:, None] - LOCAL_BLOCKS)) & nonempty[None, :]
    sc = z.masked_fill(~keep, SCORE_NEG)
    remote = sc > SCORE_NEG * 0.5
    c = remote if cand is None else (remote & cand)
    c = torch.where(~c.any(-1, keepdim=True), remote, c)
    x = torch.where(c, sc * IDX_SCALE, torch.full_like(sc, ENTMAX_NEG))  # = iq . kbar
    M = max(1, min(TOPM, nblk))
    xv, xi = x.topk(M, -1)
    prior = entmax15(xv)
    is_c = c.gather(-1, xi)
    K = max(1, min(TOPK, M))
    xi, prior, valid = xi[:, :K], prior[:, :K], is_c[:, :K]
    logp = torch.log(prior.clamp_min(FLOOR))
    cnt = valid.sum(-1, keepdim=True).clamp(min=1)
    mu = torch.where(valid, logp, torch.zeros_like(logp)).sum(-1, keepdim=True) / cnt
    bias = torch.where(valid, (logp - mu) / SIGMA, torch.zeros_like(logp))
    return xi, bias, valid


def attend(q, K, V, sel, bias, valid, q_pos):
    """q [H, n, 128], K / V [H, S, 128]; the selected blocks + the local window (fp32)."""
    S = K.shape[1]
    nblk = -(-S // BLOCK)
    kpos = torch.arange(S)
    src = torch.where(valid, bias, torch.full_like(bias, MASK_NEG))
    blk = torch.full((q.shape[1], nblk), MASK_NEG).scatter(-1, sel, src.float())
    base = blk.index_select(-1, kpos // BLOCK)
    qp = q_pos[:, None]
    causal = kpos[None, :] <= qp
    local = causal & (kpos[None, :] > (qp - LOCAL_WINDOW))
    keep = causal & (local | (base > MASK_NEG * 0.5))
    m = torch.where(local, torch.zeros_like(base), base).masked_fill(~keep, float("-inf"))
    s = (q.float() @ K.float().transpose(1, 2)) / math.sqrt(R.HD) + m[None]
    return s.softmax(-1) @ V.float()


# ------------------------------------------------------------------------------------------------ decoder
class UocrDecoder(R.Decoder):
    """reference.model.Decoder with the DASH attention and page2d rope. ``ids`` of the prompt are needed for the
    coordinates and the candidate domain; decode steps take their input token for the coordinate state machine."""

    def __init__(self, W, max_pos: int = 32768):
        super().__init__(W, max_pos=1)
        self.ik: List[Optional[torch.Tensor]] = [None] * R.NL

    def begin(self, ids: Sequence[int]):
        self.reset()
        self.ik = [None] * R.NL
        self.ids = list(ids)
        tok, page, st = page_coords(ids)
        self.coord_tok, self.coord_page, self.state = tok, page, st
        self.ipage, self.qpage = prefill_page_ids(ids, st["n_pages"], st["last_img"])
        self.nb_prefill = -(-len(ids) // BLOCK)
        ip = F.pad(self.ipage, (0, self.nb_prefill * BLOCK - len(ids)), value=-1).view(self.nb_prefill, BLOCK)
        has = ip >= 0
        big = torch.where(has, ip, torch.full_like(ip, -1))
        self.bmin = torch.where(has.any(-1), torch.where(has, ip, torch.full_like(ip, 1 << 30)).min(-1).values,
                                torch.full((self.nb_prefill,), -1))
        self.bmax = torch.where(has.any(-1), big.max(-1).values, torch.full((self.nb_prefill,), -1))
        # the official decode state (_uocr_dash_decode_allow): mcum starts at the prompt's <PAGE> count, so the k-th
        # generated <PAGE> (and its text) belongs to image page k - 1
        self.mcum = list(ids).count(PAGE_ID)
        self.pp = st["n_pages"]

    def decode_allow(self, nblk: int) -> Optional[torch.Tensor]:
        qp = self.mcum - 1 - self.pp
        if qp < 0:
            return None
        allow = torch.zeros(nblk, dtype=torch.bool)
        a = (self.bmin <= qp) & (qp <= self.bmax)
        allow[:self.nb_prefill] = a
        return allow if bool(allow.any()) else None

    def layer_dash(self, l: int, x: torch.Tensor, pos0: int, cos, sin, cand) -> torch.Tensor:
        n = x.shape[0]
        p = f"layers.{l}."
        h = R.rms_norm(x, self.g(p + "input_layernorm.weight"))
        q = F.linear(h, self.g(p + "self_attn.q_proj.weight")).view(n, R.NH, R.HD).transpose(0, 1)
        k = F.linear(h, self.g(p + "self_attn.k_proj.weight")).view(n, R.NH, R.HD).transpose(0, 1)
        v = F.linear(h, self.g(p + "self_attn.v_proj.weight")).view(n, R.NH, R.HD).transpose(0, 1)
        q, k = rotate(q, cos, sin), rotate(k, cos, sin)
        iq, ik = router_qk(self.W, l, h, cos, sin)
        if pos0 == 0:
            self.k[l], self.v[l], self.ik[l] = k, v, ik
        else:
            self.k[l] = torch.cat([self.k[l], k], 1)
            self.v[l] = torch.cat([self.v[l], v], 1)
            self.ik[l] = torch.cat([self.ik[l], ik], 0)
        kbar, nonempty = block_summaries(self.ik[l], self.g(p + "self_attn.dash_router.head_cls"))
        q_pos = torch.arange(pos0, pos0 + n)
        sel, bias, valid = route(iq, kbar, nonempty, q_pos, cand)
        o = attend(q, self.k[l], self.v[l], sel, bias, valid, q_pos).transpose(0, 1).reshape(n, R.D)
        x = x + F.linear(o.to(x.dtype), self.g(p + "self_attn.o_proj.weight"))
        h = R.rms_norm(x, self.g(p + "post_attention_layernorm.weight"))
        return x + (self._mlp(h, p + "mlp.") if l == 0 else self._moe(l, h))

    def prefill(self, rows: torch.Tensor, ids: Sequence[int]) -> torch.Tensor:
        self.begin(ids)
        cos, sin = rope2d(self.coord_tok, self.coord_page)
        nblk = -(-len(ids) // BLOCK)
        cand = block_candidates(self.ipage, self.qpage, nblk)
        x = rows
        for l in range(R.NL):
            x = self.layer_dash(l, x, 0, cos, sin, cand)
        self.n = x.shape[0]
        return F.linear(R.rms_norm(x[-1:], self.g("norm.weight")), self.W.get("lm_head.weight"))[0].float()

    def step(self, token: int) -> torch.Tensor:
        pos = self.n
        self.mcum += int(token == PAGE_ID)
        t, pg = decode_coord(self.state, token)
        cos, sin = rope2d(torch.tensor([t]), torch.tensor([pg]))
        nblk = -(-(pos + 1) // BLOCK)
        allow = self.decode_allow(nblk)
        cand = None if allow is None else allow[None, :nblk]
        x = self.embed([token])
        for l in range(R.NL):
            x = self.layer_dash(l, x, pos, cos, sin, cand)
        self.n = pos + 1
        return F.linear(R.rms_norm(x, self.g("norm.weight")), self.W.get("lm_head.weight"))[0].float()


def page_guard(logits: torch.Tensor, gen: List[int], expected: int, st: dict, eos: int = 1,
               max_page_tokens: int = 20000) -> torch.Tensor:
    """The official page-count guard (EOS banned until every page has its <PAGE>; per-page cap)."""
    if expected <= 0:
        return logits
    n = len(gen)
    if n > st["scanned"]:
        tail = gen[st["scanned"]:n]
        m = tail.count(PAGE_ID)
        if m:
            st["marker_cum"] += m
            st["page_len"] = tail[::-1].index(PAGE_ID)
        else:
            st["page_len"] += len(tail)
        st["scanned"] = n
    mc = st["marker_cum"]
    if mc > expected:
        keep = logits[eos].clone()
        logits[:] = -float("inf")
        logits[eos] = keep
    elif 0 < max_page_tokens <= st["page_len"]:
        tid = PAGE_ID if mc < expected else eos
        keep = logits[tid].clone()
        logits[:] = -float("inf")
        logits[tid] = keep
    elif mc < expected:
        logits[eos] = -float("inf")
    return logits


def generate(dec: UocrDecoder, rows: torch.Tensor, ids: Sequence[int], max_new: int, eos: int = 1,
             record: Optional[dict] = None) -> List[int]:
    logits = dec.prefill(rows, ids)
    expected = list(ids).count(PAGE_ID)
    st = {"marker_cum": 0, "scanned": 0, "page_len": 0}
    gen: List[int] = []
    for _ in range(max_new):
        if record is not None:
            record.setdefault("logits", []).append(logits)
        lg = page_guard(logits.clone(), gen, expected, st, eos)
        t = int(lg.argmax())
        gen.append(t)
        if t == eos:
            break
        logits = dec.step(t)
    return gen