# SPDX-License-Identifier: Apache-2.0 """Clean-room CPU reference of the DeepSeek-OCR family (torch only; no transformers, no remote code). Written from the architecture description in research/dsocr/ARCH.md (official files read: deepencoder.py, deepencoderv2.py, modeling_deepseekocr*.py, modeling_deepseekv2.py) and checked against the official fp32 goldens (research/dsocr/golden/check_reference.py). fp32 by default; ``dtype=torch.bfloat16`` emulates bf16 storage. * :class:`Weights`: lazy safetensors access (``get(name)`` -> fp32 tensor, cached). * :func:`sam` (SAM-ViT-B with decomposed rel-pos, windows of 14, neck, net_2 / net_3), :func:`clip_l` (CLIP-L on the SAM features), :func:`qwen2_encoder` (DeepSeek-OCR-2's causal-flow encoder), :func:`image_embeddings` (views -> projector -> the [n, 1280] rows of the image tokens, in the official order). * :class:`Decoder`: the 12-layer MoE decoder (layer 0 dense SwiGLU 6848, layers 1-11: softmax top-6 of 64 routed experts + 2 shared), KV cache, ``prefill`` / ``step`` (routing recorded), greedy ``generate`` with the HF no-repeat n-gram rule. """ from __future__ import annotations import math import os from typing import Dict, List, Optional, Sequence, Tuple import torch import torch.nn.functional as F D, NH, HD, NL = 1280, 10, 128, 12 I_DENSE, I_MOE, N_EXP, TOPK, N_SHARED = 6848, 896, 64, 6, 2 VOCAB = 129280 EPS = 1e-6 THETA = 10000.0 SAM_GLOBAL = (2, 5, 8, 11) PFX = "model." class Weights: def __init__(self, path: str, dtype=torch.float32): import json from safetensors import safe_open self.path = path idx = os.path.join(path, "model.safetensors.index.json") if os.path.exists(idx): wm = json.load(open(idx))["weight_map"] files = sorted(set(wm.values())) else: files = [f for f in os.listdir(path) if f.endswith(".safetensors")] wm = None self._h = {f: safe_open(os.path.join(path, f), framework="pt") for f in files} self._where = {} for f, h in self._h.items(): for k in h.keys(): self._where[k] = f self.dtype = dtype self._cache: Dict[str, torch.Tensor] = {} def keys(self): return self._where.keys() def __contains__(self, k): return k in self._where def get(self, k: str, cache: bool = True) -> torch.Tensor: if k in self._cache: return self._cache[k] t = self._h[self._where[k]].get_tensor(k).to(torch.float32) if self.dtype != torch.float32: t = t.to(self.dtype).float() # storage rounding, fp32 compute if cache: self._cache[k] = t return t def drop(self, prefix: str): for k in [k for k in self._cache if k.startswith(prefix)]: del self._cache[k] # ================================================================================================ vision def bicubic_resize_grid(t: torch.Tensor, size: int) -> torch.Tensor: """[g, g, C] -> [size, size, C], F.interpolate bicubic antialias (align_corners False), fp32.""" x = t.permute(2, 0, 1)[None].float() y = F.interpolate(x, size=(size, size), mode="bicubic", antialias=True, align_corners=False) return y[0].permute(1, 2, 0) def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: max_rel_dist = int(2 * max(q_size, k_size) - 1) if rel_pos.shape[0] != max_rel_dist: r = F.interpolate(rel_pos.float().reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), size=max_rel_dist, mode="linear") r = r.reshape(-1, max_rel_dist).permute(1, 0) else: r = rel_pos qc = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) kc = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) rc = (qc - kc) + (k_size - 1) * max(q_size / k_size, 1.0) return r[rc.long()] def sam_attention(W: Weights, p: str, x: torch.Tensor, nheads: int = 12) -> torch.Tensor: """x [B, H, W, C] (one window or the whole grid) -> [B, H, W, C].""" B, H, Wd, C = x.shape hd = C // nheads qkv = F.linear(x, W.get(p + "qkv.weight"), W.get(p + "qkv.bias")) qkv = qkv.reshape(B, H * Wd, 3, nheads, hd).permute(2, 0, 3, 1, 4) q, k, v = qkv.reshape(3, B * nheads, H * Wd, hd).unbind(0) Rh = get_rel_pos(H, H, W.get(p + "rel_pos_h")) Rw = get_rel_pos(Wd, Wd, W.get(p + "rel_pos_w")) rq = q.reshape(B * nheads, H, Wd, hd) rel_h = torch.einsum("bhwc,hkc->bhwk", rq, Rh) rel_w = torch.einsum("bhwc,wkc->bhwk", rq, Rw) bias = (rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]).reshape(B, nheads, H * Wd, H * Wd) q = q.reshape(B, nheads, H * Wd, hd) k = k.reshape(B, nheads, H * Wd, hd) v = v.reshape(B, nheads, H * Wd, hd) o = F.scaled_dot_product_attention(q, k, v, attn_mask=bias) o = o.reshape(B, nheads, H, Wd, hd).permute(0, 2, 3, 1, 4).reshape(B, H, Wd, C) return F.linear(o, W.get(p + "proj.weight"), W.get(p + "proj.bias")) def window_partition(x: torch.Tensor, ws: int): B, H, Wd, C = x.shape ph, pw = (ws - H % ws) % ws, (ws - Wd % ws) % ws if ph or pw: x = F.pad(x, (0, 0, 0, pw, 0, ph)) Hp, Wp = H + ph, Wd + pw x = x.view(B, Hp // ws, ws, Wp // ws, ws, C).permute(0, 1, 3, 2, 4, 5).reshape(-1, ws, ws, C) return x, (Hp, Wp) def window_unpartition(w: torch.Tensor, ws: int, pad_hw, hw): Hp, Wp = pad_hw H, Wd = hw B = w.shape[0] // (Hp * Wp // ws // ws) x = w.view(B, Hp // ws, Wp // ws, ws, ws, -1).permute(0, 1, 3, 2, 4, 5).reshape(B, Hp, Wp, -1) return x[:, :H, :Wd, :].contiguous() def layernorm2d(x: torch.Tensor, w: torch.Tensor, b: torch.Tensor, eps: float = 1e-6) -> torch.Tensor: u = x.mean(1, keepdim=True) s = (x - u).pow(2).mean(1, keepdim=True) x = (x - u) / torch.sqrt(s + eps) return w[:, None, None] * x + b[:, None, None] def sam(W: Weights, px: torch.Tensor, stages: Optional[dict] = None) -> torch.Tensor: """px [B, 3, S, S] -> [B, C_out, S / 64, S / 64] (C_out 1024 for OCR-1, 896 for OCR-2).""" p = PFX + "sam_model." x = F.conv2d(px.float(), W.get(p + "patch_embed.proj.weight"), W.get(p + "patch_embed.proj.bias"), stride=16) x = x.permute(0, 2, 3, 1) g = x.shape[1] pe = W.get(p + "pos_embed")[0] if pe.shape[0] != g: pe = bicubic_resize_grid(pe, g) x = x + pe[None] for i in range(12): b = p + f"blocks.{i}." sc = x y = F.layer_norm(x, (768,), W.get(b + "norm1.weight"), W.get(b + "norm1.bias"), eps=1e-6) if i in SAM_GLOBAL: y = sam_attention(W, b + "attn.", y) else: H, Wd = y.shape[1], y.shape[2] yw, pad = window_partition(y, 14) yw = sam_attention(W, b + "attn.", yw) y = window_unpartition(yw, 14, pad, (H, Wd)) x = sc + y y = F.layer_norm(x, (768,), W.get(b + "norm2.weight"), W.get(b + "norm2.bias"), eps=1e-6) y = F.linear(y, W.get(b + "mlp.lin1.weight"), W.get(b + "mlp.lin1.bias")) y = F.gelu(y) x = x + F.linear(y, W.get(b + "mlp.lin2.weight"), W.get(b + "mlp.lin2.bias")) if stages is not None: stages[f"sam_block{i}"] = x x = x.permute(0, 3, 1, 2) x = F.conv2d(x, W.get(p + "neck.0.weight")) x = layernorm2d(x, W.get(p + "neck.1.weight"), W.get(p + "neck.1.bias")) x = F.conv2d(x, W.get(p + "neck.2.weight"), padding=1) x = layernorm2d(x, W.get(p + "neck.3.weight"), W.get(p + "neck.3.bias")) x = F.conv2d(x, W.get(p + "net_2.weight"), stride=2, padding=1) x = F.conv2d(x, W.get(p + "net_3.weight"), stride=2, padding=1) return x def clip_l(W: Weights, sam_out: torch.Tensor, stages: Optional[dict] = None) -> torch.Tensor: """sam_out [B, 1024, g, g] -> [B, 1 + g*g, 1024] (CLIP-L transformer output, class token first).""" p = PFX + "vision_model." B = sam_out.shape[0] pe = sam_out.flatten(2).transpose(1, 2) cls = W.get(p + "embeddings.class_embedding").expand(B, 1, -1) x = torch.cat([cls, pe], 1) pos = W.get(p + "embeddings.position_embedding.weight") # [257, 1024] n = x.shape[1] g, g0 = int(math.sqrt(n)), int(math.sqrt(pos.shape[0] - 1)) if g != g0: grid = bicubic_resize_grid(pos[1:].reshape(g0, g0, -1), g).reshape(g * g, -1) pos = torch.cat([pos[:1], grid], 0) x = x + pos[None] x = F.layer_norm(x, (1024,), W.get(p + "pre_layrnorm.weight"), W.get(p + "pre_layrnorm.bias"), eps=1e-5) for i in range(24): b = p + f"transformer.layers.{i}." y = F.layer_norm(x, (1024,), W.get(b + "layer_norm1.weight"), W.get(b + "layer_norm1.bias"), eps=1e-5) qkv = F.linear(y, W.get(b + "self_attn.qkv_proj.weight"), W.get(b + "self_attn.qkv_proj.bias")) q, k, v = qkv.view(B, -1, 3, 16, 64).unbind(2) o = F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)) o = o.transpose(1, 2).reshape(B, -1, 1024) x = x + F.linear(o, W.get(b + "self_attn.out_proj.weight"), W.get(b + "self_attn.out_proj.bias")) y = F.layer_norm(x, (1024,), W.get(b + "layer_norm2.weight"), W.get(b + "layer_norm2.bias"), eps=1e-5) y = F.linear(y, W.get(b + "mlp.fc1.weight"), W.get(b + "mlp.fc1.bias")) y = y * torch.sigmoid(1.702 * y) x = x + F.linear(y, W.get(b + "mlp.fc2.weight"), W.get(b + "mlp.fc2.bias")) return x def rope_cos_sin(positions: torch.Tensor, dim: int, theta: float): """transformers 4.46 default rope: inv_freq fp32, freqs = inv_freq x pos (fp32), emb = cat(freqs, freqs).""" inv = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.int64).float() / dim)) fr = positions.float()[:, None] * inv[None, :] emb = torch.cat([fr, fr], -1) return emb.cos(), emb.sin() def rotate_half(x): h = x.shape[-1] // 2 return torch.cat([-x[..., h:], x[..., :h]], -1) def qwen2_encoder(W: Weights, sam_out: torch.Tensor) -> torch.Tensor: """DeepSeek-OCR-2 causal-flow encoder: sam_out [B, 896, g, g] -> query rows [B, n, 896] (n = g * g).""" p = PFX + "qwen2_model." B = sam_out.shape[0] x = sam_out.flatten(2).transpose(1, 2) n = x.shape[1] q = W.get(p + ("query_768.weight" if n == 144 else "query_1024.weight")) x = torch.cat([x, q[None].expand(B, -1, -1)], 1) S = 2 * n allow = torch.zeros(S, S, dtype=torch.bool) allow[:n, :n] = True allow[n:, :n] = True allow[n:, n:] = torch.ones(n, n).tril().bool() mask = torch.zeros(S, S) mask[~allow] = float("-inf") cos, sin = rope_cos_sin(torch.arange(S), 64, 1e6) mp = p + "model.model." for i in range(24): b = mp + f"layers.{i}." y = rms_norm(x, W.get(b + "input_layernorm.weight")) qh = F.linear(y, W.get(b + "self_attn.q_proj.weight"), W.get(b + "self_attn.q_proj.bias")).view(B, S, 14, 64) kh = F.linear(y, W.get(b + "self_attn.k_proj.weight"), W.get(b + "self_attn.k_proj.bias")).view(B, S, 2, 64) vh = F.linear(y, W.get(b + "self_attn.v_proj.weight"), W.get(b + "self_attn.v_proj.bias")).view(B, S, 2, 64) qh, kh, vh = qh.transpose(1, 2), kh.transpose(1, 2), vh.transpose(1, 2) qh = qh * cos + rotate_half(qh) * sin kh = kh * cos + rotate_half(kh) * sin kh = kh.repeat_interleave(7, 1) vh = vh.repeat_interleave(7, 1) o = F.scaled_dot_product_attention(qh, kh, vh, attn_mask=mask) x = x + F.linear(o.transpose(1, 2).reshape(B, S, 896), W.get(b + "self_attn.o_proj.weight")) y = rms_norm(x, W.get(b + "post_attention_layernorm.weight")) y = F.linear(F.silu(F.linear(y, W.get(b + "mlp.gate_proj.weight"))) * F.linear(y, W.get(b + "mlp.up_proj.weight")), W.get(b + "mlp.down_proj.weight")) x = x + y x = rms_norm(x, W.get(mp + "norm.weight")) return x[:, n:] def view_features(W: Weights, px: torch.Tensor, variant: str, stages: Optional[dict] = None) -> torch.Tensor: """Pixel views [B, 3, S, S] -> projected features [B, n, 1280].""" s = sam(W, px) if variant == "deepseek-ocr-2": f = qwen2_encoder(W, s) else: c = clip_l(W, s) f = torch.cat([c[:, 1:], s.flatten(2).permute(0, 2, 1)], -1) if stages is not None: stages.setdefault("sam", []).append(s) stages.setdefault("feat", []).append(f) out = F.linear(f, W.get(PFX + "projector.layers.weight"), W.get(PFX + "projector.layers.bias")) if stages is not None: stages.setdefault("proj", []).append(out) return out def image_embeddings(W: Weights, global_px, tiles_px, grid: Tuple[int, int], variant: str, stages: Optional[dict] = None) -> torch.Tensor: """The [n_image_tokens, 1280] rows (official order: tiles, global, view separator).""" g = view_features(W, torch.as_tensor(global_px)[None], variant, stages)[0] sep = W.get(PFX + "view_seperator")[None] rows = [] if variant == "deepseek-ocr-2": if tiles_px is not None: loc = view_features(W, torch.as_tensor(tiles_px), variant, stages) rows.append(loc.reshape(-1, D)) rows += [g, sep] return torch.cat(rows, 0) nl = W.get(PFX + "image_newline") if tiles_px is not None: loc = view_features(W, torch.as_tensor(tiles_px), variant, stages) cols, rws = grid n2 = loc.shape[1] h2 = w2 = int(math.isqrt(n2)) loc = loc.view(rws, cols, h2, w2, D).permute(0, 2, 1, 3, 4).reshape(rws * h2, cols * w2, D) loc = torch.cat([loc, nl[None, None].expand(rws * h2, 1, D)], 1).reshape(-1, D) rows.append(loc) h = int(math.isqrt(g.shape[0])) gg = torch.cat([g.view(h, h, D), nl[None, None].expand(h, 1, D)], 1).reshape(-1, D) rows += [gg, sep] return torch.cat(rows, 0) # ================================================================================================ decoder def rms_norm(x: torch.Tensor, w: torch.Tensor, eps: float = EPS) -> torch.Tensor: x32 = x.float() return w * (x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + eps)) class Decoder: """MoE decoder with a KV cache. ``route_log``: per MoE layer call, (layer, ids [n, 6], weights [n, 6]).""" def __init__(self, W: Weights, max_pos: int = 8192, window: int = 0): """``window`` > 0 (schift-ocr-1-beta: 128): a row at or after the prompt (``L0`` rows, set by the prefill ``forward(x, 0)``) sees every prompt row plus the rows of the last ``window`` positions, itself included (the official SlidingWindowLlamaAttention KV ring); prompt rows attend causally.""" self.W = W self.max_pos = max_pos self.window = int(window) self.L0 = 0 self.cos, self.sin = rope_cos_sin(torch.arange(max_pos), HD, THETA) self.k = [None] * NL self.v = [None] * NL self.n = 0 self.route_log: List[Tuple[int, torch.Tensor, torch.Tensor]] = [] self.record_routes = True def g(self, name: str) -> torch.Tensor: return self.W.get(PFX + name) def reset(self): self.k = [None] * NL self.v = [None] * NL self.n = 0 self.route_log = [] def _mlp(self, x, p: str): return F.linear(F.silu(F.linear(x, self.g(p + "gate_proj.weight"))) * F.linear(x, self.g(p + "up_proj.weight")), self.g(p + "down_proj.weight")) def _moe(self, l: int, x: torch.Tensor) -> torch.Tensor: p = f"layers.{l}.mlp." logits = F.linear(x.float(), self.g(p + "gate.weight").float()) scores = logits.softmax(-1, dtype=torch.float32) tw, ti = torch.topk(scores, TOPK, dim=-1, sorted=False) if self.record_routes: self.route_log.append((l, ti.clone(), tw.clone())) y = torch.zeros(x.shape[0], D, dtype=torch.float32) for e in ti.unique().tolist(): rows, slot = (ti == e).nonzero(as_tuple=True) out = self._mlp(x[rows], p + f"experts.{e}.") y.index_add_(0, rows, out.float() * tw[rows, slot][:, None]) return y.to(x.dtype) + self._mlp(x, p + "shared_experts.") def layer(self, l: int, x: torch.Tensor, pos0: int) -> torch.Tensor: n = x.shape[0] p = f"layers.{l}." h = rms_norm(x, self.g(p + "input_layernorm.weight")) q = F.linear(h, self.g(p + "self_attn.q_proj.weight")).view(n, NH, HD).transpose(0, 1) k = F.linear(h, self.g(p + "self_attn.k_proj.weight")).view(n, NH, HD).transpose(0, 1) v = F.linear(h, self.g(p + "self_attn.v_proj.weight")).view(n, NH, HD).transpose(0, 1) cos, sin = self.cos[pos0:pos0 + n], self.sin[pos0:pos0 + n] q = q * cos + rotate_half(q) * sin k = k * cos + rotate_half(k) * sin if self.k[l] is None or pos0 == 0: self.k[l], self.v[l] = k, v else: self.k[l] = torch.cat([self.k[l][:, :pos0], k], 1) self.v[l] = torch.cat([self.v[l][:, :pos0], v], 1) K, V = self.k[l], self.v[l] s = (q @ K.transpose(1, 2)) / math.sqrt(HD) tot = K.shape[1] qi = torch.arange(pos0, pos0 + n)[:, None] ki = torch.arange(tot)[None, :] hide = ki > qi if self.window: hide = hide | ((ki >= self.L0) & (qi - ki >= self.window)) s = s.masked_fill(hide, float("-inf")) o = (s.softmax(-1) @ V).transpose(0, 1).reshape(n, D) x = x + F.linear(o, self.g(p + "self_attn.o_proj.weight")) h = rms_norm(x, self.g(p + "post_attention_layernorm.weight")) x = x + (self._mlp(h, p + "mlp.") if l == 0 else self._moe(l, h)) return x def forward(self, x: torch.Tensor, pos0: int, stages: Optional[dict] = None) -> torch.Tensor: """x [n, D] input rows at positions pos0..pos0+n-1 -> logits of the LAST row [V] (fp32).""" if pos0 == 0: self.L0 = x.shape[0] for l in range(NL): x = self.layer(l, x, pos0) if stages is not None: stages.setdefault("layers", []).append(x[-32:].clone()) self.n = pos0 + x.shape[0] h = rms_norm(x[-1:], self.g("norm.weight")) return F.linear(h, self.W.get("lm_head.weight"))[0].float() def forward_all(self, x: torch.Tensor, prompt_len: Optional[int] = None) -> torch.Tensor: """Teacher-forced logits of every row [n, V] (fresh cache); ``prompt_len``: the rows after it are generated rows (the decode window applies to them).""" self.reset() self.L0 = x.shape[0] if prompt_len is None else int(prompt_len) for l in range(NL): x = self.layer(l, x, 0) self.n = x.shape[0] return F.linear(rms_norm(x, self.g("norm.weight")), self.W.get("lm_head.weight")).float() def embed(self, ids: Sequence[int]) -> torch.Tensor: return self.g("embed_tokens.weight")[torch.as_tensor(list(ids), dtype=torch.long)] def banned_ngram_tokens(seq: Sequence[int], n: int, window: int = 0, whitelist=()) -> List[int]: """HF NoRepeatNGramLogitsProcessor (window 0 = the whole sequence) / the vLLM windowed variant: tokens that would complete an n-gram already present in ``seq``.""" if n <= 0 or len(seq) + 1 < n: return [] s = list(seq) if window <= 0 else list(seq[-window:]) if len(s) + 1 < n: return [] prefix = tuple(seq[len(seq) - n + 1:]) if n > 1 else () out = set() for i in range(len(s) - n + 1): if tuple(s[i:i + n - 1]) == prefix: out.add(s[i + n - 1]) return sorted(t for t in out if t not in set(whitelist)) def generate(dec: Decoder, rows: torch.Tensor, ids: Sequence[int], max_new: int, ngram: int = 20, eos: int = 1, record: Optional[dict] = None) -> List[int]: """Greedy decode from prompt rows [L, D] (prompt ids ``ids`` for the n-gram rule).""" dec.reset() logits = dec.forward(rows, 0) seq = list(ids) out = [] L = rows.shape[0] for s in range(max_new): lg = logits.clone() if record is not None: record.setdefault("logits", []).append(logits) for t in banned_ngram_tokens(seq, ngram): lg[t] = float("-inf") t = int(lg.argmax()) out.append(t) seq.append(t) if t == eos: break logits = dec.forward(dec.embed([t]), L + s) return out