File size: 25,925 Bytes
b506011
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
from typing import Dict, Optional, Tuple, Union
from diffusers.models import UNetSpatioTemporalConditionModel
from diffusers import TextToVideoSDPipeline, StableVideoDiffusionPipeline
import torch
import torch.nn as nn
from einops import rearrange, repeat
import math
import random
from transformers import AutoTokenizer, CLIPTextModelWithProjection
import numpy as np
import os
from video_models.pipeline import MaskStableVideoDiffusionPipeline,TextStableVideoDiffusionPipeline

class Diffusion_feature_extractor(nn.Module):
    def __init__(
        self,
        pipeline=None,
        tokenizer=None,
        text_encoder=None,
        position_encoding=True,
    ):
        super().__init__()
        self.pipeline = pipeline if pipeline is not None else StableVideoDiffusionPipeline()
        self.tokenizer = tokenizer if tokenizer is not None else AutoTokenizer.from_pretrained("/cephfs/shared/llm/clip-vit-base-patch32",use_fast=False)
        self.text_encoder = text_encoder if text_encoder is not None else CLIPTextModelWithProjection.from_pretrained("/cephfs/shared/llm/clip-vit-base-patch32")
        self.num_frames = int(os.environ.get("GLOBAL_FRAME_NUM"))
        self.position_encoding = position_encoding

    @torch.no_grad()
    def forward(
            self,
            pixel_values: torch.Tensor,
            texts,
            timestep: Union[torch.Tensor, float, int],
            extract_layer_idx: Union[torch.Tensor, float, int],
            use_latent = False,
            all_layer = False,
            step_time = 1,
            max_length = 20,
    ):
        with torch.no_grad():
            # texts, tokenizer, text_encoder, img_cond=None, img_cond_mask=None, img_encoder=None, position_encode=True, use_clip=False, max_length=20
            encoder_hidden_states = self.encode_text(texts, self.tokenizer, self.text_encoder, position_encode=self.position_encoding, use_clip=True, max_length=max_length)
        encoder_hidden_states = encoder_hidden_states.to(self.pipeline.vae.dtype)

        # frames = MaskStableVideoDiffusionPipeline.__call__(self.pipeline,image=pixel_values.squeeze(1), text=encoder_hidden_states, width=pixel_values.shape[-1], height=pixel_values.shape[-2], num_frames=self.num_frames, num_inference_steps=20, max_guidance_scale=7.5, fps=7, motion_bucket_id=127, decode_chunk_size=7, mask=None).frames
        # tmpframes = []
        # for ii in range(len(frames)):
        #     tmpframe = frames[ii][3]
        #     tmpframe = torch.tensor(np.array(tmpframe),device=self.pipeline.unet.device).permute(2,0,1)[None]
        #     tmpframes.append(tmpframe/255.*2.-1)
        # pixel_values = torch.cat(tmpframes,dim=0).unsqueeze(1)

        # # tmpimgs = torch.tensor(np.array(frames[10][2]),device=self.pipeline.unet.device).permute(2,0,1)[None]
        # # image = image/255.*2.-1
        # # res = MaskStableVideoDiffusionPipeline.__call__(self.pipeline,image=image, text=encoder_hidden_states[0].unsqueeze(0), width=256, height=256, num_frames=self.num_frames, num_inference_steps=20, max_guidance_scale=2.5, fps=7, motion_bucket_id=127, decode_chunk_size=7, mask=None).frames
        
        



        height = self.pipeline.unet.config.sample_size * self.pipeline.vae_scale_factor //3
        width = self.pipeline.unet.config.sample_size * self.pipeline.vae_scale_factor //3
        self.pipeline.vae.eval()
        self.pipeline.image_encoder.eval()
        device = self.pipeline.unet.device
        dtype = self.pipeline.vae.dtype
        #print('dtype:',dtype)
        vae = self.pipeline.vae

        num_videos_per_prompt=1

        batch_size = pixel_values.shape[0]

        pixel_values = rearrange(pixel_values, 'b f c h w-> (b f) c h w').to(dtype)

        image_embeddings = encoder_hidden_states

        needs_upcasting = self.pipeline.vae.dtype == torch.float16 and self.pipeline.vae.config.force_upcast
        #if needs_upcasting:
        #    self.pipeline.vae.to(dtype=torch.float32)
        #    pixel_values.to(dtype=torch.float32)
        if pixel_values.shape[-3] == 4:
            image_latents = pixel_values/vae.config.scaling_factor
        else:
            image_latents = self.pipeline._encode_vae_image(pixel_values, device, num_videos_per_prompt, False)
        image_latents = image_latents.to(image_embeddings.dtype)

        #print('dtype:', image_latents.dtype)

        #if needs_upcasting:
        #    self.pipeline.vae.to(dtype=torch.float16)

        #num_frames = self.pipeline.unet.config.num_frames
        num_frames = self.num_frames
        image_latents = image_latents.unsqueeze(1).repeat(1, num_frames, 1, 1, 1)

        fps=4
        motion_bucket_id=127
        added_time_ids = self.pipeline._get_add_time_ids(
            fps,
            motion_bucket_id,
            0,
            image_embeddings.dtype,
            batch_size,
            num_videos_per_prompt,
            False,
        )
        added_time_ids = added_time_ids.to(device)

        self.pipeline.scheduler.set_timesteps(timestep, device=device)
        timesteps = self.pipeline.scheduler.timesteps

        num_channels_latents = self.pipeline.unet.config.in_channels
        latents = self.pipeline.prepare_latents(
            batch_size * num_videos_per_prompt,
            num_frames,
            num_channels_latents,
            height,
            width,
            image_embeddings.dtype,
            device,
            None,
            None,
        )

        for i, t in enumerate(timesteps):
            #print('step:',i)
            if i == step_time - 1:
                complete = False
            else:
                complete = True
            # complete = True
            #print('complete:',complete)

            latent_model_input = latents
            latent_model_input = self.pipeline.scheduler.scale_model_input(latent_model_input, t)

            # Concatenate image_latents over channels dimention
            # latent_model_input = torch.cat([mask, latent_model_input, image_latents], dim=2)
            latent_model_input = torch.cat([latent_model_input, image_latents], dim=2)
            #print('latent_model_input_shape:',latent_model_input.shape)
            #print('image_embeddings_shape:',image_embeddings.shape)

            # predict the noise residual
            # print('extract_layer_idx:',extract_layer_idx)
            # print('latent_model_input_shape:',latent_model_input.shape)
            # print('encoder_hidden_states:',image_embeddings.shape)
            feature_pred = self.step_unet(
                latent_model_input,
                t,
                encoder_hidden_states=image_embeddings,
                added_time_ids=added_time_ids,
                use_layer_idx=extract_layer_idx,
                all_layer = all_layer,
                complete = complete,
            )[0]
            # feature_pred = self.pipeline.unet(latent_model_input,t,encoder_hidden_states=image_embeddings,added_time_ids=added_time_ids,return_dict=False,)[0]

            # print('feature_pred_shape:',feature_pred.shape)

            if not complete:
                break

            latents = self.pipeline.scheduler.step(feature_pred, t, latents).prev_sample


            # res = self.pipeline.scheduler.step(feature_pred, t, latents)
            # pred_x0 = res.pred_original_sample
            # latents = res.prev_sample
            # frames = self.pipeline.decode_latents(pred_x0, num_frames)
            # frames = self.pipeline.video_processor.postprocess_video(video=frames, output_type="np")
            # import imageio
            # breakpoint()
            # imageio.mimsave("output.mp4", frames[3], fps=8)
            # imageio.mimsave("image.mp4", pixel_values[3].cpu().permute(1,2,0)[None], fps=8)

        return feature_pred

    # def step_unet(
    #     self,
    #     sample: torch.Tensor,
    #     timestep: Union[torch.Tensor, float, int],
    #     encoder_hidden_states: torch.Tensor,
    #     added_time_ids: torch.Tensor,
    #     use_layer_idx: int = 1,
    # ):
    #     r"""
    #     The [`UNetSpatioTemporalConditionModel`] forward method.

    #     Args:
    #         sample (`torch.Tensor`):
    #             The noisy input tensor with the following shape `(batch, num_frames, channel, height, width)`.
    #         timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
    #         encoder_hidden_states (`torch.Tensor`):
    #             The encoder hidden states with shape `(batch, sequence_length, cross_attention_dim)`.
    #         added_time_ids: (`torch.Tensor`):
    #             The additional time ids with shape `(batch, num_additional_ids)`. These are encoded with sinusoidal
    #             embeddings and added to the time embeddings.
    #         return_dict (`bool`, *optional*, defaults to `True`):
    #             Whether or not to return a [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] instead
    #             of a plain tuple.
    #     Returns:
    #         [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] or `tuple`:
    #             If `return_dict` is True, an [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] is
    #             returned, otherwise a `tuple` is returned where the first element is the sample tensor.
    #     """
    #     # By default samples have to be AT least a multiple of the overall upsampling factor.
    #     # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
    #     # However, the upsampling interpolation output size can be forced to fit any upsampling size
    #     # on the fly if necessary.
    #     # default_overall_up_factor = 2**self.num_upsamplers

    #     # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
    #     forward_upsample_size = False
    #     upsample_size = None

    #     # if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
    #     #     logger.info("Forward upsample size to force interpolation output size.")
    #     #     forward_upsample_size = True

    #     # 1. time
    #     timesteps = timestep
    #     if not torch.is_tensor(timesteps):
    #         # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
    #         # This would be a good case for the `match` statement (Python 3.10+)
    #         is_mps = sample.device.type == "mps"
    #         if isinstance(timestep, float):
    #             dtype = sample.dtype if is_mps else torch.float64
    #         else:
    #             dtype = torch.int32 if is_mps else torch.int64
    #         # print('timestep:',timestep)
    #         timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
    #     elif len(timesteps.shape) == 0:
    #         timesteps = timesteps[None].to(sample.device)

    #     # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
    #     batch_size, num_frames = sample.shape[:2]
    #     timesteps = timesteps.expand(batch_size)

    #     t_emb = self.pipeline.unet.time_proj(timesteps)

    #     # `Timesteps` does not contain any weights and will always return f32 tensors
    #     # but time_embedding might actually be running in fp16. so we need to cast here.
    #     # there might be better ways to encapsulate this.
    #     t_emb = t_emb.to(dtype=sample.dtype)

    #     emb = self.pipeline.unet.time_embedding(t_emb)

    #     time_embeds = self.pipeline.unet.add_time_proj(added_time_ids.flatten())
    #     time_embeds = time_embeds.reshape((batch_size, -1))
    #     time_embeds = time_embeds.to(emb.dtype)
    #     aug_emb = self.pipeline.unet.add_embedding(time_embeds)
    #     emb = emb + aug_emb

    #     # Flatten the batch and frames dimensions
    #     # sample: [batch, frames, channels, height, width] -> [batch * frames, channels, height, width]
    #     sample = sample.flatten(0, 1)
    #     # Repeat the embeddings num_video_frames times
    #     # emb: [batch, channels] -> [batch * frames, channels]
    #     emb = emb.repeat_interleave(num_frames, dim=0)
    #     # encoder_hidden_states: [batch, 1, channels] -> [batch * frames, 1, channels]
    #     encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0)

    #     # 2. pre-process
    #     sample = self.pipeline.unet.conv_in(sample)

    #     image_only_indicator = torch.zeros(batch_size, num_frames, dtype=sample.dtype, device=sample.device)

    #     down_block_res_samples = (sample,)
    #     for downsample_block in self.pipeline.unet.down_blocks:
    #         if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
    #             sample, res_samples = downsample_block(
    #                 hidden_states=sample,
    #                 temb=emb,
    #                 encoder_hidden_states=encoder_hidden_states,
    #                 image_only_indicator=image_only_indicator,
    #             )
    #         else:
    #             sample, res_samples = downsample_block(
    #                 hidden_states=sample,
    #                 temb=emb,
    #                 image_only_indicator=image_only_indicator,
    #             )

    #         down_block_res_samples += res_samples

    #     # 4. mid
    #     sample = self.pipeline.unet.mid_block(
    #         hidden_states=sample,
    #         temb=emb,
    #         encoder_hidden_states=encoder_hidden_states,
    #         image_only_indicator=image_only_indicator,
    #     )

    #     # 5. up
    #     for i, upsample_block in enumerate(self.pipeline.unet.up_blocks):
    #         is_final_block = i == len(self.pipeline.unet.up_blocks) - 1

    #         res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
    #         down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]

    #         # if we have not reached the final block and need to forward the
    #         # upsample size, we do it here
    #         if not is_final_block and forward_upsample_size:
    #             upsample_size = down_block_res_samples[-1].shape[2:]

    #         if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
    #             sample = upsample_block(
    #                 hidden_states=sample,
    #                 temb=emb,
    #                 res_hidden_states_tuple=res_samples,
    #                 encoder_hidden_states=encoder_hidden_states,
    #                 upsample_size=upsample_size,
    #                 image_only_indicator=image_only_indicator,
    #             )
    #         else:
    #             sample = upsample_block(
    #                 hidden_states=sample,
    #                 temb=emb,
    #                 res_hidden_states_tuple=res_samples,
    #                 upsample_size=upsample_size,
    #                 image_only_indicator=image_only_indicator,
    #             )
    #         if i == use_layer_idx:
    #             break
    #     sample = sample.reshape(batch_size, num_frames, *sample.shape[1:])

    #     return (sample,)


    # old one
    def step_unet(
        self,
        sample: torch.Tensor,
        timestep: Union[torch.Tensor, float, int],
        encoder_hidden_states: torch.Tensor,
        added_time_ids: torch.Tensor,
        use_layer_idx: int = 5,
        all_layer: bool = False,
        complete: bool = False,
    ) :
        r"""
        The [`UNetSpatioTemporalConditionModel`] forward method.

        Args:
            sample (`torch.Tensor`):
                The noisy input tensor with the following shape `(batch, num_frames, channel, height, width)`.
            timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
            encoder_hidden_states (`torch.Tensor`):
                The encoder hidden states with shape `(batch, sequence_length, cross_attention_dim)`.
            added_time_ids: (`torch.Tensor`):
                The additional time ids with shape `(batch, num_additional_ids)`. These are encoded with sinusoidal
                embeddings and added to the time embeddings.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] instead
                of a plain tuple.
        Returns:
            [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] or `tuple`:
                If `return_dict` is True, an [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] is
                returned, otherwise a `tuple` is returned where the first element is the sample tensor.
        """
        # 1. time
        timesteps = timestep
        if not torch.is_tensor(timesteps):
            # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
            # This would be a good case for the `match` statement (Python 3.10+)
            is_mps = sample.device.type == "mps"
            if isinstance(timestep, float):
                dtype = torch.float32 if is_mps else torch.float64
            else:
                dtype = torch.int32 if is_mps else torch.int64
            timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
        elif len(timesteps.shape) == 0:
            timesteps = timesteps[None].to(sample.device)

        # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
        batch_size, num_frames = sample.shape[:2]
        timesteps = timesteps.expand(batch_size)

        t_emb = self.pipeline.unet.time_proj(timesteps)

        # `Timesteps` does not contain any weights and will always return f32 tensors
        # but time_embedding might actually be running in fp16. so we need to cast here.
        # there might be better ways to encapsulate this.
        t_emb = t_emb.to(dtype=sample.dtype)

        emb = self.pipeline.unet.time_embedding(t_emb)

        time_embeds = self.pipeline.unet.add_time_proj(added_time_ids.flatten())
        time_embeds = time_embeds.reshape((batch_size, -1))
        time_embeds = time_embeds.to(emb.dtype)
        aug_emb = self.pipeline.unet.add_embedding(time_embeds)
        emb = emb + aug_emb

        # Flatten the batch and frames dimensions
        # sample: [batch, frames, channels, height, width] -> [batch * frames, channels, height, width]
        sample = sample.flatten(0, 1)
        # Repeat the embeddings num_video_frames times
        # emb: [batch, channels] -> [batch * frames, channels]
        emb = emb.repeat_interleave(num_frames, dim=0)
        # encoder_hidden_states: [batch, 1, channels] -> [batch * frames, 1, channels]
        encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0)

        # 2. pre-process
        sample = self.pipeline.unet.conv_in(sample)

        image_only_indicator = torch.zeros(batch_size, num_frames, dtype=sample.dtype, device=sample.device)

        down_block_res_samples = (sample,)
        for downsample_block in self.pipeline.unet.down_blocks:
            #print('sample_shape:',sample.shape)
            #print('emb_shape:', emb.shape)
            #print('encoder_hidden_states_shape:', encoder_hidden_states.shape)
            if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
                sample, res_samples = downsample_block(
                    hidden_states=sample,
                    temb=emb,
                    encoder_hidden_states=encoder_hidden_states,
                    image_only_indicator=image_only_indicator,
                )
            else:
                sample, res_samples = downsample_block(
                    hidden_states=sample,
                    temb=emb,
                    image_only_indicator=image_only_indicator,
                )

            down_block_res_samples += res_samples

        # 4. mid
        sample = self.pipeline.unet.mid_block(
            hidden_states=sample,
            temb=emb,
            encoder_hidden_states=encoder_hidden_states,
            image_only_indicator=image_only_indicator,
        )

        feature_list = []

        # 5. up
        for i, upsample_block in enumerate(self.pipeline.unet.up_blocks):
            res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
            down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]

            if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
                sample = upsample_block(
                    hidden_states=sample,
                    temb=emb,
                    res_hidden_states_tuple=res_samples,
                    encoder_hidden_states=encoder_hidden_states,
                    image_only_indicator=image_only_indicator,
                )
            else:
                sample = upsample_block(
                    hidden_states=sample,
                    temb=emb,
                    res_hidden_states_tuple=res_samples,
                    image_only_indicator=image_only_indicator,
                )
            if i < use_layer_idx:
                factor = 2**(use_layer_idx - i)
                feature_list.append(torch.nn.functional.interpolate(sample,scale_factor=factor))
            #print('up_sample_idx:',i)
            if i == use_layer_idx and not complete:
                feature_list.append(sample)
                break

        if not complete:
            if all_layer:
                sample = torch.cat(feature_list, dim=1)
                sample = sample.reshape(batch_size, num_frames, *sample.shape[1:])
            else:
                sample = sample.reshape(batch_size, num_frames, *sample.shape[1:])
            # 6. post-process
            return (sample,)

        else:
            sample = self.pipeline.unet.conv_norm_out(sample)
            sample = self.pipeline.unet.conv_act(sample)
            sample = self.pipeline.unet.conv_out(sample)

            # 7. Reshape back to original shape
            sample = sample.reshape(batch_size, num_frames, *sample.shape[1:])

            return (sample,)

    @torch.no_grad()
    def encode_text(self, texts, tokenizer, text_encoder, img_cond=None, img_cond_mask=None, img_encoder=None, position_encode=True, use_clip=False, max_length=20):
        def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
            """
            embed_dim: output dimension for each position
            pos: a list of positions to be encoded: size (M,)
            out: (M, D)
            """
            assert embed_dim % 2 == 0
            omega = np.arange(embed_dim // 2, dtype=np.float64)
            omega /= embed_dim / 2.
            omega = 1. / 10000**omega  # (D/2,)

            pos = pos.reshape(-1)  # (M,)
            out = np.einsum('m,d->md', pos, omega)  # (M, D/2), outer product

            emb_sin = np.sin(out) # (M, D/2)
            emb_cos = np.cos(out) # (M, D/2)

            emb = np.concatenate([emb_sin, emb_cos], axis=1)  # (M, D)
            return emb
        
        # max_length = args.clip_token_length
        with torch.no_grad():
            if use_clip:
                inputs = tokenizer(texts, padding='max_length', return_tensors="pt",truncation=True, max_length=max_length).to(text_encoder.device)
                outputs = text_encoder(**inputs)
                encoder_hidden_states = outputs.last_hidden_state # (batch, 30, 512)
                ###### will be used in the dp ##########
                # self.text_embeds = outputs.text_embeds
                ######################################
                if position_encode:
                    embed_dim, pos_num = encoder_hidden_states.shape[-1], encoder_hidden_states.shape[1]
                    pos = np.arange(pos_num,dtype=np.float64)

                    position_encode = get_1d_sincos_pos_embed_from_grid(embed_dim, pos)
                    position_encode = torch.tensor(position_encode, device=encoder_hidden_states.device, dtype=encoder_hidden_states.dtype, requires_grad=False)

                    # print("position_encode",position_encode.shape)
                    # print("encoder_hidden_states",encoder_hidden_states.shape)

                    encoder_hidden_states += position_encode
                assert encoder_hidden_states.shape[-1] == 512

                if img_encoder is not None:
                    assert img_cond is not None
                    assert img_cond_mask is not None
                    # print("img_encoder",img_encoder.shape)
                    img_cond = img_cond.to(img_encoder.device)
                    if len(img_cond.shape) == 5:
                        img_cond = img_cond.squeeze(1)
                    
                    img_hidden_states = img_encoder(img_cond).image_embeds
                    img_hidden_states[img_cond_mask] = 0.0
                    img_hidden_states = img_hidden_states.unsqueeze(1).expand(-1,encoder_hidden_states.shape[1],-1)
                    assert img_hidden_states.shape[-1] == 512
                    encoder_hidden_states = torch.cat([encoder_hidden_states, img_hidden_states], dim=-1)
                    assert encoder_hidden_states.shape[-1] == 1024
                else:
                    encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states], dim=-1)
            
            else:
                inputs = tokenizer(texts, padding='max_length', return_tensors="pt",truncation=True, max_length=32).to(text_encoder.device)
                outputs = text_encoder(**inputs)
                encoder_hidden_states = outputs.last_hidden_state # (batch, 30, 512)
                assert encoder_hidden_states.shape[1:] == (32,1024)

        return encoder_hidden_states