File size: 7,494 Bytes
5c33f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Tokenizer + prompt rendering, equivalent to the official sentence-transformers 6.3 'message' path for this model:
the chat template renders ``<prompt><content>`` (system prompt first, then the user content items in order: text
verbatim, media as ``<|image|>`` / ``<|video|>`` / ``<|audio|>`` placeholders unless the text already has them),
the processor expands every placeholder into ``<boi|boa> + n x <placeholder> + <eoi|eoa>`` (video: one block per
frame), and the tokenizer (``tokenizer.json``: SentencePiece BPE + TemplateProcessing) adds ``<bos> ... <eos>``.

The official pipeline never truncates (max_seq_length is unbounded); the server caps the sequence at a compile-time
maximum with a runtime policy (``right``: keep the first tokens and the final ``<eos>`` / ``error``)."""

from __future__ import annotations

import json
import os
from dataclasses import dataclass, field
from typing import List, Optional, Sequence, Tuple

from .. import model_spec as S

TRUNCATE = ("right", "error")


class TooLong(ValueError):
    pass


@dataclass
class MediaSlot:
    kind: str           # image | video | audio
    index: int          # index into the request's list of that kind
    start: int          # first placeholder position in the token sequence
    count: int          # number of placeholder tokens (soft tokens)
    frame: int = -1     # video: frame index


@dataclass
class Sequence_:
    ids: List[int]
    slots: List[MediaSlot] = field(default_factory=list)
    truncated: bool = False

    def __len__(self):
        return len(self.ids)


def load_prompts(model_dir: str) -> dict:
    p = os.path.join(model_dir, "config_sentence_transformers.json")
    if not os.path.exists(p):
        return {}
    return dict(json.load(open(p)).get("prompts", {}))


class Tokenizer:
    def __init__(self, model_dir: str):
        from tokenizers import Tokenizer as _T

        self._tok = _T.from_file(os.path.join(model_dir, "tokenizer.json"))
        self._tok.no_truncation()
        self._tok.no_padding()
        ids = {t: self._tok.token_to_id(t) for t in ("<bos>", "<eos>", "<pad>", S.IMAGE_TOKEN, S.AUDIO_TOKEN,
                                                    S.VIDEO_TOKEN, "<|image>", "<image|>", "<|audio>", "<audio|>")}
        want = {"<bos>": S.BOS_ID, "<eos>": S.EOS_ID, "<pad>": S.PAD_ID, S.IMAGE_TOKEN: S.IMAGE_TOKEN_ID,
                S.AUDIO_TOKEN: S.AUDIO_TOKEN_ID, S.VIDEO_TOKEN: S.VIDEO_TOKEN_ID, "<|image>": S.BOI_ID,
                "<image|>": S.EOI_ID, "<|audio>": S.BOA_ID, "<audio|>": S.EOA_ID}
        if ids != want:
            raise ValueError(f"tokenizer.json special ids differ: {ids}")
        self.prompts = load_prompts(model_dir)

    def encode_text(self, texts: Sequence[str]) -> List[List[int]]:
        """Plain texts (already prompt-prefixed) -> ids incl. <bos> / <eos>."""
        return [list(e.ids) for e in self._tok.encode_batch(list(texts), add_special_tokens=True)]

    def count(self, texts: Sequence[str]) -> List[int]:
        return [len(x) for x in self.encode_text(texts)]

    def resolve_prompt(self, prompt: Optional[str], prompt_name: Optional[str]) -> str:
        if prompt is not None and prompt_name is not None:
            raise ValueError("give either prompt or prompt_name, not both")
        if prompt_name is not None:
            if prompt_name not in self.prompts:
                raise ValueError(f"unknown prompt_name {prompt_name!r}; known: {sorted(self.prompts)}")
            return self.prompts[prompt_name]
        return prompt or ""

    def build(self, items: Sequence[Tuple[str, object]], prompt: str = "", media_tokens: dict = None,
              max_len: int = 0, truncate: str = "right") -> Sequence_:
        """``items``: ordered content [(kind, value)], kind text (value str) or image / video / audio (value = index
        into that kind's list). ``media_tokens[(kind, index)]`` = soft tokens per item (video: (frames, per_frame)).
        Placeholders already inside text items are matched to media items of that kind in order (official
        'manual placeholders' rule: then no extra placeholders are appended for media items)."""
        media_tokens = media_tokens or {}
        text = "".join(v for k, v in items if k == "text")
        manual = any(ph in text for ph in (S.IMAGE_TOKEN, S.VIDEO_TOKEN, S.AUDIO_TOKEN))
        rendered = prompt
        order = []           # media kinds in placeholder order
        for kind, v in items:
            if kind == "text":
                rendered += v
            elif not manual:
                rendered += {"image": S.IMAGE_TOKEN, "video": S.VIDEO_TOKEN, "audio": S.AUDIO_TOKEN}[kind]
        # expand placeholders in rendered order
        counters = {"image": 0, "video": 0, "audio": 0}
        out, pos = [], 0
        expanded = []
        ph_kind = {S.IMAGE_TOKEN: "image", S.VIDEO_TOKEN: "video", S.AUDIO_TOKEN: "audio"}
        while True:
            nxt = [(rendered.find(ph, pos), ph) for ph in ph_kind]
            nxt = [(i, ph) for i, ph in nxt if i >= 0]
            if not nxt:
                expanded.append(("text", rendered[pos:]))
                break
            i, ph = min(nxt)
            expanded.append(("text", rendered[pos:i]))
            kind = ph_kind[ph]
            idx = counters[kind]
            counters[kind] += 1
            if (kind, idx) not in media_tokens:
                raise ValueError(f"{kind} placeholder #{idx + 1} has no matching {kind} input")
            expanded.append((kind, idx))
            pos = i + len(ph)
        for kind in counters:
            n_given = sum(1 for (k, _i) in media_tokens if k == kind)
            if counters[kind] != n_given:
                raise ValueError(f"{counters[kind]} {kind} placeholders for {n_given} {kind} inputs")
        # tokenize: text pieces separately (added special tokens split the official string the same way)
        ids = [S.BOS_ID]
        slots: List[MediaSlot] = []
        for kind, v in expanded:
            if kind == "text":
                if v:
                    ids += list(self._tok.encode(v, add_special_tokens=False).ids)
                continue
            if kind == "image":
                n = int(media_tokens[(kind, v)])
                ids.append(S.BOI_ID)
                slots.append(MediaSlot("image", v, len(ids), n))
                ids += [S.IMAGE_TOKEN_ID] * n
                ids.append(S.EOI_ID)
            elif kind == "audio":
                n = int(media_tokens[(kind, v)])
                ids.append(S.BOA_ID)
                slots.append(MediaSlot("audio", v, len(ids), n))
                ids += [S.AUDIO_TOKEN_ID] * n
                ids.append(S.EOA_ID)
            else:
                frames, per = media_tokens[(kind, v)]
                for f in range(int(frames)):
                    ids.append(S.BOI_ID)
                    slots.append(MediaSlot("video", v, len(ids), int(per), f))
                    ids += [S.VIDEO_TOKEN_ID] * int(per)
                    ids.append(S.EOI_ID)
        ids.append(S.EOS_ID)
        seq = Sequence_(ids, slots)
        if max_len and len(ids) > max_len:
            if truncate == "error" or slots:
                raise TooLong(f"sequence has {len(ids)} tokens > max {max_len}")
            if truncate not in TRUNCATE:
                raise ValueError(f"truncate {truncate!r} not in {TRUNCATE}")
            seq = Sequence_(ids[: max_len - 1] + [S.EOS_ID], [], True)
        return seq