# SPDX-License-Identifier: Apache-2.0 """The DeepSeek-OCR family on one p150: vision encoder (ttnn, traced per view) + decoder engine (ttnn prefill + the DEC-MoE megakernel decode, or the ttnn decode), one request at a time (batch 1). dev = DsocrDevice(device, model_dir, DeviceConfig(...)) # builds the engines, captures the traces for tok in dev.generate(prep, max_new, Sampling(...), NGram(...)): # prep = frontend.prepare(...) ... dev.timings() # vision / prefill / ttft / decode ms, tokens, tokens/s of the last request No-repeat n-gram rule (the official HF ``infer``: ``no_repeat_ngram_size=20`` over prompt + output; the vLLM recipe: size 30, window 90, whitelist {, }) is applied EXACTLY with the device sampler: the megakernel decodes greedy chunks; the host checks every new token against the rule (O(1) per token with an n-gram index); a token that the rule would have banned rolls the request back to that step and replays it with the step's banned ids in STATE (the MM cores mask them before the candidate lists). Without violations (the normal case) there is no host round trip per token. """ from __future__ import annotations import os import time from dataclasses import dataclass, field, replace from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple import torch from .. import frontend as FE from ..reference import model as R @dataclass(frozen=True) class Sampling: temperature: float = 0.0 top_k: int = 0 top_p: float = 1.0 repetition_penalty: float = 1.0 seed: Optional[int] = None @property def greedy(self) -> bool: return self.temperature <= 0.0 @dataclass(frozen=True) class NGram: size: int = 20 # 0 = off window: int = 0 # 0 = the whole sequence (HF); > 0 = the last `window` tokens (vLLM) whitelist: Tuple[int, ...] = () @dataclass class DeviceConfig: variant: str = "deepseek-ocr" modes: Tuple[str, ...] = ("tiny", "small", "base", "large", "gundam") max_crops: int = 9 max_context: int = 8192 # KV cache rows (prompt + generated; with a window: largest prompt + window) window: int = 0 # decode attention window (schift-ocr-1-beta: 128; 0 = full causal) max_positions: int = 0 # with a window: positions a request may reach (prompt + generated); 0 = KV rows engine_dec: str = "ttnn" # ttnn (default: D20) | mk (the DEC-MoE megakernel: experimental, can hang) mk_recipe: str = "bfp8" # bfp8 (layers bfp8 + head bf16) | bfp8h8 | bf16 mk_attk: int = 4 mk_batch: int = 1 # launches per poll: 1 = one synchronized launch per token (back-to-back launches # are not yet proven on this program: logs/dsocr/FAULTS.md #1) vis_wdtype: str = "bf16" vis_fidelity: str = "HiFi4" pre_mlp: str = "bfp8" pre_experts: str = "bfp8" pre_fidelity: str = "HiFi2" prefill_buckets: Tuple[int, ...] = () max_prompt_text: int = 512 trace: bool = True k_max: int = 64 sparse_decode: bool = True # ttnn decode MoE over the 6 gathered experts (ttnn.embedding row gathers) tile_chunk: int = 4 # Gundam tiles per vision run (views (tile, 1 .. tile_chunk)) class NGramIndex: """Incremental banned-token sets of the no-repeat n-gram rule over a growing sequence.""" def __init__(self, ng: NGram, prompt: Sequence[int]): self.ng = ng self.seq: List[int] = list(prompt) self.idx: Dict[tuple, set] = {} n = ng.size if n > 0 and ng.window <= 0: for i in range(len(self.seq) - n + 1): self.idx.setdefault(tuple(self.seq[i:i + n - 1]), set()).add(self.seq[i + n - 1]) def banned(self) -> List[int]: """Ids banned for the NEXT token.""" n = self.ng.size if n <= 0 or len(self.seq) + 1 < n: return [] if self.ng.window > 0: return R.banned_ngram_tokens(self.seq, n, self.ng.window, self.ng.whitelist) key = tuple(self.seq[len(self.seq) - n + 1:]) out = self.idx.get(key, ()) wl = set(self.ng.whitelist) return sorted(t for t in out if t not in wl) def push(self, t: int): n = self.ng.size self.seq.append(int(t)) if n > 0 and self.ng.window <= 0 and len(self.seq) >= n: self.idx.setdefault(tuple(self.seq[-n:-1]), set()).add(self.seq[-1]) def pop(self): """Undo the last push (rollback).""" n = self.ng.size if n > 0 and self.ng.window <= 0 and len(self.seq) >= n: key = tuple(self.seq[-n:-1]) s = self.idx.get(key) # another occurrence of the same n-gram may exist earlier: recount (rare path) if s is not None: t = self.seq[-1] still = any(tuple(self.seq[i:i + n - 1]) == key and self.seq[i + n - 1] == t for i in range(len(self.seq) - n)) if not still: s.discard(t) self.seq.pop() def default_prefill_buckets(cfg: DeviceConfig, v: FE.Variant) -> List[int]: toks = [] for m in cfg.modes: b, s, c = FE.mode_params(v, m) if c: grids = [(i, j) for i in range(1, cfg.max_crops + 1) for j in range(1, cfg.max_crops + 1) if 2 <= i * j <= cfg.max_crops] toks.append(max(FE.image_token_count(v, b, s, True, gr) for gr in grids)) toks.append(FE.image_token_count(v, b, s, True, (1, 1))) else: toks.append(FE.image_token_count(v, b, s, False, (1, 1))) out = set() for t in toks: L = t + 32 # + BOS + a typical task prompt out.add(-(-L // 128) * 128) out.add(-(-(t + cfg.max_prompt_text) // 128) * 128) if v.crop_max > 16: # up to 32 tiles (schift-ocr-1-beta): a bucket every 512 rows from 1024 (config.FILL_STEP) out.update(range(1024, max(out), 512)) return sorted(out) class DsocrDevice: dash = False # Unlimited-OCR-2 (DASH attention decoder) def __init__(self, device, model_dir: str, cfg: DeviceConfig, log=print): import ttnn self.ttnn, self.device, self.cfg, self.log = ttnn, device, cfg, log self.variant = FE.VARIANTS[cfg.variant] self.W = R.Weights(model_dir) t0 = time.time() views = set() for m in cfg.modes: b, s, c = FE.mode_params(self.variant, m) if c: views.add((b, 1)) # tiles run in chunks of at most tile_chunk per traced view: the views' one-hot permutation tables # grow with the square of the batch (16 tiles in one view would need ~2.5 GB of DRAM) for n in range(1, min(cfg.tile_chunk, cfg.max_crops) + 1): views.add((self.variant.tile, n)) else: views.add((s, 1)) self.views = sorted(views) self.dash = cfg.variant == FE.UOCR2.name if cfg.variant in ("deepseek-ocr", "deepseek-ocr-2", "unlimited-ocr-2", "schift-ocr-1-beta"): from .ttnn_vision import TtnnDeepEncoder # Unlimited-OCR-2's and schift-ocr-1-beta's DeepEncoder is DeepSeek-OCR's (same code, their own weights) self.vis = TtnnDeepEncoder(device, self.W, self.views, wdtype=cfg.vis_wdtype, fidelity=cfg.vis_fidelity, log=log, variant="deepseek-ocr-2" if cfg.variant == "deepseek-ocr-2" else "deepseek-ocr") else: raise NotImplementedError(f"vision encoder of {cfg.variant}") t1 = time.time() self.buckets = list(cfg.prefill_buckets) or default_prefill_buckets(cfg, self.variant) pp = dict(mlp=cfg.pre_mlp, experts=cfg.pre_experts, pre_fid=cfg.pre_fidelity) if self.dash: from .ttnn_dash import TtnnDashDecoder if cfg.engine_dec != "ttnn": raise ValueError("Unlimited-OCR-2: the decoder engine is ttnn (DASH attention; no megakernel yet)") self.dec = TtnnDashDecoder(device, self.W, self.buckets, cfg.max_context, mlp_dtype=cfg.pre_mlp, expert_dtype=cfg.pre_experts, pre_fidelity=cfg.pre_fidelity, sparse_decode=cfg.sparse_decode) elif cfg.engine_dec == "mk": if cfg.window: # research/dsocr/patches/mk_moe_nexp72_window.patch (prepared, not enabled) raise ValueError(f"{cfg.variant}: the decode megakernel has no decode window; use dec=ttnn") from .mk_moe.engine import MkDecoder from .mk_moe.program import RECIPES self.dec = MkDecoder(device, self.W, self.buckets, cfg.max_context, recipe=RECIPES[cfg.mk_recipe], batch=cfg.mk_batch, attk=cfg.mk_attk, k_max=cfg.k_max, pre_precision=pp, log=log) else: from .ttnn_decoder import TtnnDecoder self.dec = TtnnDecoder(device, self.W, self.buckets, cfg.max_context, window=cfg.window, mlp_dtype=cfg.pre_mlp, expert_dtype=cfg.pre_experts, pre_fidelity=cfg.pre_fidelity, sparse_decode=cfg.sparse_decode) self.embed = self.W.get(R.PFX + "embed_tokens.weight", cache=False).to(torch.bfloat16) t2 = time.time() if cfg.trace: # every eager warmup (compiles; creates lazily allocated persistent buffers) BEFORE the first capture, # then the captures back to back, no device allocation after them (FAULTS.md #3) self.vis.warmup() self.dec.warmup() ttnn.synchronize_device(device) self.vis.capture() self.dec.capture() ttnn.synchronize_device(device) log(f"[dsocr] engines: vision {t1 - t0:.0f} s ({self.views}), decoder {t2 - t1:.0f} s (buckets " f"{self.buckets}), traces {time.time() - t2:.0f} s") self._t: Dict[str, Any] = {} @property def max_prompt(self) -> int: return self.buckets[-1] @property def max_context(self) -> int: return self.cfg.max_positions if self.cfg.window else self.cfg.max_context def room(self, prompt_len: int) -> int: """Tokens a prompt of ``prompt_len`` rows may generate: KV rows left, or with a decode window the positions left (the KV ring does not grow).""" return max(0, self.max_context - prompt_len) # ------------------------------------------------------------------ pieces def image_rows(self, prep: FE.Prepared) -> torch.Tensor: """The [n_image_tokens, 1280] embedding rows (official order: tiles, global, separator).""" g = self.vis.run(torch.from_numpy(prep.global_px)[None])[0] sep = self.W.get(R.PFX + "view_seperator")[None] D = R.D rows = [] if not self.variant.newline: # DeepSeek-OCR-2: tiles (144 rows each), global (256), separator if prep.tiles_px is not None: rows.append(self._tiles(prep.tiles_px).reshape(-1, D)) return torch.cat(rows + [g, sep], 0) nl = self.W.get(R.PFX + "image_newline") if prep.tiles_px is not None: loc = self._tiles(prep.tiles_px) cols, rws = prep.grid n2 = loc.shape[1] h2 = int(n2 ** 0.5) loc = loc.view(rws, cols, h2, h2, D).permute(0, 2, 1, 3, 4).reshape(rws * h2, cols * h2, D) loc = torch.cat([loc, nl[None, None].expand(rws * h2, 1, D)], 1).reshape(-1, D) rows.append(loc) h = int(g.shape[0] ** 0.5) rows.append(torch.cat([g.view(h, h, D), nl[None, None].expand(h, 1, D)], 1).reshape(-1, D)) rows.append(sep) return torch.cat(rows, 0) def _tiles(self, tiles_px) -> torch.Tensor: """Every tile's projected rows [n, rows, D], in chunks of at most ``tile_chunk`` tiles per traced view.""" t = torch.from_numpy(tiles_px) k = max(1, int(self.cfg.tile_chunk)) return torch.cat([self.vis.run(t[i:i + k]) for i in range(0, t.shape[0], k)], 0) def prompt_rows(self, prep: FE.Prepared) -> torch.Tensor: rows = self.embed[torch.tensor(prep.ids)].float() pages = prep.extra.get("pages") if prep.extra else None if pages: # Unlimited-OCR-2: every page's image rows at its own span import dataclasses for pg in pages: one = dataclasses.replace(prep, global_px=pg["global_px"], tiles_px=pg["tiles_px"], grid=pg["grid"], image_pos=pg["image_pos"], extra={}) s0, s1 = pg["image_pos"] rows[s0:s1] = self.image_rows(one) return rows s0, s1 = prep.image_pos rows[s0:s1] = self.image_rows(prep) return rows # ------------------------------------------------------------------ generation def generate(self, prep: FE.Prepared, max_new: int, sampling: Sampling = Sampling(), ngram: NGram = NGram()) -> Iterator[int]: """The tokens of one request. The decode timings (tokens / s) are recorded also when the caller stops early (EOS, max_new_tokens, cancel: the API closes the generator).""" self._t2, self._finished, n = None, False, 0 it = self._generate_inner(prep, max_new, sampling, ngram) try: for t in it: n += 1 yield t finally: it.close() if self._t2 is not None and not self._finished: self._finish(self._t2, n) def _generate_inner(self, prep: FE.Prepared, max_new: int, sampling: Sampling, ngram: NGram) -> Iterator[int]: t0 = time.time() rows = self.prompt_rows(prep) t1 = time.time() L = rows.shape[0] if L > self.max_prompt: raise ValueError(f"prompt of {L} rows exceeds the largest prefill bucket {self.max_prompt}") max_new = max(1, min(int(max_new), self.room(L))) ng = NGramIndex(ngram, prep.ids) if self.dash: self.dec.prefill(rows, L, ids=prep.ids) logits = self.dec.logits_host() elif self.cfg.engine_dec == "mk": logits = self.dec.prefill(rows, L) else: self.dec.prefill(rows, L) logits = self.dec.logits_host() guard = PageGuard(prep.ids) if self.dash else None gen = torch.Generator().manual_seed(int(sampling.seed or 0)) tok0 = _pick(logits, ng.seq, ng.banned(), sampling, gen, self.cfg.k_max, guard, []) t2 = time.time() self._t2 = t2 self._t = {"vision_ms": 1e3 * (t1 - t0), "prefill_ms": 1e3 * (t2 - t1), "ttft_ms": 1e3 * (t2 - t0), "prompt_tokens": L, "image_tokens": prep.image_pos[1] - prep.image_pos[0]} ng.push(tok0) yield tok0 n_out = 1 if tok0 == FE.EOS_ID or max_new <= 1: self._finish(t2, n_out) return if self.cfg.engine_dec != "mk" or self.dash: yield from self._gen_ttnn(L, tok0, max_new, sampling, ng, gen, t2, guard) return eng = self.dec seed = int(sampling.seed) if sampling.seed is not None else int.from_bytes(os.urandom(8), "little") kw = dict(temperature=sampling.temperature, top_k=sampling.top_k, top_p=sampling.top_p, seed=seed, penalty=sampling.repetition_penalty, seen_ids=list(prep.ids) + [tok0]) eng.start(L, tok0, max_new, ntok=1, **kw) from .mk_moe import geometry as G out = [tok0] done = False progress = bool(os.environ.get("DSOCR_MK_PROGRESS")) aborts0, n_prev, stalls, seen_bans = 0, 1, 0, set() self._t["mk_aborts"] = 0 while not done: eng.run_batch() n, done, stop, ring = eng.poll() ab = int(getattr(eng, "last_aborts", 0)) if progress: # soak evidence: the last completed launch before a hang print(f"[mk-progress] n={n} pos={L + n - 1} tok={int(ring[(n - 1) % G.S_TOKENS_MAX])} done={done}" f" aborts={ab}", flush=True) if ab > aborts0: # the hub did not commit (a core aborted): the same step is relaunched self._t["mk_aborts"] = self._t.get("mk_aborts", 0) + (ab - aborts0) aborts0 = ab stalls = stalls + 1 if n == n_prev else 1 if stalls > 3: raise RuntimeError(f"decode megakernel: step {n} aborted {stalls} times in a row") elif n == n_prev and not done: stalls += 1 if stalls > 3: raise RuntimeError(f"decode megakernel: no progress at step {n}") else: stalls = 0 n_prev = n j = len(out) rollback = None while j < n: t = int(ring[j % G.S_TOKENS_MAX]) bans = ng.banned() if t in bans: rollback = (j, bans) break ng.push(t) out.append(t) yield t j += 1 if rollback is not None: j, bans = rollback key = (j, int(ring[j % G.S_TOKENS_MAX])) if key in seen_bans: # the replay produced the banned id again (e.g. NaN logits): do not loop raise RuntimeError(f"decode megakernel: step {j} keeps producing banned token {key[1]}") seen_bans.add(key) aborts0 = 0 # eng.start rewrites STATE (S_ABORTS = 0) # replay step j with its banned ids (the step's input is out[j - 1] at cache index L + j - 1) eng.start(L, out[-1], max_new, ntok=j, ban_step=j, bans=bans, **{k: v for k, v in kw.items() if k != "seen_ids"}) done = False self._finish(t2, len(out)) def _gen_ttnn(self, L, tok0, max_new, sampling, ng, gen, t2, guard=None): out = [tok0] while len(out) < max_new: self.dec.step(out[-1], L + len(out) - 1) t = _pick(self.dec.logits_host(), ng.seq, ng.banned(), sampling, gen, self.cfg.k_max, guard, out) ng.push(t) out.append(t) yield t if t == FE.EOS_ID: break self._finish(t2, len(out)) def _finish(self, t2, n): self._finished = True dt = time.time() - t2 self._t.update(decode_ms=1e3 * dt, tokens=n, tokens_per_s=(n - 1) / dt if dt > 0 and n > 1 else 0.0) def timings(self) -> Dict[str, Any]: return dict(self._t) @property def info(self) -> Dict[str, Any]: return {"engine": {"vision": "ttnn", "prefill": "ttnn", "decode": self.cfg.engine_dec}, "precision": {"decode": self.cfg.mk_recipe if self.cfg.engine_dec == "mk" else "ttnn", "vision": self.cfg.vis_wdtype}, "views": self.views, "buckets": self.buckets} def close(self): for e in (getattr(self, "vis", None), getattr(self, "dec", None)): if e is not None: try: e.release() except Exception: # noqa: BLE001 pass class PageGuard: """Unlimited-OCR-2's page-count guard (the official ``_uocr_page_count_guard``, on by default): EOS is banned until the output has one ```` per prompt page; past that only EOS; a page longer than ``max_page_tokens`` is closed.""" def __init__(self, prompt_ids: Sequence[int], max_page_tokens: int = 20000): from ..reference import uocr2 as U self.U = U self.expected = list(prompt_ids).count(U.PAGE_ID) self.max_page_tokens = int(max_page_tokens) self.st = {"marker_cum": 0, "scanned": 0, "page_len": 0} def __call__(self, logits: torch.Tensor, gen: Sequence[int]) -> torch.Tensor: g = gen if isinstance(gen, list) else list(gen) return self.U.page_guard(logits, g, self.expected, self.st, FE.EOS_ID, self.max_page_tokens) def _pick(logits: torch.Tensor, seen: Sequence[int], banned: Sequence[int], sp: Sampling, gen: torch.Generator, k_max: int = 64, guard=None, out=None) -> int: """The next token on the host, in the order of ``backends.pick_token`` (HF): the repetition penalty over the prompt + the output, the n-gram bans, Unlimited-OCR-2's page guard, then greedy argmax or sampling from at most ``k_max`` candidates (``DSOCR_K_MAX``, as the decode megakernel's sampler: ``top_k`` 0 = ``k_max``).""" z = logits.float().clone() if sp.repetition_penalty != 1.0 and len(seen): idx = torch.as_tensor(sorted(set(int(t) for t in seen)), dtype=torch.long) s = z[idx] z[idx] = torch.where(s < 0, s * sp.repetition_penalty, s / sp.repetition_penalty) if len(banned): z[torch.as_tensor(list(banned), dtype=torch.long)] = float("-inf") if guard is not None: z = guard(z, out if out is not None else []) if sp.greedy: return int(z.argmax()) k = min(sp.top_k, k_max) if sp.top_k and sp.top_k > 0 else k_max return _sample(z, replace(sp, top_k=k), gen) def _sample(lg: torch.Tensor, sp: Sampling, gen: torch.Generator) -> int: x = lg.float() / max(sp.temperature, 1e-6) if sp.top_k and sp.top_k > 0: v, _ = x.topk(min(sp.top_k, x.numel())) x = x.masked_fill(x < v[-1], float("-inf")) p = x.softmax(-1) if sp.top_p < 1.0: sv, si = p.sort(descending=True) cum = sv.cumsum(0) drop = cum - sv > sp.top_p sv[drop] = 0 p = torch.zeros_like(p).scatter(0, si, sv) p = p / p.sum() return int(torch.multinomial(p, 1, generator=gen))