File size: 4,053 Bytes
4342a6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""5CD-AI/Vintern-Embedding-1B text path, following the model card: processor.process_queries / process_docs
("Query: ..." / "Document: ...\\nDescribe the document." inside the model's chat template), 128-dim token vectors,
MaxSim scoring (worker.maxsim_topk). Window: text is cut to max_len - 48 tokens before the template is added, so the
template's ending is never truncated; queries use the same window (card default is 100; >99% of our queries are shorter)."""
import numpy as np, torch
from transformers import AutoModel, AutoProcessor


def _no_flash_attn_check():
    """The repo's modeling files import flash_attn inside try/except and fall back to standard attention without it, but
    transformers' static import check rejects them anyway. Drop flash_attn (and decord, used only for video input) from that check (common InternVL workaround)."""
    from transformers import dynamic_module_utils as dmu
    orig = dmu.get_imports
    if getattr(orig, "_nm_patched", False):
        return
    def get_imports(filename):
        return [i for i in orig(filename) if i not in ("flash_attn", "decord")]  # decord: video input only
    get_imports._nm_patched = True
    dmu.get_imports = get_imports


def _seed_module_cache(hf):
    """transformers 4.48 resolves the repo's relative imports (modeling_intern_vit.py, ...) inside its module cache and
    fails offline when only the entry file was copied. Copy every .py of the pinned snapshot there first."""
    import shutil
    from pathlib import Path
    from huggingface_hub import snapshot_download
    from transformers.utils import HF_MODULES_CACHE
    snap = Path(snapshot_download(hf, local_files_only=True))
    dst = Path(HF_MODULES_CACHE) / "transformers_modules" / hf / snap.name
    dst.mkdir(parents=True, exist_ok=True)
    for d in (Path(HF_MODULES_CACHE) / "transformers_modules", Path(HF_MODULES_CACHE) / "transformers_modules" / hf.split("/")[0],
              Path(HF_MODULES_CACHE) / "transformers_modules" / hf, dst):
        (d / "__init__.py").touch()
    for f in snap.glob("*.py"):
        shutil.copyfile(f, dst / f.name)


def _stub_decord():
    """processing_colinternvl2.py imports decord (video decoding) at module level; the text path never calls it and
    decord has no wheel for this Python. A stub module that fails loudly if ever used."""
    import sys, types
    if "decord" in sys.modules:
        return
    m = types.ModuleType("decord")
    def _no(*a, **k):
        raise RuntimeError("decord stub: video input is not supported in this benchmark")
    m.VideoReader, m.cpu = _no, _no
    sys.modules["decord"] = m


class Vintern:
    def __init__(self, hf, max_len=512, bs=32):
        _no_flash_attn_check()
        _stub_decord()
        _seed_module_cache(hf)
        self.model = AutoModel.from_pretrained(hf, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True,
                                               trust_remote_code=True).eval().cuda()
        self.proc = AutoProcessor.from_pretrained(hf, trust_remote_code=True)
        self.tok = self.proc.tokenizer
        self.max_len, self.bs = max_len, bs

    def _cut(self, texts):
        ids = self.tok(texts, add_special_tokens=False, truncation=True, max_length=self.max_len - 48)["input_ids"]
        return self.tok.batch_decode(ids)

    @torch.inference_mode()
    def encode(self, texts, query):
        texts = self._cut(texts)
        order = np.argsort([-len(t) for t in texts])
        out = [None] * len(texts)
        for i in range(0, len(texts), self.bs):
            idx = order[i:i + self.bs]
            chunk = [texts[k] for k in idx]
            b = (self.proc.process_queries(chunk, max_length=self.max_len) if query
                 else self.proc.process_docs(chunk, max_length=self.max_len))
            ii, am = b["input_ids"].cuda(), b["attention_mask"].cuda()
            e = self.model(input_ids=ii, attention_mask=am.bfloat16())
            for r, k in enumerate(idx):
                out[k] = e[r][am[r].bool()].to(torch.bfloat16).cpu()
        return out