File size: 5,793 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Adapter: XingChen-AGI/TeleOCR (maker code modeling_naviocr.py, pinned revision a32e21d4f766317a6f42f341be57d374362bf843).
Runs in its own venv with transformers 4.57.1 (the version in the repo's generation_config.json).

The maker's class is a Qwen2.5-VL with a Qwen3-style text stack (head_dim 128, q/k RMSNorm, no q/k/v biases); the
processor is the native Qwen2_5_VLProcessor (no maker code). The maker's forward takes labels (library loss); we call
it with labels=None and use the shared summed target-token cross-entropy.
- prompt: the repo chat template with one image + our instruction, add_generation_prompt; target = label tokens +
  <|im_end|> (151645, the first generation stop id). Right padding for training, left padding for decoding.
- non-persistent buffers (rotary inv_freq) are restored from a fresh __init__ after loading (common.py).
- attention "sdpa" (flash-attn not installed). The `kernels` package is not installed, so
  use_kernel_forward_from_hub("RMSNorm") stays a no-op (no kernel download).
DECODING: the maker's generate path (GenerationMixin + its prepare_inputs_for_generation), greedy, no repetition
penalty (the repo's generation_config samples with temperature 0.1 and repetition_penalty 1.05; our protocol is
plain greedy for every arm).
"""
import copy

import torch
from transformers import AutoProcessor
from transformers.dynamic_module_utils import get_class_from_dynamic_module

from .common import (INSTRUCTION, assert_no_token_env, autocast, fresh_builder, master_dtype, remote_files_check,
                     restore_nonpersistent_buffers, target_loss_sum)

IM_END = 151645
PAD = 151643


class Adapter:
    NOTES = __doc__

    def __init__(self, model_dir, device, precision):
        assert_no_token_env()
        remote_files_check(model_dir)
        self.device = device
        cls = get_class_from_dynamic_module("modeling_naviocr.Qwen2_5_VLForConditionalGeneration", model_dir)
        cfg = cls.config_class.from_pretrained(model_dir)
        self.model = cls.from_pretrained(model_dir, config=copy.deepcopy(cfg), dtype=master_dtype(precision),
                                         use_safetensors=True, attn_implementation="sdpa")
        fixed = restore_nonpersistent_buffers(self.model, fresh_builder(cls, cfg, model_dir))
        self.NOTES = __doc__ + "\nnon-persistent buffers restored after loading: " + ", ".join(fixed)
        self.model.to(device)
        self.proc = AutoProcessor.from_pretrained(model_dir, trust_remote_code=False)
        self.tok = self.proc.tokenizer
        assert self.tok.convert_ids_to_tokens(IM_END) == "<|im_end|>"

    def enable_gradient_checkpointing(self):
        self.model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})

    def _prompt_text(self):
        msgs = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": INSTRUCTION}]}]
        return self.proc.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)

    def target_ids(self, text):
        return (self.tok(text, add_special_tokens=False).input_ids if text else []) + [IM_END]

    def loss(self, images, texts):
        pt = self._prompt_text()
        seqs, labs, pvs, thws = [], [], [], []
        for im, tx in zip(images, texts):
            enc = self.proc(text=[pt], images=[im], return_tensors="pt")
            ids = enc["input_ids"][0]
            tgt = self.target_ids(tx)
            seqs.append(torch.cat([ids, torch.tensor(tgt, dtype=torch.long)]))
            labs.append(torch.tensor([-100] * len(ids) + tgt, dtype=torch.long))
            pvs.append(enc["pixel_values"])
            thws.append(enc["image_grid_thw"])
        L = max(len(s) for s in seqs)
        inp = torch.full((len(seqs), L), PAD, dtype=torch.long)
        lab = torch.full((len(seqs), L), -100, dtype=torch.long)
        am = torch.zeros((len(seqs), L), dtype=torch.long)
        for i, (s, l) in enumerate(zip(seqs, labs)):
            inp[i, :len(s)] = s
            lab[i, :len(l)] = l
            am[i, :len(s)] = 1
        d = self.device
        pv = torch.cat(pvs).to(d)
        if pv.is_floating_point():
            pv = pv.to(next(self.model.parameters()).dtype)
        with autocast(d):
            out = self.model(input_ids=inp.to(d), attention_mask=am.to(d), pixel_values=pv,
                             image_grid_thw=torch.cat(thws).to(d), labels=None, use_cache=False)
        return target_loss_sum(out.logits, lab)

    def prepare_eval(self):
        self.model.eval()
        self.model.to(torch.bfloat16)

    @torch.inference_mode()
    def generate(self, images, max_new_tokens, temperature=None):
        """temperature=None: greedy, unchanged. Else the cap-retry sampling path (VLMC, 21 Nov; common.retry_sampling)."""
        from .common import retry_sampling, stop_records
        pt = self._prompt_text()
        self.tok.padding_side = "left"
        enc = self.proc(text=[pt] * len(images), images=images, padding=True, return_tensors="pt")
        d = self.device
        enc = {k: v.to(d) for k, v in enc.items()}
        enc["pixel_values"] = enc["pixel_values"].to(torch.bfloat16)
        self.model.model.rope_deltas = None
        gk = dict(max_new_tokens=max_new_tokens, do_sample=False, num_beams=1, eos_token_id=[IM_END, PAD],
                  pad_token_id=PAD, repetition_penalty=1.0, temperature=None, top_p=None, top_k=None)
        if temperature is not None:
            gk.update(retry_sampling(temperature))
        out = self.model.generate(**enc, **gk)
        new = out[:, enc["input_ids"].shape[1]:]
        if temperature is not None:
            return stop_records(self.tok, new, [IM_END, PAD])
        return self.tok.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False)