Download code/tt_glmocr/tt/model.py from changh95/GLM-OCR: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/changh95/GLM-OCR/resolve/main/code/tt_glmocr/tt/model.py
- Command line
-
hf download hf://changh95/GLM-OCR/code/tt_glmocr/tt/model.py
-
curl -L -o model.py https://huggingface.co/changh95/GLM-OCR/resolve/main/code/tt_glmocr/tt/model.py
11 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """GLM-OCR on the device: vision encoder -> prompt rows -> prefill -> decode (engines selectable per stage). | |
| m = GlmOcrDevice(device, W, EngineConfig(...)) | |
| m.capture() # traces of every bucket (after all allocations) | |
| for tok in m.generate(prompt, image, params): # token ids as they are decoded | |
| ... | |
| m.timings # vision / prefill / first token / decode ms of the last request | |
| Engines: vision ``ttnn`` (traced per patch bucket), prefill ``ttnn`` (traced per row bucket), decode ``ttnn`` (greedy | |
| loop of K on-device argmax steps per trace; host sampling path when sampling / repetition penalty is requested) or | |
| ``mk`` (the DEC megakernel, tt/mk_dec: on-device greedy / sampling / penalty, token ring, stop rule). | |
| """ | |
| from __future__ import annotations | |
| import time | |
| from dataclasses import dataclass, field | |
| from typing import Dict, Iterator, List, Optional, Sequence | |
| import numpy as np | |
| import torch | |
| from .. import frontend as FE | |
| from ..reference import model as R | |
| from ..reference.model import SampleParams, process_logits | |
| class EngineConfig: | |
| vision_buckets: Sequence[int] = (256, 512, 1024, 2048, 4096, 8192, 12288, 16384, 24576) | |
| prefill_buckets: Sequence[int] = (128, 256, 512, 1024, 2048, 3072, 4096, 6400) | |
| max_context: int = 10240 | |
| vision_wdtype: str = "bf16" | |
| vision_fidelity: str = "HiFi4" | |
| vision_sdpa: str = "approx" # approx (approximate exp in the vision SDPA for buckets >= 4096 patches) | exact | |
| attn_dtype: str = "bf16" | |
| mlp_dtype: str = "bfp8" | |
| head_dtype: str = "bf16" | |
| pre_fidelity: str = "HiFi4" | |
| loop_steps: int = 8 | |
| dec: str = "ttnn" | |
| mk_recipe: str = "bfp8" # DEC megakernel weight recipe (bf16 | bfp8 | bfp8h8) | |
| mk_batch: int = 8 # DEC launches per trace (= streaming granularity) | |
| mk_attk: int = 4 # split-K attention slots per kv group | |
| k_max: int = 64 | |
| class Timings: | |
| preprocess_ms: float = 0.0 | |
| vision_ms: float = 0.0 | |
| prefill_ms: float = 0.0 | |
| ttft_ms: float = 0.0 | |
| decode_ms: float = 0.0 | |
| n_tokens: int = 0 | |
| n_image_tokens: int = 0 | |
| prompt_len: int = 0 | |
| vision_bucket: int = 0 | |
| prefill_bucket: int = 0 | |
| def as_dict(self): | |
| d = dict(self.__dict__) | |
| d["decode_tok_s"] = round(1000.0 * max(0, self.n_tokens - 1) / self.decode_ms, 1) if self.decode_ms > 0 else 0 | |
| return d | |
| class GlmOcrDevice: | |
| def __init__(self, device, W: R.Weights, cfg: EngineConfig, log=print): | |
| from .ttnn_decoder import TtnnDecoder | |
| from .ttnn_vision import TtnnVision | |
| self.ttnn = __import__("ttnn") | |
| self.device, self.cfg, self.log = device, cfg, log | |
| t0 = time.time() | |
| self.embed = W["model.language_model.embed_tokens.weight"].to(torch.bfloat16) | |
| self.vision = TtnnVision(device, W, cfg.vision_buckets, wdtype=cfg.vision_wdtype, | |
| fidelity=cfg.vision_fidelity, | |
| exp_approx_min=4096 if cfg.vision_sdpa == "approx" else 1 << 30) | |
| self.mk = None | |
| if cfg.dec == "mk": | |
| from .mk_dec.engine import MkDecoder | |
| from .mk_dec.weights import RECIPES | |
| self.mk = MkDecoder(device, W, cfg.prefill_buckets, cfg.max_context, recipe=RECIPES[cfg.mk_recipe], | |
| batch=cfg.mk_batch, k_max=cfg.k_max, attk=cfg.mk_attk, | |
| pre_precision=dict(attn=cfg.attn_dtype, mlp=cfg.mlp_dtype, head=cfg.head_dtype, | |
| pre_fid=cfg.pre_fidelity), log=log) | |
| self.dec = self.mk.pre | |
| else: | |
| self.dec = TtnnDecoder(device, W, cfg.prefill_buckets, cfg.max_context, attn_dtype=cfg.attn_dtype, | |
| mlp_dtype=cfg.mlp_dtype, head_dtype=cfg.head_dtype, | |
| pre_fidelity=cfg.pre_fidelity, loop_steps=cfg.loop_steps) | |
| self.timings = Timings() | |
| log(f"[glmocr] device engines ready in {time.time() - t0:.1f}s") | |
| def max_image_tokens(self) -> int: | |
| return self.vision.buckets[-1] // 4 | |
| def max_prompt(self) -> int: | |
| return self.dec.buckets[-1] | |
| def max_context(self) -> int: | |
| return self.mk.max_pos if self.mk is not None else self.dec.max_seq | |
| def warmup(self): | |
| self.vision.warmup() | |
| (self.mk or self.dec).warmup() | |
| def capture(self): | |
| eng = self.mk or self.dec | |
| if not getattr(self.vision, "_warm", False) or not getattr(eng, "_warm", False): | |
| self.warmup() | |
| self.vision.capture() | |
| eng.capture() | |
| def release(self): | |
| self.vision.release() | |
| (self.mk or self.dec).release() | |
| # ------------------------------------------------------------------ stages | |
| def image_rows(self, img: FE.Image) -> torch.Tensor: | |
| ttnn = self.ttnn | |
| y, n, Nb = self.vision.run(img.patches, img.grid_h, img.grid_w) | |
| self.timings.vision_bucket = Nb | |
| return ttnn.to_torch(y).reshape(-1, R.T_D)[:n] | |
| def prompt_rows(self, pr: FE.Prompt, img_rows: Optional[torch.Tensor]) -> torch.Tensor: | |
| x = self.embed[torch.tensor(pr.ids, dtype=torch.long)].clone() | |
| if img_rows is not None: | |
| x[pr.image_start:pr.image_start + pr.n_image] = img_rows.to(torch.bfloat16) | |
| return x | |
| def prefill(self, pr: FE.Prompt, img_rows: Optional[torch.Tensor]) -> torch.Tensor: | |
| rows = self.prompt_rows(pr, img_rows) | |
| self.dec.prefill(rows, torch.from_numpy(pr.pos3d), pr.L) | |
| self.timings.prefill_bucket = self.dec.bucket(pr.L) | |
| return self.dec.logits_host() | |
| # ------------------------------------------------------------------ generation | |
| def generate(self, pr: FE.Prompt, img: Optional[FE.Image], max_new: int, sp: Optional[SampleParams] = None, | |
| eos: Sequence[int] = FE.EOS_IDS) -> Iterator[int]: | |
| """Yield generated token ids (the last one may be an EOS id). Greedy without penalty uses the on-device | |
| argmax loop; sampling / repetition penalty use the host path (logits read back each step).""" | |
| ttnn = self.ttnn | |
| sp = sp or SampleParams() | |
| T = self.timings = Timings(n_image_tokens=pr.n_image, prompt_len=pr.L) | |
| cap = self.max_context | |
| if self.mk is None: # the ttnn greedy loop runs K steps per trace: keep its overshoot inside the KV cache | |
| cap -= self.dec.loop_steps | |
| if pr.L + max_new > cap: | |
| max_new = cap - pr.L | |
| if max_new < 1: | |
| raise ValueError(f"prompt of {pr.L} tokens leaves no room in the KV cache ({cap})") | |
| t0 = time.perf_counter() | |
| img_rows = None | |
| if img is not None: | |
| img_rows = self.image_rows(img) | |
| t1 = time.perf_counter() | |
| T.vision_ms = 1000 * (t1 - t0) | |
| lg = self.prefill(pr, img_rows) | |
| t2 = time.perf_counter() | |
| T.prefill_ms = 1000 * (t2 - t1) | |
| seen = list(pr.ids) | |
| gen = torch.Generator().manual_seed(int(sp.seed)) if sp.seed is not None else None | |
| greedy = sp.temperature <= 0 and sp.repetition_penalty == 1.0 | |
| tok = self._pick(lg, seen, sp, gen) | |
| T.ttft_ms = 1000 * (time.perf_counter() - t0) | |
| T.n_tokens = 1 | |
| yield tok | |
| if tok in eos or max_new == 1: | |
| return | |
| n = 1 | |
| td = time.perf_counter() | |
| try: | |
| if self.mk is not None: | |
| yield from self._mk_decode(pr, tok, max_new, sp, eos, T) | |
| return | |
| if greedy: | |
| K = self.dec.loop_steps | |
| while n < max_new: | |
| p = pr.L + n - 1 | |
| out = self.dec.loop(tok, p, p + pr.rope_delta) | |
| toks = ttnn.to_torch(out).reshape(-1).tolist() | |
| for t in toks[:K]: | |
| n += 1 | |
| T.n_tokens = n | |
| tok = int(t) | |
| yield tok | |
| if tok in eos or n >= max_new: | |
| return | |
| else: | |
| seen.append(tok) | |
| while n < max_new: | |
| p = pr.L + n - 1 | |
| self.dec.step(tok, p, p + pr.rope_delta) | |
| tok = self._pick(self.dec.logits_host(), seen, sp, gen) | |
| seen.append(tok) | |
| n += 1 | |
| T.n_tokens = n | |
| yield tok | |
| if tok in eos: | |
| return | |
| finally: | |
| T.decode_ms = 1000 * (time.perf_counter() - td) | |
| def _mk_decode(self, pr: FE.Prompt, tok0: int, max_new: int, sp: SampleParams, eos, T: Timings): | |
| """DEC megakernel decode: STATE-driven (on-device sampling, penalty, stop rule); the host polls STATE once per | |
| trace of ``mk_batch`` launches and yields the new tokens from the circular ring.""" | |
| from .mk_dec import geometry as G | |
| mk = self.mk | |
| mk.start(pr.L, tok0, max_new, pr.rope_delta, temperature=sp.temperature, top_k=sp.top_k, top_p=sp.top_p, | |
| seed=sp.seed, penalty=sp.repetition_penalty, seen_ids=list(pr.ids) + [tok0], eos=tuple(eos)) | |
| n = 1 | |
| while True: | |
| mk.run_batch() | |
| ntok, done, stop, ring = mk.poll() | |
| for i in range(n, ntok): | |
| t = int(ring[i % G.S_TOKENS_MAX]) | |
| T.n_tokens = i + 1 | |
| yield t | |
| n = ntok | |
| if done or n >= max_new: | |
| return | |
| def _pick(lg: torch.Tensor, seen, sp: SampleParams, gen) -> int: | |
| z = process_logits(lg, seen, sp) | |
| 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) | |
| rm = pr.cumsum(-1) - pr > sp.top_p | |
| z[si[rm]] = -float("inf") | |
| return int(torch.multinomial(torch.softmax(z, -1), 1, generator=gen)) | |
| def teacher_forced(self, pr: FE.Prompt, img: Optional[FE.Image], tokens: Sequence[int]) -> torch.Tensor: | |
| """Logits [n, V] along a given token path: row 0 = prefill, row s = step with input tokens[s - 1].""" | |
| img_rows = self.image_rows(img) if img is not None else None | |
| out = [self.prefill(pr, img_rows)] | |
| for s in range(1, len(tokens)): | |
| if self.mk is not None: | |
| out.append(self.mk.tf_step(pr.L, s, int(tokens[s - 1]), pr.rope_delta)) | |
| continue | |
| p = pr.L + s - 1 | |
| self.dec.step(int(tokens[s - 1]), p, p + pr.rope_delta) | |
| out.append(self.dec.logits_host()) | |
| return torch.stack(out) | |