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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24191a8
 
 
 
 
dc7d8aa
 
24191a8
 
 
 
 
 
 
 
 
 
 
 
 
 
dc7d8aa
 
 
 
 
 
 
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
"""Constrained extraction and typed readouts using native Transformers models."""

from __future__ import annotations

import asyncio
import concurrent.futures
import copy
import json
import threading
from collections.abc import Callable, Iterator
from contextlib import contextmanager, nullcontext
from collections import defaultdict
from pathlib import Path
from typing import Any

import torch
from . import model as cm
from .readout import load_head, read_record
from .math import ReadoutMath, install as install_math
from .vision_cache import VisionBatchCache
from .decoder_graph import prepare as prepare_decoder_graphs

_FLASH_ATTENTION = 'kernels-community/flash-attn3@e29f138fc363b396e5d2706c8a5f6fa7d36f41e0'


def _batch_defaults(backbone: Any) -> tuple[int, int]:
    config = getattr(backbone.config, "text_config", None)
    if (backbone.device.type == "cuda" and backbone.dtype == torch.bfloat16
            and config is not None and config._attn_implementation == _FLASH_ATTENTION):
        if config.hidden_size == 4096:
            return 64, 65536
        if config.hidden_size == 5120:
            return 32, 32768
    return 8, 8192


_ATTENTION_KERNEL_LOCK = threading.RLock()


@contextmanager
def _default_attention_kernel() -> Iterator[None]:
    """Select the pinned public attention build while initializing its loader."""
    import os
    from huggingface_hub import snapshot_download
    from transformers.modeling_flash_attention_utils import lazy_import_flash_attention

    repository, revision = _FLASH_ATTENTION.rsplit("@", 1)
    build_name = "torch-stable-abi210-cu130-x86_64-linux"
    snapshot = snapshot_download(repository, revision=revision,
                                 allow_patterns=[f"build/{build_name}/**"])
    build = Path(snapshot) / "build" / build_name
    with _ATTENTION_KERNEL_LOCK:
        previous = os.environ.get("LOCAL_KERNELS")
        entries = previous.split(":") if previous else []
        entries = [entry for entry in entries if entry.partition("=")[0] != repository]
        os.environ["LOCAL_KERNELS"] = ":".join([*entries, f"{repository}={build}"])
        try:
            yield
            lazy_import_flash_attention(implementation=_FLASH_ATTENTION)
        finally:
            if previous is None:
                os.environ.pop("LOCAL_KERNELS", None)
            else:
                os.environ["LOCAL_KERNELS"] = previous


class _ConstrainedScores:
    """Capture probabilities after applying the schema's grammar constraints."""

    def __init__(self, processor: Any, score_ids: list[int], size: int) -> None:
        self.processor = processor
        self.score_ids = score_ids
        self.chosen: list[list[tuple[float, int, None]]] = [[] for _ in range(size)]
        self.first: list[list[tuple[float, int, None]]] = [[] for _ in range(size)]
        self._tokens: list[torch.Tensor] = []
        self._logprobs: list[torch.Tensor] = []
        self._first_values: torch.Tensor | None = None

    def __call__(self, input_ids: torch.Tensor, scores: torch.Tensor) -> torch.Tensor:
        if self.processor.prefilled and input_ids.is_cuda:
            input_ids = input_ids[:, -1:].cpu()
        masked = self.processor(input_ids, scores.clone())
        logprobs = torch.log_softmax(masked.float(), dim=-1)
        if not self._tokens:
            self._first_values = logprobs[:, self.score_ids]
        choices = masked.argmax(dim=-1)
        self._tokens.append(choices)
        self._logprobs.append(logprobs.gather(1, choices[:, None])[:, 0])
        return masked

    def finalize(self) -> None:
        if not self._tokens:
            return
        tokens = torch.stack(self._tokens, dim=1).cpu().tolist()
        values = torch.stack(self._logprobs, dim=1).cpu().tolist()
        self.chosen = [
            [(float(value), int(token), None)
             for token, value in zip(row_tokens, row_values, strict=True)]
            for row_tokens, row_values in zip(tokens, values, strict=True)
        ]
        if self._first_values is not None:
            selected = self._first_values.cpu().tolist()
            self.first = [
                [
                    (float(value), token, None)
                    for token, value in zip(self.score_ids, row, strict=True)
                ]
                for row in selected
            ]
        self._tokens.clear()
        self._logprobs.clear()
        self._first_values = None


class _CancellationCriteria:
    def __init__(self, cancelled: threading.Event) -> None:
        self.cancelled = cancelled

    def __call__(
        self, input_ids: torch.Tensor, scores: torch.Tensor, **kwargs: Any
    ) -> torch.Tensor:
        return torch.full(
            (input_ids.shape[0],),
            self.cancelled.is_set(),
            dtype=torch.bool,
            device=input_ids.device,
        )


class TransformersEngine:
    """Share one Transformers backbone between extraction and typed readouts."""

    def __init__(
        self,
        backbone: Any,
        head: cm.ClairicHead,
        tokenizer: Any,
        *,
        batch_size: int | None = None,
        text_batch_size: int | None = None,
        batch_token_budget: int | None = None,
    ) -> None:
        import xgrammar as xgr

        self.backbone = backbone.eval()
        self.head = head.to(backbone.device).float().eval()
        self.tokenizer = tokenizer
        default_size, default_budget = _batch_defaults(backbone)
        self.batch_size = max(1, int(default_size if batch_size is None else batch_size))
        self.text_batch_size = (
            self.batch_size if text_batch_size is None else max(1, int(text_batch_size))
        )
        self.batch_token_budget = max(1, int(
            default_budget if batch_token_budget is None else batch_token_budget
        ))
        self.device, self.dtype = backbone.device, backbone.dtype
        self.eos = tokenizer.convert_tokens_to_ids("<|im_end|>")
        self.image_token = int(backbone.config.image_token_id)
        info = xgr.TokenizerInfo.from_huggingface(
            tokenizer,
            vocab_size=backbone.get_output_embeddings().weight.shape[0],
            stop_token_ids=[self.eos],
        )
        self.compiler = xgr.GrammarCompiler(info, max_threads=2)
        self._worker = concurrent.futures.ThreadPoolExecutor(
            max_workers=1, thread_name_prefix="clairic-model"
        )
        self._vision_cache = VisionBatchCache()
        self._uncached_image_features = self.backbone.model.get_image_features
        self.backbone.model.get_image_features = self._image_features
        self._restore_math: Callable[[], None] | None = None
        self._decoder_graphs: Any = None
        self._decoder_cleanup: Any = None

    def begin_request(self) -> None:
        self._vision_cache.begin()

    async def end_request(self) -> None:
        await asyncio.get_running_loop().run_in_executor(
            self._worker, self._vision_cache.clear
        )

    def _image_features(
        self,
        pixel_values: torch.Tensor,
        image_grid_thw: torch.Tensor | None = None,
        **kwargs: Any,
    ) -> Any:
        return self._vision_cache.features(
            self._uncached_image_features,
            self.backbone.model.visual,
            pixel_values,
            image_grid_thw,
            **kwargs,
        )

    @classmethod
    def load(
        cls,
        path: Path,
        tokenizer: Any,
        *,
        device: str = "cuda",
        dtype: Any = None,
        batch_size: int | None = None,
        text_batch_size: int | None = None,
        batch_token_budget: int | None = None,
        **kwargs: Any,
    ) -> TransformersEngine:
        from transformers import Qwen3_5ForConditionalGeneration

        class _NativeQwen3_5ForConditionalGeneration(Qwen3_5ForConditionalGeneration):
            _keep_in_fp32_modules_strict: list[str] = ["A_log"]

        if dtype is None:
            dtype = torch.bfloat16 if str(device).startswith("cuda") else torch.float32
        if isinstance(dtype, str):
            dtype = getattr(torch, dtype)
        kwargs.setdefault("device_map", {"": device})
        default_flash = False
        if "attn_implementation" not in kwargs:
            attention = "sdpa"
            if str(device).startswith("cuda") and dtype == torch.bfloat16:
                if torch.cuda.get_device_capability(torch.device(device))[0] == 9:
                    attention = _FLASH_ATTENTION
                    default_flash = True
            kwargs["attn_implementation"] = {
                "text_config": attention, "vision_config": attention,
            }
        with _default_attention_kernel() if default_flash else nullcontext():
            backbone = _NativeQwen3_5ForConditionalGeneration.from_pretrained(
                path,
                dtype=dtype,
                local_files_only=True,
                **kwargs,
            )
        engine = cls(
            backbone,
            load_head(
                path,
                match_bfloat16=(
                    backbone.device.type == "cuda" and backbone.dtype == torch.bfloat16
                ),
            ),
            tokenizer,
            batch_size=batch_size,
            text_batch_size=text_batch_size,
            batch_token_budget=batch_token_budget,
        )
        try:
            engine._restore_math = install_math(backbone, engine.head)
            engine._decoder_graphs = engine._worker.submit(
                prepare_decoder_graphs, backbone, max(engine.batch_size, engine.text_batch_size)
            ).result()
        except BaseException:
            engine.shutdown()
            raise
        return engine

    def _inputs(
        self, sequences: list[list[int]], media: list[Any]
    ) -> dict[str, torch.Tensor]:
        width = max(map(len, sequences))
        pad = self.tokenizer.pad_token_id
        if pad is None:
            pad = self.eos
        inputs = {
            "input_ids": torch.tensor(
                [[pad] * (width - len(ids)) + ids for ids in sequences],
                dtype=torch.long,
                device=self.device,
            ),
            "attention_mask": torch.tensor(
                [[0] * (width - len(ids)) + [1] * len(ids) for ids in sequences],
                dtype=torch.long,
                device=self.device,
            ),
        }
        mappings = [mapping for payload in media if payload for mapping in payload]
        if mappings:
            for name in cm.MEDIA_BATCH_KEYS:
                inputs[name] = torch.cat(
                    [mapping[name] for mapping in mappings], dim=0
                ).to(
                    device=self.device,
                    dtype=self.dtype if name == "pixel_values" else torch.long,
                )
            inputs["mm_token_type_ids"] = (
                inputs["input_ids"] == self.image_token
            ).long()
        self._vision_cache.prepare(mappings, inputs, self.backbone.model.visual.dtype)
        return inputs

    def _grammar(self, parameters: dict[str, Any]) -> Any:
        if "json_schema" in parameters:
            value = parameters["json_schema"]
            return self.compiler.compile_json_schema(
                json.loads(value) if isinstance(value, str) else value,
                any_whitespace=True,
            )
        if "regex" in parameters:
            return self.compiler.compile_regex(parameters["regex"])
        if "ebnf" in parameters:
            return self.compiler.compile_grammar(parameters["ebnf"])
        raise ValueError(
            "Extraction continuations require a JSON schema, regex, or grammar"
        )

    @torch.inference_mode()
    def _generate(
        self,
        *,
        input_ids: list[int] | list[list[int]],
        image_data: Any = None,
        sampling_params: dict[str, Any] | list[dict[str, Any]],
        rid: Any = None,
        token_ids_logprob: list[int] | None = None,
        _cancelled: threading.Event | None = None,
        **kwargs: Any,
    ) -> Any:
        from xgrammar.contrib.hf import LogitsProcessor

        if _cancelled is not None and _cancelled.is_set():
            raise RuntimeError("Inference cancelled")
        if not input_ids:
            return []
        single = isinstance(input_ids[0], int)
        sequences = [input_ids] if single else input_ids
        size = len(sequences)
        if not size:
            return []
        parameters = (
            [sampling_params] * size
            if isinstance(sampling_params, dict)
            else sampling_params
        )
        media = [image_data] if single else (image_data or [None] * size)
        ids = [rid] if single else (rid or [None] * size)
        if not (len(parameters) == len(media) == len(ids) == size):
            raise ValueError("Extraction batch arguments have inconsistent lengths")
        batch_size = self.batch_size if any(media) else self.text_batch_size
        results: list[Any] = [None] * size
        groups: dict[tuple[int, tuple[int, ...]], list[int]] = defaultdict(list)
        for index, params in enumerate(parameters):
            if params.get("temperature", 0) != 0:
                raise ValueError("Clairic extraction uses deterministic decoding")
            groups[
                (
                    int(params.get("max_new_tokens", 256)),
                    tuple(params.get("stop_token_ids", [self.eos])),
                )
            ].append(index)
        for (maximum, stop_ids), indices in groups.items():
            pending: list[int] = []
            width = 0
            chunks: list[list[int]] = []
            for index in indices:
                length = len(sequences[index])
                if pending and (
                    len(pending) >= batch_size
                    or max(width, length) * (len(pending) + 1) > self.batch_token_budget
                ):
                    chunks.append(pending)
                    pending, width = [], 0
                pending.append(index)
                width = max(width, length)
            if pending:
                chunks.append(pending)
            for chunk in chunks:
                if _cancelled is not None and _cancelled.is_set():
                    raise RuntimeError("Inference cancelled")
                inputs = self._inputs(
                    [sequences[i] for i in chunk], [media[i] for i in chunk]
                )
                scores = _ConstrainedScores(
                    LogitsProcessor([self._grammar(parameters[i]) for i in chunk]),
                    token_ids_logprob or [],
                    len(chunk),
                )
                config = copy.deepcopy(self.backbone.generation_config)
                config.do_sample, config.num_beams = False, 1
                config.temperature, config.top_p, config.top_k = None, None, None
                config.max_new_tokens, config.use_cache = maximum, True
                config.eos_token_id = list(stop_ids)
                config.pad_token_id = self.tokenizer.pad_token_id or self.eos
                scope = (self._decoder_graphs.request(len(chunk))
                         if self._decoder_graphs is not None else nullcontext(None))
                with scope as native_cache:
                    generated = self.backbone.generate(
                        **inputs,
                        **({"past_key_values": native_cache} if native_cache is not None else {}),
                        generation_config=config,
                        logits_processor=[scores],
                        stopping_criteria=[_CancellationCriteria(_cancelled)]
                        if _cancelled is not None
                        else [],
                    )
                if _cancelled is not None and _cancelled.is_set():
                    raise RuntimeError("Inference cancelled")
                scores.finalize()
                continuations = (
                    generated[:, inputs["input_ids"].shape[1] :].cpu().tolist()
                )
                for offset, (index, continuation) in enumerate(
                    zip(chunk, continuations, strict=True)
                ):
                    stop = next(
                        (
                            i
                            for i, token in enumerate(continuation)
                            if token in stop_ids
                        ),
                        None,
                    )
                    output = (
                        continuation[: stop + 1] if stop is not None else continuation
                    )
                    logprobs = scores.chosen[offset][: len(output)]
                    if [item[1] for item in logprobs] != output:
                        raise RuntimeError(
                            "Generated tokens differ from constrained confidence scores"
                        )
                    text_ids = output[:-1] if stop is not None else output
                    results[index] = {
                        "output_ids": output,
                        "text": self.tokenizer.decode(
                            text_ids,
                            skip_special_tokens=False,
                            clean_up_tokenization_spaces=False,
                        ),
                        "meta_info": {
                            "id": ids[index],
                            "completion_tokens": len(output),
                            "finish_reason": {"type": "stop", "matched": output[-1]}
                            if stop is not None
                            else {"type": "length"},
                            "output_token_logprobs": logprobs,
                            "output_token_ids_logprobs": [scores.first[offset]],
                        },
                    }
        return results[0] if single else results

    async def async_generate(self, **kwargs: Any) -> Any:
        return await self._submit(
            lambda cancelled: self._generate(_cancelled=cancelled, **kwargs)
        )

    async def _submit(self, operation: Callable[[threading.Event], Any]) -> Any:
        cancelled = threading.Event()
        future = asyncio.get_running_loop().run_in_executor(
            self._worker, lambda: operation(cancelled)
        )
        try:
            return await asyncio.shield(future)
        except asyncio.CancelledError:
            cancelled.set()
            # Admission stays occupied until the worker has actually stopped.
            # A prefill cannot be interrupted; generation checks between tokens.
            while not future.done():
                try:
                    await asyncio.shield(future)
                except asyncio.CancelledError:
                    continue
                except Exception:
                    break
            if not future.cancelled():
                future.exception()
            raise

    @torch.inference_mode()
    def _read_typed(
        self,
        item: cm.EncodedRecord,
        media: Any,
        _cancelled: threading.Event | None = None,
    ) -> dict[str, dict[str, Any]]:
        if _cancelled is not None and _cancelled.is_set():
            raise RuntimeError("Inference cancelled")
        inputs = self._inputs([list(item.input_ids)], [media])
        output = self.backbone.model(**inputs, use_cache=False, return_dict=True)
        if _cancelled is not None and _cancelled.is_set():
            raise RuntimeError("Inference cancelled")
        scope = (
            ReadoutMath()
            if str(self.device).startswith("cuda") and self.dtype == torch.bfloat16
            else nullcontext()
        )
        with scope:
            values = read_record(
                self.head,
                output.last_hidden_state[0],
                item,
                self.backbone.get_output_embeddings().weight,
            )
        values = cm.expand_output(
            cm.compact_output(values).cpu(),
            item,
            bins=self.head.bins.out_features,
            estimate_lexical=self.head.estimate_lexical,
            span_trim=self.head.span_trim,
            number_groups=self.head.number_groups,
            number_pointer=self.head.number_pointer,
        )
        return cm.decode_record(values, item, self.tokenizer)

    async def read_typed(
        self, item: cm.EncodedRecord, media: Any = None
    ) -> dict[str, dict[str, Any]]:
        return await self._submit(
            lambda cancelled: self._read_typed(item, media, _cancelled=cancelled)
        )

    def _decoder_diagnostics(self) -> Any:
        if self._decoder_graphs is not None:
            return self._decoder_graphs.diagnostics()
        return self._decoder_cleanup

    def shutdown(self) -> None:
        try:
            manager, self._decoder_graphs = self._decoder_graphs, None
            def close_graphs() -> None:
                try:
                    manager.close()
                finally:
                    self._decoder_cleanup = manager.diagnostics()
            try:
                if manager is not None:
                    if threading.get_ident() == manager.thread:
                        close_graphs()
                    else:
                        self._worker.submit(close_graphs).result()
            finally:
                self._worker.shutdown(wait=True, cancel_futures=True)
            self._vision_cache.clear()
            if self.backbone.model.get_image_features == self._image_features:
                self.backbone.model.get_image_features = self._uncached_image_features
        finally:
            restore, self._restore_math = self._restore_math, None
            if restore is not None:
                restore()