File size: 14,726 Bytes
aa204f5 | 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 | # 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 = "<table><tr><td>Region</td><td>地区</td></tr><tr><td>North</td><td>1,204</td></tr></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()
|