File size: 7,566 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
"""Visual tokenizer: a small convolutional autoencoder with Finite Scalar Quantization (FSQ).



FSQ (Mentzer et al., 2023) replaces a learned VQ codebook with per-channel rounding to a fixed

grid, so there is no codebook collapse and no commitment/EMA machinery.  A 64x64 RGB frame is

downsampled 8x to an 8x8 grid; each cell's FSQ code is one discrete visual token.



The tokenizer is a *codec* (pixels <-> tokens).  It is frozen while the Quasar transformer is

trained and never generates content on its own.

"""
from __future__ import annotations

import json
from pathlib import Path

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file, save_file


class FSQ(nn.Module):
    def __init__(self, levels: tuple[int, ...]):
        super().__init__()
        lv = torch.tensor(levels, dtype=torch.int64)
        self.register_buffer("levels", lv, persistent=False)
        self.register_buffer("basis", torch.cumprod(torch.tensor([1, *levels[:-1]]), 0), persistent=False)
        self.codebook_size = int(np.prod(levels))

    def quantize(self, z: torch.Tensor) -> torch.Tensor:
        """z: [..., d] -> values in [-1, 1] on the FSQ grid (straight-through gradient)."""
        lv = self.levels.to(z.dtype)
        half_l = (lv - 1) * (1 + 1e-3) / 2
        offset = torch.where(self.levels % 2 == 0, 0.5, 0.0).to(z.dtype)
        bounded = torch.tanh(z + torch.atanh(offset / half_l)) * half_l - offset
        q = bounded + (bounded.round() - bounded).detach()
        return q / (self.levels // 2).to(z.dtype)

    def codes_to_indices(self, zhat: torch.Tensor) -> torch.Tensor:
        hw = self.levels // 2
        return ((zhat * hw + hw).round().long() * self.basis).sum(-1)

    def indices_to_codes(self, idx: torch.Tensor) -> torch.Tensor:
        hw = self.levels // 2
        return ((idx.unsqueeze(-1) // self.basis) % self.levels - hw).float() / hw.float()


class ResBlock(nn.Module):
    def __init__(self, cin: int, cout: int):
        super().__init__()
        self.n1, self.c1 = nn.GroupNorm(8, cin), nn.Conv2d(cin, cout, 3, padding=1)
        self.n2, self.c2 = nn.GroupNorm(8, cout), nn.Conv2d(cout, cout, 3, padding=1)
        self.skip = nn.Conv2d(cin, cout, 1) if cin != cout else nn.Identity()

    def forward(self, x):
        h = self.c1(F.silu(self.n1(x)))
        return self.skip(x) + self.c2(F.silu(self.n2(h)))


class VisualTokenizer(nn.Module):
    def __init__(self, levels: tuple[int, ...] = (8, 5, 5, 5), ch: int = 64, ch_mult: tuple[int, ...] = (1, 2, 4)):
        super().__init__()
        self.config = {"levels": list(levels), "ch": ch, "ch_mult": list(ch_mult)}
        self.fsq = FSQ(tuple(levels))
        chans = [ch * m for m in ch_mult]
        enc: list[nn.Module] = [nn.Conv2d(3, chans[0], 3, padding=1)]
        c = chans[0]
        for co in chans:  # each stage: resblock then stride-2 downsample
            enc += [ResBlock(c, co), nn.Conv2d(co, co, 4, stride=2, padding=1)]
            c = co
        enc += [ResBlock(c, c), ResBlock(c, c), nn.GroupNorm(8, c), nn.SiLU(), nn.Conv2d(c, len(levels), 1)]
        self.encoder = nn.Sequential(*enc)
        dec: list[nn.Module] = [nn.Conv2d(len(levels), c, 3, padding=1), ResBlock(c, c), ResBlock(c, c)]
        for co in reversed(chans):
            dec += [nn.Upsample(scale_factor=2, mode="nearest"), nn.Conv2d(c, co, 3, padding=1), ResBlock(co, co)]
            c = co
        dec += [nn.GroupNorm(8, c), nn.SiLU(), nn.Conv2d(c, 3, 3, padding=1)]
        self.decoder = nn.Sequential(*dec)
        self.downsample = 2 ** len(ch_mult)

    @property
    def codebook_size(self) -> int:
        return self.fsq.codebook_size

    # -- pixel helpers ---------------------------------------------------------------------
    @staticmethod
    def to_tensor(images: np.ndarray | torch.Tensor) -> torch.Tensor:
        """uint8 [N,H,W,3] -> float [N,3,H,W] in [-1,1]."""
        x = torch.tensor(np.asarray(images)).float()
        return x.permute(0, 3, 1, 2) / 127.5 - 1.0

    @staticmethod
    def to_uint8(x: torch.Tensor) -> np.ndarray:
        return ((x.float().clamp(-1, 1) + 1) * 127.5).round().byte().permute(0, 2, 3, 1).cpu().numpy()

    # -- core ------------------------------------------------------------------------------
    def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        """x: float [N,3,H,W] in [-1,1] -> (reconstruction, indices [N,h,w])."""
        zhat = self.fsq.quantize(self.encoder(x).permute(0, 2, 3, 1))
        return self.decoder(zhat.permute(0, 3, 1, 2)), self.fsq.codes_to_indices(zhat)

    @torch.no_grad()
    def encode(self, images: np.ndarray, batch: int = 512) -> np.ndarray:
        """uint8 [N,H,W,3] (or [N,T,H,W,3] for video) -> int64 token grid [N,(T,)h,w]."""
        images = np.asarray(images)
        lead = images.shape[:-3]
        flat = images.reshape(-1, *images.shape[-3:])
        dev = next(self.parameters()).device
        out = []
        for i in range(0, len(flat), batch):
            z = self.encoder(self.to_tensor(flat[i : i + batch]).to(dev)).permute(0, 2, 3, 1)
            out.append(self.fsq.codes_to_indices(self.fsq.quantize(z)).cpu().numpy())
        idx = np.concatenate(out)
        return idx.reshape(*lead, *idx.shape[1:])

    @torch.no_grad()
    def decode(self, indices: np.ndarray | torch.Tensor, batch: int = 512) -> np.ndarray:
        """int token grid [N,(T,)h,w] -> uint8 [N,(T,)H,W,3]."""
        idx = torch.as_tensor(np.asarray(indices), dtype=torch.long)
        lead = idx.shape[:-2]
        flat = idx.reshape(-1, *idx.shape[-2:])
        dev = next(self.parameters()).device
        out = []
        for i in range(0, len(flat), batch):
            zhat = self.fsq.indices_to_codes(flat[i : i + batch].to(dev))
            out.append(self.to_uint8(self.decoder(zhat.permute(0, 3, 1, 2))))
        px = np.concatenate(out)
        return px.reshape(*lead, *px.shape[1:])

    # -- persistence -----------------------------------------------------------------------
    def save(self, path: str | Path, extra: dict | None = None) -> None:
        path = Path(path)
        path.mkdir(parents=True, exist_ok=True)
        save_file({k: v.contiguous() for k, v in self.state_dict().items()}, str(path / "vq.safetensors"))
        (path / "vq_config.json").write_text(json.dumps(self.config | {"codebook_size": self.codebook_size, "downsample": self.downsample} | (extra or {}), indent=2))

    @classmethod
    def load(cls, path: str | Path, device: str | torch.device = "cpu") -> "VisualTokenizer":
        path = Path(path)
        cfg = json.loads((path / "vq_config.json").read_text())
        if cfg.get('multi_resolution'):
            from .multires_emu import MultiResolutionEmuCodec
            return MultiResolutionEmuCodec(path, device)
        if cfg.get("codec") in ("emu3_restricted_1000", "emu3_full_32768"):
            from .restricted_emu import RestrictedEmuCodec
            return RestrictedEmuCodec(path, device)
        m = cls(tuple(cfg["levels"]), cfg["ch"], tuple(cfg["ch_mult"]))
        m.load_state_dict(load_file(str(path / "vq.safetensors")))
        return m.to(device).eval()


def psnr(a: np.ndarray, b: np.ndarray) -> float:
    mse = float(((a.astype(np.float64) - b.astype(np.float64)) ** 2).mean())
    return float("inf") if mse == 0 else 10 * np.log10(255.0**2 / mse)