File size: 36,388 Bytes
ca1a504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
# SPDX-License-Identifier: Apache-2.0
# Adapted from this workspace's GLM-OCR bundle (tt_glmocr/config.py, Apache-2.0).
"""Serving configuration of the DeepSeek-OCR family: the variant, the weight pin and every compile-time knob
(``DSOCR_*`` environment variables, read once when the server starts; the device programs, prefill buckets and traces
are built for them). The runtime (per request) parameters are validated in ``api.py`` against the caps defined here.

One package (``tt_dsocr``) serves three models, chosen by ``DSOCR_VARIANT`` (each bundle's ``tt-model.yaml`` pins it):

* ``deepseek-ocr`` (default; ``deepseek-ai/DeepSeek-OCR``, MIT): six task presets, five resolution modes.
* ``deepseek-ocr-2`` (``deepseek-ai/DeepSeek-OCR-2``, Apache-2.0): DeepEncoder V2; the two prompts of its model card
  (tasks ``markdown`` and ``free``), modes gundam / base / small (``frontend.OCR2``).
* ``unlimited-ocr-2`` (``baidu/Unlimited-OCR-2``, model card ``license: mit``): one or more page images per request
  (``<PAGE><image>`` per page, ``frontend.prepare_pages``), task ``parse`` (its default prompt ``Multi page
  parsing.``), modes gundam (2 .. 16 tiles) / base; the DASH decoder runs with ``dec=ttnn`` only; no n-gram rule by
  default, the page-count guard always on (the official ``infer``).

No torch / ttnn / numpy import at module level (the server module must import without them): the per-variant mode
table, the task prompts and the image-token formula are mirrored here from ``frontend.py`` (host tests keep the two in
sync).
"""

from __future__ import annotations

import math
import os
from dataclasses import asdict, dataclass, field, replace
from typing import Dict, Mapping, Optional, Sequence, Tuple

from .tt import sdpa_chunks as SC

ENV_PREFIX = "DSOCR"
VOCAB = 129280                    # language_config.vocab_size (every variant)
EOS_ID = 1                        # <|end▁of▁sentence|>
IMAGE_TOKEN_ID = 128815           # <image>


# ================================================================================================ variants
@dataclass(frozen=True)
class VariantInfo:
    """Per-variant facts (the mode table mirrors ``frontend.Variant``; ``host`` = the front end exists, ``device`` =
    the device engines exist)."""

    name: str                     # the served model id
    package_repo: str             # the Hub repo of the tt-model package
    weights_repo: str
    revision: str                 # 40-hex commit of weights_repo
    license: str                  # SPDX id of the weights (as their model card declares it)
    license_file: str             # under tt_dsocr/licenses/
    weight_files: Tuple[str, ...]
    newline: bool
    tile: int
    crop_min: int
    crop_max: int
    modes: Tuple[Tuple[str, int, int, bool], ...]  # (mode, base_size, image_size, crop)
    default_mode: str
    tasks: Tuple[str, ...]        # the task presets (TASK_PROMPTS[name]); the free ``prompt`` field is always there
    host: bool
    device: bool
    todo: str = ""
    display: str = ""             # the model's name in messages
    default_task: str = "markdown"
    max_pages: int = 1            # most page images per request (cap of DSOCR_MAX_PAGES; 1 = one image)
    default_max_pages: int = 1
    dec_engines: Tuple[str, ...] = ("ttnn", "mk")   # decoder engines (DSOCR_ENGINE dec=...); the first = default
    # (D20, 2026-12-02: the tt-nn decoder is the default after the megakernel hung in the verifier's soak, FAULTS #7;
    # dec=mk stays an EXPERIMENTAL opt-in: it can hang the card, which then needs a reset)
    default_context: int = 8192   # DSOCR_MAX_CONTEXT default
    default_new_tokens: int = 8192  # DSOCR_MAX_NEW_TOKENS / DSOCR_DEFAULT_MAX_NEW_TOKENS defaults
    ngram_presets: Tuple[str, ...] = ("hf", "vllm", "off")  # the first = the default (the official infer)
    # decode attention window (schift-ocr-1-beta: 128): a generated token sees the whole prompt plus the last
    # ``window`` generated tokens (itself included); the KV cache then holds the longest prompt + window rows while the
    # positions (RoPE) run up to DSOCR_MAX_CONTEXT. 0 = full causal attention.
    window: int = 0
    context_cap: int = 16384      # DSOCR_MAX_CONTEXT upper bound (positions: prompt + generated)
    # what follows the <image> placeholder the server adds to a prompt that has none: DeepSeek-OCR's presets are all
    # "<image>\n<instruction>"; schift-ocr-1-beta's trained prompt is "<image>document parsing." (no newline: its
    # model card, README "Transformers" / vLLM usage, and the official infer use the prompt as written)
    image_sep: str = "\n"

    @property
    def multipage(self) -> bool:
        return self.max_pages > 1


_OCR1_FILES = ("model-00001-of-000001.safetensors", "model.safetensors.index.json", "config.json",
               "processor_config.json", "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json",
               "README.md", "LICENSE")
_UOCR2_FILES = ("model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors",
                "model.safetensors.index.json", "config.json", "generation_config.json", "special_tokens_map.json",
                "tokenizer.json", "tokenizer_config.json", "README.md")
_SCHIFT_FILES = ("model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors",
                 "model.safetensors.index.json", "config.json", "generation_config.json", "processor_config.json",
                 "special_tokens_map.json", "tokenizer.json", "tokenizer_config.json", "README.md", "LICENSE")
SCHIFT_PROMPT = "<image>document parsing."   # the model card's prompt (schift-ocr-1-beta)
_OCR1_MODES = (("tiny", 512, 512, False), ("small", 640, 640, False), ("base", 1024, 1024, False),
               ("large", 1280, 1280, False), ("gundam", 1024, 640, True))
_TASKS = ("markdown", "ocr", "free", "figure", "describe", "locate")
#: the task presets per variant (OCR-1: == ``frontend.TASKS``; Unlimited-OCR-2: the instruction after the
#: ``<PAGE><image>`` page runs, ``frontend.uocr2_prompt``)
_OCR1_PROMPTS = {
    "markdown": "<image>\n<|grounding|>Convert the document to markdown.",
    "ocr": "<image>\n<|grounding|>OCR this image.",
    "free": "<image>\nFree OCR.",
    "figure": "<image>\nParse the figure.",
    "describe": "<image>\nDescribe this image in detail.",
    "locate": "<image>\nLocate <|ref|>{ref}<|/ref|> in the image.",
}
UOCR2_DEFAULT_PROMPT = "Multi page parsing."      # == frontend.UOCR2_DEFAULT_PROMPT
TASK_PROMPTS: Dict[str, Dict[str, str]] = {
    "deepseek-ocr": dict(_OCR1_PROMPTS),
    # DeepSeek-OCR-2's model card documents exactly these two prompts (research/dsocr/SPEC.md D11)
    "deepseek-ocr-2": {k: _OCR1_PROMPTS[k] for k in ("markdown", "free")},
    "unlimited-ocr-2": {"parse": UOCR2_DEFAULT_PROMPT},
    # schift-ocr-1-beta (a Korean fine-tune of baidu/Unlimited-OCR v1): the model card documents this one prompt
    "schift-ocr-1-beta": {"parse": SCHIFT_PROMPT},
}
#: the output format of a request without one (``prompt`` = a free prompt)
DEFAULT_FORMAT = {"markdown": "markdown", "ocr": "markdown", "free": "raw", "figure": "raw", "describe": "raw",
                  "locate": "json", "parse": "markdown", "prompt": "raw"}
PAGE_TOKEN_ID = 128827            # <PAGE> (Unlimited-OCR-2: one marker before every page's image tokens)
MAX_PAGE_TOKENS = 20000           # Unlimited-OCR-2's page-count guard: per-page output cap (official infer; fixed)

VARIANTS: Dict[str, VariantInfo] = {
    "deepseek-ocr": VariantInfo(
        "deepseek-ocr", "changh95/DeepSeek-OCR", "deepseek-ai/DeepSeek-OCR", "9f30c71f441d010e5429c532364a86705536c53a",
        "MIT", "LICENSE-MIT-DeepSeek-OCR.txt", _OCR1_FILES, True, 640, 2, 9, _OCR1_MODES, "gundam", _TASKS,
        host=True, device=True, display="DeepSeek-OCR"),
    "deepseek-ocr-2": VariantInfo(
        "deepseek-ocr-2", "changh95/DeepSeek-OCR-2", "deepseek-ai/DeepSeek-OCR-2",
        "aaa02f3811945a91062062994c5c4a3f4c0af2b0", "Apache-2.0", "LICENSE-Apache-2.0-DeepSeek-OCR-2.txt",
        _OCR1_FILES[:-1] + ("LICENSE.txt",), False, 768, 2, 6,
        (("gundam", 1024, 768, True), ("base", 1024, 1024, False), ("small", 768, 768, False)), "gundam",
        tuple(TASK_PROMPTS["deepseek-ocr-2"]), host=True, device=True, display="DeepSeek-OCR-2"),
    "unlimited-ocr-2": VariantInfo(
        "unlimited-ocr-2", "changh95/Unlimited-OCR-2", "baidu/Unlimited-OCR-2",
        "cb16b920ec2249c4b280f3aa67942e00b5099122", "MIT", "LICENSE-MIT-Unlimited-OCR.txt", _UOCR2_FILES, True, 640,
        2, 16, (("gundam", 1024, 640, True), ("base", 1024, 1024, False)), "gundam",
        tuple(TASK_PROMPTS["unlimited-ocr-2"]), host=True, device=True, display="Unlimited-OCR-2",
        default_task="parse", max_pages=32, default_max_pages=8, dec_engines=("ttnn",), default_context=16384,
        default_new_tokens=16384, ngram_presets=("off", "sglang")),
    "schift-ocr-1-beta": VariantInfo(
        "schift-ocr-1-beta", "changh95/schift-ocr-1-beta", "schift-io/schift-ocr-1-beta",
        "8fc26dce9ef6c0307a9067ee39a97ae15ccd1cbf", "MIT", "LICENSE-MIT-schift-ocr-1-beta.txt", _SCHIFT_FILES, True,
        640, 2, 32, (("gundam", 1024, 640, True), ("base", 1024, 1024, False)), "gundam",
        tuple(TASK_PROMPTS["schift-ocr-1-beta"]), host=True, device=True, display="schift-ocr-1-beta",
        default_task="parse", default_context=32768, default_new_tokens=16384, ngram_presets=("off", "hf", "vllm"),
        window=128, context_cap=32768, dec_engines=("ttnn",), image_sep=""),
}
DEFAULT_VARIANT = "deepseek-ocr"

# ================================================================================================ choices
BACKENDS = ("device", "cpu", "fake")
ENGINES = {"vis": ("ttnn",), "pre": ("ttnn",), "dec": ("mk", "ttnn")}
DEFAULT_ENGINE = {"vis": "ttnn", "pre": "ttnn", "dec": "ttnn"}  # tt.model.DeviceConfig defaults (D20)
MK_EXPERIMENTAL = ("dec=mk (the DEC-MoE decode megakernel) is EXPERIMENTAL: it stopped responding in testing (a hang "
                   "of the card that then needs a reset, tt-smi -r); the tt-nn decoder (dec=ttnn, the default) is the "
                   "safe choice")
PRECISION_KEYS = {"vis": ("bf16", "bfp8"), "vis_fid": ("HiFi4", "HiFi2", "LoFi"),
                  "pre_mlp": ("bf16", "bfp8", "bfp4"), "pre_experts": ("bf16", "bfp8", "bfp4"),
                  "pre_fid": ("HiFi4", "HiFi2", "LoFi"), "mk": ("bfp8", "bfp8h8", "bf16")}
#: the device engine's DeviceConfig defaults (vision bf16 HiFi4; prefill MLP / experts bfp8 HiFi2; the decode
#: megakernel recipe bfp8 = bfp8 layers + bf16 head)
DEFAULT_PRECISION = {"vis": "bf16", "vis_fid": "HiFi4", "pre_mlp": "bfp8", "pre_experts": "bfp8", "pre_fid": "HiFi2",
                     "mk": "bfp8"}
#: PRECISION key -> tt.model.DeviceConfig field
PRECISION_FIELDS = {"vis": "vis_wdtype", "vis_fid": "vis_fidelity", "pre_mlp": "pre_mlp",
                    "pre_experts": "pre_experts", "pre_fid": "pre_fidelity", "mk": "mk_recipe"}
MAX_CONTEXT = 16384               # DSOCR_MAX_CONTEXT upper bound (every variant)
#: Unlimited-OCR-2: page counts that get their own derived prefill bucket (base mode; others use the next one up)
PAGE_BUCKET_STEPS = (2, 3, 4, 6, 8, 12, 16, 24, 32)
PREFILL_BUCKET_STEP = 32          # explicit buckets: multiples of 32 rows (derived ones are multiples of 128)
KV_MULTIPLE = 32                  # the megakernel's max_pos rule (tt/mk_moe/program.py)
FILL_STEP = 512                   # extra prefill buckets of variants with more than 16 tiles (tt.model mirrors it)
MK_POSITIONS_PER_ATTK = 8192      # max_pos <= 8192 x attk (256 key blocks per slot)
L1_SMALL_SIZE = 1 << 15           # conv config tensors of the vision encoder (the dev scripts' value)
WORKER_L1_SIZE = 1461248 - (64 << 10)  # == tt.mk_moe.program.WORKER_L1_SIZE: kernel-config ring 69 -> 133 KiB


def ceil_to(n: int, m: int) -> int:
    return -(-int(n) // m) * m


def mode_params(v: VariantInfo, mode: str) -> Tuple[int, int, bool]:
    for m, b, s, c in v.modes:
        if m == mode:
            return b, s, c
    raise ValueError(f"unknown mode {mode!r} for {v.name}: {[m[0] for m in v.modes]}")


def image_token_count(v: VariantInfo, base_size: int, image_size: int, crop: bool, grid: Tuple[int, int]) -> int:
    """``frontend.image_token_count`` (mirrored: that module imports numpy)."""
    nl = 1 if v.newline else 0
    if crop:
        qb = math.ceil((base_size // 16) / 4)
        n = (qb + nl) * qb + 1
        if grid[0] > 1 or grid[1] > 1:
            q = math.ceil((image_size // 16) / 4)
            n += (q * grid[0] + nl) * (q * grid[1])
        return n
    q = math.ceil((image_size // 16) / 4)
    return (q + nl) * q + 1


def _grids(max_crops: int):
    return [(i, j) for i in range(1, max_crops + 1) for j in range(1, max_crops + 1) if 2 <= i * j <= max_crops]


def mode_image_tokens(v: VariantInfo, mode: str, max_crops: int) -> Tuple[int, int]:
    """(fewest, most) image tokens of ``mode`` (crop modes: no tiles .. the worst grid within ``max_crops``)."""
    b, s, c = mode_params(v, mode)
    if not c:
        n = image_token_count(v, b, s, False, (1, 1))
        return n, n
    return (image_token_count(v, b, s, True, (1, 1)),
            max([image_token_count(v, b, s, True, g) for g in _grids(max_crops)] +
                [image_token_count(v, b, s, True, (1, 1))]))


def default_prefill_buckets(v: VariantInfo, modes: Sequence[str], max_crops: int, max_prompt_text: int,
                            max_pages: int = 1) -> Tuple[int, ...]:
    """``tt.model.default_prefill_buckets`` (mirrored: that module imports torch): per enabled mode its image-token
    counts (crop modes: the worst grid and the no-tile view), each with a short task prompt (+ 32) and with the
    longest prompt text, rounded up to 128 rows. Unlimited-OCR-2 adds one ``<PAGE>`` row per page and, with base mode
    and ``max_pages`` > 1, the base-mode documents of ``PAGE_BUCKET_STEPS`` pages (short prompt) and of ``max_pages``
    pages (short and longest prompt)."""
    toks = []
    for m in modes:
        b, s, c = mode_params(v, m)
        if c:
            toks.append(max(image_token_count(v, b, s, True, g) for g in _grids(max_crops)))
            toks.append(image_token_count(v, b, s, True, (1, 1)))
        else:
            toks.append(image_token_count(v, b, s, False, (1, 1)))
    marker = 1 if v.multipage else 0
    out = set()
    for t in toks:
        out.add(ceil_to(t + marker + 32, 128))
        out.add(ceil_to(t + marker + max_prompt_text, 128))
    if v.crop_max > 16:  # up to 32 tiles (schift-ocr-1-beta): a bucket every FILL_STEP rows from 1024
        out.update(range(1024, max(out), FILL_STEP))
    if v.multipage and max_pages > 1 and "base" in modes:
        rows = page_rows(v, "base", max_crops)[1]
        for n in [k for k in PAGE_BUCKET_STEPS if k < max_pages] + [max_pages]:
            out.add(ceil_to(n * rows + 32, 128))
        out.add(ceil_to(max_pages * rows + max_prompt_text, 128))
    return tuple(sorted(out))


def page_rows(v: VariantInfo, mode: str, max_crops: int) -> Tuple[int, int]:
    """(fewest, most) prompt rows of ONE page in ``mode``: its image tokens (+ the ``<PAGE>`` marker of a multi-page
    variant)."""
    lo, hi = mode_image_tokens(v, mode, max_crops)
    m = 1 if v.multipage else 0
    return lo + m, hi + m


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], default_dec: Optional[str] = None) -> Dict[str, str]:
    """``vis=ttnn,pre=ttnn,dec=mk`` (stages not named keep the default) or a shorthand ``mk`` / ``ttnn`` (the
    decoder). ``default_dec``: the variant's default decoder engine."""
    out = dict(DEFAULT_ENGINE)
    if default_dec:
        out["dec"] = default_dec
    s = (spec or "").strip()
    if not s:
        return out
    if s in ("ttnn", "mk"):
        return dict(out, dec=s)
    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"DSOCR_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,pre_mlp=bfp8,pre_experts=bfp8,pre_fid=HiFi2,mk=bfp8`` (keys not named keep the
    default; ``vis*`` = the vision encoder, ``pre_*`` = the ttnn prefill (and the ttnn decoder), ``mk`` = the decode
    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"DSOCR_PRECISION: {kv!r}: keys / formats {PRECISION_KEYS}")
        out[k] = v
    return out


def parse_modes(v: VariantInfo, spec: Optional[str]) -> Tuple[str, ...]:
    """``tiny,small,base,large,gundam`` (any non-empty subset of the variant's modes; kept in the variant's order)."""
    known = [m[0] for m in v.modes]
    s = (spec or "").strip()
    if not s:
        return tuple(known)
    want = {x.strip().lower() for x in s.split(",") if x.strip()}
    bad = sorted(want - set(known))
    if bad or not want:
        raise ValueError(f"DSOCR_MODES={spec!r}: a non-empty subset of {known} ({v.name})")
    return tuple(m for m in known if m in want)


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 (``DSOCR_*``); ``GET /info`` reports it (:meth:`as_env`)."""

    variant: str = DEFAULT_VARIANT
    backend: str = "device"
    model_dir: Optional[str] = None              # DSOCR_MODEL_DIR: a local checkpoint dir (development)
    revision: str = VARIANTS[DEFAULT_VARIANT].revision   # TT_MODEL_WEIGHTS_REVISION (tt-model's weights pointer)
    dispatch: str = "eth"
    device_id: int = 0
    modes: Tuple[str, ...] = tuple(m[0] for m in _OCR1_MODES)
    default_mode: str = "gundam"
    max_crops: int = 9
    max_context: int = 8192                      # KV positions (prompt + generated)
    engine: Dict[str, str] = field(default_factory=lambda: dict(DEFAULT_ENGINE))
    precision: Dict[str, str] = field(default_factory=lambda: dict(DEFAULT_PRECISION))
    mk_attk: int = 4                             # attention key slots of the decode megakernel
    loop_steps: int = 1                          # megakernel launches per poll: only 1 (synchronized launches); more
    # would replay back-to-back launches from one trace, the FAULTS #1 hang pattern, never validated (refused)
    k_max: int = 64
    max_new_tokens: int = 8192                   # cap of a request's max_tokens
    default_max_new_tokens: int = 8192           # a request without max_tokens (the official infer)
    max_prompt_tokens: int = 512                 # prompt TEXT tokens (BOS + the text around <image>)
    prefill_buckets: Optional[Tuple[int, ...]] = None   # None = default_prefill_buckets(...)
    trace: bool = True
    sparse_decode: bool = True                   # ttnn decode: MoE over the 6 gathered experts (DSOCR_SPARSE_DECODE)
    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 = 1024
    cpu_dtype: str = "fp32"                      # DSOCR_BACKEND=cpu: the reference's storage dtype
    cache_dir: Optional[str] = None              # persistent cache (the megakernel's packed weight arena)
    max_pages: int = 1                           # page images per request (Unlimited-OCR-2; else 1)

    # ---- the variant
    @property
    def info(self) -> VariantInfo:
        return VARIANTS[self.variant]

    @property
    def model_name(self) -> str:
        return self.info.name

    @property
    def weights_repo(self) -> str:
        return self.info.weights_repo

    # ---- derived compile-time sizes
    @property
    def multipage_base(self) -> bool:
        """Several pages per request in base mode (Unlimited-OCR-2's default for a document) are provisioned."""
        return self.info.multipage and self.max_pages > 1 and "base" in self.modes

    @property
    def max_image_tokens(self) -> int:
        """Most image tokens of a request: any enabled mode on one image (the Gundam worst grid within
        DSOCR_MAX_CROPS); Unlimited-OCR-2 also DSOCR_MAX_PAGES base-mode pages."""
        n = max(mode_image_tokens(self.info, m, self.max_crops)[1] for m in self.modes)
        if self.multipage_base:
            n = max(n, self.max_pages * mode_image_tokens(self.info, "base", self.max_crops)[0])
        return n

    @property
    def max_page_rows(self) -> int:
        """Prompt rows of the image part of the longest provisioned request: image tokens + the ``<PAGE>`` markers
        (Unlimited-OCR-2: one page in any enabled mode, or DSOCR_MAX_PAGES base-mode pages)."""
        n = max(page_rows(self.info, m, self.max_crops)[1] for m in self.modes)
        if self.multipage_base:
            n = max(n, self.max_pages * page_rows(self.info, "base", self.max_crops)[1])
        return n

    @property
    def max_prompt(self) -> int:
        """Longest provisioned prompt in rows: image rows + prompt text tokens (BOS included)."""
        return self.max_page_rows + self.max_prompt_tokens

    @property
    def pre_buckets(self) -> Tuple[int, ...]:
        return tuple(sorted(self.prefill_buckets)) if self.prefill_buckets else default_prefill_buckets(
            self.info, self.modes, self.max_crops, self.max_prompt_tokens, self.max_pages)

    @property
    def kv_positions(self) -> int:
        """KV cache rows: DSOCR_MAX_CONTEXT, or with a decode window the largest prefill bucket + the window."""
        if self.info.window:
            return ceil_to(max(self.pre_buckets) + self.info.window, KV_MULTIPLE)
        return ceil_to(self.max_context, KV_MULTIPLE)

    def device_kwargs(self) -> Dict[str, object]:
        """The ``tt.model.DeviceConfig`` fields this configuration sets."""
        kw: Dict[str, object] = {PRECISION_FIELDS[k]: v for k, v in self.precision.items()}
        kw.update(variant=self.variant, modes=tuple(self.modes), max_crops=self.max_crops,
                  max_context=self.kv_positions, window=self.info.window,
                  max_positions=self.max_context if self.info.window else 0,
                  engine_dec=self.engine["dec"], mk_attk=self.mk_attk,
                  mk_batch=self.loop_steps, prefill_buckets=tuple(self.pre_buckets),
                  max_prompt_text=self.max_prompt_tokens, trace=self.trace, k_max=self.k_max,
                  sparse_decode=self.sparse_decode)
        return kw

    def device_config(self):
        """The device engine's ``tt.model.DeviceConfig`` (imports torch through tt.model; never ttnn). Fields the
        engine does not have are refused (the two must stay in sync)."""
        from .tt.model import DeviceConfig

        kw = self.device_kwargs()
        missing = sorted(set(kw) - set(DeviceConfig.__dataclass_fields__))
        if missing:
            raise RuntimeError(f"tt.model.DeviceConfig has no field(s) {missing}: config.py and tt/model.py disagree")
        return DeviceConfig(**kw)

    def as_env(self) -> Dict[str, str]:
        """The effective configuration, as the environment variables that set it."""
        return {
            "DSOCR_VARIANT": self.variant, "DSOCR_BACKEND": self.backend, "DSOCR_DISPATCH": self.dispatch,
            "DSOCR_MODES": ",".join(self.modes), "DSOCR_DEFAULT_MODE": self.default_mode,
            "DSOCR_MAX_CROPS": str(self.max_crops), "DSOCR_MAX_CONTEXT": str(self.max_context),
            "DSOCR_ENGINE": ",".join(f"{k}={v}" for k, v in self.engine.items()),
            "DSOCR_PRECISION": ",".join(f"{k}={v}" for k, v in self.precision.items()),
            "DSOCR_MK_ATTK": str(self.mk_attk), "DSOCR_LOOP_STEPS": str(self.loop_steps),
            "DSOCR_K_MAX": str(self.k_max), "DSOCR_MAX_NEW_TOKENS": str(self.max_new_tokens),
            "DSOCR_DEFAULT_MAX_NEW_TOKENS": str(self.default_max_new_tokens),
            "DSOCR_MAX_PROMPT_TOKENS": str(self.max_prompt_tokens),
            "DSOCR_PREFILL_BUCKETS": ",".join(map(str, self.pre_buckets)), "DSOCR_TRACE": "1" if self.trace else "0",
            "DSOCR_QUEUE_DEPTH": str(self.queue_depth), "DSOCR_QUEUE_TIMEOUT_S": f"{self.queue_timeout_s:g}",
            "DSOCR_MAX_BODY_MB": f"{self.max_body_mb:g}", "DSOCR_MAX_INPUT_MEGAPIXELS": f"{self.max_input_megapixels:g}",
            "DSOCR_ALLOW_URLS": "1" if self.allow_urls else "0", "DSOCR_URL_TIMEOUT_S": f"{self.url_timeout_s:g}",
            "DSOCR_TORCH_THREADS": str(self.torch_threads), "DSOCR_TRACE_REGION_MB": str(self.trace_region_mb),
            "DSOCR_CPU_DTYPE": self.cpu_dtype, "DSOCR_CACHE_DIR": self.cache_dir or "",
            "DSOCR_MAX_PAGES": str(self.max_pages), "TT_MODEL_WEIGHTS_REVISION": self.revision,
            "DSOCR_SPARSE_DECODE": "1" if self.sparse_decode else "0",
        }

    def as_dict(self) -> Dict[str, object]:
        d = asdict(self)
        d.update(modes=list(self.modes), prefill_buckets=list(self.pre_buckets), max_prompt=self.max_prompt,
                 max_image_tokens=self.max_image_tokens, max_page_rows=self.max_page_rows,
                 kv_positions=self.kv_positions, weights_repo=self.weights_repo)
        return d


def resolve_config(env: Optional[Mapping[str, str]] = None, **overrides) -> ServeConfig:
    """The configuration from the environment (``DSOCR_*``, ``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)
    variant = (env.get("DSOCR_VARIANT") or DEFAULT_VARIANT).strip().lower()
    if variant not in VARIANTS:
        raise ValueError(f"DSOCR_VARIANT={variant!r}: one of {sorted(VARIANTS)}")
    v = VARIANTS[variant]
    if not v.host:
        raise ValueError(f"DSOCR_VARIANT={variant!r} is not implemented yet ({v.todo})")
    backend = (env.get("DSOCR_BACKEND") or "device").strip().lower()
    backend = {"tt": "device", "ttnn": "device"}.get(backend, backend)
    if backend not in BACKENDS:
        raise ValueError(f"DSOCR_BACKEND={backend!r}: one of {BACKENDS}")
    dispatch = (env.get("DSOCR_DISPATCH") or "eth").strip().lower()
    if dispatch not in ("eth", "worker"):
        raise ValueError(f"DSOCR_DISPATCH={dispatch!r}: eth | worker")
    revision = (env.get("TT_MODEL_WEIGHTS_REVISION") or env.get("TT_WEIGHTS_REVISION") or v.revision).strip()
    cpu_dtype = (env.get("DSOCR_CPU_DTYPE") or "fp32").strip().lower()
    if cpu_dtype not in ("fp32", "bf16"):
        raise ValueError(f"DSOCR_CPU_DTYPE={cpu_dtype!r}: fp32 | bf16")
    modes = parse_modes(v, env.get("DSOCR_MODES"))
    dm = (env.get("DSOCR_DEFAULT_MODE") or "").strip().lower()
    if not dm:
        dm = v.default_mode if v.default_mode in modes else modes[0]
    cfg = ServeConfig(
        variant=variant, backend=backend, model_dir=(env.get("DSOCR_MODEL_DIR") or "").strip() or None,
        revision=revision, dispatch=dispatch, device_id=_num(env, "TT_DEVICE_ID", int, 0, 0, 64),
        modes=modes, default_mode=dm,
        max_crops=_num(env, "DSOCR_MAX_CROPS", int, v.crop_max, 2, v.crop_max),
        max_context=_num(env, "DSOCR_MAX_CONTEXT", int, v.default_context, 1024, v.context_cap),
        engine=parse_engine(env.get("DSOCR_ENGINE"), v.dec_engines[0]),
        precision=parse_precision(env.get("DSOCR_PRECISION")),
        mk_attk=_num(env, "DSOCR_MK_ATTK", int, 4, 1, 6),
        loop_steps=_num(env, "DSOCR_LOOP_STEPS", int, 1, 1, 1),
        k_max=_num(env, "DSOCR_K_MAX", int, 64, 1, 64),
        max_new_tokens=_num(env, "DSOCR_MAX_NEW_TOKENS", int, v.default_new_tokens, 16, 16384),
        default_max_new_tokens=_num(env, "DSOCR_DEFAULT_MAX_NEW_TOKENS", int, v.default_new_tokens, 1, 16384),
        max_prompt_tokens=_num(env, "DSOCR_MAX_PROMPT_TOKENS", int, 512, 16, 4096),
        prefill_buckets=parse_buckets("DSOCR_PREFILL_BUCKETS", env.get("DSOCR_PREFILL_BUCKETS"),
                                      PREFILL_BUCKET_STEP, 16384),
        trace=_bool(env, "DSOCR_TRACE", True),
        sparse_decode=_bool(env, "DSOCR_SPARSE_DECODE", True),
        queue_depth=_num(env, "DSOCR_QUEUE_DEPTH", int, 8, 0, 1024),
        queue_timeout_s=_num(env, "DSOCR_QUEUE_TIMEOUT_S", float, 300.0, 1.0, 86400.0),
        max_body_mb=_num(env, "DSOCR_MAX_BODY_MB", float, 64.0, 1.0, 1024.0),
        max_input_megapixels=_num(env, "DSOCR_MAX_INPUT_MEGAPIXELS", float, 50.0, 0.1, 400.0),
        allow_urls=_bool(env, "DSOCR_ALLOW_URLS", False),
        url_timeout_s=_num(env, "DSOCR_URL_TIMEOUT_S", float, 15.0, 1.0, 600.0),
        torch_threads=_num(env, "DSOCR_TORCH_THREADS", int, 4, 1, 64),
        trace_region_mb=_num(env, "DSOCR_TRACE_REGION_MB", int, 1024, 64, 4096),
        cpu_dtype=cpu_dtype,
        cache_dir=(env.get("DSOCR_CACHE_DIR") or env.get("TT_DIT_CACHE_DIR") or "").strip() or None,
        max_pages=_max_pages(env, v),
    )
    if overrides:
        cfg = replace(cfg, **overrides)
    validate(cfg)
    return cfg


def _max_pages(env: Mapping[str, str], v: VariantInfo) -> int:
    if not v.multipage:
        raw = env.get("DSOCR_MAX_PAGES")
        if raw is not None and str(raw).strip() not in ("", "1"):
            raise ValueError(f"DSOCR_MAX_PAGES={raw!r}: {v.name} reads one image per request (only unlimited-ocr-2 "
                             "takes several pages)")
        return 1
    return _num(env, "DSOCR_MAX_PAGES", int, v.default_max_pages, 1, v.max_pages)


def validate(cfg: ServeConfig) -> None:
    """Cross-field checks (ValueError naming the variables)."""
    if cfg.variant not in VARIANTS or not VARIANTS[cfg.variant].host:
        raise ValueError(f"DSOCR_VARIANT={cfg.variant!r}: not available")
    v = cfg.info
    if not cfg.modes or any(m not in [x[0] for x in v.modes] for m in cfg.modes):
        raise ValueError(f"DSOCR_MODES={','.join(cfg.modes)!r}: a non-empty subset of {[x[0] for x in v.modes]}")
    if cfg.default_mode not in cfg.modes:
        raise ValueError(f"DSOCR_DEFAULT_MODE={cfg.default_mode!r}: one of the enabled modes {list(cfg.modes)} "
                         "(DSOCR_MODES)")
    if not 2 <= cfg.max_crops <= v.crop_max:
        raise ValueError(f"DSOCR_MAX_CROPS={cfg.max_crops}: 2 .. {v.crop_max} ({v.name})")
    if not 1 <= cfg.max_pages <= v.max_pages:
        raise ValueError(f"DSOCR_MAX_PAGES={cfg.max_pages}: 1 .. {v.max_pages} ({v.name})")
    if cfg.engine.get("dec") not in v.dec_engines:
        raise ValueError(f"DSOCR_ENGINE: dec={cfg.engine.get('dec')}: {v.name} decodes with "
                         f"{' | '.join('dec=' + e for e in v.dec_engines)}"
                         + (" (the DASH sparse attention has no megakernel)" if v.multipage else ""))
    if cfg.default_max_new_tokens > cfg.max_new_tokens:
        raise ValueError(f"DSOCR_DEFAULT_MAX_NEW_TOKENS={cfg.default_max_new_tokens} > DSOCR_MAX_NEW_TOKENS="
                         f"{cfg.max_new_tokens}")
    pb = cfg.pre_buckets
    if v.multipage:  # the DASH prefill attention is a plain masked SDPA over each bucket: an even key-chunk split
        for b in pb:
            try:
                SC.chunks("DASH prefill attention", b, b, SC.dash_chunk(b), SC.dash_chunk(b))
            except (AssertionError, ValueError):
                raise ValueError(f"DSOCR_PREFILL_BUCKETS: {b} rows cannot be split into an even number of key chunks "
                                 f"of at most {SC.K_CHUNK_MAX} rows (the tt-metal SDPA odd-chunk issue): use a "
                                 "multiple of 128 or a neighbouring multiple of 32") from None
    if pb[-1] < cfg.max_prompt:
        raise ValueError(f"DSOCR_PREFILL_BUCKETS: the largest bucket {pb[-1]} rows < the longest prompt "
                         f"{cfg.max_prompt} ({cfg.max_page_rows} image rows of the enabled modes"
                         + (" / DSOCR_MAX_PAGES" if v.multipage else "") + " + DSOCR_MAX_PROMPT_TOKENS)")
    if v.window and cfg.max_context < pb[-1] + 64:
        raise ValueError(f"DSOCR_MAX_CONTEXT={cfg.max_context}: the positions must cover the largest prefill bucket "
                         f"({pb[-1]} rows) plus at least 64 generated tokens")
    if cfg.kv_positions < pb[-1] + 64:
        raise ValueError(f"DSOCR_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 DSOCR_MAX_CROPS / "
                         "DSOCR_MAX_PROMPT_TOKENS / DSOCR_MODES" + (" / DSOCR_MAX_PAGES" if v.multipage else ""))
    if cfg.engine["dec"] == "mk" and cfg.kv_positions > MK_POSITIONS_PER_ATTK * cfg.mk_attk:
        raise ValueError(f"DSOCR_MAX_CONTEXT={cfg.max_context}: the decode megakernel holds at most "
                         f"{MK_POSITIONS_PER_ATTK} x DSOCR_MK_ATTK = {MK_POSITIONS_PER_ATTK * cfg.mk_attk} positions")
    if not 1 <= cfg.mk_attk <= 6 or cfg.loop_steps != 1 or not 1 <= cfg.k_max <= 64:
        raise ValueError("DSOCR_MK_ATTK 1..6, DSOCR_LOOP_STEPS 1 (several megakernel launches per poll are not validated: FAULTS #1), DSOCR_K_MAX 1..64")
    for k in DEFAULT_ENGINE:
        if cfg.engine.get(k) not in ENGINES[k]:
            raise ValueError(f"DSOCR_ENGINE: {k}={cfg.engine.get(k)!r}: one of {ENGINES[k]}")


# ================================================================================================ weights
def resolve_model_dir(cfg: ServeConfig) -> str:
    """Local directory of the checkpoint: ``DSOCR_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). The checkpoint's Python files (remote code) are
    never downloaded nor executed."""
    if cfg.model_dir:
        for f in ("config.json", "tokenizer.json"):
            if not os.path.isfile(os.path.join(cfg.model_dir, f)):
                raise RuntimeError(f"DSOCR_MODEL_DIR={cfg.model_dir!r} has no {f}")
        return cfg.model_dir
    from huggingface_hub import snapshot_download

    return snapshot_download(repo_id=cfg.weights_repo, revision=cfg.revision,
                             allow_patterns=list(cfg.info.weight_files),
                             local_files_only=os.environ.get("HF_HUB_OFFLINE") == "1")