Download quasar/inference/generate.py from AtlasAI-org/Quasar: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/AtlasAI-org/Quasar/resolve/main/quasar/inference/generate.py
- Command line
-
hf download hf://AtlasAI-org/Quasar/quasar/inference/generate.py
-
curl -L -o generate.py https://huggingface.co/AtlasAI-org/Quasar/resolve/main/quasar/inference/generate.py
16.5 kB
| """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 ------------------------------------------------------------------ | |
| 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 | |