GLM-OCR / code /tt_glmocr /config.py
changh95's picture
tt-model push glm-ocr (container)
aa204f5 verified
Raw History Blame Contribute Delete
19.4 kB
# SPDX-License-Identifier: Apache-2.0
"""GLM-OCR serving configuration: the weight pin and every compile-time knob (``GLMOCR_*`` environment variables,
read once when the server starts; the device programs, buckets and traces are built for them).
No torch / ttnn / numpy import at module level (the server module must import without them). The runtime (per
request) parameters are validated in ``api.py`` against the caps defined here.
Units: ``max_pixels`` / ``min_pixels`` are the official processor units (``preprocessor_config.json`` ``size``): the
smart_resize of GLM-OCR counts two frames, so the resized image area is at most ``max_pixels / 2`` and one LLM image
token covers 28 x 28 = 784 pixels: ``image tokens = max_pixels / (2 * 784)`` at most (9,633,792 -> 6144 tokens).
"""
from __future__ import annotations
import os
from dataclasses import asdict, dataclass, field, replace
from typing import Dict, Mapping, Optional, Tuple
# ================================================================================================ identity / weights
MODEL_NAME = "glm-ocr"
PACKAGE_REPO = "changh95/GLM-OCR"
WEIGHTS_REPO = "zai-org/GLM-OCR"
WEIGHTS_REVISION = "2e85a62840ccac27daa451df36c736c4636b8628"
WEIGHT_FILES = ["model.safetensors", "config.json", "generation_config.json", "tokenizer.json", "tokenizer_config.json",
"preprocessor_config.json", "processor_config.json", "chat_template.jinja", "README.md"]
ENV_PREFIX = "GLMOCR"
# ================================================================================================ fixed model facts
PIXELS_PER_TOKEN = 784 # 28 x 28 pixels per LLM image token (patch 14, merge 2)
FRAMES = 2 # the official smart_resize counts 2 frames (temporal patch)
OFFICIAL_MIN_PIXELS = 12544 # processor size.shortest_edge (8 image tokens)
OFFICIAL_MAX_PIXELS = 9633792 # processor size.longest_edge (6144 image tokens)
HARD_MAX_IMAGE_TOKENS = 6144 # the SDK's image_expect_length; the official max_pixels
TEMPLATE_TOKENS = 8 # [gMASK] <sop> <|user|> \n <|begin_of_image|> <|end_of_image|> <|assistant|> \n
# ================================================================================================ choices
BACKENDS = ("device", "cpu", "fake")
ENGINES = {"vis": ("ttnn",), "pre": ("ttnn",), "dec": ("ttnn", "mk")}
DEFAULT_ENGINE = {"vis": "ttnn", "pre": "ttnn", "dec": "mk"} # dec=mk: gates passed 2026-11-30 (research/glmocr/SPEC.md)
PRECISION_KEYS = {"vis": ("bf16", "bfp8", "bfp4"), "vis_fid": ("HiFi4", "HiFi2", "LoFi"),
"attn": ("bf16", "bfp8"), "mlp": ("bf16", "bfp8", "bfp4"), "head": ("bf16", "bfp8"),
"pre_fid": ("HiFi4", "HiFi2", "LoFi"), "mk": ("bf16", "bfp8", "bfp8h8"),
"vis_sdpa": ("exact", "approx")}
#: the device engine's EngineConfig defaults (vision bf16 HiFi4; ttnn decoder / prefill attention bf16, MLP bfp8,
#: head bf16; the decoder megakernel (dec=mk) recipe bfp8 = bfp8 layers + bf16 head)
DEFAULT_PRECISION = {"vis": "bf16", "vis_fid": "HiFi4", "attn": "bf16", "mlp": "bfp8", "head": "bf16",
"pre_fid": "HiFi4", "mk": "bfp8", "vis_sdpa": "approx"}
#: PRECISION key -> tt.model.EngineConfig field
PRECISION_FIELDS = {"vis": "vision_wdtype", "vis_fid": "vision_fidelity", "attn": "attn_dtype", "mlp": "mlp_dtype",
"head": "head_dtype", "pre_fid": "pre_fidelity", "mk": "mk_recipe", "vis_sdpa": "vision_sdpa"}
VISION_BUCKET_STEP = 256 # tt/ttnn_vision.py: patch buckets are multiples of 256 patches
PREFILL_BUCKET_STEP = 128 # prefill SDPA chunks (q / k chunk 128)
KV_MULTIPLE = 64 # tt/ttnn_decoder.py CACHE_TILE_MULTIPLE
def ceil_to(n: int, m: int) -> int:
return -(-int(n) // m) * m
def tokens_to_max_pixels(tokens: int) -> int:
"""max_pixels (official units) that admits ``tokens`` LLM image tokens."""
return FRAMES * PIXELS_PER_TOKEN * int(tokens)
def max_pixels_to_tokens(max_pixels: int) -> int:
return int(max_pixels) // (FRAMES * PIXELS_PER_TOKEN)
def default_vision_buckets(max_image_tokens: int) -> Tuple[int, ...]:
"""Patch buckets (4 patches per image token), the device engine's ladder (tt/ttnn_vision.default_buckets, kept
in sync by hand: that module imports torch): 64 .. 6144 tokens, capped by ``max_image_tokens`` (top bucket rounded
up to 64 tokens)."""
toks = [64, 128, 256, 512, 1024, 2048, 3072, 4096, 6144]
out = [4 * t for t in toks if t < max_image_tokens] + [4 * ceil_to(max_image_tokens, 64)]
return tuple(sorted(set(out)))
def default_prefill_buckets(max_prompt: int) -> Tuple[int, ...]:
"""Row buckets: 128, 256, 512, 1024, 2048, 3072, 4096, 6400 below the top, then the longest prompt rounded up to
128 (a ladder bucket within 128 rows of the top is dropped)."""
top = ceil_to(max_prompt, PREFILL_BUCKET_STEP)
ladder = [b for b in (128, 256, 512, 1024, 2048, 3072, 4096, 6400) if b < top - PREFILL_BUCKET_STEP]
return tuple(sorted(set(ladder + [top])))
def parse_buckets(name: str, spec: Optional[str], step: int, hi: int) -> Optional[Tuple[int, ...]]:
if spec is None or not str(spec).strip():
return None
try:
b = tuple(sorted({int(x) for x in str(spec).split(",") if x.strip()}))
except ValueError:
raise ValueError(f"{name}={spec!r}: comma-separated integers") from None
if not b or len(b) > 24 or any(x % step or x < step or x > hi for x in b):
raise ValueError(f"{name}={spec!r}: 1..24 multiples of {step} in [{step}, {hi}]")
return b
def parse_engine(spec: Optional[str]) -> Dict[str, str]:
"""``vis=ttnn,pre=ttnn,dec=mk`` (stages not named keep the default) or a shorthand ``ttnn`` / ``mk``."""
out = dict(DEFAULT_ENGINE)
s = (spec or "").strip()
if not s:
return out
if s in ("ttnn", "mk"):
return {k: (s if s in ENGINES[k] else out[k]) for k in ENGINES}
for kv in s.split(","):
if not kv.strip():
continue
k, _, v = kv.partition("=")
k, v = k.strip(), v.strip()
if k not in ENGINES or v not in ENGINES[k]:
raise ValueError(f"GLMOCR_ENGINE: {kv!r}: stages / engines {ENGINES}")
out[k] = v
return out
def parse_precision(spec: Optional[str]) -> Dict[str, str]:
"""``vis=bf16,vis_fid=HiFi4,attn=bf16,mlp=bfp8,head=bf16,pre_fid=HiFi4,mk=bfp8`` (keys not named keep the
default; ``attn`` / ``mlp`` / ``head`` / ``pre_fid`` are the ttnn decoder and prefill, ``mk`` the decoder
megakernel's weight recipe)."""
out = dict(DEFAULT_PRECISION)
for kv in (spec or "").split(","):
if not kv.strip():
continue
k, _, v = kv.partition("=")
k, v = k.strip(), v.strip()
if k not in PRECISION_KEYS or v not in PRECISION_KEYS[k]:
raise ValueError(f"GLMOCR_PRECISION: {kv!r}: keys / formats {PRECISION_KEYS}")
out[k] = v
return out
def _bool(env: Mapping[str, str], name: str, default: bool) -> bool:
raw = env.get(name)
if raw is None or str(raw).strip() == "":
return default
s = str(raw).strip().lower()
if s in ("1", "true", "yes", "on"):
return True
if s in ("0", "false", "no", "off"):
return False
raise ValueError(f"{name}={raw!r}: a boolean (1 / 0, true / false)")
def _num(env: Mapping[str, str], name: str, cast, default, lo=None, hi=None):
raw = env.get(name)
if raw is None or str(raw).strip() == "":
return default
try:
v = cast(str(raw).strip())
except ValueError:
raise ValueError(f"{name}={raw!r}: not {'an integer' if cast is int else 'a number'}") from None
if (lo is not None and v < lo) or (hi is not None and v > hi):
raise ValueError(f"{name}={raw!r}: out of range [{lo}, {hi}]")
return v
# ================================================================================================ the configuration
@dataclass(frozen=True)
class ServeConfig:
"""Everything fixed at server start (``GLMOCR_*``); ``GET /info`` reports it (:meth:`as_env`)."""
backend: str = "device"
model_dir: Optional[str] = None # GLMOCR_MODEL_DIR: a local checkpoint dir (development)
revision: str = WEIGHTS_REVISION # TT_MODEL_WEIGHTS_REVISION (tt-model's weights pointer)
dispatch: str = "eth"
device_id: int = 0
engine: Dict[str, str] = field(default_factory=lambda: dict(DEFAULT_ENGINE))
precision: Dict[str, str] = field(default_factory=lambda: dict(DEFAULT_PRECISION))
max_image_tokens: int = HARD_MAX_IMAGE_TOKENS
max_context: int = 10240 # KV positions (prompt + generated)
max_new_tokens: int = 8192 # cap of a request's max_tokens
default_max_new_tokens: int = 4096 # a request without max_tokens
max_prompt_tokens: int = 1024 # prompt text tokens (task prompt / free prompt / extraction schema)
vision_buckets: Optional[Tuple[int, ...]] = None # None = default_vision_buckets(max_image_tokens)
prefill_buckets: Optional[Tuple[int, ...]] = None # None = default_prefill_buckets(max_prompt)
k_max: int = 64
loop_steps: int = 8 # greedy decode steps per trace launch (streaming granularity)
queue_depth: int = 8
queue_timeout_s: float = 300.0
max_body_mb: float = 64.0
max_input_megapixels: float = 50.0 # decoded image size before resizing (decompression bombs)
allow_urls: bool = False # http(s) image URLs (the server fetches them)
url_timeout_s: float = 15.0
torch_threads: int = 4
trace_region_mb: int = 512
cpu_dtype: str = "fp32" # GLMOCR_BACKEND=cpu: the reference's dtype
cache_dir: Optional[str] = None # persistent cache (the megakernel's packed weight streams)
# ---- derived compile-time sizes
@property
def max_prompt(self) -> int:
"""Longest prompt in rows: template + image tokens + prompt text tokens."""
return TEMPLATE_TOKENS + self.max_image_tokens + self.max_prompt_tokens
@property
def vis_buckets(self) -> Tuple[int, ...]:
return tuple(sorted(self.vision_buckets)) if self.vision_buckets else default_vision_buckets(
self.max_image_tokens)
@property
def pre_buckets(self) -> Tuple[int, ...]:
return tuple(sorted(self.prefill_buckets)) if self.prefill_buckets else default_prefill_buckets(
self.max_prompt)
@property
def kv_positions(self) -> int:
return ceil_to(self.max_context, KV_MULTIPLE)
@property
def max_pixels_cap(self) -> int:
"""Largest runtime max_pixels (official units)."""
return tokens_to_max_pixels(self.max_image_tokens)
@property
def default_max_pixels(self) -> int:
return min(OFFICIAL_MAX_PIXELS, self.max_pixels_cap)
def engine_kwargs(self) -> Dict[str, object]:
"""The ``tt.model.EngineConfig`` fields this configuration sets (``GLMOCR_LOOP_STEPS`` is the streaming
granularity of both decoders: ttnn loop steps and megakernel launches per trace)."""
kw: Dict[str, object] = {PRECISION_FIELDS[k]: v for k, v in self.precision.items()}
kw.update(vision_buckets=tuple(self.vis_buckets), prefill_buckets=tuple(self.pre_buckets),
max_context=self.kv_positions, loop_steps=self.loop_steps, mk_batch=self.loop_steps,
k_max=self.k_max, dec=self.engine["dec"])
return kw
def engine_config(self):
"""The device engine's ``tt.model.EngineConfig`` (imports torch through tt.model). Fields the engine does not
have are refused (the two must stay in sync)."""
from .tt.model import EngineConfig
kw = self.engine_kwargs()
missing = sorted(set(kw) - set(EngineConfig.__dataclass_fields__))
if missing:
raise RuntimeError(f"tt.model.EngineConfig has no field(s) {missing}: config.py and tt/model.py disagree")
return EngineConfig(**kw)
def as_env(self) -> Dict[str, str]:
"""The effective configuration, as the environment variables that set it."""
return {
"GLMOCR_BACKEND": self.backend, "GLMOCR_DISPATCH": self.dispatch,
"GLMOCR_ENGINE": ",".join(f"{k}={v}" for k, v in self.engine.items()),
"GLMOCR_PRECISION": ",".join(f"{k}={v}" for k, v in self.precision.items()),
"GLMOCR_MAX_IMAGE_TOKENS": str(self.max_image_tokens), "GLMOCR_MAX_CONTEXT": str(self.max_context),
"GLMOCR_MAX_NEW_TOKENS": str(self.max_new_tokens),
"GLMOCR_DEFAULT_MAX_NEW_TOKENS": str(self.default_max_new_tokens),
"GLMOCR_MAX_PROMPT_TOKENS": str(self.max_prompt_tokens),
"GLMOCR_VISION_BUCKETS": ",".join(map(str, self.vis_buckets)),
"GLMOCR_PREFILL_BUCKETS": ",".join(map(str, self.pre_buckets)),
"GLMOCR_K_MAX": str(self.k_max), "GLMOCR_LOOP_STEPS": str(self.loop_steps),
"GLMOCR_QUEUE_DEPTH": str(self.queue_depth), "GLMOCR_QUEUE_TIMEOUT_S": f"{self.queue_timeout_s:g}",
"GLMOCR_MAX_BODY_MB": f"{self.max_body_mb:g}",
"GLMOCR_MAX_INPUT_MEGAPIXELS": f"{self.max_input_megapixels:g}",
"GLMOCR_ALLOW_URLS": "1" if self.allow_urls else "0", "GLMOCR_URL_TIMEOUT_S": f"{self.url_timeout_s:g}",
"GLMOCR_TORCH_THREADS": str(self.torch_threads), "GLMOCR_TRACE_REGION_MB": str(self.trace_region_mb),
"GLMOCR_CACHE_DIR": self.cache_dir or "", "TT_MODEL_WEIGHTS_REVISION": self.revision,
}
def as_dict(self) -> Dict[str, object]:
d = asdict(self)
d.update(vision_buckets=list(self.vis_buckets), prefill_buckets=list(self.pre_buckets),
max_prompt=self.max_prompt, kv_positions=self.kv_positions, max_pixels_cap=self.max_pixels_cap)
return d
def resolve_config(env: Optional[Mapping[str, str]] = None, **overrides) -> ServeConfig:
"""The configuration from the environment (``GLMOCR_*``, ``TT_MODEL_WEIGHTS_REVISION`` / ``TT_WEIGHTS_REVISION``,
``TT_DEVICE_ID``); a bad value raises ValueError naming the variable. ``overrides`` replace fields afterwards
(then validated again)."""
env = dict(os.environ if env is None else env)
backend = (env.get("GLMOCR_BACKEND") or "device").strip().lower()
backend = {"tt": "device", "ttnn": "device"}.get(backend, backend)
if backend not in BACKENDS:
raise ValueError(f"GLMOCR_BACKEND={backend!r}: one of {BACKENDS}")
dispatch = (env.get("GLMOCR_DISPATCH") or "eth").strip().lower()
if dispatch not in ("eth", "worker"):
raise ValueError(f"GLMOCR_DISPATCH={dispatch!r}: eth | worker")
revision = (env.get("TT_MODEL_WEIGHTS_REVISION") or env.get("TT_WEIGHTS_REVISION") or WEIGHTS_REVISION).strip()
cpu_dtype = (env.get("GLMOCR_CPU_DTYPE") or "fp32").strip().lower()
if cpu_dtype not in ("fp32", "bf16"):
raise ValueError(f"GLMOCR_CPU_DTYPE={cpu_dtype!r}: fp32 | bf16")
mit = _num(env, "GLMOCR_MAX_IMAGE_TOKENS", int, HARD_MAX_IMAGE_TOKENS, 256, HARD_MAX_IMAGE_TOKENS)
cfg = ServeConfig(
backend=backend, model_dir=(env.get("GLMOCR_MODEL_DIR") or "").strip() or None, revision=revision,
dispatch=dispatch, device_id=_num(env, "TT_DEVICE_ID", int, 0, 0, 64),
engine=parse_engine(env.get("GLMOCR_ENGINE")), precision=parse_precision(env.get("GLMOCR_PRECISION")),
max_image_tokens=mit,
max_context=_num(env, "GLMOCR_MAX_CONTEXT", int, 10240, 1024, 32768),
max_new_tokens=_num(env, "GLMOCR_MAX_NEW_TOKENS", int, 8192, 16, 32768),
default_max_new_tokens=_num(env, "GLMOCR_DEFAULT_MAX_NEW_TOKENS", int, 4096, 1, 32768),
max_prompt_tokens=_num(env, "GLMOCR_MAX_PROMPT_TOKENS", int, 1024, 16, 4096),
vision_buckets=parse_buckets("GLMOCR_VISION_BUCKETS", env.get("GLMOCR_VISION_BUCKETS"), VISION_BUCKET_STEP,
4 * HARD_MAX_IMAGE_TOKENS),
prefill_buckets=parse_buckets("GLMOCR_PREFILL_BUCKETS", env.get("GLMOCR_PREFILL_BUCKETS"),
PREFILL_BUCKET_STEP, 16384),
k_max=_num(env, "GLMOCR_K_MAX", int, 64, 1, 64),
loop_steps=_num(env, "GLMOCR_LOOP_STEPS", int, 8, 1, 64),
queue_depth=_num(env, "GLMOCR_QUEUE_DEPTH", int, 8, 0, 1024),
queue_timeout_s=_num(env, "GLMOCR_QUEUE_TIMEOUT_S", float, 300.0, 1.0, 86400.0),
max_body_mb=_num(env, "GLMOCR_MAX_BODY_MB", float, 64.0, 1.0, 1024.0),
max_input_megapixels=_num(env, "GLMOCR_MAX_INPUT_MEGAPIXELS", float, 50.0, 0.1, 400.0),
allow_urls=_bool(env, "GLMOCR_ALLOW_URLS", False),
url_timeout_s=_num(env, "GLMOCR_URL_TIMEOUT_S", float, 15.0, 1.0, 600.0),
torch_threads=_num(env, "GLMOCR_TORCH_THREADS", int, 4, 1, 64),
trace_region_mb=_num(env, "GLMOCR_TRACE_REGION_MB", int, 512, 64, 4096),
cpu_dtype=cpu_dtype,
cache_dir=(env.get("GLMOCR_CACHE_DIR") or env.get("TT_DIT_CACHE_DIR") or "").strip() or None,
)
if overrides:
cfg = replace(cfg, **overrides)
validate(cfg)
return cfg
def validate(cfg: ServeConfig) -> None:
"""Cross-field checks (ValueError naming the variables)."""
if cfg.default_max_new_tokens > cfg.max_new_tokens:
raise ValueError(f"GLMOCR_DEFAULT_MAX_NEW_TOKENS={cfg.default_max_new_tokens} > GLMOCR_MAX_NEW_TOKENS="
f"{cfg.max_new_tokens}")
vb = cfg.vis_buckets
if vb[-1] < 4 * cfg.max_image_tokens:
raise ValueError(f"GLMOCR_VISION_BUCKETS: the largest bucket {vb[-1]} patches < 4 x GLMOCR_MAX_IMAGE_TOKENS "
f"= {4 * cfg.max_image_tokens}")
pb = cfg.pre_buckets
if pb[-1] < cfg.max_prompt:
raise ValueError(f"GLMOCR_PREFILL_BUCKETS: the largest bucket {pb[-1]} rows < the longest prompt "
f"{cfg.max_prompt} (GLMOCR_MAX_IMAGE_TOKENS + GLMOCR_MAX_PROMPT_TOKENS + {TEMPLATE_TOKENS})")
if cfg.kv_positions < pb[-1] + 64:
raise ValueError(f"GLMOCR_MAX_CONTEXT={cfg.max_context}: the KV cache must hold the largest prefill bucket "
f"({pb[-1]} rows) plus at least 64 generated tokens: raise it or lower "
"GLMOCR_MAX_IMAGE_TOKENS / GLMOCR_MAX_PROMPT_TOKENS")
if cfg.loop_steps > 64 or cfg.k_max > 64:
raise ValueError("GLMOCR_LOOP_STEPS / GLMOCR_K_MAX: at most 64")
# ================================================================================================ weights
def resolve_model_dir(cfg: ServeConfig) -> str:
"""Local directory of the checkpoint: ``GLMOCR_MODEL_DIR`` (development) or the Hugging Face cache snapshot of
the pinned revision (``tt-model serve`` downloads it into the cache mounted at /hf before the server starts; a
missing file is downloaded here; ``HF_HUB_OFFLINE=1``: the cache only)."""
if cfg.model_dir:
if not os.path.isfile(os.path.join(cfg.model_dir, "config.json")):
raise RuntimeError(f"GLMOCR_MODEL_DIR={cfg.model_dir!r} has no config.json")
return cfg.model_dir
from huggingface_hub import snapshot_download
return snapshot_download(repo_id=WEIGHTS_REPO, revision=cfg.revision, allow_patterns=WEIGHT_FILES,
local_files_only=os.environ.get("HF_HUB_OFFLINE") == "1")