Download code/tt_paddleocr/config.py from changh95/PaddleOCR-VL: direct link, hf CLI and curl.
- Browser
- Download file 7.37 kB
-
https://huggingface.co/changh95/PaddleOCR-VL/resolve/main/code/tt_paddleocr/config.py
- Command line
-
hf download hf://changh95/PaddleOCR-VL/code/tt_paddleocr/config.py
-
curl -L -o config.py https://huggingface.co/changh95/PaddleOCR-VL/resolve/main/code/tt_paddleocr/config.py
7.37 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """PaddleOCR-VL model configuration, serve profiles (vl / 1.5 / 1.6), weight pins, task presets and the server's | |
| compile-time settings. No torch / ttnn import at module level (the server module must import without them).""" | |
| from __future__ import annotations | |
| import json | |
| import os | |
| from dataclasses import dataclass | |
| from typing import Dict, List, Optional, Tuple | |
| # ============================================================================================ profiles and weights | |
| #: serve profile -> (HF repo, pinned revision). All three share the architecture (identical config.json and | |
| #: modeling code); they differ in weights, image-processor pixel limits, chat template and task set. | |
| WEIGHTS: Dict[str, Tuple[str, str]] = { | |
| "vl": ("PaddlePaddle/PaddleOCR-VL", "dae2996584399c9fb7eabfeecf8acd2c7cae95b7"), | |
| "1.5": ("PaddlePaddle/PaddleOCR-VL-1.5", "1e5216083435c7851caad5d691ef55aab81b5949"), | |
| "1.6": ("PaddlePaddle/PaddleOCR-VL-1.6", "132c45f52c0a26ed5a6b2f6bd8e3985794cc27dd"), | |
| } | |
| PROFILES = tuple(WEIGHTS) | |
| DEFAULT_PROFILE = "1.6" | |
| WEIGHT_FILES = ["model.safetensors", "config.json", "generation_config.json", "preprocessor_config.json", | |
| "tokenizer.json", "tokenizer_config.json", "added_tokens.json", "special_tokens_map.json", | |
| "chat_template.jinja", "LICENSE", "README.md"] | |
| # fixed token ids (tokenizer.json, identical ids in the three repos) | |
| UNK, BOS, EOS = 0, 1, 2 | |
| CLS = 100273 # <|begin_of_sentence|> (checked against the tokenizer at load) | |
| IMAGE_PLACEHOLDER = 100295 | |
| IMAGE_START, IMAGE_END = 101305, 101306 | |
| LOC0 = 100297 # <|LOC_0|> .. <|LOC_1000|> = 100297 .. 101297 | |
| #: documented task prompts (model cards); spotting / seal exist from 1.5 on | |
| TASKS: Dict[str, str] = { | |
| "ocr": "OCR:", | |
| "table": "Table Recognition:", | |
| "formula": "Formula Recognition:", | |
| "chart": "Chart Recognition:", | |
| "spotting": "Spotting:", | |
| "seal": "Seal Recognition:", | |
| } | |
| PROFILE_TASKS = {"vl": ("ocr", "table", "formula", "chart"), | |
| "1.5": tuple(TASKS), "1.6": tuple(TASKS)} | |
| #: spotting preset (1.5 / 1.6 model cards): 2x LANCZOS upscale when both sides < 1500, max_pixels 2048 * 28 * 28 | |
| SPOTTING_UPSCALE_THRESHOLD = 1500 | |
| SPOTTING_MAX_PIXELS = 2048 * 28 * 28 | |
| class VisionConfig: | |
| d: int = 1152 | |
| layers: int = 27 | |
| heads: int = 16 | |
| ffn: int = 4304 | |
| patch: int = 14 | |
| merge: int = 2 | |
| pos_grid: int = 27 # 384 / 14: learned 27 x 27 position table, bilinearly resized per image | |
| eps: float = 1e-6 | |
| proj_eps: float = 1e-5 | |
| rope_theta: float = 10000.0 | |
| def head_dim(self) -> int: | |
| return self.d // self.heads # 72 | |
| def patch_dim(self) -> int: | |
| return 3 * self.patch * self.patch # 588 | |
| class DecoderConfig: | |
| d: int = 1024 | |
| inter: int = 3072 | |
| layers: int = 18 | |
| heads: int = 16 | |
| kv_heads: int = 2 | |
| head_dim: int = 128 | |
| vocab: int = 103424 | |
| eps: float = 1e-5 | |
| theta: float = 500000.0 | |
| mrope_section: Tuple[int, int, int] = (16, 24, 24) | |
| class ProfileConfig: | |
| """Per-version pre / post-processing (everything else is shared).""" | |
| profile: str | |
| min_pixels: int | |
| max_pixels: int | |
| assistant: str # generation prompt suffix of the chat template | |
| tasks: Tuple[str, ...] | |
| default_max_new_tokens: int | |
| PROFILE_CONFIGS: Dict[str, ProfileConfig] = { | |
| # vl: preprocessor_config min 147384 / max 2822400, template "Assistant: ", README max_new_tokens 1024 | |
| "vl": ProfileConfig("vl", 147384, 2822400, "Assistant: ", PROFILE_TASKS["vl"], 1024), | |
| # 1.5 / 1.6: min 112896 / max 1003520 (= 1280 * 28 * 28), template "Assistant:\n", README max_new_tokens 512 | |
| "1.5": ProfileConfig("1.5", 112896, 1003520, "Assistant:\n", PROFILE_TASKS["1.5"], 512), | |
| "1.6": ProfileConfig("1.6", 112896, 1003520, "Assistant:\n", PROFILE_TASKS["1.6"], 512), | |
| } | |
| class ModelConfig: | |
| profile: str | |
| vision: VisionConfig | |
| dec: DecoderConfig | |
| prof: ProfileConfig | |
| def builtin(cls, profile: str) -> "ModelConfig": | |
| if profile not in PROFILE_CONFIGS: | |
| raise ValueError(f"unknown profile {profile!r}; known {PROFILES}") | |
| return cls(profile, VisionConfig(), DecoderConfig(), PROFILE_CONFIGS[profile]) | |
| def from_dir(cls, path: str, profile: str) -> "ModelConfig": | |
| """Checks the checkpoint against the built-in architecture (the port supports exactly this one).""" | |
| c = json.load(open(os.path.join(path, "config.json"))) | |
| v = c["vision_config"] | |
| vis = VisionConfig(d=v["hidden_size"], layers=v["num_hidden_layers"], heads=v["num_attention_heads"], | |
| ffn=v["intermediate_size"], patch=v["patch_size"], merge=v["spatial_merge_size"], | |
| pos_grid=v["image_size"] // v["patch_size"], eps=v["layer_norm_eps"]) | |
| dec = DecoderConfig(d=c["hidden_size"], inter=c["intermediate_size"], layers=c["num_hidden_layers"], | |
| heads=c["num_attention_heads"], kv_heads=c["num_key_value_heads"], | |
| head_dim=c["head_dim"], vocab=c["vocab_size"], eps=c["rms_norm_eps"], | |
| theta=float(c["rope_theta"]), | |
| mrope_section=tuple(c["rope_scaling"]["mrope_section"])) | |
| if vis != VisionConfig() or dec != DecoderConfig(): | |
| raise ValueError(f"{path}: architecture differs from PaddleOCR-VL 0.9B ({vis}, {dec})") | |
| pp = os.path.join(path, "preprocessor_config.json") | |
| base = PROFILE_CONFIGS[profile] | |
| if os.path.exists(pp): | |
| p = json.load(open(pp)) | |
| base = ProfileConfig(profile, int(p["min_pixels"]), int(p["max_pixels"]), base.assistant, base.tasks, | |
| base.default_max_new_tokens) | |
| return cls(profile, vis, dec, base) | |
| def resolve_weights_dir(profile: str, revision: Optional[str] = None, cache_dir: Optional[str] = None) -> str: | |
| """Local snapshot dir of the profile's pinned weights (PADDLEOCR_WEIGHTS_DIR overrides; else the HF cache -- | |
| ``tt-model serve`` fetched the profile's checkpoint at its pinned commit -- downloading if needed; | |
| HF_HUB_OFFLINE=1: the cache only).""" | |
| env = os.environ.get("PADDLEOCR_WEIGHTS_DIR") | |
| if env: | |
| return env | |
| repo, rev = WEIGHTS[profile] | |
| from huggingface_hub import snapshot_download | |
| return snapshot_download(repo_id=repo, revision=revision or rev, allow_patterns=WEIGHT_FILES, cache_dir=cache_dir, | |
| local_files_only=os.environ.get("HF_HUB_OFFLINE") == "1") | |
| def ceil_to(n: int, m: int) -> int: | |
| return -(-int(n) // m) * m | |
| #: prefill bucket steps (prompt tokens); the smallest prompt is 157 tokens (min_pixels: 144 image tokens + 13) | |
| PRE_BASE = (192, 256, 384, 512, 768, 1024, 1280, 1536, 2048, 2560, 3072, 3712) | |
| def derive_pre_buckets(vis_buckets, extra: int = 64) -> List[int]: | |
| """Prefill buckets up to the largest prompt of the largest vision bucket (image tokens + up to ``extra`` text | |
| tokens): the PRE_BASE steps at least 128 below it, then that top bucket (a multiple of 32).""" | |
| top = ceil_to(max(int(b) for b in vis_buckets) // 4 + int(extra), 32) | |
| return sorted({b for b in PRE_BASE if b <= top - 128} | {top}) | |