File size: 14,945 Bytes
8c31d70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Optional

import torch
from einops import rearrange

from .ar_tokenizer_quantizers import FSQuantizer

# Make sure jit model output consistenly during consecutive calls
# Check here: https://github.com/pytorch/pytorch/issues/74534
torch._C._jit_set_texpr_fuser_enabled(False)


def load_jit_model(jit_filepath: str = None, device: str = "cuda") -> torch.jit.ScriptModule:
    """Loads a torch.jit.ScriptModule from a filepath.

    Args:
        jit_filepath: The filepath to the JIT-compiled model.
        device: The device to load the model onto, default=cuda.
    Returns:
        The JIT compiled model loaded to device and on eval mode.
    """
    # Make sure jit model output consistenly during consecutive calls
    # Check here: https://github.com/pytorch/pytorch/issues/74534
    torch._C._jit_set_texpr_fuser_enabled(False)

    model = torch.jit.load(jit_filepath)
    return model.eval().to(device)


class BaseDiscreteVideoFSQTokenizer(torch.nn.Module):
    """
    A base class for  Discrete Video FSQ Tokenizer that handles data type conversions, and normalization
    using provided mean and standard deviation values for latent space representation.
    Derived classes should load pre-trained encoder and decoder components into a encoder and decoder attributes.

    Attributes:
        encoder (Module | Callable): Encoder loaded from storage.
        decoder (Module | Callable): Decoder loaded from storage.
        dtype (dtype): Data type for model tensors, determined by whether bf16 is enabled.

    Args:
        name (str): Name of the model, used for differentiating cache file paths.
        latent_ch (int, optional): Number of latent channels (default is 6).
        is_bf16 (bool, optional): Flag to use Brain Floating Point 16-bit data type (default is True).
        pixel_chunk_duration (int): The duration (in number of frames) of each chunk of video data at the pixel level.
        latent_chunk_duration (int): The duration (in number of frames) of each chunk at the latent representation level.
        max_enc_batch_size (int): The maximum batch size to process in one go to avoid memory overflow.
        level (list[int]): The level defined in FSQ quantizer.
        compression_ratio (list[int]): The compression factor for (T, H, W).
    """

    def __init__(
        self,
        name: str,
        latent_ch: int = 6,
        is_bf16: bool = True,
        pixel_chunk_duration: int = 25,
        latent_chunk_duration: int = 4,
        max_enc_batch_size: int = 8,
        max_dec_batch_size: int = 4,
        levels: list[int] = [8, 8, 8, 5, 5, 5],
        compression_ratio: list[int] = [8, 16, 16],
    ):
        super().__init__()
        self.channel = latent_ch
        self.name = name
        dtype = torch.bfloat16 if is_bf16 else torch.float32
        self.dtype = dtype
        self.pixel_chunk_duration = pixel_chunk_duration
        self.latent_chunk_duration = latent_chunk_duration
        self.max_enc_batch_size = max_enc_batch_size
        self.max_dec_batch_size = max_dec_batch_size
        self.levels = levels
        self.compress_ratio = compression_ratio
        self.fsq_quantizer = FSQuantizer(levels)

    @property
    def latent_ch(self) -> int:
        """
        Returns the number of latent channels in the tokenizer.
        """
        return self.channel

    @torch.no_grad()
    def encode(self, state: torch.Tensor, pixel_chunk_duration: Optional[int] = None) -> torch.Tensor:
        B, C, T, H, W = state.shape
        if pixel_chunk_duration is None:
            # Use the default pixel chunk duration and latent chunk duration
            pixel_chunk_duration = self.pixel_chunk_duration
            latent_chunk_duration = self.latent_chunk_duration
        else:
            # Update the latent chunk duration based on the given pixel chunk duration
            latent_chunk_duration = 1 + (pixel_chunk_duration - 1) // self.compress_ratio[0]

        assert (
            T % pixel_chunk_duration == 0
        ), f"Temporal dimension {T} is not divisible by chunk_length {pixel_chunk_duration}"
        state = rearrange(state, "b c (n t) h w -> (b n) c t h w", t=pixel_chunk_duration)

        # use max_enc_batch_size to avoid OOM
        if state.shape[0] > self.max_enc_batch_size:
            quantized_out_list = []
            indices_list = []
            for i in range(0, state.shape[0], self.max_enc_batch_size):
                indices, quantized_out, _ = self.encoder(state[i : i + self.max_enc_batch_size].to(self.dtype))
                quantized_out_list.append(quantized_out)
                indices_list.append(indices)
            quantized_out = torch.cat(quantized_out_list, dim=0)
            indices = torch.cat(indices_list, dim=0)
        else:
            indices, quantized_out, _ = self.encoder(state.to(self.dtype))
        assert quantized_out.shape[2] == latent_chunk_duration
        return rearrange(quantized_out, "(b n) c t h w -> b c (n t) h w", b=B), rearrange(
            indices, "(b n) t h w -> b (n t) h w", b=B
        )

    @torch.no_grad()
    def decode(self, indices: torch.Tensor, pixel_chunk_duration: Optional[int] = None) -> torch.Tensor:
        B, T, _, _ = indices.shape
        if pixel_chunk_duration is None:
            pixel_chunk_duration = self.pixel_chunk_duration
            latent_chunk_duration = self.latent_chunk_duration
        else:
            latent_chunk_duration = 1 + (pixel_chunk_duration - 1) // self.compress_ratio[0]
        assert (
            T % latent_chunk_duration == 0
        ), f"Temporal dimension {T} is not divisible by chunk_length {latent_chunk_duration}"
        indices = rearrange(indices, "b (n t) h w -> (b n) t h w", t=latent_chunk_duration)

        # use max_dec_batch_size to avoid OOM
        if indices.shape[0] > self.max_dec_batch_size:
            state = []
            for i in range(0, indices.shape[0], self.max_dec_batch_size):
                state.append(self.decoder(indices[i : i + self.max_dec_batch_size]))
            state = torch.cat(state, dim=0)
        else:
            state = self.decoder(indices)

        assert state.shape[2] == pixel_chunk_duration
        return rearrange(state, "(b n) c t h w -> b c (n t) h w", b=B)

    def reset_dtype(self, *args, **kwargs):
        """
        Resets the data type of the encoder and decoder to the model's default data type.

        Args:
            *args, **kwargs: Unused, present to allow flexibility in method calls.
        """
        del args, kwargs
        self.decoder.to(self.dtype)
        self.encoder.to(self.dtype)


class DiscreteVideoFSQJITTokenizer(BaseDiscreteVideoFSQTokenizer):
    """
    A JIT compiled Discrete Video FSQ Tokenizer that loads pre-trained encoder
    and decoder components from a remote store, handles data type conversions, and normalization
    using provided mean and standard deviation values for latent space representation.

    Attributes:
        encoder (Module): The JIT compiled encoder loaded from storage.
        decoder (Module): The JIT compiled decoder loaded from storage.
        dtype (dtype): Data type for model tensors, determined by whether bf16 is enabled.

    Args:
        enc_fp (str): File path to the encoder's JIT file on the remote store.
        dec_fp (str): File path to the decoder's JIT file on the remote store.
        name (str): Name of the model, used for differentiating cache file paths.
        latent_ch (int, optional): Number of latent channels (default is 6).
        is_bf16 (bool, optional): Flag to use Brain Floating Point 16-bit data type (default is True).
        pixel_chunk_duration (int): The duration (in number of frames) of each chunk of video data at the pixel level.
        latent_chunk_duration (int): The duration (in number of frames) of each chunk at the latent representation level.
        max_enc_batch_size (int): The maximum batch size to process in one go to avoid memory overflow.
        level (list[int]): The level defined in FSQ quantizer.
        compression_ratio (list[int]): The compression factor for (T, H, W).
    """

    def __init__(
        self,
        enc_fp: str,
        dec_fp: str,
        name: str,
        latent_ch: int = 6,
        is_bf16: bool = True,
        pixel_chunk_duration: int = 25,
        latent_chunk_duration: int = 4,
        max_enc_batch_size: int = 8,
        max_dec_batch_size: int = 4,
        levels: list[int] = [8, 8, 8, 5, 5, 5],
        compression_ratio: list[int] = [8, 16, 16],
    ):
        super().__init__(
            name,
            latent_ch,
            is_bf16,
            pixel_chunk_duration,
            latent_chunk_duration,
            max_enc_batch_size,
            max_dec_batch_size,
            levels,
            compression_ratio,
        )

        self.load_encoder(enc_fp)
        self.load_decoder(dec_fp)

    def load_encoder(self, enc_fp: str) -> None:
        """
        Load the encoder from the remote store.

        Args:
        - enc_fp (str): File path to the encoder's JIT file on the remote store.
        """
        self.encoder = load_jit_model(enc_fp, device="cuda")
        self.encoder.eval()
        for param in self.encoder.parameters():
            param.requires_grad = False
        self.encoder.to(self.dtype)

    def load_decoder(self, dec_fp: str) -> None:
        """
        Load the decoder from the remote store.

        Args:
        - dec_fp (str): File path to the decoder's JIT file on the remote store.
        """
        self.decoder = load_jit_model(dec_fp, device="cuda")
        self.decoder.eval()
        for param in self.decoder.parameters():
            param.requires_grad = False
        self.decoder.to(self.dtype)


class DiscreteVideoFSQStateDictTokenizer(BaseDiscreteVideoFSQTokenizer):
    """
    A Discrete Video FSQ Tokenizer that loads weights from pre-trained JITed encoder
    into as nn.Module so that encoder can be "torch.compile()" and JITed decoder, so it can be torch.compiled,
    handles data type conversions, and normalization using provided mean and standard deviation values for latent
    space representation.

    Attributes:
        tokenizer_module (Module): Tokenizer module with weights loaded from JIT checkpoints
        encoder (Callable): tokenizer_module's encode method
        decoder (Callable): tokenizer_module's decode method
        dtype (dtype): Data type for model tensors, determined by whether bf16 is enabled.

    Args:
        enc_fp (str): File path to the encoder's JIT file on the remote store.
        dec_fp (str): File path to the decoder's JIT file on the remote store.
        tokenizer_module (Module): Tokenizer module that will have it's weights loaded
        name (str): Name of the model, used for differentiating cache file paths.
        latent_ch (int, optional): Number of latent channels (default is 6).
        is_bf16 (bool, optional): Flag to use Brain Floating Point 16-bit data type (default is True).
        pixel_chunk_duration (int): The duration (in number of frames) of each chunk of video data at the pixel level.
        latent_chunk_duration (int): The duration (in number of frames) of each chunk at the latent representation level.
        max_enc_batch_size (int): The maximum batch size to process in one go to avoid memory overflow.
        level (list[int]): The level defined in FSQ quantizer.
        compression_ratio (list[int]): The compression factor for (T, H, W).
    """

    def __init__(
        self,
        enc_fp: str,
        dec_fp: str,
        tokenizer_module: torch.nn.Module,
        name: str,
        latent_ch: int = 6,
        is_bf16: bool = True,
        pixel_chunk_duration: int = 25,
        latent_chunk_duration: int = 4,
        max_enc_batch_size: int = 8,
        max_dec_batch_size: int = 4,
        levels: list[int] = [8, 8, 8, 5, 5, 5],
        compression_ratio: list[int] = [8, 16, 16],
    ):
        super().__init__(
            name,
            latent_ch,
            is_bf16,
            pixel_chunk_duration,
            latent_chunk_duration,
            max_enc_batch_size,
            max_dec_batch_size,
            levels,
            compression_ratio,
        )

        self.load_encoder_and_decoder(enc_fp, dec_fp, tokenizer_module)

    def load_encoder_and_decoder(self, enc_fp: str, dec_fp: str, tokenizer_module: torch.nn.Module) -> None:
        """
        Load the encoder from the remote store.

        Args:
        - enc_fp (str): File path to the encoder's JIT file on the remote store.
        - def_fp (str): File path to the decoder's JIT file on the remote store.
        - tokenizer_module (Module): Tokenizer module that was used to create JIT checkpoints
        """
        self.decoder = load_jit_model(dec_fp)

        self.decoder.eval()
        for param in self.decoder.parameters():
            param.requires_grad = False
        self.decoder.to(self.dtype)

        encoder_sd = load_jit_model(enc_fp).state_dict()

        del tokenizer_module.post_quant_conv
        del tokenizer_module.decoder

        state_dict = {
            k: v
            for k, v in (encoder_sd).items()
            #  Variables captured by JIT
            if k
            not in (
                "encoder.patcher3d.wavelets",
                "encoder.patcher3d._arange",
                "encoder.patcher3d.patch_size_buffer",
                "quantizer._levels",
                "quantizer._basis",
                "quantizer.implicit_codebook",
            )
        }

        tokenizer_module.load_state_dict(state_dict)

        tokenizer_module.eval()
        for param in tokenizer_module.parameters():
            param.requires_grad = False
        tokenizer_module.to(self.dtype)

        self.tokenizer_module = tokenizer_module
        self.encoder = self.tokenizer_module.encode

    def reset_dtype(self, *args, **kwargs):
        """
        Resets the data type of the encoder and decoder to the model's default data type.

        Args:
            *args, **kwargs: Unused, present to allow flexibility in method calls.
        """
        del args, kwargs
        self.decoder.to(self.dtype)
        self.tokenizer_module.to(self.dtype)