File size: 12,299 Bytes
d2a1a41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Version-2 modality packets. One vocabulary and next-token objective for every task.



Version 1 remains immutable for old checkpoints. These are deterministic codecs and

serialization rules, not trained modality generators. Audio is frame-major RVQ.

Meshes use quantized vertex coordinates followed by indexed triangle faces.

"""
from __future__ import annotations

from dataclasses import asdict, dataclass
import json

import numpy as np

from .multimodal import Sample


MARKERS = ["pad", "bos", "eos", "input", "output", "text", "/text", "image", "/image",
           "video", "/video", "frame", "/frame", "audio", "/audio", "mesh", "/mesh",
           "vertices", "faces", "tools", "/tools", "calls", "/calls"]
TASKS = ("text", "chat_text", "t2i", "i2t", "t2v", "v2t", "vcont", "t2a", "a2t", "t2m", "m2t", "tools", "mixed", "coding")


@dataclass(frozen=True)
class UniversalVocab:
    text_size: int = 16384
    visual_size: int = 1000
    audio_size: int = 1024
    audio_books: int = 4
    coordinate_bins: int = 512
    max_vertices: int = 128
    max_faces: int = 128
    frame_tokens: int = 64
    max_frames: int = 8
    max_audio_frames: int = 160
    schema_version: int = 2
    special_tokens: tuple[str, ...] = ()

    def __post_init__(self):
        if self.schema_version not in (2, 3) or min(self.text_size, self.visual_size, self.audio_size, self.audio_books,
                                          self.coordinate_bins, self.max_vertices, self.frame_tokens, self.max_frames) < 1:
            raise ValueError("invalid v2 vocabulary")
        if len(MARKERS) + len(TASKS) + self.max_frames > 256:
            raise ValueError("structural vocabulary exceeds reserved slots")
        expected = tuple(MARKERS + ["task:" + t for t in TASKS] + ["time:" + str(i) for i in range(self.max_frames)])
        if self.schema_version == 3:
            # Append within the existing 256 reserved IDs; never renumber trained tokens.
            expected += ("resolution:128",)
        if self.special_tokens and tuple(self.special_tokens) != expected:
            raise ValueError("saved structural token registration differs from schema v2")
        object.__setattr__(self, "special_tokens", expected)

    def to_dict(self):
        d = asdict(self)
        d["special_tokens"] = list(self.special_tokens)
        return d

    @property
    def ranges(self) -> dict[str, tuple[int, int]]:
        sizes = {"text": self.text_size, "structure": 256, "vision": self.visual_size,
                 "audio": self.audio_size * self.audio_books, "coordinate": self.coordinate_bins, "index": self.max_vertices}
        out, start = {}, 0
        for k, n in sizes.items():
            out[k] = (start, start + n)
            start += n
        return out

    @property
    def size(self):
        return ((self.ranges["index"][1] + 63) // 64) * 64

    def special(self, name: str) -> int:
        return self.text_size + self.special_tokens.index(name)

    @property
    def pad(self):
        return self.special("pad")

    @property
    def visual_offset(self): return self.ranges["vision"][0]

    @property
    def tokens_per_frame(self): return 256 if self.schema_version == 3 else self.frame_tokens

    def _codes(self, values, kind, shape=None):
        a = np.asarray(values)
        lo, hi = self.ranges[kind]
        if a.dtype.kind not in "iu" or not a.size or (shape is not None and a.shape != shape) or a.min() < 0 or a.max() >= hi - lo:
            raise ValueError(f"invalid {kind} code values/shape: {a.shape}")
        return (a.reshape(-1) + lo).tolist()

    def packet(self, segment: dict, encode) -> list[int]:
        k = segment["type"]
        s = self.special
        if k in ("text", "tools", "calls"):
            text = segment.get("text", "") if k == "text" else json.dumps(segment["value"], sort_keys=True, separators=(",", ":"), ensure_ascii=False)
            ids = encode(text)
            if any(t < 0 or t >= self.text_size for t in ids):
                raise ValueError("text tokenizer does not fit the saved vocabulary")
            return [s(k), *ids, s("/" + k)]
        if k == "image":
            a = np.asarray(segment["codes"])
            if self.schema_version == 3 and a.size == 256:
                return [s(k), s('resolution:128'), *self._codes(a.reshape(-1), 'vision', (256,)), s('/image')]
            return [s(k), *self._codes(a.reshape(-1), "vision", (self.frame_tokens,)), s("/" + k)]
        if k == "video":
            a = np.asarray(segment["codes"])
            if a.ndim < 2 or not 1 <= len(a) <= self.max_frames:
                raise ValueError("video requires 1..max_frames frames")
            out = [s(k)]
            for i, frame in enumerate(a):
                out += [s("frame"), s("time:" + str(i)), *self._codes(frame.reshape(-1), "vision", (self.frame_tokens,)), s("/frame")]
            return out + [s("/video")]
        if k == "audio":
            a = np.asarray(segment["codes"])  # [frames,books], different ID range for each book
            if a.ndim != 2 or a.shape[1] != self.audio_books or not 1 <= len(a) <= self.max_audio_frames or a.dtype.kind not in "iu" or a.min() < 0 or a.max() >= self.audio_size:
                raise ValueError("audio requires integer [frames,books] codes within limits")
            offsets = self.ranges["audio"][0] + np.arange(self.audio_books) * self.audio_size
            return [s(k), *(a + offsets).reshape(-1).tolist(), s("/audio")]
        if k == "mesh":
            vertices, faces = np.asarray(segment["vertices"]), np.asarray(segment["faces"])
            if vertices.ndim != 2 or vertices.shape[1] != 3 or not 3 <= len(vertices) <= self.max_vertices:
                raise ValueError("mesh vertices must be quantized [3..max_vertices,3]")
            if faces.ndim != 2 or faces.shape[1] != 3 or not 1 <= len(faces) <= self.max_faces:
                raise ValueError("mesh faces must be triangle indices")
            if faces.min() < 0 or faces.max() >= len(vertices) or any(len(set(f)) != 3 for f in faces.tolist()):
                raise ValueError("mesh contains invalid/degenerate face indices")
            return [s(k), s("vertices"), *self._codes(vertices, "coordinate"), s("faces"), *self._codes(faces, "index"), s("/mesh")]
        raise ValueError(f"unknown packet type: {k}")

    def build(self, task: str, inputs: list[dict], outputs: list[dict], encode, context: int = 1024) -> Sample:
        if not outputs:
            raise ValueError("sample needs a target")
        t = [self.special("bos"), self.special("task:" + task), self.special("input")]
        for seg in inputs:
            t.extend(self.packet(seg, encode))
        t.append(self.special("output"))
        target = len(t)
        for seg in outputs:
            t.extend(self.packet(seg, encode))
        t.append(self.special("eos"))
        if len(t) - 1 > context:
            raise ValueError(f"sample has {len(t)-1} input tokens, exceeds context={context}; resegment at an aligned boundary")
        self.validate(t)
        return Sample(np.array(t, dtype=np.int32), target)

    def validate(self, tokens: list[int]) -> None:
        """Strict packet parser; rejects cross-book codes, broken mesh indices and wrong frame counts."""
        p = TokenGrammar(self)
        for token in tokens:
            if not p.accepts(token):
                raise ValueError(f"illegal token {token} in state {p.state}")
            p.advance(token)
        if p.state != "done":
            raise ValueError("incomplete sequence")


class TokenGrammar:
    """Incremental grammar for validation and constrained decoding (accepts/advance).



    Structural validity only: JSON schema validation for tools is a separate step.

    """
    def __init__(self, v: UniversalVocab):
        self.v, self.state, self.count = v, "bos", 0
        self.side, self.frames, self.vertices, self.faces = "input", 0, 0, 0
        self.triangle: list[int] = []
        self.output_packets = 0
        self.image_tokens = v.frame_tokens
        self.image_resolution_explicit = False

    def accepts(self, t: int) -> bool:
        v, s, st = self.v, self.v.special, self.state
        inside = lambda k: v.ranges[k][0] <= t < v.ranges[k][1]
        if st in ("bos", "input", "eos"):
            return t == s(st)
        if st == "task":
            return t in [s("task:" + k) for k in TASKS]
        if st == "packets":
            return t in [s(k) for k in ("text", "tools", "calls", "image", "video", "audio", "mesh")] or (self.side == "input" and t == s("output")) or (self.side == "output" and self.output_packets > 0 and t == s("eos"))
        if st in ("text", "tools", "calls"):
            return inside("text") or t == s("/" + st)
        if st == "image":
            if v.schema_version == 3 and self.count == 0 and not self.image_resolution_explicit and t == s('resolution:128'):
                return True
            return inside("vision") if self.count < self.image_tokens else t == s("/image")
        if st == "video":
            return (t == s("frame") and self.frames < v.max_frames) or (t == s("/video") and self.frames > 0)
        if st == "time":
            return t == s("time:" + str(self.frames))
        if st == "frame":
            return inside("vision") if self.count < v.frame_tokens else t == s("/frame")
        if st == "audio":
            book = self.count % v.audio_books
            lo = v.ranges["audio"][0] + book * v.audio_size
            return (lo <= t < lo + v.audio_size and self.count < v.audio_books * v.max_audio_frames) or (self.count > 0 and book == 0 and t == s("/audio"))
        if st == "mesh":
            return t == s("vertices")
        if st == "vertices":
            return (inside("coordinate") and self.count < 3 * v.max_vertices) or (self.count >= 9 and self.count % 3 == 0 and t == s("faces"))
        if st == "faces":
            idx = t - v.ranges["index"][0]
            return (0 <= idx < self.vertices and idx not in self.triangle and self.count < 3 * v.max_faces) or (self.count >= 3 and self.count % 3 == 0 and t == s("/mesh"))
        return False

    def advance(self, t: int):
        if not self.accepts(t):
            raise ValueError(f"illegal token {t} in {self.state}")
        v, s, st = self.v, self.v.special, self.state
        if st == "bos": self.state = "task"
        elif st == "task": self.state = "input"
        elif st == "input": self.state = "packets"
        elif st == "packets":
            if t == s("output"): self.side = "output"
            elif t == s("eos"): self.state = "done"
            else:
                self.state = next(k for k in ("text", "tools", "calls", "image", "video", "audio", "mesh") if t == s(k))
                self.count, self.frames = 0, 0
                self.image_tokens, self.image_resolution_explicit = v.frame_tokens, False
                self.output_packets += self.side == "output"
        elif st in ("text", "tools", "calls", "image", "audio"):
            if st == 'image' and v.schema_version == 3 and t == s('resolution:128'):
                self.image_tokens, self.image_resolution_explicit = 256, True
            elif t == s("/" + st): self.state = "packets"
            else: self.count += 1
        elif st == "video":
            self.state = "packets" if t == s("/video") else "time"
        elif st == "time": self.state, self.count = "frame", 0
        elif st == "frame":
            if t == s("/frame"): self.frames, self.state = self.frames + 1, "video"
            else: self.count += 1
        elif st == "mesh": self.state, self.count = "vertices", 0
        elif st == "vertices":
            if t == s("faces"): self.vertices, self.state, self.count, self.triangle = self.count // 3, "faces", 0, []
            else: self.count += 1
        elif st == "faces":
            if t == s("/mesh"): self.state = "packets"
            else:
                self.count += 1
                self.triangle.append(t - v.ranges["index"][0])
                if self.count % 3 == 0: self.triangle = []