File size: 15,044 Bytes
2bfd19c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# Copyright (c) 2025 SandAI. All Rights Reserved.
#
# 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.

import gc
import os
import tempfile

import ffmpeg
import torch
from einops import rearrange

import inference.infra.distributed.parallel_state as mpu
from inference.common import MagiConfig, magi_logger
from inference.model.vae import AutoModel, DiagonalGaussianDistribution, VideoTokenizerABC


############################################
# VaeHelper
###########################################
class SingletonMeta(type):
    """
    Singleton metaclass
    """

    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]


class VaeHelper(metaclass=SingletonMeta):
    def __init__(self):
        # Initialize cache dict
        if not hasattr(self, "vae_cache_dict"):
            self.vae_cache_dict = {}

    @staticmethod
    def get_vae(vae_ckpt: str) -> VideoTokenizerABC:
        """
        Load a pretrained VAE model.

        Args:
            vae_ckpt (str): Path to the pretrained VAE checkpoint.

        Returns:
            VideoTokenizerABC: Pretrained VAE model.
        """
        vae_helper = VaeHelper()

        if vae_ckpt not in vae_helper.vae_cache_dict:
            vae = AutoModel.from_pretrained(vae_ckpt)
            vae.encode = vae_helper.patch_vae_encode.__get__(vae)
            vae.cuda()
            vae.eval()
            vae.bfloat16()
            if os.environ.get("OFFLOAD_VAE_CACHE") == "true":
                return vae
            vae_helper.vae_cache_dict[vae_ckpt] = vae
        return vae_helper.vae_cache_dict[vae_ckpt]

    @staticmethod
    @torch.no_grad()
    def patch_vae_encode(vae: callable, x: torch.Tensor) -> torch.Tensor:
        """
        Encode the input video.

        Args:
            x (torch.Tensor): Input video tensor with shape (N, C, T, H, W).
            sample_posterior (bool): Whether to sample from the posterior.

        Returns:
            torch.Tensor: Encoded tensor with additional information.
        """
        if not isinstance(x, torch.Tensor):
            raise TypeError(f"Expected input x to be torch.Tensor, but got {type(x)}.")
        if len(x.shape) != 5:
            raise ValueError(f"Expected input tensor x to have shape (N, C, T, H, W), but got {x.shape}.")

        if not hasattr(vae, "encoder") or not callable(vae.encoder):
            raise AttributeError("Encoder is not defined or callable. Please initialize 'self.encoder'.")

        # for setting vae encoding to deterministic
        N, C, T, H, W = x.shape
        if T == 1:
            x = x.expand(-1, -1, 4, -1, -1)
            x = vae.encoder(x)
            posterior = DiagonalGaussianDistribution(x)
            z = posterior.mode()

            return z[:, :, :1, :, :].type(x.dtype)
        else:
            x = vae.encoder(x)
            posterior = DiagonalGaussianDistribution(x)
            z = posterior.mode()

            return z.type(x.dtype)

    @staticmethod
    def encode(
        video: torch.Tensor,
        vae: VideoTokenizerABC,
        tile_sample_min_length: int = 16,
        tile_sample_min_height: int = 256,
        tile_sample_min_width: int = 256,
        spatial_tile_overlap_factor: float = 0.25,
        temporal_tile_overlap_factor: float = 0,
        allow_spatial_tiling: bool = True,
        parallel_group: torch.distributed.ProcessGroup = None,
    ) -> torch.Tensor:
        """
        Encode the input tensor.
        Args:
            video (torch.Tensor): Input tensor with shape (N, T, C, H, W).
            vae (VideoTokenizerABC): Pretrained VAE model.
            tile_sample_min_length (int): Minimum length of the tile sample.
            tile_sample_min_height (int): Minimum height of the tile sample.
            tile_sample_min_width (int): Minimum width of the tile sample.
            spatial_tile_overlap_factor (float): Spatial tile overlap factor.
            allow_spatial_tiling (bool): Allow spatial tiling.
            parallel_group (ProcessGroup): Distributed encoding group.
        Returns:
            torch.Tensor: Encoded tensor.
        """
        assert video.dim() == 5, f"Expected input tensor to have shape (N, T, C, H, W), but got {video.shape}."
        video = video.cuda()
        video = (video / 127.5) - 1.0
        video = video.bfloat16()
        moments = vae.tiled_encode_3d(
            video,
            tile_sample_min_length=tile_sample_min_length,
            tile_sample_min_height=tile_sample_min_height,
            tile_sample_min_width=tile_sample_min_width,
            spatial_tile_overlap_factor=spatial_tile_overlap_factor,
            temporal_tile_overlap_factor=temporal_tile_overlap_factor,
            allow_spatial_tiling=allow_spatial_tiling,
            parallel_group=parallel_group,
        )

        return moments

    @staticmethod
    def decode(
        chunk: torch.Tensor,
        vae: VideoTokenizerABC,
        tile_sample_min_height: int = 256,
        tile_sample_min_width: int = 256,
        spatial_tile_overlap_factor: float = 0.25,
        temporal_tile_overlap_factor: float = 0,
        tile_sample_min_length: int = 16,
        allow_spatial_tiling: bool = True,
        uint8_output: bool = True,
        parallel_group: torch.distributed.ProcessGroup = None,
    ) -> torch.Tensor:
        """
        Decode the input tensor.
        Args:
            chunk (torch.Tensor): Input tensor with shape (N, C, T, H, W).
            vae (VideoTokenizerABC): Pretrained VAE model.
            tile_sample_min_length (int): Minimum length of the tile sample.
            tile_sample_min_height (int): Minimum height of the tile sample.
            tile_sample_min_width (int): Minimum width of the tile sample.
            spatial_tile_overlap_factor (float): Spatial tile overlap factor.
            temporal_tile_overlap_factor (float): Temporal tile overlap factor.
            allow_spatial_tiling (bool): Allow spatial tiling.
            uint8_output (bool): Whether to output uint8 tensor.
            parallel_group (ProcessGroup): Distributed decoding group.
        Returns:
            torch.Tensor: Decoded tensor.
        """
        with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
            chunk = vae.tiled_decode_3d(
                chunk,
                tile_sample_min_height=tile_sample_min_height,
                tile_sample_min_width=tile_sample_min_width,
                spatial_tile_overlap_factor=spatial_tile_overlap_factor,
                temporal_tile_overlap_factor=temporal_tile_overlap_factor,
                tile_sample_min_length=tile_sample_min_length,
                allow_spatial_tiling=allow_spatial_tiling,
                parallel_group=parallel_group,
            )
        chunk = rearrange(chunk, "b c t h w -> (b t) c h w")
        if uint8_output:
            chunk = (chunk * 127.5) + 127.5
            chunk = chunk.clamp(0, 255)
            chunk = chunk.type(torch.uint8)
        return chunk


############################################
# Process to get prefix video
###########################################


def ffmpeg_i2v(image_path, w=384, h=224, aspect_policy="fit"):
    r = ffmpeg.input("pipe:0", format="image2pipe")
    if aspect_policy == "crop":
        r = r.filter("scale", w, h, force_original_aspect_ratio="increase").filter("crop", w, h)
    elif aspect_policy == "pad":
        r = r.filter("scale", w, h, force_original_aspect_ratio="decrease").filter(
            "pad", w, h, "(ow-iw)/2", "(oh-ih)/2", color="black"
        )
    elif aspect_policy == "fit":
        r = r.filter("scale", w, h)
    else:
        magi_logger.warning(f"Unknown aspect policy: {aspect_policy}, using fit as fallback")
        r = r.filter("scale", w, h)
    image_byte = open(image_path, "rb").read()
    try:
        out, _ = r.output("pipe:", format="rawvideo", pix_fmt="rgb24", vframes=1).run(
            input=image_byte, capture_stdout=True, capture_stderr=True
        )
    except ffmpeg.Error as e:
        print(f"Error occurred: {e.stderr.decode()}")
        raise e

    video = torch.frombuffer(out, dtype=torch.uint8).view(1, h, w, 3)
    return video


def ffmpeg_v2v(video_path, fps, w=384, h=224, prefix_frame=None, prefix_video_max_chunk=5):
    if video_path is None:
        return None
    out, _ = (
        ffmpeg.input(video_path, ss=0, format="mp4")
        .filter("fps", fps=fps)
        .filter("scale", w, h)
        .output("pipe:", format="rawvideo", pix_fmt="rgb24", nostdin=None)
        .run(capture_stdout=True, capture_stderr=True)
    )

    video = torch.frombuffer(out, dtype=torch.uint8).view(-1, h, w, 3)

    if prefix_frame is not None:
        return video[:prefix_frame]
    else:
        num_frames_to_read = video.shape[0]
        if num_frames_to_read < fps:
            clip_length = 1
        else:
            PREFIX_VIDEO_MAX_FRAMES = prefix_video_max_chunk * fps
            clip_length = min(num_frames_to_read // fps * fps, PREFIX_VIDEO_MAX_FRAMES)
        return video[-clip_length:]


def save_video_to_disk(video: torch.Tensor, save_path: str, fps: int) -> bytes:
    # TCHW -> THWC
    video = video.permute(0, 2, 3, 1).cpu().numpy()
    _, H, W, _ = video.shape
    with tempfile.NamedTemporaryFile(delete=False) as temp_file:
        temp_file.write(video.tobytes())
        temp_file.flush()
        temp_file_path = temp_file.name

    try:
        output, err = (
            ffmpeg
            .input(temp_file_path, format="rawvideo", pix_fmt="rgb24", s=f"{W}x{H}", r=fps)
            .output(save_path, format='mp4', vcodec='libx264', pix_fmt='yuv420p')
            .overwrite_output()
            .run(capture_stdout=True, capture_stderr=True)
        )
        print("✅ Video saved successfully.")
    except ffmpeg.Error as e:
        stderr_output = e.stderr.decode('utf8') if e.stderr else "No stderr output"
        print("❌ FFmpeg Error:")
        print("="*60)
        print(stderr_output)
        print("="*60)
        raise RuntimeError("Failed to encode video with FFmpeg") from e

        os.remove(temp_file_path)
        return output

    os.remove(temp_file_path)
    return output


def encode_prefix_video(prefix_video, fps, vae_ckpt, scale_factor, parallel_group):
    if prefix_video is None:
        return None
    magi_logger.debug(
        f"rank {torch.distributed.get_rank()} memory allocated before vae encode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB"
    )
    magi_logger.debug(
        f"rank {torch.distributed.get_rank()} memory reserved before vae encode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB"
    )

    # THWC -> NCTHW
    prefix_video = prefix_video.permute(3, 0, 1, 2).unsqueeze(0)
    magi_logger.debug(f"prefix_video.shape: {prefix_video.shape}")
    vae_model = VaeHelper.get_vae(vae_ckpt)
    tile_sample_min_length = fps // 2
    prefix_video = VaeHelper.encode(
        prefix_video,
        vae_model,
        tile_sample_min_height=256,
        tile_sample_min_width=256,
        spatial_tile_overlap_factor=0.25,
        temporal_tile_overlap_factor=0,
        tile_sample_min_length=tile_sample_min_length,
        allow_spatial_tiling=True,
        parallel_group=parallel_group,
    )
    prefix_video = prefix_video * scale_factor
    magi_logger.debug(
        f"rank {torch.distributed.get_rank()} memory allocated after vae encode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB"
    )
    magi_logger.debug(
        f"rank {torch.distributed.get_rank()} memory reserved after vae encode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB"
    )
    return prefix_video


def process_image(image_path: str, config: MagiConfig) -> torch.Tensor:
    prefix_video = ffmpeg_i2v(image_path, w=config.runtime_config.video_size_w, h=config.runtime_config.video_size_h)
    prefix_video = encode_prefix_video(
        prefix_video,
        config.runtime_config.fps,
        config.runtime_config.vae_pretrained,
        config.runtime_config.scale_factor,
        parallel_group=mpu.get_tp_group(with_context_parallel=True),
    )
    return prefix_video


def process_prefix_video(prefix_video_path: str, config: MagiConfig) -> torch.Tensor:
    prefix_video = ffmpeg_v2v(
        prefix_video_path,
        fps=config.runtime_config.fps,
        prefix_frame=None,    # Modified
        w=config.runtime_config.video_size_w,
        h=config.runtime_config.video_size_h,
    )
    prefix_video = encode_prefix_video(
        prefix_video,
        config.runtime_config.fps,
        config.runtime_config.vae_pretrained,
        config.runtime_config.scale_factor,
        parallel_group=mpu.get_tp_group(with_context_parallel=True),
    )
    return prefix_video


############################################
# Process to get final video
############################################
def decode_chunk(chunk, vae_ckpt, scale_factor, tile_sample_min_length, parallel_group):
    magi_logger.debug(
        f"rank {torch.distributed.get_rank()} memory allocated before vae decode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB"
    )
    magi_logger.debug(
        f"rank {torch.distributed.get_rank()} memory reserved before vae decode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB"
    )

    vae_model = VaeHelper.get_vae(vae_ckpt)
    decoded_chunk = VaeHelper.decode(
        chunk / scale_factor,
        vae_model,
        tile_sample_min_height=256,
        tile_sample_min_width=256,
        spatial_tile_overlap_factor=0.25,
        temporal_tile_overlap_factor=0,
        tile_sample_min_length=tile_sample_min_length,
        allow_spatial_tiling=True,
        parallel_group=parallel_group,
    )
    magi_logger.debug(
        f"rank {torch.distributed.get_rank()} memory allocated after vae decode: {torch.cuda.memory_allocated() / 1024**3:.2f} GB"
    )
    magi_logger.debug(
        f"rank {torch.distributed.get_rank()} memory reserved after vae decode: {torch.cuda.memory_reserved() / 1024**3:.2f} GB"
    )
    return decoded_chunk


def post_chunk_process(chunk: torch.Tensor, config: MagiConfig):
    tile_sample_min_length = config.runtime_config.fps // 2
    chunk = decode_chunk(
        chunk,
        config.runtime_config.vae_pretrained,
        config.runtime_config.scale_factor,
        tile_sample_min_length,
        parallel_group=mpu.get_tp_group(with_context_parallel=True),
    )
    gc.collect()
    torch.cuda.empty_cache()
    return chunk