DeepSeek-OCR-2 / code /tt_dsocr /backends.py
changh95's picture
tt-model push deepseek-ocr-2 (container)
c60a316 verified
Raw History Blame Contribute Delete
21.9 kB
# SPDX-License-Identifier: Apache-2.0
# Adapted from this workspace's GLM-OCR bundle (tt_glmocr/backends.py, Apache-2.0).
"""Generation backends of the DeepSeek-OCR family behind one protocol (``DSOCR_BACKEND``):
* :class:`DeviceBackend` (``device``): the p150 engines of ``tt/model.py`` (``DsocrDevice``: ttnn vision encoder,
ttnn prefill, DEC-MoE megakernel or ttnn decode). It never opens or closes the chip itself: the caller passes an
opened device (the server's lifespan opens and closes it on the main thread; ``api.DeepSeekOcr.from_config`` opens
one for Python use). Every device specific lives here, in one place.
* :class:`CpuBackend` (``cpu``): the clean-room CPU reference (``reference/model.py``; Unlimited-OCR-2's DASH decoder
``reference/uocr2.py``; fp32 or bf16 storage); slow (minutes for a Gundam page), for development and checks.
* :class:`FakeBackend` (``fake``): a deterministic stand-in without weights or device (host tests, the image's
verify step): the reply is fixed per task prompt (Unlimited-OCR-2: one ``<PAGE>`` per input page), one token per
step.
The API (``api.py``) does all host work (image decoding, the official views / tiles / prompt ids, detokenization,
stop rules, output formats); a backend only turns a ``frontend.Prepared`` into generated token ids.
Importing this module imports neither torch nor ttnn (``frontend`` imports numpy).
"""
from __future__ import annotations
import os
import re
import time
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence, Tuple
try: # Python >= 3.8
from typing import Protocol
except ImportError: # pragma: no cover
Protocol = object # type: ignore[assignment]
from . import config as C
from . import frontend as FE
@dataclass(frozen=True)
class Sampling:
"""Decoding parameters of one request (validated by the API); mirrors ``tt.model.Sampling``."""
temperature: float = 0.0 # 0 = greedy (the official infer)
top_k: int = 0 # 0 = off
top_p: float = 1.0
repetition_penalty: float = 1.0
seed: Optional[int] = None
@property
def greedy(self) -> bool:
return self.temperature <= 0.0
def as_dict(self) -> Dict[str, Any]:
return {"temperature": self.temperature, "top_k": self.top_k, "top_p": self.top_p,
"repetition_penalty": self.repetition_penalty, "seed": self.seed}
@dataclass(frozen=True)
class NGram:
"""The no-repeat n-gram rule of one request; mirrors ``tt.model.NGram``. ``size`` 0 = off; ``window`` 0 = the
whole sequence (prompt + output: HF ``NoRepeatNGramLogitsProcessor``), > 0 = the last ``window`` tokens (vLLM
``NGramPerReqLogitsProcessor``); ``whitelist`` ids are never banned."""
size: int = 20
window: int = 0
whitelist: Tuple[int, ...] = field(default_factory=tuple)
def as_dict(self) -> Dict[str, Any]:
return {"no_repeat_ngram_size": self.size, "ngram_window": self.window,
"ngram_whitelist": list(self.whitelist)}
#: request presets (``ngram_preset``; which ones a variant offers and its default: ``config.VariantInfo``):
#: ``hf`` = DeepSeek-OCR / DeepSeek-OCR-2's HF ``infer`` (their default), ``vllm`` = DeepSeek-OCR's vLLM recipe,
#: ``off`` = no rule (Unlimited-OCR-2's ``infer`` default), ``sglang`` = Unlimited-OCR-2's SGLang client (size 35,
#: window 128 for one page; the API widens the window to ``SGLANG_MULTIPAGE_WINDOW`` for several pages)
NGRAM_PRESETS = {"hf": NGram(20, 0, ()), "vllm": NGram(30, 90, (128821, 128822)), "off": NGram(0, 0, ()),
"sglang": NGram(35, 128, ())}
SGLANG_MULTIPAGE_WINDOW = 1024
class Backend(Protocol):
"""What the API needs from a backend."""
name: str
max_prompt: int # longest prompt (rows: image tokens + text tokens)
max_context: int # KV positions (prompt + generated)
def room(self, prompt_len: int) -> int:
"""How many tokens a prompt of ``prompt_len`` rows leaves for generation."""
def generate(self, prep: FE.Prepared, max_new: int, sampling: Sampling, ngram: NGram) -> Iterator[int]:
"""Generated token ids, one at a time (the last one may be EOS = 1); stops at EOS or ``max_new``."""
def timings(self) -> Dict[str, Any]:
"""Stage timings of the last :meth:`generate` (ms, tokens, tokens/s)."""
@property
def info(self) -> Dict[str, Any]:
"""``backend``, ``engine``, ``precision``, ``device`` for ``/info``."""
def close(self) -> None:
"""Release what the backend holds (traces, buffers); never closes a device it did not open."""
# ================================================================================================ host sampling
def pick_token(logits, seen: Sequence[int], banned: Sequence[int], sp: Sampling, gen) -> int:
"""HF order on the host: repetition penalty (over prompt + output) -> n-gram bans -> greedy argmax, or temperature
-> top-k -> top-p -> multinomial (``gen``: a seeded torch.Generator)."""
import torch
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 sp.greedy:
return int(torch.argmax(z))
z = z / sp.temperature
if sp.top_k > 0:
kth = torch.topk(z, min(sp.top_k, z.numel())).values[-1]
z[z < kth] = -float("inf")
if sp.top_p < 1.0:
sz, si = torch.sort(z, descending=True)
pr = torch.softmax(sz, -1)
z[si[pr.cumsum(-1) - pr > sp.top_p]] = -float("inf")
return int(torch.multinomial(torch.softmax(z, -1), 1, generator=gen))
# ================================================================================================ fake
class FakeBackend:
"""Deterministic stand-in: the reply depends only on the prompt (see :meth:`reply`); its tokens (the tokenizer's
encoding) are yielded one per step, then EOS (id 1)."""
name = "fake"
TEXT = "Fake OCR: café, 你好 🙂 — line 1."
MARKDOWN = ("<|ref|>title<|/ref|><|det|>[[52, 40, 948, 98]]<|/det|>\n# Fake Report\n\n"
"<|ref|>text<|/ref|><|det|>[[52, 120, 948, 300]]<|/det|>\n" + TEXT + " Let $a \\coloneqq b$.\n\n"
"<|ref|>image<|/ref|><|det|>[[100, 400, 500, 800]]<|/det|>\n\n"
"<|ref|>table<|/ref|><|det|>[[52, 820, 948, 960]]<|/det|>\n"
"<table><tr><td>Region</td><td>地区</td></tr><tr><td>North</td><td>1,204</td></tr></table>")
OCR = "<|ref|>" + TEXT + "<|/ref|><|det|>[[12, 40, 980, 950]]<|/det|>"
FIGURE = "Fake figure: a bar chart of quarterly sales."
DESCRIBE = "Fake description: a white image with one line of black text."
LOCATE_BOX = "[[100, 200, 300, 400]]"
#: Unlimited-OCR-2: one page of output (``{n}`` = the page number); the reply repeats it once per input page
PAGE = ("<PAGE><BLOCK>title[52, 40, 948, 98]<FORK># Fake Page {n}<BLOCK>text[52, 120, 948, 300]<FORK>" + TEXT +
"<BLOCK>image[100, 400, 500, 800]<FORK><BLOCK>equation[52, 820, 948, 960]<FORK>$$\nx = {n}\n$$")
#: seconds per generated token (tests set it to exercise the queue)
token_delay_s = 0.0
def __init__(self, cfg: C.ServeConfig, tok):
self.cfg, self.tok = cfg, tok
self.max_prompt = cfg.pre_buckets[-1]
self.max_context = cfg.max_context if cfg.info.window else cfg.kv_positions # positions (decode window)
self._t: Dict[str, Any] = {}
self.generated = 0
self.last_ngram: Optional[NGram] = None
def room(self, prompt_len: int) -> int:
return self.max_context - int(prompt_len)
#: schift-ocr-1-beta's det-only block format (its ``<image>document parsing.`` prompt)
DET = ("<|det|>title [52, 40, 948, 98]<|/det|>가짜 문서 제목\n<|det|>text [52, 120, 948, 300]<|/det|>" + TEXT + "\n"
"<|det|>table [52, 320, 948, 600]<|/det|><table><tr><td>항목</td><td>값</td></tr><tr><td>a</td><td>1</td>"
"</tr></table>")
@classmethod
def reply(cls, prompt: str) -> str:
"""The fake output for a normalized prompt (``frontend.normalize_prompt``)."""
t = prompt.strip()
if t == FE.normalize_prompt(C.SCHIFT_PROMPT):
return cls.DET
presets = {FE.normalize_prompt(v): k for k, v in FE.TASKS.items() if k != "locate"}
task = presets.get(t)
if task == "markdown":
return cls.MARKDOWN
if task == "ocr":
return cls.OCR
if task == "free":
return cls.TEXT
if task == "figure":
return cls.FIGURE
if task == "describe":
return cls.DESCRIBE
m = re.fullmatch(r"<image>\nLocate <\|ref\|>(.*)<\|/ref\|> in the image\.", t, re.DOTALL)
if m:
return "<|ref|>" + m.group(1) + "<|/ref|><|det|>" + cls.LOCATE_BOX + "<|/det|>"
return "Fake reply to: " + t.replace(FE.IMAGE_TOKEN, "").strip()
@classmethod
def reply_pages(cls, prompt: str, n_pages: int) -> str:
"""Unlimited-OCR-2: the fake output for an expanded prompt (``frontend.uocr2_prompt``) of ``n_pages``
pages: ``PAGE`` per page for the ``parse`` prompt, else one ``<PAGE>`` + a fixed text per page."""
t = prompt.strip()
instr = t.replace(FE.PAGE_TOKEN, "").replace(FE.IMAGE_TOKEN, "").strip()
if instr == FE.UOCR2_DEFAULT_PROMPT:
return "".join(cls.PAGE.format(n=i + 1) for i in range(n_pages))
return "".join(f"{FE.PAGE_TOKEN}Fake reply to: {instr} (page {i + 1})" for i in range(n_pages))
def generate(self, prep: FE.Prepared, max_new: int, sampling: Sampling, ngram: NGram) -> Iterator[int]:
t0 = time.perf_counter()
self.last_ngram = ngram
pages = (prep.extra or {}).get("pages")
text = self.reply_pages(prep.prompt, len(pages)) if pages is not None else self.reply(prep.prompt)
ids = list(self.tok.encode(text)) + [FE.EOS_ID]
n_img = prep.image_pos[1] - prep.image_pos[0]
self._t = {"vision_ms": 0.0, "prefill_ms": 0.0, "ttft_ms": 0.0, "decode_ms": 0.0, "tokens": 0,
"tokens_per_s": 0.0, "prompt_tokens": len(prep.ids), "image_tokens": n_img}
try:
for i, t in enumerate(ids[:max(1, int(max_new))]):
if self.token_delay_s:
time.sleep(self.token_delay_s)
self._t["tokens"] = i + 1
self.generated += 1
yield int(t)
finally:
self._t["decode_ms"] = 1e3 * (time.perf_counter() - t0)
def timings(self) -> Dict[str, Any]:
return dict(self._t)
@property
def info(self) -> Dict[str, Any]:
return {"backend": "fake", "engine": {"vis": "fake", "pre": "fake", "dec": "fake"}, "precision": None,
"device": None}
def close(self) -> None:
pass
# ================================================================================================ CPU reference
class CpuBackend:
"""The clean-room CPU reference (fp32 by default: bit-exact with the official fp32 model on the goldens), greedy
or sampled on the host, with the exact no-repeat n-gram rule. Slow: development and small checks only."""
name = "cpu"
def __init__(self, cfg: C.ServeConfig, model_dir: str, log: Callable[[str], None] = print):
import torch
from .reference import model as R
self.torch, self.R, self.cfg = torch, R, cfg
log(f"Loading weights from {model_dir} ({cfg.cpu_dtype}, CPU reference)")
self.W = R.Weights(model_dir, torch.float32 if cfg.cpu_dtype == "fp32" else torch.bfloat16)
self.max_prompt = cfg.pre_buckets[-1] # the device's limits, for parity
self.max_context = cfg.max_context if cfg.info.window else cfg.kv_positions # positions (decode window)
self._t: Dict[str, Any] = {}
def room(self, prompt_len: int) -> int:
return self.max_context - int(prompt_len)
def generate(self, prep: FE.Prepared, max_new: int, sampling: Sampling, ngram: NGram) -> Iterator[int]:
if (prep.extra or {}).get("pages") is not None:
yield from self._generate_pages(prep, max_new, sampling, ngram)
return
torch, R, W = self.torch, self.R, self.W
from .tt.model import NGram as TNGram
from .tt.model import NGramIndex
L = len(prep.ids)
s0, s1 = prep.image_pos
T = self._t = {"vision_ms": 0.0, "prefill_ms": 0.0, "ttft_ms": 0.0, "decode_ms": 0.0, "tokens": 0,
"tokens_per_s": 0.0, "prompt_tokens": L, "image_tokens": s1 - s0}
t0 = time.perf_counter()
with torch.inference_mode():
emb = R.image_embeddings(W, prep.global_px, prep.tiles_px, prep.grid, self.cfg.variant)
t1 = time.perf_counter()
dec = R.Decoder(W, max_pos=self.max_context, window=self.cfg.info.window)
dec.record_routes = False
with torch.inference_mode():
rows = dec.embed(prep.ids).float().clone()
rows[s0:s1] = emb
lg = dec.forward(rows, 0)
t2 = time.perf_counter()
T["vision_ms"], T["prefill_ms"] = 1e3 * (t1 - t0), 1e3 * (t2 - t1)
gen = torch.Generator().manual_seed(int(sampling.seed)) if sampling.seed is not None else None
ng = NGramIndex(TNGram(ngram.size, ngram.window, tuple(ngram.whitelist)), prep.ids)
n = 0
td = time.perf_counter()
try:
while True:
with torch.inference_mode():
t = pick_token(lg, ng.seq, ng.banned(), sampling, gen)
n += 1
ng.push(t)
T["tokens"] = n
if n == 1:
T["ttft_ms"] = 1e3 * (time.perf_counter() - t0)
td = time.perf_counter()
yield t
if t == FE.EOS_ID or n >= max_new:
return
with torch.inference_mode():
lg = dec.forward(dec.embed([t]).float(), L + n - 1)
finally:
dt = time.perf_counter() - td
T["decode_ms"] = 1e3 * dt
T["tokens_per_s"] = (n - 1) / dt if dt > 0 and n > 1 else 0.0
def _generate_pages(self, prep: FE.Prepared, max_new: int, sampling: Sampling, ngram: NGram) -> Iterator[int]:
"""Unlimited-OCR-2 (``reference/uocr2.py``): DeepSeek-OCR's DeepEncoder per page, the DASH decoder; per step
the n-gram bans, then the official page-count guard (``max_page_tokens`` = ``config.MAX_PAGE_TOKENS``), then
the pick (``reference.uocr2.generate``'s order)."""
torch, R, W = self.torch, self.R, self.W
from .reference import uocr2 as U
from .tt.model import NGram as TNGram
from .tt.model import NGramIndex
L = len(prep.ids)
pages = prep.extra["pages"]
T = self._t = {"vision_ms": 0.0, "prefill_ms": 0.0, "ttft_ms": 0.0, "decode_ms": 0.0, "tokens": 0,
"tokens_per_s": 0.0, "prompt_tokens": L,
"image_tokens": sum(p["image_pos"][1] - p["image_pos"][0] for p in pages)}
t0 = time.perf_counter()
dec = U.UocrDecoder(W, max_pos=self.max_context)
with torch.inference_mode():
rows = dec.embed(prep.ids).float().clone()
for pg in pages: # DeepSeek-OCR's DeepEncoder (the same code; the checkpoint's own weights)
s0, s1 = pg["image_pos"]
rows[s0:s1] = R.image_embeddings(W, pg["global_px"], pg["tiles_px"], pg["grid"], "deepseek-ocr")
t1 = time.perf_counter()
with torch.inference_mode():
lg = dec.prefill(rows, prep.ids)
t2 = time.perf_counter()
T["vision_ms"], T["prefill_ms"] = 1e3 * (t1 - t0), 1e3 * (t2 - t1)
gen = torch.Generator().manual_seed(int(sampling.seed)) if sampling.seed is not None else None
ng = NGramIndex(TNGram(ngram.size, ngram.window, tuple(ngram.whitelist)), prep.ids)
expected = list(prep.ids).count(U.PAGE_ID)
st = {"marker_cum": 0, "scanned": 0, "page_len": 0}
out: List[int] = []
td = time.perf_counter()
try:
while True:
with torch.inference_mode():
z = lg.float().clone()
for b in ng.banned():
z[b] = -float("inf")
z = U.page_guard(z, out, expected, st, FE.EOS_ID, C.MAX_PAGE_TOKENS)
t = pick_token(z, ng.seq, (), sampling, gen)
out.append(t)
ng.push(t)
T["tokens"] = len(out)
if len(out) == 1:
T["ttft_ms"] = 1e3 * (time.perf_counter() - t0)
td = time.perf_counter()
yield t
if t == FE.EOS_ID or len(out) >= max_new:
return
with torch.inference_mode():
lg = dec.step(t)
finally:
dt = time.perf_counter() - td
n = len(out)
T["decode_ms"] = 1e3 * dt
T["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 {"backend": "cpu", "engine": {"vis": "cpu", "pre": "cpu", "dec": "cpu"},
"precision": {"all": self.cfg.cpu_dtype}, "device": None}
def close(self) -> None:
self.W = None
# ================================================================================================ device
def open_chip(cfg: C.ServeConfig):
"""Open the p150 for this configuration (ETH dispatch by default: the 12 x 10 grid; WORKER only on request)."""
from .ttaw import device as D
# the DEC-MoE megakernel program (~80 KiB of binaries + RTAs) needs the larger kernel-config ring; the ttnn engines
# alone keep the default worker L1 (logs/dsocr/FAULTS.md #3)
kw = {"worker_l1_size": C.WORKER_L1_SIZE} if cfg.engine.get("dec") == "mk" else {}
return D.open_device(cfg.device_id, dispatch=cfg.dispatch, num_command_queues=1,
trace_region_size=int(cfg.trace_region_mb) << 20, l1_small_size=C.L1_SMALL_SIZE,
allow_fallback=cfg.dispatch != "eth", **kw)
def close_chip(device) -> None:
from .ttaw import device as D
D.close_device(device)
class DeviceBackend:
"""The p150 engines (``tt/model.py`` ``DsocrDevice``): the vision encoder (one trace per view size of the enabled
modes), the prefill (one trace per row bucket), the decode (``dec=mk``: the DEC-MoE megakernel, on-device
sampling and the exact n-gram rule with host replay; ``dec=ttnn``: the ttnn decoder). Built and warmed (every
trace captured) in the constructor, on the thread that will run every later device call."""
name = "device"
def __init__(self, cfg: C.ServeConfig, device, model_dir: str, log: Callable[[str], None] = print):
if not cfg.info.device:
raise RuntimeError(f"DSOCR_VARIANT={cfg.variant}: no device engines yet ({cfg.info.todo})")
if cfg.cache_dir: # the megakernel's packed weight arena and its host sampler library (persistent mount)
os.environ.setdefault("DSOCR_MK_CACHE", os.path.join(cfg.cache_dir, "mk_moe"))
os.environ.setdefault("DSOCR_MKS_CACHE", os.path.join(cfg.cache_dir, "mks"))
os.environ.setdefault("GLMOCR_MKS_CACHE", os.environ["DSOCR_MKS_CACHE"]) # tt/mk_moe/sampler_host.py
from .ttaw import device as D
from .tt.model import DsocrDevice
self.cfg, self.device = cfg, device
dc = cfg.device_config() # Unlimited-OCR-2: tt.model builds the DASH decoder (dec=ttnn) and 2 .. 16 tiles
t0 = time.perf_counter()
if dc.engine_dec == "mk":
log("WARNING: " + C.MK_EXPERIMENTAL)
log(f"Building the device engines from {model_dir}: {dc}")
self.m = DsocrDevice(device, model_dir, dc, log=log)
self.build_s = time.perf_counter() - t0
self.max_prompt = int(self.m.max_prompt)
self.max_context = int(self.m.max_context)
mi = dict(getattr(self.m, "info", {}) or {})
self._info = {"backend": "device", "engine": dict(cfg.engine), "precision": dict(cfg.precision),
"device": D.describe_device(device, cfg.device_id), "loop_steps": cfg.loop_steps,
"mk_attk": cfg.mk_attk, "views": [list(v) for v in mi.get("views", [])],
"prefill_buckets": list(mi.get("buckets", [])), "kv_positions": self.max_context,
"build_s": round(self.build_s, 1)}
if cfg.engine.get("dec") == "mk":
self._info["warning"] = C.MK_EXPERIMENTAL
def room(self, prompt_len: int) -> int:
return int(self.m.room(int(prompt_len)))
def generate(self, prep: FE.Prepared, max_new: int, sampling: Sampling, ngram: NGram) -> Iterator[int]:
from .tt import model as TM
sp = TM.Sampling(sampling.temperature, sampling.top_k, sampling.top_p, sampling.repetition_penalty,
sampling.seed)
ng = TM.NGram(ngram.size, ngram.window, tuple(ngram.whitelist))
yield from self.m.generate(prep, int(max_new), sp, ng)
def timings(self) -> Dict[str, Any]:
return dict(self.m.timings())
@property
def info(self) -> Dict[str, Any]:
return dict(self._info)
def close(self) -> None:
m, self.m = getattr(self, "m", None), None
if m is not None:
m.close()