# SPDX-License-Identifier: Apache-2.0
"""Generation backends of GLM-OCR behind one protocol (``GLMOCR_BACKEND``):
* :class:`DeviceBackend` (``device``): the p150 engines of ``tt/model.py`` (``GlmOcrDevice``). 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.GlmOcr.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``); slow, for development and
checks with small images.
* :class:`FakeBackend` (``fake``): a deterministic stand-in without weights or device (host tests, the image's
verify step): the output text is fixed per task prompt, one token per step.
The API (``api.py``) does all host work (image decoding, smart_resize, patches, prompt, positions, detokenization,
stop rules, output formats); a backend only turns (prompt, image patches) into generated token ids.
Importing this module imports neither torch nor ttnn.
"""
from __future__ import annotations
import importlib.util
import json
import os
import time
from dataclasses import dataclass
from typing import Any, Callable, Dict, Iterator, List, Optional, Sequence
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
from .postprocess import EXTRACT_PREFACE
@dataclass(frozen=True)
class Sampling:
"""Decoding parameters of one request (validated by the API)."""
temperature: float = 0.0 # 0 = greedy (generation_config.json: do_sample false)
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}
class Backend(Protocol):
"""What the API needs from a backend."""
name: str
max_image_tokens: int # largest image (LLM image tokens) the backend accepts
max_prompt: int # longest prompt (rows: template + 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, prompt: FE.Prompt, image: Optional[FE.Image], max_new: int,
sampling: Sampling) -> Iterator[int]:
"""Generated token ids, one at a time (the last one may be an EOS id); stops at EOS or ``max_new``."""
def timings(self) -> Dict[str, Any]:
"""Stage timings of the last :meth:`generate` (ms)."""
@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."""
def pick_token(logits, seen: Sequence[int], sp: Sampling, gen) -> int:
"""transformers' order: repetition penalty -> temperature -> top-k -> top-p -> multinomial (greedy = argmax after
the penalty); identical to ``GlmOcrDevice._pick`` and ``reference.model.generate``."""
import torch
from .reference.model import SampleParams, process_logits
z = process_logits(logits, seen, SampleParams(sp.temperature, sp.top_k, sp.top_p, sp.repetition_penalty, sp.seed))
if sp.temperature <= 0:
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 text (see :meth:`reply`); its tokens (the
tokenizer's encoding) are yielded one per step, then ``<|user|>`` (59253, the EOS the model emits)."""
name = "fake"
TEXT = "Fake OCR: café, 你好 🙂 — line 1."
TABLE = "
"
FORMULA = "$$\nx = \\frac {- b \\pm \\sqrt {b ^ {2} - 4 a c}}{2 a}\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_image_tokens = cfg.max_image_tokens
self.max_prompt = cfg.pre_buckets[-1]
self.max_context = cfg.kv_positions
self._t: Dict[str, Any] = {}
self.generated = 0
def room(self, prompt_len: int) -> int:
return self.max_context - int(prompt_len)
@classmethod
def reply(cls, text: str) -> str:
t = text.strip()
if t.startswith(EXTRACT_PREFACE.strip()):
try:
schema = json.loads(t[len(EXTRACT_PREFACE.strip()):])
except ValueError:
schema = {}
return "```json\n" + json.dumps(_fill(schema), ensure_ascii=False, indent=2) + "\n```"
if t == FE.TASK_PROMPTS["table"]:
return cls.TABLE
if t == FE.TASK_PROMPTS["formula"]:
return cls.FORMULA
if t == FE.TASK_PROMPTS["text"]:
return cls.TEXT
return "Fake reply to: " + t
def _prompt_text(self, prompt: FE.Prompt) -> str:
ids = prompt.ids
start = prompt.image_start + prompt.n_image + 1 if prompt.n_image else 4
end = len(ids) - 2 # <|assistant|> \n
return self.tok.decode(ids[start:end], skip_special=True)
def generate(self, prompt: FE.Prompt, image: Optional[FE.Image], max_new: int,
sampling: Sampling) -> Iterator[int]:
t0 = time.perf_counter()
ids = list(self.tok.encode(self.reply(self._prompt_text(prompt)))) + [FE.EOS_IDS[1]]
self._t = {"vision_ms": 0.0, "prefill_ms": 0.0, "ttft_ms": 0.0, "decode_ms": 0.0, "n_tokens": 0,
"n_image_tokens": prompt.n_image, "prompt_len": prompt.L}
for i, t in enumerate(ids[:max(1, int(max_new))]):
if self.token_delay_s:
time.sleep(self.token_delay_s)
self._t["n_tokens"] = i + 1
self.generated += 1
yield int(t)
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
def _fill(schema: Any) -> Any:
if isinstance(schema, dict):
return {k: _fill(v) for k, v in schema.items()}
if isinstance(schema, list):
return [_fill(v) for v in schema[:1]]
return "fake"
# ================================================================================================ CPU reference
class CpuBackend:
"""The clean-room CPU reference (fp32 by default: bit-exact with the official transformers model), greedy or
sampled on the host. Slow (minutes for a page): 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_image_tokens = cfg.max_image_tokens
self.max_prompt = cfg.pre_buckets[-1]
self.max_context = cfg.kv_positions
self._t: Dict[str, Any] = {}
def room(self, prompt_len: int) -> int:
return self.max_context - int(prompt_len)
def generate(self, prompt: FE.Prompt, image: Optional[FE.Image], max_new: int,
sampling: Sampling) -> Iterator[int]:
torch, R, W = self.torch, self.R, self.W
T = self._t = {"vision_ms": 0.0, "prefill_ms": 0.0, "ttft_ms": 0.0, "decode_ms": 0.0, "n_tokens": 0,
"n_image_tokens": prompt.n_image, "prompt_len": prompt.L}
t0 = time.perf_counter()
with torch.inference_mode():
emb = (R.vision(W, torch.from_numpy(image.patches), image.grid_h, image.grid_w)
if image is not None else None)
t1 = time.perf_counter()
dec = R.Decoder(W)
with torch.inference_mode():
lg = dec.forward(R.prompt_rows(W, prompt.ids, prompt.image_start, emb),
torch.from_numpy(prompt.pos3d))[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
seen: List[int] = list(prompt.ids)
emb_tab = W["model.language_model.embed_tokens.weight"]
n = 0
td = time.perf_counter()
try:
while True:
with torch.inference_mode():
t = pick_token(lg, seen, sampling, gen)
n += 1
seen.append(t)
T["n_tokens"] = n
if n == 1:
T["ttft_ms"] = 1e3 * (time.perf_counter() - t0)
yield t
if t in FE.EOS_IDS or n >= max_new:
return
p = prompt.L + n - 1 + prompt.rope_delta
with torch.inference_mode():
lg = dec.forward(emb_tab[t][None], torch.full((3, 1), p, dtype=torch.long))[0]
finally:
T["decode_ms"] = 1e3 * (time.perf_counter() - td)
def timings(self) -> Dict[str, Any]:
d = dict(self._t)
if d.get("decode_ms"):
d["decode_tok_s"] = round(1e3 * max(0, d["n_tokens"] - 1) / d["decode_ms"], 1)
return d
@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
return D.open_device(cfg.device_id, dispatch=cfg.dispatch, num_command_queues=1,
trace_region_size=int(cfg.trace_region_mb) << 20,
allow_fallback=cfg.dispatch != "eth")
def close_chip(device) -> None:
from .ttaw import device as D
D.close_device(device)
class DeviceBackend:
"""The p150 engines (``tt/model.py``): vision encoder (one trace per patch bucket), prefill (one trace per row
bucket), decode (``dec=ttnn``: K greedy steps per trace launch, host sampling path when sampling / a repetition
penalty is requested; ``dec=mk``: the decoder megakernel when the package has it). 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):
import torch
from .reference import model as R
from .tt.model import GlmOcrDevice
from .ttaw.device import describe_device
if cfg.engine["dec"] == "mk" and importlib.util.find_spec(__package__ + ".tt.mk_dec") is None:
raise RuntimeError("GLMOCR_ENGINE dec=mk: this package has no decoder megakernel (tt/mk_dec); use dec=ttnn")
if cfg.cache_dir: # the megakernel's packed weight streams (persistent: /weight-cache in the container)
os.environ.setdefault("GLMOCR_MK_CACHE", os.path.join(cfg.cache_dir, "mk_dec"))
self.cfg, self.device = cfg, device
ec = cfg.engine_config()
t0 = time.perf_counter()
log(f"Loading weights from {model_dir}")
W = R.Weights(model_dir, torch.bfloat16)
log(f"Building the device engines: {ec}")
self.m = GlmOcrDevice(device, W, ec, log=log)
del W
log("Warming up: compiling programs and capturing traces")
self.m.capture()
self.build_s = time.perf_counter() - t0
self.loop_steps = int(ec.loop_steps)
self.max_image_tokens = min(cfg.max_image_tokens, int(self.m.max_image_tokens))
self.max_prompt = int(self.m.max_prompt)
self.max_context = int(getattr(self.m, "max_context", None) or self.m.dec.max_seq)
self._info = {"backend": "device", "engine": dict(cfg.engine), "precision": dict(cfg.precision),
"device": describe_device(device, cfg.device_id), "loop_steps": self.loop_steps,
"vision_buckets": list(self.m.vision.buckets), "prefill_buckets": list(self.m.dec.buckets),
"kv_positions": self.max_context, "build_s": round(self.build_s, 1)}
def room(self, prompt_len: int) -> int:
# a trace launch decodes loop_steps tokens (ttnn loop / megakernel batch): keep all their KV rows inside the cache
return self.max_context - int(prompt_len) - self.loop_steps
def generate(self, prompt: FE.Prompt, image: Optional[FE.Image], max_new: int,
sampling: Sampling) -> Iterator[int]:
from .reference.model import SampleParams
sp = SampleParams(sampling.temperature, sampling.top_k, sampling.top_p, sampling.repetition_penalty,
sampling.seed)
yield from self.m.generate(prompt, image, int(max_new), sp)
def timings(self) -> Dict[str, Any]:
return self.m.timings.as_dict()
@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.release()