File size: 16,454 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
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
"""Unified generation engine: every capability is one call into the same trained backbone.



    eng = QuasarEngine("checkpoints/quasar-exp/instruct/final")

    eng.generate_text("Once upon a time")

    eng.generate_image("a large red circle in the center on a black background")

    eng.generate_video("a small blue circle moving right on a navy background")

    eng.describe_image(img); eng.describe_video(frames); eng.continue_video(frames)

    eng.edit_image(img, "change the color to green"); eng.image_to_video(img, "... moving up ...")

    eng.chat("Make a video of a blue ball bouncing.")



The visual tokenizer only converts pixels <-> tokens; all content tokens are sampled from the

Quasar transformer.  Capabilities the checkpoint was never trained on raise CapabilityError

unless force=True, so untrained noise is never presented as a result.

"""
from __future__ import annotations

from pathlib import Path

import numpy as np
import torch
from PIL import Image

from ..data.preprocessing import load_video, prepare_image
from ..tokenizers.text import TextTokenizer
from ..tokenizers.vision import VisualTokenizer
from ..training.checkpoint import load_quasar
from .decoding import Masks, Sampling, StructureFSM, sample_next

CAPABILITY_TASKS = {
    "generate_text": ("text",), "chat": ("chat_text", "chat_mm"), "generate_image": ("t2i",), "complete_image": ("t2i",),
    "describe_image": ("i2t",), "edit_image": ("i2i",), "generate_video": ("t2v",), "image_to_video": ("t2v",),
    "continue_video": ("vcont",), "describe_video": ("v2t",),
}
TRAINED_FRAMES = 8  # clips in training have 8 frames (t0..t7)


class CapabilityError(RuntimeError):
    pass


# ------------------------------------------------------------------------------- media io
def save_video(frames: np.ndarray, path: str | Path, fps: int = 4, scale: int = 4) -> Path:
    """Write uint8 [T,H,W,3] as .mp4 (H.264, browser-playable) or .gif, upscaled `scale`x (nearest)."""
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    big = np.asarray(frames).repeat(scale, 1).repeat(scale, 2)
    if path.suffix.lower() == ".gif":
        ims = [Image.fromarray(f) for f in big]
        ims[0].save(path, save_all=True, append_images=ims[1:], duration=int(1000 / fps), loop=0)
        return path
    import imageio_ffmpeg

    T, H, W, _ = big.shape
    w = imageio_ffmpeg.write_frames(str(path), (W, H), fps=fps, codec="libx264", pix_fmt_out="yuv420p", macro_block_size=1,
                                    output_params=["-crf", "18"])
    w.send(None)
    for f in big:
        w.send(np.ascontiguousarray(f))
    w.close()
    return path


def normalize_prompt(p: str) -> str:
    """Training captions are lower-case without a trailing period."""
    return p.strip().rstrip(".").lower()


# ------------------------------------------------------------------------------- engine
class QuasarEngine:
    def __init__(self, ckpt: str | Path, device: str | None = None):
        self.ckpt = Path(ckpt)
        self.device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
        self.model, self.vocab, self.meta = load_quasar(self.ckpt, self.device)
        if getattr(self.vocab, "schema_version", 1) in (2,3):
            raise CapabilityError("This is a v2 preparation checkpoint. V2 generation/codec reconstruction must be validated and trained before exposing it in the legacy demo.")
        self.model.eval()
        self.tok = TextTokenizer.load(self.ckpt / "tokenizers" / "text_tokenizer.json")
        self.vq = VisualTokenizer.load(self.ckpt / "tokenizers" / "vq", self.device)
        self.masks = Masks(self.vocab, self.device)
        self.amp = torch.bfloat16 if self.device.type == "cuda" and torch.cuda.is_bf16_supported() else None

    # -- capability bookkeeping ------------------------------------------------------------
    def capabilities(self) -> dict[str, dict]:
        tt: dict[str, int] = {}
        for k, n in self.meta.get("task_target_tokens", {}).items():  # 'user/t2i' counts toward 't2i'
            base = k.rpartition("/")[2]
            tt[base] = tt.get(base, 0) + int(n)
        return {m: {"trained": all(tt.get(t, 0) > 0 for t in ts), "target_tokens": {t: tt.get(t, 0) for t in ts}}
                for m, ts in CAPABILITY_TASKS.items()}

    def _require(self, method: str, force: bool) -> None:
        if force:
            return
        cap = self.capabilities()[method]
        if not cap["trained"]:
            raise CapabilityError(
                f"'{method}' has not been trained in this checkpoint (stage '{self.meta.get('stage')}', "
                f"target tokens seen: {cap['target_tokens']}). Train a stage that includes these tasks, "
                f"or pass force=True to sample the untrained model anyway.")

    # -- token helpers ---------------------------------------------------------------------
    def enc(self, s: str) -> list[int]:
        return self.tok.encode(s)

    def image_codes(self, image) -> np.ndarray:
        return self.vq.encode(prepare_image(image)[None])[0]

    def video_codes(self, frames) -> np.ndarray:
        return self.vq.encode(load_video(frames)[None])[0]

    # -- core decode loop ------------------------------------------------------------------
    @torch.no_grad()
    def _decode(self, prefix: list[int], fsm_kwargs: dict, n: int, sp: Sampling, uncond_prefix: list[int] | None = None) -> list[list[int]]:
        m, dev = self.model, self.device
        if len(prefix) >= m.cfg.max_seq_len:
            raise ValueError(f"prompt is {len(prefix)} tokens; the model context is {m.cfg.max_seq_len}")
        max_len = min(m.cfg.max_seq_len, len(prefix) + sp.max_new_tokens)
        guided = uncond_prefix is not None and sp.cfg_scale != 1.0
        amp = torch.autocast(dev.type, dtype=self.amp) if self.amp else torch.autocast(dev.type, enabled=False)

        def start(pref):
            cache = m.new_cache(n, max_len)
            hist = torch.tensor(pref, device=dev).repeat(n, 1)
            with amp:
                return cache, hist, m(hist, cache=cache)[:, -1].float()

        cache, hist, logits = start(prefix)
        if guided:
            ucache, uhist, ulogits = start(uncond_prefix)
        fsms = [StructureFSM(self.vocab, **fsm_kwargs) for _ in range(n)]
        gen = torch.Generator(device=dev).manual_seed(sp.seed)
        out = torch.empty(n, 0, dtype=torch.long, device=dev)
        pos, upos = len(prefix), len(uncond_prefix or [])
        while pos < max_len and not all(f.done for f in fsms):
            cons = [f.constraint(self.masks) for f in fsms]
            forced = torch.tensor([c[0] if c[0] is not None else -1 for c in cons], device=dev)
            if (forced >= 0).all():
                nxt = forced
            else:
                legal = torch.stack([c[1] if c[1] is not None else self.masks.text for c in cons])
                lg = logits
                if guided:
                    vis = torch.tensor([f.in_visual for f in fsms], device=dev)[:, None]
                    lg = torch.where(vis, ulogits + sp.cfg_scale * (logits - ulogits), logits)
                nxt = sample_next(lg, legal, sp, gen, out, self.vocab.text_size)
                nxt = torch.where(forced >= 0, forced, nxt)
            for f, t in zip(fsms, nxt.tolist()):
                f.advance(t)
            out = torch.cat([out, nxt[:, None]], 1)
            hist = torch.cat([hist, nxt[:, None]], 1)
            if all(f.done for f in fsms) or pos + 1 >= max_len:
                break
            with amp:
                logits = m(nxt[:, None], vis_pos=m.visual_positions(hist)[:, -1:], cache=cache, start=pos)[:, -1].float()
                if guided:
                    uhist = torch.cat([uhist, nxt[:, None]], 1)
                    ulogits = m(nxt[:, None], vis_pos=m.visual_positions(uhist)[:, -1:], cache=ucache, start=upos)[:, -1].float()
            pos += 1
            upos += 1
        res = []
        for row in out.tolist():
            res.append(row[: row.index(self.vocab.eos)] if self.vocab.eos in row else row)
        return res

    def _text(self, ids: list[int]) -> str:
        return self.tok.decode([i for i in ids if i < self.vocab.text_size]).strip()

    def _visual(self, ids: list[int], kind: str) -> np.ndarray:
        segs = [s for k, s in self.vocab.parse(ids) if k == kind]
        if not segs:
            raise RuntimeError(f"generation produced no {kind} block")
        return self.vq.decode(segs[0][None])[0]

    # -- public API ------------------------------------------------------------------------
    def generate_text(self, prompt: str, sp: Sampling | None = None, force: bool = False) -> str:
        """Continue `prompt` with the base language-model head (TinyStories-style text)."""
        self._require("generate_text", force)
        sp = sp or Sampling(temperature=0.8, top_k=50, top_p=0.95, repetition_penalty=1.1, max_new_tokens=200)
        return self._text(self._decode([self.vocab.bos, self.vocab.task("text"), *self.enc(prompt)], {"mode": "text"}, 1, sp)[0])

    def generate_image(self, prompt: str, n: int = 1, sp: Sampling | None = None, force: bool = False) -> list[np.ndarray]:
        self._require("generate_image", force)
        sp = sp or Sampling(temperature=1.0, top_k=100, cfg_scale=3.0)
        v = self.vocab
        prefix = [v.bos, v.task("t2i"), *self.enc(normalize_prompt(prompt)), v.img_start]
        rows = self._decode(prefix, {"mode": "image"}, n, sp, uncond_prefix=[v.bos, v.task("t2i"), v.img_start])
        return [self.vq.decode(np.array(r[: v.tokens_per_frame]).reshape(1, *v.grid) - v.visual_offset)[0] for r in rows]

    def complete_image(self, image, prompt: str = "", keep_rows: int = 4, n: int = 1, sp: Sampling | None = None, force: bool = False) -> list[np.ndarray]:
        """Keep the top `keep_rows` token rows of `image` and let the model fill in the rest."""
        self._require("complete_image", force)
        sp = sp or Sampling(temperature=1.0, top_k=100)
        v = self.vocab
        keep = (self.image_codes(image).reshape(-1)[: keep_rows * v.grid[1]] + v.visual_offset).tolist()
        prefix = [v.bos, v.task("t2i"), *self.enc(normalize_prompt(prompt)), v.img_start, *keep]
        rows = self._decode(prefix, {"mode": "image", "codes_done": len(keep)}, n, sp)
        return [self.vq.decode(np.array(keep + r[: v.tokens_per_frame - len(keep)]).reshape(1, *v.grid) - v.visual_offset)[0] for r in rows]

    def describe_image(self, image, sp: Sampling | None = None, force: bool = False) -> str:
        self._require("describe_image", force)
        sp = sp or Sampling(temperature=0.0, max_new_tokens=48)
        v = self.vocab
        return self._text(self._decode([v.bos, v.task("i2t"), *v.image_tokens(self.image_codes(image))], {"mode": "text"}, 1, sp)[0])

    def edit_image(self, image, instruction: str, n: int = 1, sp: Sampling | None = None, force: bool = False) -> list[np.ndarray]:
        self._require("edit_image", force)
        sp = sp or Sampling(temperature=1.0, top_k=100)
        v = self.vocab
        prefix = [v.bos, v.task("i2i"), *self.enc(normalize_prompt(instruction)), *v.image_tokens(self.image_codes(image)), v.img_start]
        rows = self._decode(prefix, {"mode": "image"}, n, sp)
        return [self.vq.decode(np.array(r[: v.tokens_per_frame]).reshape(1, *v.grid) - v.visual_offset)[0] for r in rows]

    def _check_frames(self, n_frames: int, force: bool) -> None:
        if n_frames > TRAINED_FRAMES and not force:
            raise CapabilityError(f"clips were trained with {TRAINED_FRAMES} frames; use continue_video to extend beyond that")

    def generate_video(self, prompt: str, n_frames: int = 8, n: int = 1, sp: Sampling | None = None, force: bool = False) -> list[np.ndarray]:
        self._require("generate_video", force)
        self._check_frames(n_frames, force)
        sp = sp or Sampling(temperature=1.0, top_k=100, cfg_scale=3.0, max_new_tokens=n_frames * (self.vocab.tokens_per_frame + 3) + 4)
        v = self.vocab
        prefix = [v.bos, v.task("t2v"), *self.enc(normalize_prompt(prompt)), v.vid_start]
        rows = self._decode(prefix, {"mode": "video", "n_frames": n_frames, "first_ts": 0}, n, sp, uncond_prefix=[v.bos, v.task("t2v"), v.vid_start])
        return [self.vq.decode(self.vocab.parse([v.vid_start, *r])[0][1]) for r in rows]

    def image_to_video(self, image, prompt: str, n_frames: int = 8, n: int = 1, sp: Sampling | None = None, force: bool = False) -> list[np.ndarray]:
        """Use `image` as frame 0 of a text-conditioned clip and generate the remaining frames."""
        self._require("image_to_video", force)
        self._check_frames(n_frames, force)
        sp = sp or Sampling(temperature=1.0, top_k=100, cfg_scale=3.0, max_new_tokens=n_frames * (self.vocab.tokens_per_frame + 3) + 4)
        v = self.vocab
        f0 = v.frame_tokens(self.image_codes(image), 0)
        prefix = [v.bos, v.task("t2v"), *self.enc(normalize_prompt(prompt)), v.vid_start, *f0]
        rows = self._decode(prefix, {"mode": "video", "n_frames": n_frames, "first_ts": 1, "frames_done": 1}, n, sp,
                            uncond_prefix=[v.bos, v.task("t2v"), v.vid_start, *f0])
        return [self.vq.decode(self.vocab.parse([v.vid_start, *f0, *r])[0][1]) for r in rows]

    def continue_video(self, frames, n_new: int = 4, context: int = 4, sp: Sampling | None = None, force: bool = False) -> np.ndarray:
        """Append `n_new` frames.  Rolls a window of the last `context` frames (re-timestamped from t0),

        so clips can be extended beyond the 8-frame training length."""
        self._require("continue_video", force)
        v = self.vocab
        codes = self.video_codes(frames)
        context = min(context, TRAINED_FRAMES - 1)
        out = list(codes)
        while len(out) < len(codes) + n_new:
            ctx = np.stack(out[-context:])
            k = len(ctx)
            todo = min(TRAINED_FRAMES - k, len(codes) + n_new - len(out))
            s = sp or Sampling(temperature=1.0, top_k=100, seed=len(out))
            s = Sampling(**{**s.__dict__, "max_new_tokens": todo * (v.tokens_per_frame + 3) + 4})
            prefix = [v.bos, v.task("vcont"), *v.video_tokens(ctx, close=False)]
            r = self._decode(prefix, {"mode": "video", "n_frames": k + todo, "first_ts": k, "frames_done": k}, 1, s)[0]
            new = v.parse([v.vid_start, *v.video_tokens(ctx, close=False)[1:], *r])[0][1][k:]
            out += list(new)
        return self.vq.decode(np.stack(out))

    def describe_video(self, frames, sp: Sampling | None = None, force: bool = False) -> str:
        self._require("describe_video", force)
        sp = sp or Sampling(temperature=0.0, max_new_tokens=48)
        v = self.vocab
        return self._text(self._decode([v.bos, v.task("v2t"), *v.video_tokens(self.video_codes(frames))], {"mode": "text"}, 1, sp)[0])

    def chat(self, message: str, image=None, video=None, sp: Sampling | None = None, force: bool = False) -> list[tuple[str, object]]:
        """Instruction-following turn.  Returns segments: ('text', str) / ('image', array) / ('video', array)."""
        self._require("chat", force)
        v = self.vocab
        sp = sp or Sampling(temperature=0.7, top_k=50, top_p=0.95, repetition_penalty=1.1, max_new_tokens=700)
        user: list[int] = []
        if image is not None:
            user += v.image_tokens(self.image_codes(image))
        if video is not None:
            user += v.video_tokens(self.video_codes(video))
        user += self.enc((" " if user else "") + message.strip())
        prefix = [v.bos, v.user, *user, v.assistant]
        ids = self._decode(prefix, {"mode": "text", "allow_media": True, "stop_after_media": False}, 1, sp)[0]
        segs: list[tuple[str, object]] = []
        for kind, val in v.parse(ids):
            if kind == "text":
                segs.append(("text", self._text(val)))
            elif kind == "image":
                segs.append(("image", self.vq.decode(val[None])[0]))
            else:
                segs.append(("video", self.vq.decode(val)))
        return segs