Skip to content

SkyReels-V2: Infinite-length Film Generative model

SkyReels-V2 by the SkyReels Team.

Recent advances in video generation have been driven by diffusion models and autoregressive frameworks, yet critical challenges persist in harmonizing prompt adherence, visual quality, motion dynamics, and duration: compromises in motion dynamics to enhance temporal visual quality, constrained video duration (5-10 seconds) to prioritize resolution, and inadequate shot-aware generation stemming from general-purpose MLLMs' inability to interpret cinematic grammar, such as shot composition, actor expressions, and camera motions. These intertwined limitations hinder realistic long-form synthesis and professional film-style generation. To address these limitations, we propose SkyReels-V2, an Infinite-length Film Generative Model, that synergizes Multi-modal Large Language Model (MLLM), Multi-stage Pretraining, Reinforcement Learning, and Diffusion Forcing Framework. Firstly, we design a comprehensive structural representation of video that combines the general descriptions by the Multi-modal LLM and the detailed shot language by sub-expert models. Aided with human annotation, we then train a unified Video Captioner, named SkyCaptioner-V1, to efficiently label the video data. Secondly, we establish progressive-resolution pretraining for the fundamental video generation, followed by a four-stage post-training enhancement: Initial concept-balanced Supervised Fine-Tuning (SFT) improves baseline quality; Motion-specific Reinforcement Learning (RL) training with human-annotated and synthetic distortion data addresses dynamic artifacts; Our diffusion forcing framework with non-decreasing noise schedules enables long-video synthesis in an efficient search space; Final high-quality SFT refines visual fidelity. All the code and models are available at this https URL.

You can find all the original SkyReels-V2 checkpoints under the Skywork organization.

The following SkyReels-V2 models are supported in Diffusers: - SkyReels-V2 DF 1.3B - 540P - SkyReels-V2 DF 14B - 540P - SkyReels-V2 DF 14B - 720P - SkyReels-V2 T2V 14B - 540P - SkyReels-V2 T2V 14B - 720P - SkyReels-V2 I2V 1.3B - 540P - SkyReels-V2 I2V 14B - 540P - SkyReels-V2 I2V 14B - 720P - SkyReels-V2 FLF2V 1.3B - 540P

Tip

Click on the SkyReels-V2 models in the right sidebar for more examples of video generation.

A Visual Demonstration

    An example with these parameters:
    base_num_frames=97, num_frames=97, num_inference_steps=30, ar_step=5, causal_block_size=5

    vae_scale_factor_temporal -> 4
    num_latent_frames: (97-1)//vae_scale_factor_temporal+1 = 25 frames -> 5 blocks of 5 frames each

    base_num_latent_frames = (97-1)//vae_scale_factor_temporal+1 = 25 → blocks = 25//5 = 5 blocks
    This 5 blocks means the maximum context length of the model is 25 frames in the latent space.

    Asynchronous Processing Timeline:
    ┌─────────────────────────────────────────────────────────────────┐
    │ Steps:    1    6   11   16   21   26   31   36   41   46   50   │
    │ Block 1: [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]                       │
    │ Block 2:      [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]                  │
    │ Block 3:           [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]             │
    │ Block 4:                [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]        │
    │ Block 5:                     [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■]   │
    └─────────────────────────────────────────────────────────────────┘

    For Long Videos (num_frames > base_num_frames):
    base_num_frames acts as the "sliding window size" for processing long videos.

    Example: 257-frame video with base_num_frames=97, overlap_history=17
    ┌──── Iteration 1 (frames 1-97) ────┐
    │ Processing window: 97 frames      │ → 5 blocks, async processing
    │ Generates: frames 1-97            │
    └───────────────────────────────────┘
                ┌────── Iteration 2 (frames 81-177) ──────┐
                │ Processing window: 97 frames            │
                │ Overlap: 17 frames (81-97) from prev    │ → 5 blocks, async processing
                │ Generates: frames 98-177                │
                └─────────────────────────────────────────┘
                            ┌────── Iteration 3 (frames 161-257) ──────┐
                            │ Processing window: 97 frames             │
                            │ Overlap: 17 frames (161-177) from prev   │ → 5 blocks, async processing
                            │ Generates: frames 178-257                │
                            └──────────────────────────────────────────┘

    Each iteration independently runs the asynchronous processing with its own 5 blocks.
    base_num_frames controls:
    1. Memory usage (larger window = more VRAM)
    2. Model context length (must match training constraints)
    3. Number of blocks per iteration (base_num_latent_frames // causal_block_size)

    Each block takes 30 steps to complete denoising.
    Block N starts at step: 1 + (N-1) x ar_step
    Total steps: 30 + (5-1) x 5 = 50 steps


    Synchronous mode (ar_step=0) would process all blocks/frames simultaneously:
    ┌──────────────────────────────────────────────┐
    │ Steps:       1            ...            30  │
    │ All blocks: [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■] │
    └──────────────────────────────────────────────┘
    Total steps: 30 steps


    An example on how the step matrix is constructed for asynchronous processing:
    Given the parameters: (num_inference_steps=30, flow_shift=8, num_frames=97, ar_step=5, causal_block_size=5)
    - num_latent_frames = (97 frames - 1) // (4 temporal downsampling) + 1 = 25
    - step_template = [999, 995, 991, 986, 980, 975, 969, 963, 956, 948,
                       941, 932, 922, 912, 901, 888, 874, 859, 841, 822,
                       799, 773, 743, 708, 666, 615, 551, 470, 363, 216]

    The algorithm creates a 50x25 step_matrix where:
    - Row 1:  [999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999]
    - Row 2:  [995, 995, 995, 995, 995, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999]
    - Row 3:  [991, 991, 991, 991, 991, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999]
    - ...
    - Row 7:  [969, 969, 969, 969, 969, 995, 995, 995, 995, 995, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999, 999]
    - ...
    - Row 21: [799, 799, 799, 799, 799, 888, 888, 888, 888, 888, 941, 941, 941, 941, 941, 975, 975, 975, 975, 975, 999, 999, 999, 999, 999]
    - ...
    - Row 35: [  0,   0,   0,   0,   0, 216, 216, 216, 216, 216, 666, 666, 666, 666, 666, 822, 822, 822, 822, 822, 901, 901, 901, 901, 901]
    - ...
    - Row 42: [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 551, 551, 551, 551, 551, 773, 773, 773, 773, 773]
    - ...
    - Row 50: [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0, 216, 216, 216, 216, 216]

    Detailed Row 6 Analysis:
    - step_matrix[5]:       [ 975, 975, 975, 975, 975, 999, 999, 999, 999, 999, 999,  ...,  999]
    - step_index[5]:        [   6,   6,   6,   6,   6,   1,   1,   1,   1,   1,   0,  ...,    0]
    - step_update_mask[5]:  [True,True,True,True,True,True,True,True,True,True,False, ...,False]
    - valid_interval[5]:    (0, 25)

    Key Pattern: Block i lags behind Block i-1 by exactly ar_step=5 timesteps, creating the
    staggered "diffusion forcing" effect where later blocks condition on cleaner earlier blocks.

Text-to-Video Generation

The example below demonstrates how to generate a video from text.

Refer to the Reduce memory usage guide for more details about the various memory saving techniques.

From the original repo:

You can use --ar_step 5 to enable asynchronous inference. When asynchronous inference, --causal_block_size 5 is recommended while it is not supposed to be set for synchronous generation... Asynchronous inference will take more steps to diffuse the whole sequence which means it will be SLOWER than synchronous mode. In our experiments, asynchronous inference may improve the instruction following and visual consistent performance.

# pip install ftfy
import mindspore as ms
from mindone.diffusers import AutoModel, SkyReelsV2DiffusionForcingPipeline, UniPCMultistepScheduler
from mindone.diffusers.utils import export_to_video

vae = AutoModel.from_pretrained("Skywork/SkyReels-V2-DF-1.3B-540P-Diffusers", subfolder="vae", mindspore_dtype=ms.float32)
transformer = AutoModel.from_pretrained("Skywork/SkyReels-V2-DF-1.3B-540P-Diffusers", subfolder="transformer", mindspore_dtype=ms.bfloat16)

pipeline = SkyReelsV2DiffusionForcingPipeline.from_pretrained(
    "Skywork/SkyReels-V2-DF-1.3B-540P-Diffusers",
    vae=vae,
    transformer=transformer,
    mindspore_dtype=ms.bfloat16
)
flow_shift = 8.0  # 8.0 for T2V, 5.0 for I2V
pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config, flow_shift=flow_shift)

prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."

output = pipeline(
    prompt=prompt,
    num_inference_steps=30,
    height=544,  # 720 for 720P
    width=960,   # 1280 for 720P
    num_frames=97,
    base_num_frames=97,  # 121 for 720P
    ar_step=5,  # Controls asynchronous inference (0 for synchronous mode)
    causal_block_size=5,  # Number of frames in each block for asynchronous processing
    overlap_history=None,  # Number of frames to overlap for smooth transitions in long videos; 17 for long video generations
    addnoise_condition=20,  # Improves consistency in long video generation
)[0][0]
export_to_video(output, "T2V.mp4", fps=24, quality=8)

First-Last-Frame-to-Video Generation

The example below demonstrates how to use the image-to-video pipeline to generate a video using a text description, a starting frame, and an ending frame.

import math
import numpy as np
import mindspore as ms
from mindone.diffusers import AutoencoderKLWan, SkyReelsV2DiffusionForcingImageToVideoPipeline, UniPCMultistepScheduler
from mindone.diffusers.utils import export_to_video, load_image


model_id = "Skywork/SkyReels-V2-DF-1.3B-540P-Diffusers"
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", mindspore_dtype=ms.float32)
pipeline = SkyReelsV2DiffusionForcingImageToVideoPipeline.from_pretrained(
    model_id, vae=vae, mindspore_dtype=ms.bfloat16
)
flow_shift = 5.0  # 8.0 for T2V, 5.0 for I2V
pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config, flow_shift=flow_shift)

first_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png")
last_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png")

def aspect_ratio_resize(image, pipeline, max_area=720 * 1280):
    aspect_ratio = image.height / image.width
    mod_value = pipeline.vae_scale_factor_spatial * pipeline.transformer.config.patch_size[1]
    height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
    width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
    image = image.resize((width, height))
    return image, height, width

def center_crop_pil(img, output_size):
    if isinstance(output_size, int):
        output_size = (output_size, output_size)
    elif isinstance(output_size, tuple) and len(output_size) == 1:
        output_size = (output_size[0], output_size[0])

    width, height = img.size
    target_height, target_width = output_size

    left = (width - target_width) / 2
    top = (height - target_height) / 2
    right = (width + target_width) / 2
    bottom = (height + target_height) / 2

    left = math.floor(left)
    top = math.floor(top)
    right = math.floor(right)
    bottom = math.floor(bottom)

    return img.crop((left, top, right, bottom))

def center_crop_resize(image, height, width):
    # Calculate resize ratio to match first frame dimensions
    resize_ratio = max(width / image.width, height / image.height)

    # Resize the image
    width = round(image.width * resize_ratio)
    height = round(image.height * resize_ratio)
    size = [width, height]
    image = center_crop_pil(image, size)

    return image, height, width

first_frame, height, width = aspect_ratio_resize(first_frame, pipeline)
if last_frame.size != first_frame.size:
    last_frame, _, _ = center_crop_resize(last_frame, height, width)

prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."

output = pipeline(
    image=first_frame, last_image=last_frame, prompt=prompt, height=height, width=width, guidance_scale=5.0
)[0][0]
export_to_video(output, "output.mp4", fps=24, quality=8)

Video-to-Video Generation

SkyReelsV2DiffusionForcingVideoToVideoPipeline extends a given video.

import numpy as np
import mindspore as ms
from mindone.diffusers import AutoencoderKLWan, SkyReelsV2DiffusionForcingVideoToVideoPipeline, UniPCMultistepScheduler
from mindone.diffusers.utils import export_to_video, load_video


model_id = "Skywork/SkyReels-V2-DF-1.3B-540P-Diffusers"
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", mindspore_dtype=ms.float32)
pipeline = SkyReelsV2DiffusionForcingVideoToVideoPipeline.from_pretrained(
    model_id, vae=vae, mindspore_dtype=ms.bfloat16
)
flow_shift = 5.0  # 8.0 for T2V, 5.0 for I2V
pipeline.scheduler = UniPCMultistepScheduler.from_config(pipeline.scheduler.config, flow_shift=flow_shift)

video = load_video("input_video.mp4")

prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."

output = pipeline(
    video=video, prompt=prompt, height=544, width=960, guidance_scale=5.0,
    num_inference_steps=30, num_frames=257, base_num_frames=97, overlap_history=17#, ar_step=5, causal_block_size=5,
)[0][0]
export_to_video(output, "output.mp4", fps=24, quality=8)
# Total frames will be the number of frames of given video + 257

mindone.diffusers.SkyReelsV2DiffusionForcingPipeline

Bases: DiffusionPipeline, SkyReelsV2LoraLoaderMixin

Pipeline for Text-to-Video (t2v) generation using SkyReels-V2 with diffusion forcing.

This model inherits from [DiffusionPipeline]. Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a specific device, etc.).

PARAMETER DESCRIPTION
tokenizer

Tokenizer from T5, specifically the google/umt5-xxl variant.

TYPE: [`AutoTokenizer`]

text_encoder

T5, specifically the google/umt5-xxl variant.

TYPE: [`UMT5EncoderModel`]

transformer

Conditional Transformer to denoise the encoded image latents.

TYPE: [`SkyReelsV2Transformer3DModel`]

scheduler

A scheduler to be used in combination with transformer to denoise the encoded image latents.

TYPE: [`UniPCMultistepScheduler`]

vae

Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.

TYPE: [`AutoencoderKLWan`]

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing.py
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
class SkyReelsV2DiffusionForcingPipeline(DiffusionPipeline, SkyReelsV2LoraLoaderMixin):
    """
    Pipeline for Text-to-Video (t2v) generation using SkyReels-V2 with diffusion forcing.

    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
    implemented for all pipelines (downloading, saving, running on a specific device, etc.).

    Args:
        tokenizer ([`AutoTokenizer`]):
            Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
            specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        text_encoder ([`UMT5EncoderModel`]):
            [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
            the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        transformer ([`SkyReelsV2Transformer3DModel`]):
            Conditional Transformer to denoise the encoded image latents.
        scheduler ([`UniPCMultistepScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
        vae ([`AutoencoderKLWan`]):
            Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
    """

    model_cpu_offload_seq = "text_encoder->transformer->vae"
    _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]

    def __init__(
        self,
        tokenizer: AutoTokenizer,
        text_encoder: UMT5EncoderModel,
        transformer: SkyReelsV2Transformer3DModel,
        vae: AutoencoderKLWan,
        scheduler: UniPCMultistepScheduler,
    ):
        super().__init__()

        self.register_modules(
            vae=vae,
            text_encoder=text_encoder,
            tokenizer=tokenizer,
            transformer=transformer,
            scheduler=scheduler,
        )

        self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
        self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
        self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)

    # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline._get_t5_prompt_embeds
    def _get_t5_prompt_embeds(
        self,
        prompt: Union[str, List[str]] = None,
        num_videos_per_prompt: int = 1,
        max_sequence_length: int = 226,
        dtype: Optional[ms.Type] = None,
    ):
        dtype = dtype or self.text_encoder.dtype

        prompt = [prompt] if isinstance(prompt, str) else prompt
        prompt = [prompt_clean(u) for u in prompt]
        batch_size = len(prompt)

        text_inputs = self.tokenizer(
            prompt,
            padding="max_length",
            max_length=max_sequence_length,
            truncation=True,
            add_special_tokens=True,
            return_attention_mask=True,
            return_tensors="np",
        )
        text_input_ids, mask = ms.tensor(text_inputs.input_ids), ms.tensor(text_inputs.attention_mask)
        seq_lens = mask.gt(0).sum(dim=1).long()

        prompt_embeds = self.text_encoder(text_input_ids, mask)[0]
        prompt_embeds = prompt_embeds.to(dtype=dtype)
        prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
        prompt_embeds = mint.stack(
            [mint.cat([u, u.new_zeros((max_sequence_length - u.shape[0], u.shape[1]))]) for u in prompt_embeds], dim=0
        )

        # duplicate text embeddings for each generation per prompt, using mps friendly method
        _, seq_len, _ = prompt_embeds.shape
        prompt_embeds = prompt_embeds.tile((1, num_videos_per_prompt, 1))
        prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)

        return prompt_embeds

    # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
    def encode_prompt(
        self,
        prompt: Union[str, List[str]],
        negative_prompt: Optional[Union[str, List[str]]] = None,
        do_classifier_free_guidance: bool = True,
        num_videos_per_prompt: int = 1,
        prompt_embeds: Optional[ms.Tensor] = None,
        negative_prompt_embeds: Optional[ms.Tensor] = None,
        max_sequence_length: int = 226,
        dtype: Optional[ms.Type] = None,
    ):
        r"""
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
                Whether to use classifier free guidance or not.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                Number of videos that should be generated per prompt.
            prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            negative_prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            dtype: (`ms.Type`, *optional*):
                mindspore dtype
        """
        prompt = [prompt] if isinstance(prompt, str) else prompt
        if prompt is not None:
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        if prompt_embeds is None:
            prompt_embeds = self._get_t5_prompt_embeds(
                prompt=prompt,
                num_videos_per_prompt=num_videos_per_prompt,
                max_sequence_length=max_sequence_length,
                dtype=dtype,
            )

        if do_classifier_free_guidance and negative_prompt_embeds is None:
            negative_prompt = negative_prompt or ""
            negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt

            if prompt is not None and type(prompt) is not type(negative_prompt):
                raise TypeError(
                    f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
                    f" {type(prompt)}."
                )
            elif batch_size != len(negative_prompt):
                raise ValueError(
                    f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
                    f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                    " the batch size of `prompt`."
                )

            negative_prompt_embeds = self._get_t5_prompt_embeds(
                prompt=negative_prompt,
                num_videos_per_prompt=num_videos_per_prompt,
                max_sequence_length=max_sequence_length,
                dtype=dtype,
            )

        return prompt_embeds, negative_prompt_embeds

    def check_inputs(
        self,
        prompt,
        negative_prompt,
        height,
        width,
        prompt_embeds=None,
        negative_prompt_embeds=None,
        callback_on_step_end_tensor_inputs=None,
        overlap_history=None,
        num_frames=None,
        base_num_frames=None,
    ):
        if height % 16 != 0 or width % 16 != 0:
            raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")

        if callback_on_step_end_tensor_inputs is not None and not all(
            k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
        ):
            raise ValueError(
                f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"  # noqa: E501
            )

        if prompt is not None and prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
                " only forward one of the two."
            )
        elif negative_prompt is not None and negative_prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
                " only forward one of the two."
            )
        elif prompt is None and prompt_embeds is None:
            raise ValueError(
                "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
            )
        elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
            raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
        elif negative_prompt is not None and (
            not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
        ):
            raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")

        if num_frames > base_num_frames and overlap_history is None:
            raise ValueError(
                "`overlap_history` is required when `num_frames` exceeds `base_num_frames` to ensure smooth transitions in long video generation. "
                "Please specify a value for `overlap_history`. Recommended values are 17 or 37."
            )

    def prepare_latents(
        self,
        batch_size: int,
        num_channels_latents: int = 16,
        height: int = 480,
        width: int = 832,
        num_frames: int = 97,
        dtype: Optional[ms.Type] = None,
        generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
        latents: Optional[ms.Tensor] = None,
        base_latent_num_frames: Optional[int] = None,
        video_latents: Optional[ms.Tensor] = None,
        causal_block_size: Optional[int] = None,
        overlap_history_latent_frames: Optional[int] = None,
        long_video_iter: Optional[int] = None,
    ) -> ms.Tensor:
        if latents is not None:
            return latents.to(dtype=dtype)

        num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
        latent_height = height // self.vae_scale_factor_spatial
        latent_width = width // self.vae_scale_factor_spatial

        prefix_video_latents = None
        prefix_video_latents_frames = 0

        if video_latents is not None:  # long video generation at the iterations other than the first one
            prefix_video_latents = video_latents[:, :, -overlap_history_latent_frames:]

            if prefix_video_latents.shape[2] % causal_block_size != 0:
                truncate_len_latents = prefix_video_latents.shape[2] % causal_block_size
                logger.warning(
                    f"The length of prefix video latents is truncated by {truncate_len_latents} frames for the causal block size alignment. "
                    f"This truncation ensures compatibility with the causal block size, which is required for proper processing. "
                    f"However, it may slightly affect the continuity of the generated video at the truncation boundary."
                )
                prefix_video_latents = prefix_video_latents[:, :, :-truncate_len_latents]
            prefix_video_latents_frames = prefix_video_latents.shape[2]

            finished_frame_num = (
                long_video_iter * (base_latent_num_frames - overlap_history_latent_frames)
                + overlap_history_latent_frames
            )
            left_frame_num = num_latent_frames - finished_frame_num
            num_latent_frames = min(left_frame_num + overlap_history_latent_frames, base_latent_num_frames)
        elif base_latent_num_frames is not None:  # long video generation at the first iteration
            num_latent_frames = base_latent_num_frames
        else:  # short video generation
            num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1

        shape = (
            batch_size,
            num_channels_latents,
            num_latent_frames,
            latent_height,
            latent_width,
        )
        if isinstance(generator, list) and len(generator) != batch_size:
            raise ValueError(
                f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
                f" size of {batch_size}. Make sure the batch size matches the length of the generators."
            )

        latents = randn_tensor(shape, generator=generator, dtype=dtype)

        return latents, num_latent_frames, prefix_video_latents, prefix_video_latents_frames

    def generate_timestep_matrix(
        self,
        num_latent_frames: int,
        step_template: ms.Tensor,
        base_num_latent_frames: int,
        ar_step: int = 5,
        num_pre_ready: int = 0,
        causal_block_size: int = 1,
        shrink_interval_with_mask: bool = False,
    ) -> tuple[ms.Tensor, ms.Tensor, ms.Tensor, list[tuple]]:
        """
        This function implements the core diffusion forcing algorithm that creates a coordinated denoising schedule
        across temporal frames. It supports both synchronous and asynchronous generation modes:

        **Synchronous Mode** (ar_step=0, causal_block_size=1):
        - All frames are denoised simultaneously at each timestep
        - Each frame follows the same denoising trajectory: [1000, 800, 600, ..., 0]
        - Simpler but may have less temporal consistency for long videos

        **Asynchronous Mode** (ar_step>0, causal_block_size>1):
        - Frames are grouped into causal blocks and processed block/chunk-wise
        - Each block is denoised in a staggered pattern creating a "denoising wave"
        - Earlier blocks are more denoised, later blocks lag behind by ar_step timesteps
        - Creates stronger temporal dependencies and better consistency

        Args:
            num_latent_frames (int): Total number of latent frames to generate
            step_template (ms.Tensor): Base timestep schedule (e.g., [1000, 800, 600, ..., 0])
            base_num_latent_frames (int): Maximum frames the model can process in one forward pass
            ar_step (int, optional): Autoregressive step size for temporal lag.
                                   0 = synchronous, >0 = asynchronous. Defaults to 5.
            num_pre_ready (int, optional):
                                         Number of frames already denoised (e.g., from prefix in a video2video task).
                                         Defaults to 0.
            causal_block_size (int, optional): Number of frames processed as a causal block.
                                             Defaults to 1.
            shrink_interval_with_mask (bool, optional): Whether to optimize processing intervals.
                                                      Defaults to False.

        Returns:
            tuple containing:
                - step_matrix (ms.Tensor): Matrix of timesteps for each frame at each iteration Shape:
                  [num_iterations, num_latent_frames]
                - step_index (ms.Tensor): Index matrix for timestep lookup Shape: [num_iterations,
                  num_latent_frames]
                - step_update_mask (ms.Tensor): Boolean mask indicating which frames to update Shape:
                  [num_iterations, num_latent_frames]
                - valid_interval (list[tuple]): List of (start, end) intervals for each iteration

        Raises:
            ValueError: If ar_step is too small for the given configuration
        """
        # Initialize lists to store the scheduling matrices and metadata
        step_matrix, step_index = [], []  # Will store timestep values and indices for each iteration
        update_mask, valid_interval = [], []  # Will store update masks and processing intervals

        # Calculate total number of denoising iterations (add 1 for initial noise state)
        num_iterations = len(step_template) + 1

        # Convert frame counts to block counts for causal processing
        # Each block contains causal_block_size frames that are processed together
        # E.g.: 25 frames ÷ 5 = 5 blocks total
        num_blocks = num_latent_frames // causal_block_size
        base_num_blocks = base_num_latent_frames // causal_block_size

        # Validate ar_step is sufficient for the given configuration
        # In asynchronous mode, we need enough timesteps to create the staggered pattern
        if base_num_blocks < num_blocks:
            min_ar_step = len(step_template) / base_num_blocks
            if ar_step < min_ar_step:
                raise ValueError(f"`ar_step` should be at least {math.ceil(min_ar_step)} in your setting")

        # Extend step_template with boundary values for easier indexing
        # 999: dummy value for counter starting from 1
        # 0: final timestep (completely denoised)
        step_template = mint.cat(
            [ms.tensor([999], dtype=ms.int64), step_template.long(), ms.tensor([0], dtype=ms.int64)]
        )

        # Initialize the previous row state (tracks denoising progress for each block)
        # 0 means not started, num_iterations means fully denoised
        pre_row = mint.zeros(num_blocks, dtype=ms.int64)

        # Mark pre-ready frames (e.g., from prefix video for a video2video task) as already at final denoising state
        if num_pre_ready > 0:
            pre_row[: num_pre_ready // causal_block_size] = num_iterations

        # Main loop: Generate denoising schedule until all frames are fully denoised
        while not mint.all(pre_row >= (num_iterations - 1)):
            # Create new row representing the next denoising step
            new_row = mint.zeros(num_blocks, dtype=ms.int64)

            # Apply diffusion forcing logic for each block
            for i in range(num_blocks):
                if i == 0 or pre_row[i - 1] >= (
                    num_iterations - 1
                ):  # the first frame or the last frame is completely denoised
                    new_row[i] = pre_row[i] + 1
                else:
                    # Asynchronous mode: lag behind previous block by ar_step timesteps
                    # This creates the "diffusion forcing" staggered pattern
                    new_row[i] = new_row[i - 1] - ar_step

            # Clamp values to valid range [0, num_iterations]
            new_row = new_row.clamp(0, num_iterations)

            # Create update mask: True for blocks that need denoising update at this iteration
            # Exclude blocks that haven't started (new_row != pre_row) or are finished (new_row != num_iterations)
            # Final state example: [False, ..., False, True, True, True, True, True]
            # where first 20 frames are done (False) and last 5 frames still need updates (True)
            update_mask.append((new_row != pre_row) & (new_row != num_iterations))

            # Store the iteration state
            step_index.append(new_row)  # Index into step_template
            step_matrix.append(step_template[new_row])  # Actual timestep values
            pre_row = new_row  # Update for next iteration

        # For videos longer than model capacity, we process in sliding windows
        terminal_flag = base_num_blocks

        # Optional optimization: shrink interval based on first update mask
        if shrink_interval_with_mask:
            idx_sequence = mint.arange(num_blocks, dtype=ms.int64)
            update_mask = update_mask[0]
            update_mask_idx = idx_sequence[update_mask]
            last_update_idx = update_mask_idx[-1].item()
            terminal_flag = last_update_idx + 1

        # Each interval defines which frames to process in the current forward pass
        for curr_mask in update_mask:
            # Extend terminal flag if current mask has updates beyond current terminal
            if terminal_flag < num_blocks and curr_mask[terminal_flag]:
                terminal_flag += 1
            # Create interval: [start, end) where start ensures we don't exceed model capacity
            valid_interval.append((max(terminal_flag - base_num_blocks, 0), terminal_flag))

        # Convert lists to tensors for efficient processing
        step_update_mask = mint.stack(update_mask, dim=0)
        step_index = mint.stack(step_index, dim=0)
        step_matrix = mint.stack(step_matrix, dim=0)

        # Each block's schedule is replicated to all frames within that block
        if causal_block_size > 1:
            # Expand each block to causal_block_size frames
            step_update_mask = step_update_mask.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
            step_index = step_index.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
            step_matrix = step_matrix.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
            # Scale intervals from block-level to frame-level
            valid_interval = [(s * causal_block_size, e * causal_block_size) for s, e in valid_interval]

        return step_matrix, step_index, step_update_mask, valid_interval

    @property
    def guidance_scale(self):
        return self._guidance_scale

    @property
    def do_classifier_free_guidance(self):
        return self._guidance_scale > 1.0

    @property
    def num_timesteps(self):
        return self._num_timesteps

    @property
    def current_timestep(self):
        return self._current_timestep

    @property
    def interrupt(self):
        return self._interrupt

    @property
    def attention_kwargs(self):
        return self._attention_kwargs

    def __call__(
        self,
        prompt: Union[str, List[str]],
        negative_prompt: Union[str, List[str]] = None,
        height: int = 544,
        width: int = 960,
        num_frames: int = 97,
        num_inference_steps: int = 50,
        guidance_scale: float = 6.0,
        num_videos_per_prompt: Optional[int] = 1,
        generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
        latents: Optional[ms.Tensor] = None,
        prompt_embeds: Optional[ms.Tensor] = None,
        negative_prompt_embeds: Optional[ms.Tensor] = None,
        output_type: Optional[str] = "np",
        return_dict: bool = False,
        attention_kwargs: Optional[Dict[str, Any]] = None,
        callback_on_step_end: Optional[
            Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
        ] = None,
        callback_on_step_end_tensor_inputs: List[str] = ["latents"],
        max_sequence_length: int = 512,
        overlap_history: Optional[int] = None,
        addnoise_condition: float = 0,
        base_num_frames: int = 97,
        ar_step: int = 0,
        causal_block_size: Optional[int] = None,
        fps: int = 24,
    ):
        r"""
        The call function to the pipeline for generation.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
                instead.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            height (`int`, defaults to `544`):
                The height of the generated video.
            width (`int`, defaults to `960`):
                The width of the generated video.
            num_frames (`int`, defaults to `97`):
                The number of frames in the generated video.
            num_inference_steps (`int`, defaults to `50`):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            guidance_scale (`float`, defaults to `6.0`):
                Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
                `guidance_scale` is defined as `w` of equation 2. of [Imagen
                Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
                1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
                usually at the expense of lower image quality. (**6.0 for T2V**, **5.0 for I2V**)
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            generator (`np.random.Generator` or `List[np.random.Generator]`, *optional*):
                A [`np.random.Generator`](https://numpy.org/doc/stable/reference/random/generator.html) to make
                generation deterministic.
            latents (`ms.Tensor`, *optional*):
                Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor is generated by sampling using the supplied random `generator`.
            prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `prompt` input argument.
            negative_prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `negative_prompt` input argument.
            output_type (`str`, *optional*, defaults to `"np"`):
                The output format of the generated image. Choose between `PIL.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `False`):
                Whether or not to return a [`SkyReelsV2PipelineOutput`] instead of a plain tuple.
            attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
                `self.processor` in
                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
                A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
                each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
                DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
                list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
            callback_on_step_end_tensor_inputs (`List`, *optional*):
                The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
                will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
                `._callback_tensor_inputs` attribute of your pipeline class.
            max_sequence_length (`int`, *optional*, defaults to `512`):
                The maximum sequence length of the prompt.
            overlap_history (`int`, *optional*, defaults to `None`):
                Number of frames to overlap for smooth transitions in long videos. If `None`, the pipeline assumes
                short video generation mode, and no overlap is applied. 17 and 37 are recommended to set.
            addnoise_condition (`float`, *optional*, defaults to `0`):
                This is used to help smooth the long video generation by adding some noise to the clean condition. Too
                large noise can cause the inconsistency as well. 20 is a recommended value, and you may try larger
                ones, but it is recommended to not exceed 50.
            base_num_frames (`int`, *optional*, defaults to `97`):
                97 or 121 | Base frame count (**97 for 540P**, **121 for 720P**)
            ar_step (`int`, *optional*, defaults to `0`):
                Controls asynchronous inference (0 for synchronous mode) You can set `ar_step=5` to enable asynchronous
                inference. When asynchronous inference, `causal_block_size=5` is recommended while it is not supposed
                to be set for synchronous generation. Asynchronous inference will take more steps to diffuse the whole
                sequence which means it will be SLOWER than synchronous mode. In our experiments, asynchronous
                inference may improve the instruction following and visual consistent performance.
            causal_block_size (`int`, *optional*, defaults to `None`):
                The number of frames in each block/chunk. Recommended when using asynchronous inference (when ar_step >
                0)
            fps (`int`, *optional*, defaults to `24`):
                Frame rate of the generated video

        Examples:

        Returns:
            [`~SkyReelsV2PipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`SkyReelsV2PipelineOutput`] is returned, otherwise a `tuple` is returned
                where the first element is a list with the generated images and the second element is a list of `bool`s
                indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
        """

        if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
            callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs

        # 1. Check inputs. Raise error if not correct
        self.check_inputs(
            prompt,
            negative_prompt,
            height,
            width,
            prompt_embeds,
            negative_prompt_embeds,
            callback_on_step_end_tensor_inputs,
            overlap_history,
            num_frames,
            base_num_frames,
        )

        if addnoise_condition > 60:
            logger.warning(
                f"The value of 'addnoise_condition' is too large ({addnoise_condition}) and may cause inconsistencies in long video generation. A value of 20 is recommended."  # noqa: E501
            )

        if num_frames % self.vae_scale_factor_temporal != 1:
            logger.warning(
                f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
            )
            num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
        num_frames = max(num_frames, 1)

        self._guidance_scale = guidance_scale
        self._attention_kwargs = attention_kwargs
        self._current_timestep = None
        self._interrupt = False

        # 2. Define call parameters
        if prompt is not None and isinstance(prompt, str):
            batch_size = 1
        elif prompt is not None and isinstance(prompt, list):
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        # 3. Encode input prompt
        prompt_embeds, negative_prompt_embeds = self.encode_prompt(
            prompt=prompt,
            negative_prompt=negative_prompt,
            do_classifier_free_guidance=self.do_classifier_free_guidance,
            num_videos_per_prompt=num_videos_per_prompt,
            prompt_embeds=prompt_embeds,
            negative_prompt_embeds=negative_prompt_embeds,
            max_sequence_length=max_sequence_length,
        )

        transformer_dtype = self.transformer.dtype
        prompt_embeds = prompt_embeds.to(transformer_dtype)
        if negative_prompt_embeds is not None:
            negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)

        # 4. Prepare timesteps
        self.scheduler.set_timesteps(num_inference_steps)
        timesteps = self.scheduler.timesteps

        if causal_block_size is None:
            causal_block_size = self.transformer.config.num_frame_per_block
        else:
            self.transformer._set_ar_attention(causal_block_size)

        fps_embeds = [fps] * prompt_embeds.shape[0]
        fps_embeds = [0 if i == 16 else 1 for i in fps_embeds]
        # TODO: adapt to graph mode. List[int] is not supported in graph mode unless wrapped in ms.mutable
        fps_embeds = tuple(fps_embeds)

        # Determine if we're doing long video generation
        is_long_video = overlap_history is not None and base_num_frames is not None and num_frames > base_num_frames
        # Initialize accumulated_latents to store all latents in one tensor
        accumulated_latents = None
        if is_long_video:
            # Long video generation setup
            overlap_history_latent_frames = (overlap_history - 1) // self.vae_scale_factor_temporal + 1
            num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
            base_latent_num_frames = (
                (base_num_frames - 1) // self.vae_scale_factor_temporal + 1
                if base_num_frames is not None
                else num_latent_frames
            )
            n_iter = (
                1
                + (num_latent_frames - base_latent_num_frames - 1)
                // (base_latent_num_frames - overlap_history_latent_frames)
                + 1
            )
        else:
            # Short video generation setup
            n_iter = 1
            base_latent_num_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1

        # Loop through iterations (multiple iterations only for long videos)
        for iter_idx in range(n_iter):
            if is_long_video:
                logger.debug(f"Processing iteration {iter_idx + 1}/{n_iter} for long video generation...")

            # 5. Prepare latent variables
            num_channels_latents = self.transformer.config.in_channels
            (
                latents,
                current_num_latent_frames,
                prefix_video_latents,
                prefix_video_latents_frames,
            ) = self.prepare_latents(
                batch_size * num_videos_per_prompt,
                num_channels_latents,
                height,
                width,
                num_frames,
                ms.float32,
                generator,
                latents if iter_idx == 0 else None,
                video_latents=accumulated_latents,  # Pass latents directly instead of decoded video
                base_latent_num_frames=base_latent_num_frames if is_long_video else None,
                causal_block_size=causal_block_size,
                overlap_history_latent_frames=overlap_history_latent_frames if is_long_video else None,
                long_video_iter=iter_idx if is_long_video else None,
            )

            if prefix_video_latents_frames > 0:
                latents[:, :, :prefix_video_latents_frames, :, :] = prefix_video_latents.to(transformer_dtype)

            # 6. Prepare sample schedulers and timestep matrix
            sample_schedulers = []
            for _ in range(current_num_latent_frames):
                sample_scheduler = deepcopy(self.scheduler)
                sample_scheduler.set_timesteps(num_inference_steps)
                sample_schedulers.append(sample_scheduler)

            # Different matrix generation for short vs long video
            step_matrix, _, step_update_mask, valid_interval = self.generate_timestep_matrix(
                current_num_latent_frames,
                timesteps,
                current_num_latent_frames if is_long_video else base_latent_num_frames,
                ar_step,
                prefix_video_latents_frames,
                causal_block_size,
            )

            # 7. Denoising loop
            num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
            self._num_timesteps = len(step_matrix)

            with self.progress_bar(total=len(step_matrix)) as progress_bar:
                for i, t in enumerate(step_matrix):
                    if self.interrupt:
                        continue

                    self._current_timestep = t
                    valid_interval_start, valid_interval_end = valid_interval[i]
                    latent_model_input = (
                        latents[:, :, valid_interval_start:valid_interval_end, :, :].to(transformer_dtype).clone()
                    )
                    timestep = t.broadcast_to((latents.shape[0], -1))[
                        :, valid_interval_start:valid_interval_end
                    ].clone()

                    if addnoise_condition > 0 and valid_interval_start < prefix_video_latents_frames:
                        noise_factor = 0.001 * addnoise_condition
                        latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :] = (
                            latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                            * (1.0 - noise_factor)
                            + mint.randn_like(
                                latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                            )
                            * noise_factor
                        )
                        timestep[:, valid_interval_start:prefix_video_latents_frames] = addnoise_condition

                    noise_pred = self.transformer(
                        hidden_states=latent_model_input,
                        timestep=timestep,
                        encoder_hidden_states=prompt_embeds,
                        enable_diffusion_forcing=True,
                        fps=fps_embeds,
                        attention_kwargs=attention_kwargs,
                        return_dict=False,
                    )[0]
                    if self.do_classifier_free_guidance:
                        noise_uncond = self.transformer(
                            hidden_states=latent_model_input,
                            timestep=timestep,
                            encoder_hidden_states=negative_prompt_embeds,
                            enable_diffusion_forcing=True,
                            fps=fps_embeds,
                            attention_kwargs=attention_kwargs,
                            return_dict=False,
                        )[0]
                        noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)

                    update_mask_i = step_update_mask[i]
                    for idx in range(valid_interval_start, valid_interval_end):
                        if update_mask_i[idx].item():
                            latents[:, :, idx, :, :] = sample_schedulers[idx].step(
                                noise_pred[:, :, idx - valid_interval_start, :, :],
                                t[idx],
                                latents[:, :, idx, :, :],
                                return_dict=False,
                            )[0]

                    if callback_on_step_end is not None:
                        callback_kwargs = {}
                        for k in callback_on_step_end_tensor_inputs:
                            callback_kwargs[k] = locals()[k]
                        callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)

                        latents = callback_outputs.pop("latents", latents)
                        prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
                        negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)

                    # call the callback, if provided
                    if i == len(step_matrix) - 1 or (
                        (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
                    ):
                        progress_bar.update()

            # Handle latent accumulation for long videos or use the current latents for short videos
            if is_long_video:
                if accumulated_latents is None:
                    accumulated_latents = latents
                else:
                    # Keep overlap frames for conditioning but don't include them in final output
                    accumulated_latents = mint.cat(
                        [accumulated_latents, latents[:, :, overlap_history_latent_frames:]], dim=2
                    )

        if is_long_video:
            latents = accumulated_latents

        self._current_timestep = None

        # Final decoding step - convert latents to pixels
        if not output_type == "latent":
            latents = latents.to(self.vae.dtype)
            latents_mean = (
                ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
            )
            latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
                latents.dtype
            )
            latents = latents / latents_std + latents_mean
            # TODO: we use pynative mode here since cache in vae.decode which not supported in graph mode
            with pynative_context():
                video = self.vae.decode(latents, return_dict=False)[0]
            video = self.video_processor.postprocess_video(video, output_type=output_type)
        else:
            video = latents

        if not return_dict:
            return (video,)

        return SkyReelsV2PipelineOutput(frames=video)

mindone.diffusers.SkyReelsV2DiffusionForcingPipeline.__call__(prompt, negative_prompt=None, height=544, width=960, num_frames=97, num_inference_steps=50, guidance_scale=6.0, num_videos_per_prompt=1, generator=None, latents=None, prompt_embeds=None, negative_prompt_embeds=None, output_type='np', return_dict=False, attention_kwargs=None, callback_on_step_end=None, callback_on_step_end_tensor_inputs=['latents'], max_sequence_length=512, overlap_history=None, addnoise_condition=0, base_num_frames=97, ar_step=0, causal_block_size=None, fps=24)

The call function to the pipeline for generation.

PARAMETER DESCRIPTION
prompt

The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds. instead.

TYPE: `str` or `List[str]`, *optional*

negative_prompt

The prompt or prompts not to guide the image generation. If not defined, one has to pass negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is less than 1).

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

height

The height of the generated video.

TYPE: `int`, defaults to `544` DEFAULT: 544

width

The width of the generated video.

TYPE: `int`, defaults to `960` DEFAULT: 960

num_frames

The number of frames in the generated video.

TYPE: `int`, defaults to `97` DEFAULT: 97

num_inference_steps

The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.

TYPE: `int`, defaults to `50` DEFAULT: 50

guidance_scale

Guidance scale as defined in Classifier-Free Diffusion Guidance. guidance_scale is defined as w of equation 2. of Imagen Paper. Guidance scale is enabled by setting guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to the text prompt, usually at the expense of lower image quality. (6.0 for T2V, 5.0 for I2V)

TYPE: `float`, defaults to `6.0` DEFAULT: 6.0

num_videos_per_prompt

The number of images to generate per prompt.

TYPE: `int`, *optional*, defaults to 1 DEFAULT: 1

generator

A np.random.Generator to make generation deterministic.

TYPE: `np.random.Generator` or `List[np.random.Generator]`, *optional* DEFAULT: None

latents

Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor is generated by sampling using the supplied random generator.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

negative_prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the negative_prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

output_type

The output format of the generated image. Choose between PIL.Image or np.array.

TYPE: `str`, *optional*, defaults to `"np"` DEFAULT: 'np'

return_dict

Whether or not to return a [SkyReelsV2PipelineOutput] instead of a plain tuple.

TYPE: `bool`, *optional*, defaults to `False` DEFAULT: False

attention_kwargs

A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under self.processor in diffusers.models.attention_processor.

TYPE: `dict`, *optional* DEFAULT: None

callback_on_step_end

A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a list of all tensors as specified by callback_on_step_end_tensor_inputs.

TYPE: `Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional* DEFAULT: None

callback_on_step_end_tensor_inputs

The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list will be passed as callback_kwargs argument. You will only be able to include variables listed in the ._callback_tensor_inputs attribute of your pipeline class.

TYPE: `List`, *optional* DEFAULT: ['latents']

max_sequence_length

The maximum sequence length of the prompt.

TYPE: `int`, *optional*, defaults to `512` DEFAULT: 512

overlap_history

Number of frames to overlap for smooth transitions in long videos. If None, the pipeline assumes short video generation mode, and no overlap is applied. 17 and 37 are recommended to set.

TYPE: `int`, *optional*, defaults to `None` DEFAULT: None

addnoise_condition

This is used to help smooth the long video generation by adding some noise to the clean condition. Too large noise can cause the inconsistency as well. 20 is a recommended value, and you may try larger ones, but it is recommended to not exceed 50.

TYPE: `float`, *optional*, defaults to `0` DEFAULT: 0

base_num_frames

97 or 121 | Base frame count (97 for 540P, 121 for 720P)

TYPE: `int`, *optional*, defaults to `97` DEFAULT: 97

ar_step

Controls asynchronous inference (0 for synchronous mode) You can set ar_step=5 to enable asynchronous inference. When asynchronous inference, causal_block_size=5 is recommended while it is not supposed to be set for synchronous generation. Asynchronous inference will take more steps to diffuse the whole sequence which means it will be SLOWER than synchronous mode. In our experiments, asynchronous inference may improve the instruction following and visual consistent performance.

TYPE: `int`, *optional*, defaults to `0` DEFAULT: 0

causal_block_size

The number of frames in each block/chunk. Recommended when using asynchronous inference (when ar_step > 0)

TYPE: `int`, *optional*, defaults to `None` DEFAULT: None

fps

Frame rate of the generated video

TYPE: `int`, *optional*, defaults to `24` DEFAULT: 24

RETURNS DESCRIPTION

[~SkyReelsV2PipelineOutput] or tuple: If return_dict is True, [SkyReelsV2PipelineOutput] is returned, otherwise a tuple is returned where the first element is a list with the generated images and the second element is a list of bools indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing.py
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
def __call__(
    self,
    prompt: Union[str, List[str]],
    negative_prompt: Union[str, List[str]] = None,
    height: int = 544,
    width: int = 960,
    num_frames: int = 97,
    num_inference_steps: int = 50,
    guidance_scale: float = 6.0,
    num_videos_per_prompt: Optional[int] = 1,
    generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
    latents: Optional[ms.Tensor] = None,
    prompt_embeds: Optional[ms.Tensor] = None,
    negative_prompt_embeds: Optional[ms.Tensor] = None,
    output_type: Optional[str] = "np",
    return_dict: bool = False,
    attention_kwargs: Optional[Dict[str, Any]] = None,
    callback_on_step_end: Optional[
        Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
    ] = None,
    callback_on_step_end_tensor_inputs: List[str] = ["latents"],
    max_sequence_length: int = 512,
    overlap_history: Optional[int] = None,
    addnoise_condition: float = 0,
    base_num_frames: int = 97,
    ar_step: int = 0,
    causal_block_size: Optional[int] = None,
    fps: int = 24,
):
    r"""
    The call function to the pipeline for generation.

    Args:
        prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
            instead.
        negative_prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts not to guide the image generation. If not defined, one has to pass
            `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
            less than `1`).
        height (`int`, defaults to `544`):
            The height of the generated video.
        width (`int`, defaults to `960`):
            The width of the generated video.
        num_frames (`int`, defaults to `97`):
            The number of frames in the generated video.
        num_inference_steps (`int`, defaults to `50`):
            The number of denoising steps. More denoising steps usually lead to a higher quality image at the
            expense of slower inference.
        guidance_scale (`float`, defaults to `6.0`):
            Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
            `guidance_scale` is defined as `w` of equation 2. of [Imagen
            Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
            1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
            usually at the expense of lower image quality. (**6.0 for T2V**, **5.0 for I2V**)
        num_videos_per_prompt (`int`, *optional*, defaults to 1):
            The number of images to generate per prompt.
        generator (`np.random.Generator` or `List[np.random.Generator]`, *optional*):
            A [`np.random.Generator`](https://numpy.org/doc/stable/reference/random/generator.html) to make
            generation deterministic.
        latents (`ms.Tensor`, *optional*):
            Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
            generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
            tensor is generated by sampling using the supplied random `generator`.
        prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
            provided, text embeddings are generated from the `prompt` input argument.
        negative_prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
            provided, text embeddings are generated from the `negative_prompt` input argument.
        output_type (`str`, *optional*, defaults to `"np"`):
            The output format of the generated image. Choose between `PIL.Image` or `np.array`.
        return_dict (`bool`, *optional*, defaults to `False`):
            Whether or not to return a [`SkyReelsV2PipelineOutput`] instead of a plain tuple.
        attention_kwargs (`dict`, *optional*):
            A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
            `self.processor` in
            [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
        callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
            A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
            each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
            DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
            list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
        callback_on_step_end_tensor_inputs (`List`, *optional*):
            The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
            will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
            `._callback_tensor_inputs` attribute of your pipeline class.
        max_sequence_length (`int`, *optional*, defaults to `512`):
            The maximum sequence length of the prompt.
        overlap_history (`int`, *optional*, defaults to `None`):
            Number of frames to overlap for smooth transitions in long videos. If `None`, the pipeline assumes
            short video generation mode, and no overlap is applied. 17 and 37 are recommended to set.
        addnoise_condition (`float`, *optional*, defaults to `0`):
            This is used to help smooth the long video generation by adding some noise to the clean condition. Too
            large noise can cause the inconsistency as well. 20 is a recommended value, and you may try larger
            ones, but it is recommended to not exceed 50.
        base_num_frames (`int`, *optional*, defaults to `97`):
            97 or 121 | Base frame count (**97 for 540P**, **121 for 720P**)
        ar_step (`int`, *optional*, defaults to `0`):
            Controls asynchronous inference (0 for synchronous mode) You can set `ar_step=5` to enable asynchronous
            inference. When asynchronous inference, `causal_block_size=5` is recommended while it is not supposed
            to be set for synchronous generation. Asynchronous inference will take more steps to diffuse the whole
            sequence which means it will be SLOWER than synchronous mode. In our experiments, asynchronous
            inference may improve the instruction following and visual consistent performance.
        causal_block_size (`int`, *optional*, defaults to `None`):
            The number of frames in each block/chunk. Recommended when using asynchronous inference (when ar_step >
            0)
        fps (`int`, *optional*, defaults to `24`):
            Frame rate of the generated video

    Examples:

    Returns:
        [`~SkyReelsV2PipelineOutput`] or `tuple`:
            If `return_dict` is `True`, [`SkyReelsV2PipelineOutput`] is returned, otherwise a `tuple` is returned
            where the first element is a list with the generated images and the second element is a list of `bool`s
            indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
    """

    if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
        callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs

    # 1. Check inputs. Raise error if not correct
    self.check_inputs(
        prompt,
        negative_prompt,
        height,
        width,
        prompt_embeds,
        negative_prompt_embeds,
        callback_on_step_end_tensor_inputs,
        overlap_history,
        num_frames,
        base_num_frames,
    )

    if addnoise_condition > 60:
        logger.warning(
            f"The value of 'addnoise_condition' is too large ({addnoise_condition}) and may cause inconsistencies in long video generation. A value of 20 is recommended."  # noqa: E501
        )

    if num_frames % self.vae_scale_factor_temporal != 1:
        logger.warning(
            f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
        )
        num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
    num_frames = max(num_frames, 1)

    self._guidance_scale = guidance_scale
    self._attention_kwargs = attention_kwargs
    self._current_timestep = None
    self._interrupt = False

    # 2. Define call parameters
    if prompt is not None and isinstance(prompt, str):
        batch_size = 1
    elif prompt is not None and isinstance(prompt, list):
        batch_size = len(prompt)
    else:
        batch_size = prompt_embeds.shape[0]

    # 3. Encode input prompt
    prompt_embeds, negative_prompt_embeds = self.encode_prompt(
        prompt=prompt,
        negative_prompt=negative_prompt,
        do_classifier_free_guidance=self.do_classifier_free_guidance,
        num_videos_per_prompt=num_videos_per_prompt,
        prompt_embeds=prompt_embeds,
        negative_prompt_embeds=negative_prompt_embeds,
        max_sequence_length=max_sequence_length,
    )

    transformer_dtype = self.transformer.dtype
    prompt_embeds = prompt_embeds.to(transformer_dtype)
    if negative_prompt_embeds is not None:
        negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)

    # 4. Prepare timesteps
    self.scheduler.set_timesteps(num_inference_steps)
    timesteps = self.scheduler.timesteps

    if causal_block_size is None:
        causal_block_size = self.transformer.config.num_frame_per_block
    else:
        self.transformer._set_ar_attention(causal_block_size)

    fps_embeds = [fps] * prompt_embeds.shape[0]
    fps_embeds = [0 if i == 16 else 1 for i in fps_embeds]
    # TODO: adapt to graph mode. List[int] is not supported in graph mode unless wrapped in ms.mutable
    fps_embeds = tuple(fps_embeds)

    # Determine if we're doing long video generation
    is_long_video = overlap_history is not None and base_num_frames is not None and num_frames > base_num_frames
    # Initialize accumulated_latents to store all latents in one tensor
    accumulated_latents = None
    if is_long_video:
        # Long video generation setup
        overlap_history_latent_frames = (overlap_history - 1) // self.vae_scale_factor_temporal + 1
        num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
        base_latent_num_frames = (
            (base_num_frames - 1) // self.vae_scale_factor_temporal + 1
            if base_num_frames is not None
            else num_latent_frames
        )
        n_iter = (
            1
            + (num_latent_frames - base_latent_num_frames - 1)
            // (base_latent_num_frames - overlap_history_latent_frames)
            + 1
        )
    else:
        # Short video generation setup
        n_iter = 1
        base_latent_num_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1

    # Loop through iterations (multiple iterations only for long videos)
    for iter_idx in range(n_iter):
        if is_long_video:
            logger.debug(f"Processing iteration {iter_idx + 1}/{n_iter} for long video generation...")

        # 5. Prepare latent variables
        num_channels_latents = self.transformer.config.in_channels
        (
            latents,
            current_num_latent_frames,
            prefix_video_latents,
            prefix_video_latents_frames,
        ) = self.prepare_latents(
            batch_size * num_videos_per_prompt,
            num_channels_latents,
            height,
            width,
            num_frames,
            ms.float32,
            generator,
            latents if iter_idx == 0 else None,
            video_latents=accumulated_latents,  # Pass latents directly instead of decoded video
            base_latent_num_frames=base_latent_num_frames if is_long_video else None,
            causal_block_size=causal_block_size,
            overlap_history_latent_frames=overlap_history_latent_frames if is_long_video else None,
            long_video_iter=iter_idx if is_long_video else None,
        )

        if prefix_video_latents_frames > 0:
            latents[:, :, :prefix_video_latents_frames, :, :] = prefix_video_latents.to(transformer_dtype)

        # 6. Prepare sample schedulers and timestep matrix
        sample_schedulers = []
        for _ in range(current_num_latent_frames):
            sample_scheduler = deepcopy(self.scheduler)
            sample_scheduler.set_timesteps(num_inference_steps)
            sample_schedulers.append(sample_scheduler)

        # Different matrix generation for short vs long video
        step_matrix, _, step_update_mask, valid_interval = self.generate_timestep_matrix(
            current_num_latent_frames,
            timesteps,
            current_num_latent_frames if is_long_video else base_latent_num_frames,
            ar_step,
            prefix_video_latents_frames,
            causal_block_size,
        )

        # 7. Denoising loop
        num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
        self._num_timesteps = len(step_matrix)

        with self.progress_bar(total=len(step_matrix)) as progress_bar:
            for i, t in enumerate(step_matrix):
                if self.interrupt:
                    continue

                self._current_timestep = t
                valid_interval_start, valid_interval_end = valid_interval[i]
                latent_model_input = (
                    latents[:, :, valid_interval_start:valid_interval_end, :, :].to(transformer_dtype).clone()
                )
                timestep = t.broadcast_to((latents.shape[0], -1))[
                    :, valid_interval_start:valid_interval_end
                ].clone()

                if addnoise_condition > 0 and valid_interval_start < prefix_video_latents_frames:
                    noise_factor = 0.001 * addnoise_condition
                    latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :] = (
                        latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                        * (1.0 - noise_factor)
                        + mint.randn_like(
                            latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                        )
                        * noise_factor
                    )
                    timestep[:, valid_interval_start:prefix_video_latents_frames] = addnoise_condition

                noise_pred = self.transformer(
                    hidden_states=latent_model_input,
                    timestep=timestep,
                    encoder_hidden_states=prompt_embeds,
                    enable_diffusion_forcing=True,
                    fps=fps_embeds,
                    attention_kwargs=attention_kwargs,
                    return_dict=False,
                )[0]
                if self.do_classifier_free_guidance:
                    noise_uncond = self.transformer(
                        hidden_states=latent_model_input,
                        timestep=timestep,
                        encoder_hidden_states=negative_prompt_embeds,
                        enable_diffusion_forcing=True,
                        fps=fps_embeds,
                        attention_kwargs=attention_kwargs,
                        return_dict=False,
                    )[0]
                    noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)

                update_mask_i = step_update_mask[i]
                for idx in range(valid_interval_start, valid_interval_end):
                    if update_mask_i[idx].item():
                        latents[:, :, idx, :, :] = sample_schedulers[idx].step(
                            noise_pred[:, :, idx - valid_interval_start, :, :],
                            t[idx],
                            latents[:, :, idx, :, :],
                            return_dict=False,
                        )[0]

                if callback_on_step_end is not None:
                    callback_kwargs = {}
                    for k in callback_on_step_end_tensor_inputs:
                        callback_kwargs[k] = locals()[k]
                    callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)

                    latents = callback_outputs.pop("latents", latents)
                    prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
                    negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)

                # call the callback, if provided
                if i == len(step_matrix) - 1 or (
                    (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
                ):
                    progress_bar.update()

        # Handle latent accumulation for long videos or use the current latents for short videos
        if is_long_video:
            if accumulated_latents is None:
                accumulated_latents = latents
            else:
                # Keep overlap frames for conditioning but don't include them in final output
                accumulated_latents = mint.cat(
                    [accumulated_latents, latents[:, :, overlap_history_latent_frames:]], dim=2
                )

    if is_long_video:
        latents = accumulated_latents

    self._current_timestep = None

    # Final decoding step - convert latents to pixels
    if not output_type == "latent":
        latents = latents.to(self.vae.dtype)
        latents_mean = (
            ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
        )
        latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
            latents.dtype
        )
        latents = latents / latents_std + latents_mean
        # TODO: we use pynative mode here since cache in vae.decode which not supported in graph mode
        with pynative_context():
            video = self.vae.decode(latents, return_dict=False)[0]
        video = self.video_processor.postprocess_video(video, output_type=output_type)
    else:
        video = latents

    if not return_dict:
        return (video,)

    return SkyReelsV2PipelineOutput(frames=video)

mindone.diffusers.SkyReelsV2DiffusionForcingPipeline.encode_prompt(prompt, negative_prompt=None, do_classifier_free_guidance=True, num_videos_per_prompt=1, prompt_embeds=None, negative_prompt_embeds=None, max_sequence_length=226, dtype=None)

Encodes the prompt into text encoder hidden states.

PARAMETER DESCRIPTION
prompt

prompt to be encoded

TYPE: `str` or `List[str]`, *optional*

negative_prompt

The prompt or prompts not to guide the image generation. If not defined, one has to pass negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is less than 1).

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

do_classifier_free_guidance

Whether to use classifier free guidance or not.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

num_videos_per_prompt

Number of videos that should be generated per prompt.

TYPE: `int`, *optional*, defaults to 1 DEFAULT: 1

prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, text embeddings will be generated from prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

negative_prompt_embeds

Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

dtype

(ms.Type, optional): mindspore dtype

TYPE: Optional[Type] DEFAULT: None

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing.py
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
def encode_prompt(
    self,
    prompt: Union[str, List[str]],
    negative_prompt: Optional[Union[str, List[str]]] = None,
    do_classifier_free_guidance: bool = True,
    num_videos_per_prompt: int = 1,
    prompt_embeds: Optional[ms.Tensor] = None,
    negative_prompt_embeds: Optional[ms.Tensor] = None,
    max_sequence_length: int = 226,
    dtype: Optional[ms.Type] = None,
):
    r"""
    Encodes the prompt into text encoder hidden states.

    Args:
        prompt (`str` or `List[str]`, *optional*):
            prompt to be encoded
        negative_prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts not to guide the image generation. If not defined, one has to pass
            `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
            less than `1`).
        do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
            Whether to use classifier free guidance or not.
        num_videos_per_prompt (`int`, *optional*, defaults to 1):
            Number of videos that should be generated per prompt.
        prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
            provided, text embeddings will be generated from `prompt` input argument.
        negative_prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
            weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
            argument.
        dtype: (`ms.Type`, *optional*):
            mindspore dtype
    """
    prompt = [prompt] if isinstance(prompt, str) else prompt
    if prompt is not None:
        batch_size = len(prompt)
    else:
        batch_size = prompt_embeds.shape[0]

    if prompt_embeds is None:
        prompt_embeds = self._get_t5_prompt_embeds(
            prompt=prompt,
            num_videos_per_prompt=num_videos_per_prompt,
            max_sequence_length=max_sequence_length,
            dtype=dtype,
        )

    if do_classifier_free_guidance and negative_prompt_embeds is None:
        negative_prompt = negative_prompt or ""
        negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt

        if prompt is not None and type(prompt) is not type(negative_prompt):
            raise TypeError(
                f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
                f" {type(prompt)}."
            )
        elif batch_size != len(negative_prompt):
            raise ValueError(
                f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
                f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                " the batch size of `prompt`."
            )

        negative_prompt_embeds = self._get_t5_prompt_embeds(
            prompt=negative_prompt,
            num_videos_per_prompt=num_videos_per_prompt,
            max_sequence_length=max_sequence_length,
            dtype=dtype,
        )

    return prompt_embeds, negative_prompt_embeds

mindone.diffusers.SkyReelsV2DiffusionForcingPipeline.generate_timestep_matrix(num_latent_frames, step_template, base_num_latent_frames, ar_step=5, num_pre_ready=0, causal_block_size=1, shrink_interval_with_mask=False)

This function implements the core diffusion forcing algorithm that creates a coordinated denoising schedule across temporal frames. It supports both synchronous and asynchronous generation modes:

Synchronous Mode (ar_step=0, causal_block_size=1): - All frames are denoised simultaneously at each timestep - Each frame follows the same denoising trajectory: [1000, 800, 600, ..., 0] - Simpler but may have less temporal consistency for long videos

Asynchronous Mode (ar_step>0, causal_block_size>1): - Frames are grouped into causal blocks and processed block/chunk-wise - Each block is denoised in a staggered pattern creating a "denoising wave" - Earlier blocks are more denoised, later blocks lag behind by ar_step timesteps - Creates stronger temporal dependencies and better consistency

PARAMETER DESCRIPTION
num_latent_frames

Total number of latent frames to generate

TYPE: int

step_template

Base timestep schedule (e.g., [1000, 800, 600, ..., 0])

TYPE: Tensor

base_num_latent_frames

Maximum frames the model can process in one forward pass

TYPE: int

ar_step

Autoregressive step size for temporal lag. 0 = synchronous, >0 = asynchronous. Defaults to 5.

TYPE: int DEFAULT: 5

num_pre_ready
                     Number of frames already denoised (e.g., from prefix in a video2video task).
                     Defaults to 0.

TYPE: int DEFAULT: 0

causal_block_size

Number of frames processed as a causal block. Defaults to 1.

TYPE: int DEFAULT: 1

shrink_interval_with_mask

Whether to optimize processing intervals. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tuple[Tensor, Tensor, Tensor, list[tuple]]

tuple containing: - step_matrix (ms.Tensor): Matrix of timesteps for each frame at each iteration Shape: [num_iterations, num_latent_frames] - step_index (ms.Tensor): Index matrix for timestep lookup Shape: [num_iterations, num_latent_frames] - step_update_mask (ms.Tensor): Boolean mask indicating which frames to update Shape: [num_iterations, num_latent_frames] - valid_interval (list[tuple]): List of (start, end) intervals for each iteration

RAISES DESCRIPTION
ValueError

If ar_step is too small for the given configuration

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing.py
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
def generate_timestep_matrix(
    self,
    num_latent_frames: int,
    step_template: ms.Tensor,
    base_num_latent_frames: int,
    ar_step: int = 5,
    num_pre_ready: int = 0,
    causal_block_size: int = 1,
    shrink_interval_with_mask: bool = False,
) -> tuple[ms.Tensor, ms.Tensor, ms.Tensor, list[tuple]]:
    """
    This function implements the core diffusion forcing algorithm that creates a coordinated denoising schedule
    across temporal frames. It supports both synchronous and asynchronous generation modes:

    **Synchronous Mode** (ar_step=0, causal_block_size=1):
    - All frames are denoised simultaneously at each timestep
    - Each frame follows the same denoising trajectory: [1000, 800, 600, ..., 0]
    - Simpler but may have less temporal consistency for long videos

    **Asynchronous Mode** (ar_step>0, causal_block_size>1):
    - Frames are grouped into causal blocks and processed block/chunk-wise
    - Each block is denoised in a staggered pattern creating a "denoising wave"
    - Earlier blocks are more denoised, later blocks lag behind by ar_step timesteps
    - Creates stronger temporal dependencies and better consistency

    Args:
        num_latent_frames (int): Total number of latent frames to generate
        step_template (ms.Tensor): Base timestep schedule (e.g., [1000, 800, 600, ..., 0])
        base_num_latent_frames (int): Maximum frames the model can process in one forward pass
        ar_step (int, optional): Autoregressive step size for temporal lag.
                               0 = synchronous, >0 = asynchronous. Defaults to 5.
        num_pre_ready (int, optional):
                                     Number of frames already denoised (e.g., from prefix in a video2video task).
                                     Defaults to 0.
        causal_block_size (int, optional): Number of frames processed as a causal block.
                                         Defaults to 1.
        shrink_interval_with_mask (bool, optional): Whether to optimize processing intervals.
                                                  Defaults to False.

    Returns:
        tuple containing:
            - step_matrix (ms.Tensor): Matrix of timesteps for each frame at each iteration Shape:
              [num_iterations, num_latent_frames]
            - step_index (ms.Tensor): Index matrix for timestep lookup Shape: [num_iterations,
              num_latent_frames]
            - step_update_mask (ms.Tensor): Boolean mask indicating which frames to update Shape:
              [num_iterations, num_latent_frames]
            - valid_interval (list[tuple]): List of (start, end) intervals for each iteration

    Raises:
        ValueError: If ar_step is too small for the given configuration
    """
    # Initialize lists to store the scheduling matrices and metadata
    step_matrix, step_index = [], []  # Will store timestep values and indices for each iteration
    update_mask, valid_interval = [], []  # Will store update masks and processing intervals

    # Calculate total number of denoising iterations (add 1 for initial noise state)
    num_iterations = len(step_template) + 1

    # Convert frame counts to block counts for causal processing
    # Each block contains causal_block_size frames that are processed together
    # E.g.: 25 frames ÷ 5 = 5 blocks total
    num_blocks = num_latent_frames // causal_block_size
    base_num_blocks = base_num_latent_frames // causal_block_size

    # Validate ar_step is sufficient for the given configuration
    # In asynchronous mode, we need enough timesteps to create the staggered pattern
    if base_num_blocks < num_blocks:
        min_ar_step = len(step_template) / base_num_blocks
        if ar_step < min_ar_step:
            raise ValueError(f"`ar_step` should be at least {math.ceil(min_ar_step)} in your setting")

    # Extend step_template with boundary values for easier indexing
    # 999: dummy value for counter starting from 1
    # 0: final timestep (completely denoised)
    step_template = mint.cat(
        [ms.tensor([999], dtype=ms.int64), step_template.long(), ms.tensor([0], dtype=ms.int64)]
    )

    # Initialize the previous row state (tracks denoising progress for each block)
    # 0 means not started, num_iterations means fully denoised
    pre_row = mint.zeros(num_blocks, dtype=ms.int64)

    # Mark pre-ready frames (e.g., from prefix video for a video2video task) as already at final denoising state
    if num_pre_ready > 0:
        pre_row[: num_pre_ready // causal_block_size] = num_iterations

    # Main loop: Generate denoising schedule until all frames are fully denoised
    while not mint.all(pre_row >= (num_iterations - 1)):
        # Create new row representing the next denoising step
        new_row = mint.zeros(num_blocks, dtype=ms.int64)

        # Apply diffusion forcing logic for each block
        for i in range(num_blocks):
            if i == 0 or pre_row[i - 1] >= (
                num_iterations - 1
            ):  # the first frame or the last frame is completely denoised
                new_row[i] = pre_row[i] + 1
            else:
                # Asynchronous mode: lag behind previous block by ar_step timesteps
                # This creates the "diffusion forcing" staggered pattern
                new_row[i] = new_row[i - 1] - ar_step

        # Clamp values to valid range [0, num_iterations]
        new_row = new_row.clamp(0, num_iterations)

        # Create update mask: True for blocks that need denoising update at this iteration
        # Exclude blocks that haven't started (new_row != pre_row) or are finished (new_row != num_iterations)
        # Final state example: [False, ..., False, True, True, True, True, True]
        # where first 20 frames are done (False) and last 5 frames still need updates (True)
        update_mask.append((new_row != pre_row) & (new_row != num_iterations))

        # Store the iteration state
        step_index.append(new_row)  # Index into step_template
        step_matrix.append(step_template[new_row])  # Actual timestep values
        pre_row = new_row  # Update for next iteration

    # For videos longer than model capacity, we process in sliding windows
    terminal_flag = base_num_blocks

    # Optional optimization: shrink interval based on first update mask
    if shrink_interval_with_mask:
        idx_sequence = mint.arange(num_blocks, dtype=ms.int64)
        update_mask = update_mask[0]
        update_mask_idx = idx_sequence[update_mask]
        last_update_idx = update_mask_idx[-1].item()
        terminal_flag = last_update_idx + 1

    # Each interval defines which frames to process in the current forward pass
    for curr_mask in update_mask:
        # Extend terminal flag if current mask has updates beyond current terminal
        if terminal_flag < num_blocks and curr_mask[terminal_flag]:
            terminal_flag += 1
        # Create interval: [start, end) where start ensures we don't exceed model capacity
        valid_interval.append((max(terminal_flag - base_num_blocks, 0), terminal_flag))

    # Convert lists to tensors for efficient processing
    step_update_mask = mint.stack(update_mask, dim=0)
    step_index = mint.stack(step_index, dim=0)
    step_matrix = mint.stack(step_matrix, dim=0)

    # Each block's schedule is replicated to all frames within that block
    if causal_block_size > 1:
        # Expand each block to causal_block_size frames
        step_update_mask = step_update_mask.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
        step_index = step_index.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
        step_matrix = step_matrix.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
        # Scale intervals from block-level to frame-level
        valid_interval = [(s * causal_block_size, e * causal_block_size) for s, e in valid_interval]

    return step_matrix, step_index, step_update_mask, valid_interval

mindone.diffusers.SkyReelsV2DiffusionForcingImageToVideoPipeline

Bases: DiffusionPipeline, SkyReelsV2LoraLoaderMixin

Pipeline for Image-to-Video (i2v) generation using SkyReels-V2 with diffusion forcing.

This model inherits from [DiffusionPipeline]. Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a specific device, etc.).

PARAMETER DESCRIPTION
tokenizer

Tokenizer from T5, specifically the google/umt5-xxl variant.

TYPE: [`AutoTokenizer`]

text_encoder

T5, specifically the google/umt5-xxl variant.

TYPE: [`UMT5EncoderModel`]

transformer

Conditional Transformer to denoise the encoded image latents.

TYPE: [`SkyReelsV2Transformer3DModel`]

scheduler

A scheduler to be used in combination with transformer to denoise the encoded image latents.

TYPE: [`UniPCMultistepScheduler`]

vae

Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.

TYPE: [`AutoencoderKLWan`]

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_i2v.py
 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
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
class SkyReelsV2DiffusionForcingImageToVideoPipeline(DiffusionPipeline, SkyReelsV2LoraLoaderMixin):
    """
    Pipeline for Image-to-Video (i2v) generation using SkyReels-V2 with diffusion forcing.

    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
    implemented for all pipelines (downloading, saving, running on a specific device, etc.).

    Args:
        tokenizer ([`AutoTokenizer`]):
            Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
            specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        text_encoder ([`UMT5EncoderModel`]):
            [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
            the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        transformer ([`SkyReelsV2Transformer3DModel`]):
            Conditional Transformer to denoise the encoded image latents.
        scheduler ([`UniPCMultistepScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
        vae ([`AutoencoderKLWan`]):
            Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
    """

    model_cpu_offload_seq = "text_encoder->transformer->vae"
    _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]

    def __init__(
        self,
        tokenizer: AutoTokenizer,
        text_encoder: UMT5EncoderModel,
        transformer: SkyReelsV2Transformer3DModel,
        vae: AutoencoderKLWan,
        scheduler: UniPCMultistepScheduler,
    ):
        super().__init__()

        self.register_modules(
            vae=vae,
            text_encoder=text_encoder,
            tokenizer=tokenizer,
            transformer=transformer,
            scheduler=scheduler,
        )

        self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
        self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
        self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)

    # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline._get_t5_prompt_embeds
    def _get_t5_prompt_embeds(
        self,
        prompt: Union[str, List[str]] = None,
        num_videos_per_prompt: int = 1,
        max_sequence_length: int = 226,
        dtype: Optional[ms.Type] = None,
    ):
        dtype = dtype or self.text_encoder.dtype

        prompt = [prompt] if isinstance(prompt, str) else prompt
        prompt = [prompt_clean(u) for u in prompt]
        batch_size = len(prompt)

        text_inputs = self.tokenizer(
            prompt,
            padding="max_length",
            max_length=max_sequence_length,
            truncation=True,
            add_special_tokens=True,
            return_attention_mask=True,
            return_tensors="np",
        )
        text_input_ids, mask = ms.tensor(text_inputs.input_ids), ms.tensor(text_inputs.attention_mask)
        seq_lens = mask.gt(0).sum(dim=1).long()

        prompt_embeds = self.text_encoder(text_input_ids, mask)[0]
        prompt_embeds = prompt_embeds.to(dtype=dtype)
        prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
        prompt_embeds = mint.stack(
            [mint.cat([u, u.new_zeros((max_sequence_length - u.shape[0], u.shape[1]))]) for u in prompt_embeds], dim=0
        )

        # duplicate text embeddings for each generation per prompt, using mps friendly method
        _, seq_len, _ = prompt_embeds.shape
        prompt_embeds = prompt_embeds.tile((1, num_videos_per_prompt, 1))
        prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)

        return prompt_embeds

    # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
    def encode_prompt(
        self,
        prompt: Union[str, List[str]],
        negative_prompt: Optional[Union[str, List[str]]] = None,
        do_classifier_free_guidance: bool = True,
        num_videos_per_prompt: int = 1,
        prompt_embeds: Optional[ms.Tensor] = None,
        negative_prompt_embeds: Optional[ms.Tensor] = None,
        max_sequence_length: int = 226,
        dtype: Optional[ms.Type] = None,
    ):
        r"""
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
                Whether to use classifier free guidance or not.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                Number of videos that should be generated per prompt.
            prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            negative_prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            dtype: (`ms.Type`, *optional*):
                mindspore dtype
        """
        prompt = [prompt] if isinstance(prompt, str) else prompt
        if prompt is not None:
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        if prompt_embeds is None:
            prompt_embeds = self._get_t5_prompt_embeds(
                prompt=prompt,
                num_videos_per_prompt=num_videos_per_prompt,
                max_sequence_length=max_sequence_length,
                dtype=dtype,
            )

        if do_classifier_free_guidance and negative_prompt_embeds is None:
            negative_prompt = negative_prompt or ""
            negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt

            if prompt is not None and type(prompt) is not type(negative_prompt):
                raise TypeError(
                    f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
                    f" {type(prompt)}."
                )
            elif batch_size != len(negative_prompt):
                raise ValueError(
                    f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
                    f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                    " the batch size of `prompt`."
                )

            negative_prompt_embeds = self._get_t5_prompt_embeds(
                prompt=negative_prompt,
                num_videos_per_prompt=num_videos_per_prompt,
                max_sequence_length=max_sequence_length,
                dtype=dtype,
            )

        return prompt_embeds, negative_prompt_embeds

    def check_inputs(
        self,
        prompt,
        negative_prompt,
        image,
        height,
        width,
        prompt_embeds=None,
        negative_prompt_embeds=None,
        image_embeds=None,
        callback_on_step_end_tensor_inputs=None,
        overlap_history=None,
        num_frames=None,
        base_num_frames=None,
    ):
        if image is not None and image_embeds is not None:
            raise ValueError(
                f"Cannot forward both `image`: {image} and `image_embeds`: {image_embeds}. Please make sure to"
                " only forward one of the two."
            )
        if image is None and image_embeds is None:
            raise ValueError(
                "Provide either `image` or `image_embeds`. Cannot leave both `image` and `image_embeds` undefined."
            )
        if image is not None and not isinstance(image, ms.Tensor) and not isinstance(image, PIL.Image.Image):
            raise ValueError(f"`image` has to be of type `ms.Tensor` or `PIL.Image.Image` but is {type(image)}")
        if height % 16 != 0 or width % 16 != 0:
            raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")

        if callback_on_step_end_tensor_inputs is not None and not all(
            k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
        ):
            raise ValueError(
                f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"  # noqa: E501
            )

        if prompt is not None and prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
                " only forward one of the two."
            )
        elif negative_prompt is not None and negative_prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
                " only forward one of the two."
            )
        elif prompt is None and prompt_embeds is None:
            raise ValueError(
                "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
            )
        elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
            raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
        elif negative_prompt is not None and (
            not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
        ):
            raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")

        if num_frames > base_num_frames and overlap_history is None:
            raise ValueError(
                "`overlap_history` is required when `num_frames` exceeds `base_num_frames` to ensure smooth transitions in long video generation. "
                "Please specify a value for `overlap_history`. Recommended values are 17 or 37."
            )

    def prepare_latents(
        self,
        image: Optional[PipelineImageInput],
        batch_size: int,
        num_channels_latents: int = 16,
        height: int = 480,
        width: int = 832,
        num_frames: int = 97,
        dtype: Optional[ms.Type] = None,
        generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
        latents: Optional[ms.Tensor] = None,
        last_image: Optional[ms.Tensor] = None,
        video_latents: Optional[ms.Tensor] = None,
        base_latent_num_frames: Optional[int] = None,
        causal_block_size: Optional[int] = None,
        overlap_history_latent_frames: Optional[int] = None,
        long_video_iter: Optional[int] = None,
    ) -> Tuple[ms.Tensor, ms.Tensor]:
        num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
        latent_height = height // self.vae_scale_factor_spatial
        latent_width = width // self.vae_scale_factor_spatial

        prefix_video_latents_frames = 0

        if video_latents is not None:  # long video generation at the iterations other than the first one
            condition = video_latents[:, :, -overlap_history_latent_frames:]

            if condition.shape[2] % causal_block_size != 0:
                truncate_len_latents = condition.shape[2] % causal_block_size
                logger.warning(
                    f"The length of prefix video latents is truncated by {truncate_len_latents} frames for the causal block size alignment. "
                    f"This truncation ensures compatibility with the causal block size, which is required for proper processing. "
                    f"However, it may slightly affect the continuity of the generated video at the truncation boundary."
                )
                condition = condition[:, :, :-truncate_len_latents]
            prefix_video_latents_frames = condition.shape[2]

            finished_frame_num = (
                long_video_iter * (base_latent_num_frames - overlap_history_latent_frames)
                + overlap_history_latent_frames
            )
            left_frame_num = num_latent_frames - finished_frame_num
            num_latent_frames = min(left_frame_num + overlap_history_latent_frames, base_latent_num_frames)
        elif base_latent_num_frames is not None:  # long video generation at the first iteration
            num_latent_frames = base_latent_num_frames
        else:  # short video generation
            num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1

        shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
        if isinstance(generator, list) and len(generator) != batch_size:
            raise ValueError(
                f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
                f" size of {batch_size}. Make sure the batch size matches the length of the generators."
            )

        if latents is None:
            latents = randn_tensor(shape, generator=generator, dtype=dtype)
        else:
            latents = latents.to(dtype=dtype)

        if image is not None:
            image = image.unsqueeze(2)
            if last_image is not None:
                last_image = last_image.unsqueeze(2)
                video_condition = mint.cat([image, last_image], dim=0)
            else:
                video_condition = image

            video_condition = video_condition.to(dtype=self.vae.dtype)

            latents_mean = (
                ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
            )
            latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
                latents.dtype
            )

            if isinstance(generator, list):
                latent_condition = [
                    retrieve_latents(self.vae, self.vae.encode(video_condition)[0], sample_mode="argmax")
                    for _ in generator
                ]
                latent_condition = mint.cat(latent_condition)
            else:
                latent_condition = retrieve_latents(self.vae, self.vae.encode(video_condition)[0], sample_mode="argmax")
                latent_condition = latent_condition.repeat_interleave(batch_size, dim=0)

            latent_condition = latent_condition.to(dtype)
            condition = (latent_condition - latents_mean) * latents_std
            prefix_video_latents_frames = condition.shape[2]

        return latents, num_latent_frames, condition, prefix_video_latents_frames

    # Copied from diffusers.pipelines.skyreels_v2.pipeline_skyreels_v2_diffusion_forcing.SkyReelsV2DiffusionForcingPipeline.generate_timestep_matrix
    def generate_timestep_matrix(
        self,
        num_latent_frames: int,
        step_template: ms.Tensor,
        base_num_latent_frames: int,
        ar_step: int = 5,
        num_pre_ready: int = 0,
        causal_block_size: int = 1,
        shrink_interval_with_mask: bool = False,
    ) -> tuple[ms.Tensor, ms.Tensor, ms.Tensor, list[tuple]]:
        """
        This function implements the core diffusion forcing algorithm that creates a coordinated denoising schedule
        across temporal frames. It supports both synchronous and asynchronous generation modes:

        **Synchronous Mode** (ar_step=0, causal_block_size=1):
        - All frames are denoised simultaneously at each timestep
        - Each frame follows the same denoising trajectory: [1000, 800, 600, ..., 0]
        - Simpler but may have less temporal consistency for long videos

        **Asynchronous Mode** (ar_step>0, causal_block_size>1):
        - Frames are grouped into causal blocks and processed block/chunk-wise
        - Each block is denoised in a staggered pattern creating a "denoising wave"
        - Earlier blocks are more denoised, later blocks lag behind by ar_step timesteps
        - Creates stronger temporal dependencies and better consistency

        Args:
            num_latent_frames (int): Total number of latent frames to generate
            step_template (ms.Tensor): Base timestep schedule (e.g., [1000, 800, 600, ..., 0])
            base_num_latent_frames (int): Maximum frames the model can process in one forward pass
            ar_step (int, optional): Autoregressive step size for temporal lag.
                                   0 = synchronous, >0 = asynchronous. Defaults to 5.
            num_pre_ready (int, optional):
                                         Number of frames already denoised (e.g., from prefix in a video2video task).
                                         Defaults to 0.
            causal_block_size (int, optional): Number of frames processed as a causal block.
                                             Defaults to 1.
            shrink_interval_with_mask (bool, optional): Whether to optimize processing intervals.
                                                      Defaults to False.

        Returns:
            tuple containing:
                - step_matrix (ms.Tensor): Matrix of timesteps for each frame at each iteration Shape:
                  [num_iterations, num_latent_frames]
                - step_index (ms.Tensor): Index matrix for timestep lookup Shape: [num_iterations,
                  num_latent_frames]
                - step_update_mask (ms.Tensor): Boolean mask indicating which frames to update Shape:
                  [num_iterations, num_latent_frames]
                - valid_interval (list[tuple]): List of (start, end) intervals for each iteration

        Raises:
            ValueError: If ar_step is too small for the given configuration
        """
        # Initialize lists to store the scheduling matrices and metadata
        step_matrix, step_index = [], []  # Will store timestep values and indices for each iteration
        update_mask, valid_interval = [], []  # Will store update masks and processing intervals

        # Calculate total number of denoising iterations (add 1 for initial noise state)
        num_iterations = len(step_template) + 1

        # Convert frame counts to block counts for causal processing
        # Each block contains causal_block_size frames that are processed together
        # E.g.: 25 frames ÷ 5 = 5 blocks total
        num_blocks = num_latent_frames // causal_block_size
        base_num_blocks = base_num_latent_frames // causal_block_size

        # Validate ar_step is sufficient for the given configuration
        # In asynchronous mode, we need enough timesteps to create the staggered pattern
        if base_num_blocks < num_blocks:
            min_ar_step = len(step_template) / base_num_blocks
            if ar_step < min_ar_step:
                raise ValueError(f"`ar_step` should be at least {math.ceil(min_ar_step)} in your setting")

        # Extend step_template with boundary values for easier indexing
        # 999: dummy value for counter starting from 1
        # 0: final timestep (completely denoised)
        step_template = mint.cat(
            [ms.tensor([999], dtype=ms.int64), step_template.long(), ms.tensor([0], dtype=ms.int64)]
        )

        # Initialize the previous row state (tracks denoising progress for each block)
        # 0 means not started, num_iterations means fully denoised
        pre_row = mint.zeros(num_blocks, dtype=ms.int64)

        # Mark pre-ready frames (e.g., from prefix video for a video2video task) as already at final denoising state
        if num_pre_ready > 0:
            pre_row[: num_pre_ready // causal_block_size] = num_iterations

        # Main loop: Generate denoising schedule until all frames are fully denoised
        while not mint.all(pre_row >= (num_iterations - 1)):
            # Create new row representing the next denoising step
            new_row = mint.zeros(num_blocks, dtype=ms.int64)

            # Apply diffusion forcing logic for each block
            for i in range(num_blocks):
                if i == 0 or pre_row[i - 1] >= (
                    num_iterations - 1
                ):  # the first frame or the last frame is completely denoised
                    new_row[i] = pre_row[i] + 1
                else:
                    # Asynchronous mode: lag behind previous block by ar_step timesteps
                    # This creates the "diffusion forcing" staggered pattern
                    new_row[i] = new_row[i - 1] - ar_step

            # Clamp values to valid range [0, num_iterations]
            new_row = new_row.clamp(0, num_iterations)

            # Create update mask: True for blocks that need denoising update at this iteration
            # Exclude blocks that haven't started (new_row != pre_row) or are finished (new_row != num_iterations)
            # Final state example: [False, ..., False, True, True, True, True, True]
            # where first 20 frames are done (False) and last 5 frames still need updates (True)
            update_mask.append((new_row != pre_row) & (new_row != num_iterations))

            # Store the iteration state
            step_index.append(new_row)  # Index into step_template
            step_matrix.append(step_template[new_row])  # Actual timestep values
            pre_row = new_row  # Update for next iteration

        # For videos longer than model capacity, we process in sliding windows
        terminal_flag = base_num_blocks

        # Optional optimization: shrink interval based on first update mask
        if shrink_interval_with_mask:
            idx_sequence = mint.arange(num_blocks, dtype=ms.int64)
            update_mask = update_mask[0]
            update_mask_idx = idx_sequence[update_mask]
            last_update_idx = update_mask_idx[-1].item()
            terminal_flag = last_update_idx + 1

        # Each interval defines which frames to process in the current forward pass
        for curr_mask in update_mask:
            # Extend terminal flag if current mask has updates beyond current terminal
            if terminal_flag < num_blocks and curr_mask[terminal_flag]:
                terminal_flag += 1
            # Create interval: [start, end) where start ensures we don't exceed model capacity
            valid_interval.append((max(terminal_flag - base_num_blocks, 0), terminal_flag))

        # Convert lists to tensors for efficient processing
        step_update_mask = mint.stack(update_mask, dim=0)
        step_index = mint.stack(step_index, dim=0)
        step_matrix = mint.stack(step_matrix, dim=0)

        # Each block's schedule is replicated to all frames within that block
        if causal_block_size > 1:
            # Expand each block to causal_block_size frames
            step_update_mask = step_update_mask.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
            step_index = step_index.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
            step_matrix = step_matrix.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
            # Scale intervals from block-level to frame-level
            valid_interval = [(s * causal_block_size, e * causal_block_size) for s, e in valid_interval]

        return step_matrix, step_index, step_update_mask, valid_interval

    @property
    def guidance_scale(self):
        return self._guidance_scale

    @property
    def do_classifier_free_guidance(self):
        return self._guidance_scale > 1.0

    @property
    def num_timesteps(self):
        return self._num_timesteps

    @property
    def current_timestep(self):
        return self._current_timestep

    @property
    def interrupt(self):
        return self._interrupt

    @property
    def attention_kwargs(self):
        return self._attention_kwargs

    def __call__(
        self,
        image: PipelineImageInput,
        prompt: Union[str, List[str]] = None,
        negative_prompt: Union[str, List[str]] = None,
        height: int = 544,
        width: int = 960,
        num_frames: int = 97,
        num_inference_steps: int = 50,
        guidance_scale: float = 5.0,
        num_videos_per_prompt: Optional[int] = 1,
        generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
        latents: Optional[ms.Tensor] = None,
        prompt_embeds: Optional[ms.Tensor] = None,
        negative_prompt_embeds: Optional[ms.Tensor] = None,
        image_embeds: Optional[ms.Tensor] = None,
        last_image: Optional[ms.Tensor] = None,
        output_type: Optional[str] = "np",
        return_dict: bool = False,
        attention_kwargs: Optional[Dict[str, Any]] = None,
        callback_on_step_end: Optional[
            Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
        ] = None,
        callback_on_step_end_tensor_inputs: List[str] = ["latents"],
        max_sequence_length: int = 512,
        overlap_history: Optional[int] = None,
        addnoise_condition: float = 0,
        base_num_frames: int = 97,
        ar_step: int = 0,
        causal_block_size: Optional[int] = None,
        fps: int = 24,
    ):
        r"""
        The call function to the pipeline for generation.

        Args:
            image (`PipelineImageInput`):
                The input image to condition the generation on. Must be an image, a list of images or a `ms.Tensor`.
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
                instead.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            height (`int`, defaults to `544`):
                The height of the generated video.
            width (`int`, defaults to `960`):
                The width of the generated video.
            num_frames (`int`, defaults to `97`):
                The number of frames in the generated video.
            num_inference_steps (`int`, defaults to `50`):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            guidance_scale (`float`, defaults to `5.0`):
                Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
                `guidance_scale` is defined as `w` of equation 2. of [Imagen
                Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
                1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
                usually at the expense of lower image quality. (**6.0 for T2V**, **5.0 for I2V**)
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            generator (`np.random.Generator` or `List[np.random.Generator]`, *optional*):
                A [`np.random.Generator`](https://numpy.org/doc/stable/reference/random/generator.html) to make
                generation deterministic.
            latents (`ms.Tensor`, *optional*):
                Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor is generated by sampling using the supplied random `generator`.
            prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `prompt` input argument.
            negative_prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `negative_prompt` input argument.
            image_embeds (`ms.Tensor`, *optional*):
                Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
                image embeddings are generated from the `image` input argument.
            last_image (`ms.Tensor`, *optional*):
                Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
                image embeddings are generated from the `image` input argument.
            output_type (`str`, *optional*, defaults to `"np"`):
                The output format of the generated image. Choose between `PIL.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `False`):
                Whether or not to return a [`SkyReelsV2PipelineOutput`] instead of a plain tuple.
            attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
                `self.processor` in
                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
                A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
                each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
                DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
                list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
            callback_on_step_end_tensor_inputs (`List`, *optional*):
                The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
                will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
                `._callback_tensor_inputs` attribute of your pipeline class.
            max_sequence_length (`int`, *optional*, defaults to `512`):
                The maximum sequence length of the prompt.
            overlap_history (`int`, *optional*, defaults to `None`):
                Number of frames to overlap for smooth transitions in long videos. If `None`, the pipeline assumes
                short video generation mode, and no overlap is applied. 17 and 37 are recommended to set.
            addnoise_condition (`float`, *optional*, defaults to `0`):
                This is used to help smooth the long video generation by adding some noise to the clean condition. Too
                large noise can cause the inconsistency as well. 20 is a recommended value, and you may try larger
                ones, but it is recommended to not exceed 50.
            base_num_frames (`int`, *optional*, defaults to `97`):
                97 or 121 | Base frame count (**97 for 540P**, **121 for 720P**)
            ar_step (`int`, *optional*, defaults to `0`):
                Controls asynchronous inference (0 for synchronous mode) You can set `ar_step=5` to enable asynchronous
                inference. When asynchronous inference, `causal_block_size=5` is recommended while it is not supposed
                to be set for synchronous generation. Asynchronous inference will take more steps to diffuse the whole
                sequence which means it will be SLOWER than synchronous mode. In our experiments, asynchronous
                inference may improve the instruction following and visual consistent performance.
            causal_block_size (`int`, *optional*, defaults to `None`):
                The number of frames in each block/chunk. Recommended when using asynchronous inference (when ar_step >
                0)
            fps (`int`, *optional*, defaults to `24`):
                Frame rate of the generated video

        Examples:

        Returns:
            [`~SkyReelsV2PipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`SkyReelsV2PipelineOutput`] is returned, otherwise a `tuple` is returned
                where the first element is a list with the generated images and the second element is a list of `bool`s
                indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
        """

        if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
            callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs

        # 1. Check inputs. Raise error if not correct
        self.check_inputs(
            prompt,
            negative_prompt,
            image,
            height,
            width,
            prompt_embeds,
            negative_prompt_embeds,
            image_embeds,
            callback_on_step_end_tensor_inputs,
            overlap_history,
            num_frames,
            base_num_frames,
        )

        if addnoise_condition > 60:
            logger.warning(
                f"The value of 'addnoise_condition' is too large ({addnoise_condition}) and may cause inconsistencies in long video generation. A value of 20 is recommended."  # noqa: E501
            )

        if num_frames % self.vae_scale_factor_temporal != 1:
            logger.warning(
                f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
            )
            num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
        num_frames = max(num_frames, 1)

        self._guidance_scale = guidance_scale
        self._attention_kwargs = attention_kwargs
        self._current_timestep = None
        self._interrupt = False

        # 2. Define call parameters
        if prompt is not None and isinstance(prompt, str):
            batch_size = 1
        elif prompt is not None and isinstance(prompt, list):
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        # 3. Encode input prompt
        prompt_embeds, negative_prompt_embeds = self.encode_prompt(
            prompt=prompt,
            negative_prompt=negative_prompt,
            do_classifier_free_guidance=self.do_classifier_free_guidance,
            num_videos_per_prompt=num_videos_per_prompt,
            prompt_embeds=prompt_embeds,
            negative_prompt_embeds=negative_prompt_embeds,
            max_sequence_length=max_sequence_length,
        )

        transformer_dtype = self.transformer.dtype
        prompt_embeds = prompt_embeds.to(transformer_dtype)
        if negative_prompt_embeds is not None:
            negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)

        # 4. Prepare timesteps
        self.scheduler.set_timesteps(num_inference_steps)
        timesteps = self.scheduler.timesteps

        if causal_block_size is None:
            causal_block_size = self.transformer.config.num_frame_per_block
        else:
            self.transformer._set_ar_attention(causal_block_size)

        fps_embeds = [fps] * prompt_embeds.shape[0]
        fps_embeds = [0 if i == 16 else 1 for i in fps_embeds]
        # TODO: adapt to graph mode. List[int] is not supported in graph mode unless wrapped in ms.mutable
        fps_embeds = tuple(fps_embeds)

        # Determine if we're doing long video generation
        is_long_video = overlap_history is not None and base_num_frames is not None and num_frames > base_num_frames
        # Initialize accumulated_latents to store all latents in one tensor
        accumulated_latents = None
        if is_long_video:
            # Long video generation setup
            overlap_history_latent_frames = (overlap_history - 1) // self.vae_scale_factor_temporal + 1
            num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
            base_latent_num_frames = (
                (base_num_frames - 1) // self.vae_scale_factor_temporal + 1
                if base_num_frames is not None
                else num_latent_frames
            )
            n_iter = (
                1
                + (num_latent_frames - base_latent_num_frames - 1)
                // (base_latent_num_frames - overlap_history_latent_frames)
                + 1
            )
        else:
            # Short video generation setup
            n_iter = 1
            base_latent_num_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1

        image = self.video_processor.preprocess(image, height=height, width=width).to(dtype=ms.float32)

        if last_image is not None:
            last_image = self.video_processor.preprocess(last_image, height=height, width=width).to(dtype=ms.float32)

        # Loop through iterations (multiple iterations only for long videos)
        for iter_idx in range(n_iter):
            if is_long_video:
                logger.debug(f"Processing iteration {iter_idx + 1}/{n_iter} for long video generation...")

            num_channels_latents = self.vae.config.z_dim
            latents, current_num_latent_frames, condition, prefix_video_latents_frames = self.prepare_latents(
                image if iter_idx == 0 else None,
                batch_size * num_videos_per_prompt,
                num_channels_latents,
                height,
                width,
                num_frames,
                ms.float32,
                generator,
                latents if iter_idx == 0 else None,
                last_image,
                video_latents=accumulated_latents,  # Pass latents directly instead of decoded video
                base_latent_num_frames=base_latent_num_frames if is_long_video else None,
                causal_block_size=causal_block_size,
                overlap_history_latent_frames=overlap_history_latent_frames if is_long_video else None,
                long_video_iter=iter_idx if is_long_video else None,
            )

            if iter_idx == 0:
                latents[:, :, :prefix_video_latents_frames, :, :] = condition[: (condition.shape[0] + 1) // 2].to(
                    transformer_dtype
                )
            else:
                latents[:, :, :prefix_video_latents_frames, :, :] = condition.to(transformer_dtype)

            if iter_idx == 0 and last_image is not None:
                end_video_latents = condition[condition.shape[0] // 2 :].to(transformer_dtype)

            if last_image is not None and iter_idx + 1 == n_iter:
                latents = mint.cat([latents, end_video_latents.float()], dim=2)
                base_latent_num_frames += prefix_video_latents_frames
                current_num_latent_frames += prefix_video_latents_frames

            # 4. Prepare sample schedulers and timestep matrix
            sample_schedulers = []
            for _ in range(current_num_latent_frames):
                sample_scheduler = deepcopy(self.scheduler)
                sample_scheduler.set_timesteps(num_inference_steps)
                sample_schedulers.append(sample_scheduler)
            step_matrix, _, step_update_mask, valid_interval = self.generate_timestep_matrix(
                current_num_latent_frames,
                timesteps,
                base_latent_num_frames,
                ar_step,
                prefix_video_latents_frames,
                causal_block_size,
            )

            if last_image is not None and iter_idx + 1 == n_iter:
                step_matrix[:, -prefix_video_latents_frames:] = 0
                step_update_mask[:, -prefix_video_latents_frames:] = False

            # 6. Denoising loop
            num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
            self._num_timesteps = len(step_matrix)

            with self.progress_bar(total=len(step_matrix)) as progress_bar:
                for i, t in enumerate(step_matrix):
                    if self.interrupt:
                        continue

                    self._current_timestep = t
                    valid_interval_start, valid_interval_end = valid_interval[i]
                    latent_model_input = (
                        latents[:, :, valid_interval_start:valid_interval_end, :, :].to(transformer_dtype).clone()
                    )
                    timestep = t.broadcast_to((latents.shape[0], -1))[
                        :, valid_interval_start:valid_interval_end
                    ].clone()

                    if addnoise_condition > 0 and valid_interval_start < prefix_video_latents_frames:
                        noise_factor = 0.001 * addnoise_condition
                        latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :] = (
                            latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                            * (1.0 - noise_factor)
                            + mint.randn_like(
                                latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                            )
                            * noise_factor
                        )
                        timestep[:, valid_interval_start:prefix_video_latents_frames] = addnoise_condition

                    noise_pred = self.transformer(
                        hidden_states=latent_model_input,
                        timestep=timestep,
                        encoder_hidden_states=prompt_embeds,
                        enable_diffusion_forcing=True,
                        fps=fps_embeds,
                        attention_kwargs=attention_kwargs,
                        return_dict=False,
                    )[0]
                    if self.do_classifier_free_guidance:
                        noise_uncond = self.transformer(
                            hidden_states=latent_model_input,
                            timestep=timestep,
                            encoder_hidden_states=negative_prompt_embeds,
                            enable_diffusion_forcing=True,
                            fps=fps_embeds,
                            attention_kwargs=attention_kwargs,
                            return_dict=False,
                        )[0]
                        noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)

                    update_mask_i = step_update_mask[i]
                    for idx in range(valid_interval_start, valid_interval_end):
                        if update_mask_i[idx].item():
                            latents[:, :, idx, :, :] = sample_schedulers[idx].step(
                                noise_pred[:, :, idx - valid_interval_start, :, :],
                                t[idx],
                                latents[:, :, idx, :, :],
                                return_dict=False,
                            )[0]

                    if callback_on_step_end is not None:
                        callback_kwargs = {}
                        for k in callback_on_step_end_tensor_inputs:
                            callback_kwargs[k] = locals()[k]
                        callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)

                        latents = callback_outputs.pop("latents", latents)
                        prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
                        negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)

                    # call the callback, if provided
                    if i == len(step_matrix) - 1 or (
                        (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
                    ):
                        progress_bar.update()

            # Handle latent accumulation for long videos or use the current latents for short videos
            if is_long_video:
                if accumulated_latents is None:
                    accumulated_latents = latents
                else:
                    # Keep overlap frames for conditioning but don't include them in final output
                    accumulated_latents = mint.cat(
                        [accumulated_latents, latents[:, :, overlap_history_latent_frames:]],
                        dim=2,
                    )

        if is_long_video:
            latents = accumulated_latents

        self._current_timestep = None

        # Final decoding step - convert latents to pixels
        if not output_type == "latent":
            if last_image is not None:
                latents = latents[:, :, :-prefix_video_latents_frames, :, :].to(self.vae.dtype)
            latents_mean = (
                ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
            )
            latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
                latents.dtype
            )
            latents = latents / latents_std + latents_mean
            # TODO: we use pynative mode here since cache in vae.decode which not supported in graph mode
            with pynative_context():
                video = self.vae.decode(latents, return_dict=False)[0]
            video = self.video_processor.postprocess_video(video, output_type=output_type)
        else:
            video = latents

        if not return_dict:
            return (video,)

        return SkyReelsV2PipelineOutput(frames=video)

mindone.diffusers.SkyReelsV2DiffusionForcingImageToVideoPipeline.__call__(image, prompt=None, negative_prompt=None, height=544, width=960, num_frames=97, num_inference_steps=50, guidance_scale=5.0, num_videos_per_prompt=1, generator=None, latents=None, prompt_embeds=None, negative_prompt_embeds=None, image_embeds=None, last_image=None, output_type='np', return_dict=False, attention_kwargs=None, callback_on_step_end=None, callback_on_step_end_tensor_inputs=['latents'], max_sequence_length=512, overlap_history=None, addnoise_condition=0, base_num_frames=97, ar_step=0, causal_block_size=None, fps=24)

The call function to the pipeline for generation.

PARAMETER DESCRIPTION
image

The input image to condition the generation on. Must be an image, a list of images or a ms.Tensor.

TYPE: `PipelineImageInput`

prompt

The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds. instead.

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

negative_prompt

The prompt or prompts not to guide the image generation. If not defined, one has to pass negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is less than 1).

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

height

The height of the generated video.

TYPE: `int`, defaults to `544` DEFAULT: 544

width

The width of the generated video.

TYPE: `int`, defaults to `960` DEFAULT: 960

num_frames

The number of frames in the generated video.

TYPE: `int`, defaults to `97` DEFAULT: 97

num_inference_steps

The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.

TYPE: `int`, defaults to `50` DEFAULT: 50

guidance_scale

Guidance scale as defined in Classifier-Free Diffusion Guidance. guidance_scale is defined as w of equation 2. of Imagen Paper. Guidance scale is enabled by setting guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to the text prompt, usually at the expense of lower image quality. (6.0 for T2V, 5.0 for I2V)

TYPE: `float`, defaults to `5.0` DEFAULT: 5.0

num_videos_per_prompt

The number of images to generate per prompt.

TYPE: `int`, *optional*, defaults to 1 DEFAULT: 1

generator

A np.random.Generator to make generation deterministic.

TYPE: `np.random.Generator` or `List[np.random.Generator]`, *optional* DEFAULT: None

latents

Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor is generated by sampling using the supplied random generator.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

negative_prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the negative_prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

image_embeds

Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided, image embeddings are generated from the image input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

last_image

Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided, image embeddings are generated from the image input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

output_type

The output format of the generated image. Choose between PIL.Image or np.array.

TYPE: `str`, *optional*, defaults to `"np"` DEFAULT: 'np'

return_dict

Whether or not to return a [SkyReelsV2PipelineOutput] instead of a plain tuple.

TYPE: `bool`, *optional*, defaults to `False` DEFAULT: False

attention_kwargs

A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under self.processor in diffusers.models.attention_processor.

TYPE: `dict`, *optional* DEFAULT: None

callback_on_step_end

A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a list of all tensors as specified by callback_on_step_end_tensor_inputs.

TYPE: `Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional* DEFAULT: None

callback_on_step_end_tensor_inputs

The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list will be passed as callback_kwargs argument. You will only be able to include variables listed in the ._callback_tensor_inputs attribute of your pipeline class.

TYPE: `List`, *optional* DEFAULT: ['latents']

max_sequence_length

The maximum sequence length of the prompt.

TYPE: `int`, *optional*, defaults to `512` DEFAULT: 512

overlap_history

Number of frames to overlap for smooth transitions in long videos. If None, the pipeline assumes short video generation mode, and no overlap is applied. 17 and 37 are recommended to set.

TYPE: `int`, *optional*, defaults to `None` DEFAULT: None

addnoise_condition

This is used to help smooth the long video generation by adding some noise to the clean condition. Too large noise can cause the inconsistency as well. 20 is a recommended value, and you may try larger ones, but it is recommended to not exceed 50.

TYPE: `float`, *optional*, defaults to `0` DEFAULT: 0

base_num_frames

97 or 121 | Base frame count (97 for 540P, 121 for 720P)

TYPE: `int`, *optional*, defaults to `97` DEFAULT: 97

ar_step

Controls asynchronous inference (0 for synchronous mode) You can set ar_step=5 to enable asynchronous inference. When asynchronous inference, causal_block_size=5 is recommended while it is not supposed to be set for synchronous generation. Asynchronous inference will take more steps to diffuse the whole sequence which means it will be SLOWER than synchronous mode. In our experiments, asynchronous inference may improve the instruction following and visual consistent performance.

TYPE: `int`, *optional*, defaults to `0` DEFAULT: 0

causal_block_size

The number of frames in each block/chunk. Recommended when using asynchronous inference (when ar_step > 0)

TYPE: `int`, *optional*, defaults to `None` DEFAULT: None

fps

Frame rate of the generated video

TYPE: `int`, *optional*, defaults to `24` DEFAULT: 24

RETURNS DESCRIPTION

[~SkyReelsV2PipelineOutput] or tuple: If return_dict is True, [SkyReelsV2PipelineOutput] is returned, otherwise a tuple is returned where the first element is a list with the generated images and the second element is a list of bools indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_i2v.py
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
def __call__(
    self,
    image: PipelineImageInput,
    prompt: Union[str, List[str]] = None,
    negative_prompt: Union[str, List[str]] = None,
    height: int = 544,
    width: int = 960,
    num_frames: int = 97,
    num_inference_steps: int = 50,
    guidance_scale: float = 5.0,
    num_videos_per_prompt: Optional[int] = 1,
    generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
    latents: Optional[ms.Tensor] = None,
    prompt_embeds: Optional[ms.Tensor] = None,
    negative_prompt_embeds: Optional[ms.Tensor] = None,
    image_embeds: Optional[ms.Tensor] = None,
    last_image: Optional[ms.Tensor] = None,
    output_type: Optional[str] = "np",
    return_dict: bool = False,
    attention_kwargs: Optional[Dict[str, Any]] = None,
    callback_on_step_end: Optional[
        Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
    ] = None,
    callback_on_step_end_tensor_inputs: List[str] = ["latents"],
    max_sequence_length: int = 512,
    overlap_history: Optional[int] = None,
    addnoise_condition: float = 0,
    base_num_frames: int = 97,
    ar_step: int = 0,
    causal_block_size: Optional[int] = None,
    fps: int = 24,
):
    r"""
    The call function to the pipeline for generation.

    Args:
        image (`PipelineImageInput`):
            The input image to condition the generation on. Must be an image, a list of images or a `ms.Tensor`.
        prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
            instead.
        negative_prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts not to guide the image generation. If not defined, one has to pass
            `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
            less than `1`).
        height (`int`, defaults to `544`):
            The height of the generated video.
        width (`int`, defaults to `960`):
            The width of the generated video.
        num_frames (`int`, defaults to `97`):
            The number of frames in the generated video.
        num_inference_steps (`int`, defaults to `50`):
            The number of denoising steps. More denoising steps usually lead to a higher quality image at the
            expense of slower inference.
        guidance_scale (`float`, defaults to `5.0`):
            Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
            `guidance_scale` is defined as `w` of equation 2. of [Imagen
            Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
            1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
            usually at the expense of lower image quality. (**6.0 for T2V**, **5.0 for I2V**)
        num_videos_per_prompt (`int`, *optional*, defaults to 1):
            The number of images to generate per prompt.
        generator (`np.random.Generator` or `List[np.random.Generator]`, *optional*):
            A [`np.random.Generator`](https://numpy.org/doc/stable/reference/random/generator.html) to make
            generation deterministic.
        latents (`ms.Tensor`, *optional*):
            Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
            generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
            tensor is generated by sampling using the supplied random `generator`.
        prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
            provided, text embeddings are generated from the `prompt` input argument.
        negative_prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
            provided, text embeddings are generated from the `negative_prompt` input argument.
        image_embeds (`ms.Tensor`, *optional*):
            Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
            image embeddings are generated from the `image` input argument.
        last_image (`ms.Tensor`, *optional*):
            Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
            image embeddings are generated from the `image` input argument.
        output_type (`str`, *optional*, defaults to `"np"`):
            The output format of the generated image. Choose between `PIL.Image` or `np.array`.
        return_dict (`bool`, *optional*, defaults to `False`):
            Whether or not to return a [`SkyReelsV2PipelineOutput`] instead of a plain tuple.
        attention_kwargs (`dict`, *optional*):
            A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
            `self.processor` in
            [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
        callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
            A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
            each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
            DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
            list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
        callback_on_step_end_tensor_inputs (`List`, *optional*):
            The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
            will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
            `._callback_tensor_inputs` attribute of your pipeline class.
        max_sequence_length (`int`, *optional*, defaults to `512`):
            The maximum sequence length of the prompt.
        overlap_history (`int`, *optional*, defaults to `None`):
            Number of frames to overlap for smooth transitions in long videos. If `None`, the pipeline assumes
            short video generation mode, and no overlap is applied. 17 and 37 are recommended to set.
        addnoise_condition (`float`, *optional*, defaults to `0`):
            This is used to help smooth the long video generation by adding some noise to the clean condition. Too
            large noise can cause the inconsistency as well. 20 is a recommended value, and you may try larger
            ones, but it is recommended to not exceed 50.
        base_num_frames (`int`, *optional*, defaults to `97`):
            97 or 121 | Base frame count (**97 for 540P**, **121 for 720P**)
        ar_step (`int`, *optional*, defaults to `0`):
            Controls asynchronous inference (0 for synchronous mode) You can set `ar_step=5` to enable asynchronous
            inference. When asynchronous inference, `causal_block_size=5` is recommended while it is not supposed
            to be set for synchronous generation. Asynchronous inference will take more steps to diffuse the whole
            sequence which means it will be SLOWER than synchronous mode. In our experiments, asynchronous
            inference may improve the instruction following and visual consistent performance.
        causal_block_size (`int`, *optional*, defaults to `None`):
            The number of frames in each block/chunk. Recommended when using asynchronous inference (when ar_step >
            0)
        fps (`int`, *optional*, defaults to `24`):
            Frame rate of the generated video

    Examples:

    Returns:
        [`~SkyReelsV2PipelineOutput`] or `tuple`:
            If `return_dict` is `True`, [`SkyReelsV2PipelineOutput`] is returned, otherwise a `tuple` is returned
            where the first element is a list with the generated images and the second element is a list of `bool`s
            indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
    """

    if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
        callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs

    # 1. Check inputs. Raise error if not correct
    self.check_inputs(
        prompt,
        negative_prompt,
        image,
        height,
        width,
        prompt_embeds,
        negative_prompt_embeds,
        image_embeds,
        callback_on_step_end_tensor_inputs,
        overlap_history,
        num_frames,
        base_num_frames,
    )

    if addnoise_condition > 60:
        logger.warning(
            f"The value of 'addnoise_condition' is too large ({addnoise_condition}) and may cause inconsistencies in long video generation. A value of 20 is recommended."  # noqa: E501
        )

    if num_frames % self.vae_scale_factor_temporal != 1:
        logger.warning(
            f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
        )
        num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
    num_frames = max(num_frames, 1)

    self._guidance_scale = guidance_scale
    self._attention_kwargs = attention_kwargs
    self._current_timestep = None
    self._interrupt = False

    # 2. Define call parameters
    if prompt is not None and isinstance(prompt, str):
        batch_size = 1
    elif prompt is not None and isinstance(prompt, list):
        batch_size = len(prompt)
    else:
        batch_size = prompt_embeds.shape[0]

    # 3. Encode input prompt
    prompt_embeds, negative_prompt_embeds = self.encode_prompt(
        prompt=prompt,
        negative_prompt=negative_prompt,
        do_classifier_free_guidance=self.do_classifier_free_guidance,
        num_videos_per_prompt=num_videos_per_prompt,
        prompt_embeds=prompt_embeds,
        negative_prompt_embeds=negative_prompt_embeds,
        max_sequence_length=max_sequence_length,
    )

    transformer_dtype = self.transformer.dtype
    prompt_embeds = prompt_embeds.to(transformer_dtype)
    if negative_prompt_embeds is not None:
        negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)

    # 4. Prepare timesteps
    self.scheduler.set_timesteps(num_inference_steps)
    timesteps = self.scheduler.timesteps

    if causal_block_size is None:
        causal_block_size = self.transformer.config.num_frame_per_block
    else:
        self.transformer._set_ar_attention(causal_block_size)

    fps_embeds = [fps] * prompt_embeds.shape[0]
    fps_embeds = [0 if i == 16 else 1 for i in fps_embeds]
    # TODO: adapt to graph mode. List[int] is not supported in graph mode unless wrapped in ms.mutable
    fps_embeds = tuple(fps_embeds)

    # Determine if we're doing long video generation
    is_long_video = overlap_history is not None and base_num_frames is not None and num_frames > base_num_frames
    # Initialize accumulated_latents to store all latents in one tensor
    accumulated_latents = None
    if is_long_video:
        # Long video generation setup
        overlap_history_latent_frames = (overlap_history - 1) // self.vae_scale_factor_temporal + 1
        num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
        base_latent_num_frames = (
            (base_num_frames - 1) // self.vae_scale_factor_temporal + 1
            if base_num_frames is not None
            else num_latent_frames
        )
        n_iter = (
            1
            + (num_latent_frames - base_latent_num_frames - 1)
            // (base_latent_num_frames - overlap_history_latent_frames)
            + 1
        )
    else:
        # Short video generation setup
        n_iter = 1
        base_latent_num_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1

    image = self.video_processor.preprocess(image, height=height, width=width).to(dtype=ms.float32)

    if last_image is not None:
        last_image = self.video_processor.preprocess(last_image, height=height, width=width).to(dtype=ms.float32)

    # Loop through iterations (multiple iterations only for long videos)
    for iter_idx in range(n_iter):
        if is_long_video:
            logger.debug(f"Processing iteration {iter_idx + 1}/{n_iter} for long video generation...")

        num_channels_latents = self.vae.config.z_dim
        latents, current_num_latent_frames, condition, prefix_video_latents_frames = self.prepare_latents(
            image if iter_idx == 0 else None,
            batch_size * num_videos_per_prompt,
            num_channels_latents,
            height,
            width,
            num_frames,
            ms.float32,
            generator,
            latents if iter_idx == 0 else None,
            last_image,
            video_latents=accumulated_latents,  # Pass latents directly instead of decoded video
            base_latent_num_frames=base_latent_num_frames if is_long_video else None,
            causal_block_size=causal_block_size,
            overlap_history_latent_frames=overlap_history_latent_frames if is_long_video else None,
            long_video_iter=iter_idx if is_long_video else None,
        )

        if iter_idx == 0:
            latents[:, :, :prefix_video_latents_frames, :, :] = condition[: (condition.shape[0] + 1) // 2].to(
                transformer_dtype
            )
        else:
            latents[:, :, :prefix_video_latents_frames, :, :] = condition.to(transformer_dtype)

        if iter_idx == 0 and last_image is not None:
            end_video_latents = condition[condition.shape[0] // 2 :].to(transformer_dtype)

        if last_image is not None and iter_idx + 1 == n_iter:
            latents = mint.cat([latents, end_video_latents.float()], dim=2)
            base_latent_num_frames += prefix_video_latents_frames
            current_num_latent_frames += prefix_video_latents_frames

        # 4. Prepare sample schedulers and timestep matrix
        sample_schedulers = []
        for _ in range(current_num_latent_frames):
            sample_scheduler = deepcopy(self.scheduler)
            sample_scheduler.set_timesteps(num_inference_steps)
            sample_schedulers.append(sample_scheduler)
        step_matrix, _, step_update_mask, valid_interval = self.generate_timestep_matrix(
            current_num_latent_frames,
            timesteps,
            base_latent_num_frames,
            ar_step,
            prefix_video_latents_frames,
            causal_block_size,
        )

        if last_image is not None and iter_idx + 1 == n_iter:
            step_matrix[:, -prefix_video_latents_frames:] = 0
            step_update_mask[:, -prefix_video_latents_frames:] = False

        # 6. Denoising loop
        num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
        self._num_timesteps = len(step_matrix)

        with self.progress_bar(total=len(step_matrix)) as progress_bar:
            for i, t in enumerate(step_matrix):
                if self.interrupt:
                    continue

                self._current_timestep = t
                valid_interval_start, valid_interval_end = valid_interval[i]
                latent_model_input = (
                    latents[:, :, valid_interval_start:valid_interval_end, :, :].to(transformer_dtype).clone()
                )
                timestep = t.broadcast_to((latents.shape[0], -1))[
                    :, valid_interval_start:valid_interval_end
                ].clone()

                if addnoise_condition > 0 and valid_interval_start < prefix_video_latents_frames:
                    noise_factor = 0.001 * addnoise_condition
                    latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :] = (
                        latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                        * (1.0 - noise_factor)
                        + mint.randn_like(
                            latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                        )
                        * noise_factor
                    )
                    timestep[:, valid_interval_start:prefix_video_latents_frames] = addnoise_condition

                noise_pred = self.transformer(
                    hidden_states=latent_model_input,
                    timestep=timestep,
                    encoder_hidden_states=prompt_embeds,
                    enable_diffusion_forcing=True,
                    fps=fps_embeds,
                    attention_kwargs=attention_kwargs,
                    return_dict=False,
                )[0]
                if self.do_classifier_free_guidance:
                    noise_uncond = self.transformer(
                        hidden_states=latent_model_input,
                        timestep=timestep,
                        encoder_hidden_states=negative_prompt_embeds,
                        enable_diffusion_forcing=True,
                        fps=fps_embeds,
                        attention_kwargs=attention_kwargs,
                        return_dict=False,
                    )[0]
                    noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)

                update_mask_i = step_update_mask[i]
                for idx in range(valid_interval_start, valid_interval_end):
                    if update_mask_i[idx].item():
                        latents[:, :, idx, :, :] = sample_schedulers[idx].step(
                            noise_pred[:, :, idx - valid_interval_start, :, :],
                            t[idx],
                            latents[:, :, idx, :, :],
                            return_dict=False,
                        )[0]

                if callback_on_step_end is not None:
                    callback_kwargs = {}
                    for k in callback_on_step_end_tensor_inputs:
                        callback_kwargs[k] = locals()[k]
                    callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)

                    latents = callback_outputs.pop("latents", latents)
                    prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
                    negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)

                # call the callback, if provided
                if i == len(step_matrix) - 1 or (
                    (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
                ):
                    progress_bar.update()

        # Handle latent accumulation for long videos or use the current latents for short videos
        if is_long_video:
            if accumulated_latents is None:
                accumulated_latents = latents
            else:
                # Keep overlap frames for conditioning but don't include them in final output
                accumulated_latents = mint.cat(
                    [accumulated_latents, latents[:, :, overlap_history_latent_frames:]],
                    dim=2,
                )

    if is_long_video:
        latents = accumulated_latents

    self._current_timestep = None

    # Final decoding step - convert latents to pixels
    if not output_type == "latent":
        if last_image is not None:
            latents = latents[:, :, :-prefix_video_latents_frames, :, :].to(self.vae.dtype)
        latents_mean = (
            ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
        )
        latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
            latents.dtype
        )
        latents = latents / latents_std + latents_mean
        # TODO: we use pynative mode here since cache in vae.decode which not supported in graph mode
        with pynative_context():
            video = self.vae.decode(latents, return_dict=False)[0]
        video = self.video_processor.postprocess_video(video, output_type=output_type)
    else:
        video = latents

    if not return_dict:
        return (video,)

    return SkyReelsV2PipelineOutput(frames=video)

mindone.diffusers.SkyReelsV2DiffusionForcingImageToVideoPipeline.encode_prompt(prompt, negative_prompt=None, do_classifier_free_guidance=True, num_videos_per_prompt=1, prompt_embeds=None, negative_prompt_embeds=None, max_sequence_length=226, dtype=None)

Encodes the prompt into text encoder hidden states.

PARAMETER DESCRIPTION
prompt

prompt to be encoded

TYPE: `str` or `List[str]`, *optional*

negative_prompt

The prompt or prompts not to guide the image generation. If not defined, one has to pass negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is less than 1).

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

do_classifier_free_guidance

Whether to use classifier free guidance or not.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

num_videos_per_prompt

Number of videos that should be generated per prompt.

TYPE: `int`, *optional*, defaults to 1 DEFAULT: 1

prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, text embeddings will be generated from prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

negative_prompt_embeds

Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

dtype

(ms.Type, optional): mindspore dtype

TYPE: Optional[Type] DEFAULT: None

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_i2v.py
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
def encode_prompt(
    self,
    prompt: Union[str, List[str]],
    negative_prompt: Optional[Union[str, List[str]]] = None,
    do_classifier_free_guidance: bool = True,
    num_videos_per_prompt: int = 1,
    prompt_embeds: Optional[ms.Tensor] = None,
    negative_prompt_embeds: Optional[ms.Tensor] = None,
    max_sequence_length: int = 226,
    dtype: Optional[ms.Type] = None,
):
    r"""
    Encodes the prompt into text encoder hidden states.

    Args:
        prompt (`str` or `List[str]`, *optional*):
            prompt to be encoded
        negative_prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts not to guide the image generation. If not defined, one has to pass
            `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
            less than `1`).
        do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
            Whether to use classifier free guidance or not.
        num_videos_per_prompt (`int`, *optional*, defaults to 1):
            Number of videos that should be generated per prompt.
        prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
            provided, text embeddings will be generated from `prompt` input argument.
        negative_prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
            weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
            argument.
        dtype: (`ms.Type`, *optional*):
            mindspore dtype
    """
    prompt = [prompt] if isinstance(prompt, str) else prompt
    if prompt is not None:
        batch_size = len(prompt)
    else:
        batch_size = prompt_embeds.shape[0]

    if prompt_embeds is None:
        prompt_embeds = self._get_t5_prompt_embeds(
            prompt=prompt,
            num_videos_per_prompt=num_videos_per_prompt,
            max_sequence_length=max_sequence_length,
            dtype=dtype,
        )

    if do_classifier_free_guidance and negative_prompt_embeds is None:
        negative_prompt = negative_prompt or ""
        negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt

        if prompt is not None and type(prompt) is not type(negative_prompt):
            raise TypeError(
                f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
                f" {type(prompt)}."
            )
        elif batch_size != len(negative_prompt):
            raise ValueError(
                f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
                f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                " the batch size of `prompt`."
            )

        negative_prompt_embeds = self._get_t5_prompt_embeds(
            prompt=negative_prompt,
            num_videos_per_prompt=num_videos_per_prompt,
            max_sequence_length=max_sequence_length,
            dtype=dtype,
        )

    return prompt_embeds, negative_prompt_embeds

mindone.diffusers.SkyReelsV2DiffusionForcingImageToVideoPipeline.generate_timestep_matrix(num_latent_frames, step_template, base_num_latent_frames, ar_step=5, num_pre_ready=0, causal_block_size=1, shrink_interval_with_mask=False)

This function implements the core diffusion forcing algorithm that creates a coordinated denoising schedule across temporal frames. It supports both synchronous and asynchronous generation modes:

Synchronous Mode (ar_step=0, causal_block_size=1): - All frames are denoised simultaneously at each timestep - Each frame follows the same denoising trajectory: [1000, 800, 600, ..., 0] - Simpler but may have less temporal consistency for long videos

Asynchronous Mode (ar_step>0, causal_block_size>1): - Frames are grouped into causal blocks and processed block/chunk-wise - Each block is denoised in a staggered pattern creating a "denoising wave" - Earlier blocks are more denoised, later blocks lag behind by ar_step timesteps - Creates stronger temporal dependencies and better consistency

PARAMETER DESCRIPTION
num_latent_frames

Total number of latent frames to generate

TYPE: int

step_template

Base timestep schedule (e.g., [1000, 800, 600, ..., 0])

TYPE: Tensor

base_num_latent_frames

Maximum frames the model can process in one forward pass

TYPE: int

ar_step

Autoregressive step size for temporal lag. 0 = synchronous, >0 = asynchronous. Defaults to 5.

TYPE: int DEFAULT: 5

num_pre_ready
                     Number of frames already denoised (e.g., from prefix in a video2video task).
                     Defaults to 0.

TYPE: int DEFAULT: 0

causal_block_size

Number of frames processed as a causal block. Defaults to 1.

TYPE: int DEFAULT: 1

shrink_interval_with_mask

Whether to optimize processing intervals. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tuple[Tensor, Tensor, Tensor, list[tuple]]

tuple containing: - step_matrix (ms.Tensor): Matrix of timesteps for each frame at each iteration Shape: [num_iterations, num_latent_frames] - step_index (ms.Tensor): Index matrix for timestep lookup Shape: [num_iterations, num_latent_frames] - step_update_mask (ms.Tensor): Boolean mask indicating which frames to update Shape: [num_iterations, num_latent_frames] - valid_interval (list[tuple]): List of (start, end) intervals for each iteration

RAISES DESCRIPTION
ValueError

If ar_step is too small for the given configuration

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_i2v.py
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
def generate_timestep_matrix(
    self,
    num_latent_frames: int,
    step_template: ms.Tensor,
    base_num_latent_frames: int,
    ar_step: int = 5,
    num_pre_ready: int = 0,
    causal_block_size: int = 1,
    shrink_interval_with_mask: bool = False,
) -> tuple[ms.Tensor, ms.Tensor, ms.Tensor, list[tuple]]:
    """
    This function implements the core diffusion forcing algorithm that creates a coordinated denoising schedule
    across temporal frames. It supports both synchronous and asynchronous generation modes:

    **Synchronous Mode** (ar_step=0, causal_block_size=1):
    - All frames are denoised simultaneously at each timestep
    - Each frame follows the same denoising trajectory: [1000, 800, 600, ..., 0]
    - Simpler but may have less temporal consistency for long videos

    **Asynchronous Mode** (ar_step>0, causal_block_size>1):
    - Frames are grouped into causal blocks and processed block/chunk-wise
    - Each block is denoised in a staggered pattern creating a "denoising wave"
    - Earlier blocks are more denoised, later blocks lag behind by ar_step timesteps
    - Creates stronger temporal dependencies and better consistency

    Args:
        num_latent_frames (int): Total number of latent frames to generate
        step_template (ms.Tensor): Base timestep schedule (e.g., [1000, 800, 600, ..., 0])
        base_num_latent_frames (int): Maximum frames the model can process in one forward pass
        ar_step (int, optional): Autoregressive step size for temporal lag.
                               0 = synchronous, >0 = asynchronous. Defaults to 5.
        num_pre_ready (int, optional):
                                     Number of frames already denoised (e.g., from prefix in a video2video task).
                                     Defaults to 0.
        causal_block_size (int, optional): Number of frames processed as a causal block.
                                         Defaults to 1.
        shrink_interval_with_mask (bool, optional): Whether to optimize processing intervals.
                                                  Defaults to False.

    Returns:
        tuple containing:
            - step_matrix (ms.Tensor): Matrix of timesteps for each frame at each iteration Shape:
              [num_iterations, num_latent_frames]
            - step_index (ms.Tensor): Index matrix for timestep lookup Shape: [num_iterations,
              num_latent_frames]
            - step_update_mask (ms.Tensor): Boolean mask indicating which frames to update Shape:
              [num_iterations, num_latent_frames]
            - valid_interval (list[tuple]): List of (start, end) intervals for each iteration

    Raises:
        ValueError: If ar_step is too small for the given configuration
    """
    # Initialize lists to store the scheduling matrices and metadata
    step_matrix, step_index = [], []  # Will store timestep values and indices for each iteration
    update_mask, valid_interval = [], []  # Will store update masks and processing intervals

    # Calculate total number of denoising iterations (add 1 for initial noise state)
    num_iterations = len(step_template) + 1

    # Convert frame counts to block counts for causal processing
    # Each block contains causal_block_size frames that are processed together
    # E.g.: 25 frames ÷ 5 = 5 blocks total
    num_blocks = num_latent_frames // causal_block_size
    base_num_blocks = base_num_latent_frames // causal_block_size

    # Validate ar_step is sufficient for the given configuration
    # In asynchronous mode, we need enough timesteps to create the staggered pattern
    if base_num_blocks < num_blocks:
        min_ar_step = len(step_template) / base_num_blocks
        if ar_step < min_ar_step:
            raise ValueError(f"`ar_step` should be at least {math.ceil(min_ar_step)} in your setting")

    # Extend step_template with boundary values for easier indexing
    # 999: dummy value for counter starting from 1
    # 0: final timestep (completely denoised)
    step_template = mint.cat(
        [ms.tensor([999], dtype=ms.int64), step_template.long(), ms.tensor([0], dtype=ms.int64)]
    )

    # Initialize the previous row state (tracks denoising progress for each block)
    # 0 means not started, num_iterations means fully denoised
    pre_row = mint.zeros(num_blocks, dtype=ms.int64)

    # Mark pre-ready frames (e.g., from prefix video for a video2video task) as already at final denoising state
    if num_pre_ready > 0:
        pre_row[: num_pre_ready // causal_block_size] = num_iterations

    # Main loop: Generate denoising schedule until all frames are fully denoised
    while not mint.all(pre_row >= (num_iterations - 1)):
        # Create new row representing the next denoising step
        new_row = mint.zeros(num_blocks, dtype=ms.int64)

        # Apply diffusion forcing logic for each block
        for i in range(num_blocks):
            if i == 0 or pre_row[i - 1] >= (
                num_iterations - 1
            ):  # the first frame or the last frame is completely denoised
                new_row[i] = pre_row[i] + 1
            else:
                # Asynchronous mode: lag behind previous block by ar_step timesteps
                # This creates the "diffusion forcing" staggered pattern
                new_row[i] = new_row[i - 1] - ar_step

        # Clamp values to valid range [0, num_iterations]
        new_row = new_row.clamp(0, num_iterations)

        # Create update mask: True for blocks that need denoising update at this iteration
        # Exclude blocks that haven't started (new_row != pre_row) or are finished (new_row != num_iterations)
        # Final state example: [False, ..., False, True, True, True, True, True]
        # where first 20 frames are done (False) and last 5 frames still need updates (True)
        update_mask.append((new_row != pre_row) & (new_row != num_iterations))

        # Store the iteration state
        step_index.append(new_row)  # Index into step_template
        step_matrix.append(step_template[new_row])  # Actual timestep values
        pre_row = new_row  # Update for next iteration

    # For videos longer than model capacity, we process in sliding windows
    terminal_flag = base_num_blocks

    # Optional optimization: shrink interval based on first update mask
    if shrink_interval_with_mask:
        idx_sequence = mint.arange(num_blocks, dtype=ms.int64)
        update_mask = update_mask[0]
        update_mask_idx = idx_sequence[update_mask]
        last_update_idx = update_mask_idx[-1].item()
        terminal_flag = last_update_idx + 1

    # Each interval defines which frames to process in the current forward pass
    for curr_mask in update_mask:
        # Extend terminal flag if current mask has updates beyond current terminal
        if terminal_flag < num_blocks and curr_mask[terminal_flag]:
            terminal_flag += 1
        # Create interval: [start, end) where start ensures we don't exceed model capacity
        valid_interval.append((max(terminal_flag - base_num_blocks, 0), terminal_flag))

    # Convert lists to tensors for efficient processing
    step_update_mask = mint.stack(update_mask, dim=0)
    step_index = mint.stack(step_index, dim=0)
    step_matrix = mint.stack(step_matrix, dim=0)

    # Each block's schedule is replicated to all frames within that block
    if causal_block_size > 1:
        # Expand each block to causal_block_size frames
        step_update_mask = step_update_mask.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
        step_index = step_index.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
        step_matrix = step_matrix.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
        # Scale intervals from block-level to frame-level
        valid_interval = [(s * causal_block_size, e * causal_block_size) for s, e in valid_interval]

    return step_matrix, step_index, step_update_mask, valid_interval

mindone.diffusers.SkyReelsV2DiffusionForcingVideoToVideoPipeline

Bases: DiffusionPipeline, SkyReelsV2LoraLoaderMixin

Pipeline for Video-to-Video (v2v) generation using SkyReels-V2 with diffusion forcing.

This model inherits from [DiffusionPipeline]. Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a specific device, etc.).

PARAMETER DESCRIPTION
tokenizer

Tokenizer from T5, specifically the google/umt5-xxl variant.

TYPE: [`AutoTokenizer`]

text_encoder

T5, specifically the google/umt5-xxl variant.

TYPE: [`UMT5EncoderModel`]

transformer

Conditional Transformer to denoise the encoded image latents.

TYPE: [`SkyReelsV2Transformer3DModel`]

scheduler

A scheduler to be used in combination with transformer to denoise the encoded image latents.

TYPE: [`UniPCMultistepScheduler`]

vae

Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.

TYPE: [`AutoencoderKLWan`]

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_v2v.py
 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
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
class SkyReelsV2DiffusionForcingVideoToVideoPipeline(DiffusionPipeline, SkyReelsV2LoraLoaderMixin):
    """
    Pipeline for Video-to-Video (v2v) generation using SkyReels-V2 with diffusion forcing.

    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
    implemented for all pipelines (downloading, saving, running on a specific device, etc.).

    Args:
        tokenizer ([`AutoTokenizer`]):
            Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
            specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        text_encoder ([`UMT5EncoderModel`]):
            [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
            the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        transformer ([`SkyReelsV2Transformer3DModel`]):
            Conditional Transformer to denoise the encoded image latents.
        scheduler ([`UniPCMultistepScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
        vae ([`AutoencoderKLWan`]):
            Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
    """

    model_cpu_offload_seq = "text_encoder->transformer->vae"
    _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]

    def __init__(
        self,
        tokenizer: AutoTokenizer,
        text_encoder: UMT5EncoderModel,
        transformer: SkyReelsV2Transformer3DModel,
        vae: AutoencoderKLWan,
        scheduler: UniPCMultistepScheduler,
    ):
        super().__init__()

        self.register_modules(
            vae=vae,
            text_encoder=text_encoder,
            tokenizer=tokenizer,
            transformer=transformer,
            scheduler=scheduler,
        )

        self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
        self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
        self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)

    # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline._get_t5_prompt_embeds
    def _get_t5_prompt_embeds(
        self,
        prompt: Union[str, List[str]] = None,
        num_videos_per_prompt: int = 1,
        max_sequence_length: int = 226,
        dtype: Optional[ms.Type] = None,
    ):
        dtype = dtype or self.text_encoder.dtype

        prompt = [prompt] if isinstance(prompt, str) else prompt
        prompt = [prompt_clean(u) for u in prompt]
        batch_size = len(prompt)

        text_inputs = self.tokenizer(
            prompt,
            padding="max_length",
            max_length=max_sequence_length,
            truncation=True,
            add_special_tokens=True,
            return_attention_mask=True,
            return_tensors="np",
        )
        text_input_ids, mask = ms.tensor(text_inputs.input_ids), ms.tensor(text_inputs.attention_mask)
        seq_lens = mask.gt(0).sum(dim=1).long()

        prompt_embeds = self.text_encoder(text_input_ids, mask)[0]
        prompt_embeds = prompt_embeds.to(dtype=dtype)
        prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
        prompt_embeds = mint.stack(
            [mint.cat([u, u.new_zeros((max_sequence_length - u.shape[0], u.shape[1]))]) for u in prompt_embeds], dim=0
        )

        # duplicate text embeddings for each generation per prompt, using mps friendly method
        _, seq_len, _ = prompt_embeds.shape
        prompt_embeds = prompt_embeds.tile((1, num_videos_per_prompt, 1))
        prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)

        return prompt_embeds

    # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
    def encode_prompt(
        self,
        prompt: Union[str, List[str]],
        negative_prompt: Optional[Union[str, List[str]]] = None,
        do_classifier_free_guidance: bool = True,
        num_videos_per_prompt: int = 1,
        prompt_embeds: Optional[ms.Tensor] = None,
        negative_prompt_embeds: Optional[ms.Tensor] = None,
        max_sequence_length: int = 226,
        dtype: Optional[ms.Type] = None,
    ):
        r"""
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
                Whether to use classifier free guidance or not.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                Number of videos that should be generated per prompt.
            prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            negative_prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            dtype: (`ms.Type`, *optional*):
                mindspore dtype
        """
        prompt = [prompt] if isinstance(prompt, str) else prompt
        if prompt is not None:
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        if prompt_embeds is None:
            prompt_embeds = self._get_t5_prompt_embeds(
                prompt=prompt,
                num_videos_per_prompt=num_videos_per_prompt,
                max_sequence_length=max_sequence_length,
                dtype=dtype,
            )

        if do_classifier_free_guidance and negative_prompt_embeds is None:
            negative_prompt = negative_prompt or ""
            negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt

            if prompt is not None and type(prompt) is not type(negative_prompt):
                raise TypeError(
                    f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
                    f" {type(prompt)}."
                )
            elif batch_size != len(negative_prompt):
                raise ValueError(
                    f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
                    f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                    " the batch size of `prompt`."
                )

            negative_prompt_embeds = self._get_t5_prompt_embeds(
                prompt=negative_prompt,
                num_videos_per_prompt=num_videos_per_prompt,
                max_sequence_length=max_sequence_length,
                dtype=dtype,
            )

        return prompt_embeds, negative_prompt_embeds

    def check_inputs(
        self,
        prompt,
        negative_prompt,
        height,
        width,
        video=None,
        latents=None,
        prompt_embeds=None,
        negative_prompt_embeds=None,
        callback_on_step_end_tensor_inputs=None,
        overlap_history=None,
        num_frames=None,
        base_num_frames=None,
    ):
        if height % 16 != 0 or width % 16 != 0:
            raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")

        if callback_on_step_end_tensor_inputs is not None and not all(
            k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
        ):
            raise ValueError(
                f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"  # noqa: E501
            )

        if prompt is not None and prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
                " only forward one of the two."
            )
        elif negative_prompt is not None and negative_prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
                " only forward one of the two."
            )
        elif prompt is None and prompt_embeds is None:
            raise ValueError(
                "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
            )
        elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
            raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
        elif negative_prompt is not None and (
            not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
        ):
            raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")

        if video is not None and latents is not None:
            raise ValueError("Only one of `video` or `latents` should be provided")

        if num_frames > base_num_frames and overlap_history is None:
            raise ValueError(
                "`overlap_history` is required when `num_frames` exceeds `base_num_frames` to ensure smooth transitions in long video generation. "
                "Please specify a value for `overlap_history`. Recommended values are 17 or 37."
            )

    def prepare_latents(
        self,
        video: ms.Tensor,
        batch_size: int = 1,
        num_channels_latents: int = 16,
        height: int = 480,
        width: int = 832,
        num_frames: int = 97,
        dtype: Optional[ms.Type] = None,
        generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
        latents: Optional[ms.Tensor] = None,
        video_latents: Optional[ms.Tensor] = None,
        base_latent_num_frames: Optional[int] = None,
        overlap_history: Optional[int] = None,
        causal_block_size: Optional[int] = None,
        overlap_history_latent_frames: Optional[int] = None,
        long_video_iter: Optional[int] = None,
    ) -> ms.Tensor:
        if latents is not None:
            return latents.to(dtype=dtype)

        num_latent_frames = (
            (num_frames - 1) // self.vae_scale_factor_temporal + 1 if latents is None else latents.shape[2]
        )
        latent_height = height // self.vae_scale_factor_spatial
        latent_width = width // self.vae_scale_factor_spatial

        if long_video_iter == 0:
            prefix_video_latents = [
                retrieve_latents(
                    self.vae,
                    self.vae.encode(
                        vid.unsqueeze(0)[:, :, -overlap_history:] if vid.dim() == 4 else vid[:, :, -overlap_history:]
                    )[0],
                    sample_mode="argmax",
                )
                for vid in video
            ]
            prefix_video_latents = mint.cat(prefix_video_latents, dim=0).to(dtype)

            latents_mean = (
                ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(self.vae.dtype)
            )
            latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
                self.vae.dtype
            )
            prefix_video_latents = (prefix_video_latents - latents_mean) * latents_std
        else:
            prefix_video_latents = video_latents[:, :, -overlap_history_latent_frames:]

        if prefix_video_latents.shape[2] % causal_block_size != 0:
            truncate_len_latents = prefix_video_latents.shape[2] % causal_block_size
            logger.warning(
                f"The length of prefix video latents is truncated by {truncate_len_latents} frames for the causal block size alignment. "
                f"This truncation ensures compatibility with the causal block size, which is required for proper processing. "
                f"However, it may slightly affect the continuity of the generated video at the truncation boundary."
            )
            prefix_video_latents = prefix_video_latents[:, :, :-truncate_len_latents]
        prefix_video_latents_frames = prefix_video_latents.shape[2]

        finished_frame_num = (
            long_video_iter * (base_latent_num_frames - overlap_history_latent_frames) + overlap_history_latent_frames
        )
        left_frame_num = num_latent_frames - finished_frame_num
        num_latent_frames = min(left_frame_num + overlap_history_latent_frames, base_latent_num_frames)

        shape = (
            batch_size,
            num_channels_latents,
            num_latent_frames,
            latent_height,
            latent_width,
        )
        if isinstance(generator, list) and len(generator) != batch_size:
            raise ValueError(
                f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
                f" size of {batch_size}. Make sure the batch size matches the length of the generators."
            )

        latents = randn_tensor(shape, generator=generator, dtype=dtype)

        return latents, num_latent_frames, prefix_video_latents, prefix_video_latents_frames

    # Copied from diffusers.pipelines.skyreels_v2.pipeline_skyreels_v2_diffusion_forcing.SkyReelsV2DiffusionForcingPipeline.generate_timestep_matrix
    def generate_timestep_matrix(
        self,
        num_latent_frames: int,
        step_template: ms.Tensor,
        base_num_latent_frames: int,
        ar_step: int = 5,
        num_pre_ready: int = 0,
        causal_block_size: int = 1,
        shrink_interval_with_mask: bool = False,
    ) -> tuple[ms.Tensor, ms.Tensor, ms.Tensor, list[tuple]]:
        """
        This function implements the core diffusion forcing algorithm that creates a coordinated denoising schedule
        across temporal frames. It supports both synchronous and asynchronous generation modes:

        **Synchronous Mode** (ar_step=0, causal_block_size=1):
        - All frames are denoised simultaneously at each timestep
        - Each frame follows the same denoising trajectory: [1000, 800, 600, ..., 0]
        - Simpler but may have less temporal consistency for long videos

        **Asynchronous Mode** (ar_step>0, causal_block_size>1):
        - Frames are grouped into causal blocks and processed block/chunk-wise
        - Each block is denoised in a staggered pattern creating a "denoising wave"
        - Earlier blocks are more denoised, later blocks lag behind by ar_step timesteps
        - Creates stronger temporal dependencies and better consistency

        Args:
            num_latent_frames (int): Total number of latent frames to generate
            step_template (ms.Tensor): Base timestep schedule (e.g., [1000, 800, 600, ..., 0])
            base_num_latent_frames (int): Maximum frames the model can process in one forward pass
            ar_step (int, optional): Autoregressive step size for temporal lag.
                                   0 = synchronous, >0 = asynchronous. Defaults to 5.
            num_pre_ready (int, optional):
                                         Number of frames already denoised (e.g., from prefix in a video2video task).
                                         Defaults to 0.
            causal_block_size (int, optional): Number of frames processed as a causal block.
                                             Defaults to 1.
            shrink_interval_with_mask (bool, optional): Whether to optimize processing intervals.
                                                      Defaults to False.

        Returns:
            tuple containing:
                - step_matrix (ms.Tensor): Matrix of timesteps for each frame at each iteration Shape:
                  [num_iterations, num_latent_frames]
                - step_index (ms.Tensor): Index matrix for timestep lookup Shape: [num_iterations,
                  num_latent_frames]
                - step_update_mask (ms.Tensor): Boolean mask indicating which frames to update Shape:
                  [num_iterations, num_latent_frames]
                - valid_interval (list[tuple]): List of (start, end) intervals for each iteration

        Raises:
            ValueError: If ar_step is too small for the given configuration
        """
        # Initialize lists to store the scheduling matrices and metadata
        step_matrix, step_index = [], []  # Will store timestep values and indices for each iteration
        update_mask, valid_interval = [], []  # Will store update masks and processing intervals

        # Calculate total number of denoising iterations (add 1 for initial noise state)
        num_iterations = len(step_template) + 1

        # Convert frame counts to block counts for causal processing
        # Each block contains causal_block_size frames that are processed together
        # E.g.: 25 frames ÷ 5 = 5 blocks total
        num_blocks = num_latent_frames // causal_block_size
        base_num_blocks = base_num_latent_frames // causal_block_size

        # Validate ar_step is sufficient for the given configuration
        # In asynchronous mode, we need enough timesteps to create the staggered pattern
        if base_num_blocks < num_blocks:
            min_ar_step = len(step_template) / base_num_blocks
            if ar_step < min_ar_step:
                raise ValueError(f"`ar_step` should be at least {math.ceil(min_ar_step)} in your setting")

        # Extend step_template with boundary values for easier indexing
        # 999: dummy value for counter starting from 1
        # 0: final timestep (completely denoised)
        step_template = mint.cat(
            [ms.tensor([999], dtype=ms.int64), step_template.long(), ms.tensor([0], dtype=ms.int64)]
        )

        # Initialize the previous row state (tracks denoising progress for each block)
        # 0 means not started, num_iterations means fully denoised
        pre_row = mint.zeros(num_blocks, dtype=ms.int64)

        # Mark pre-ready frames (e.g., from prefix video for a video2video task) as already at final denoising state
        if num_pre_ready > 0:
            pre_row[: num_pre_ready // causal_block_size] = num_iterations

        # Main loop: Generate denoising schedule until all frames are fully denoised
        while not mint.all(pre_row >= (num_iterations - 1)):
            # Create new row representing the next denoising step
            new_row = mint.zeros(num_blocks, dtype=ms.int64)

            # Apply diffusion forcing logic for each block
            for i in range(num_blocks):
                if i == 0 or pre_row[i - 1] >= (
                    num_iterations - 1
                ):  # the first frame or the last frame is completely denoised
                    new_row[i] = pre_row[i] + 1
                else:
                    # Asynchronous mode: lag behind previous block by ar_step timesteps
                    # This creates the "diffusion forcing" staggered pattern
                    new_row[i] = new_row[i - 1] - ar_step

            # Clamp values to valid range [0, num_iterations]
            new_row = new_row.clamp(0, num_iterations)

            # Create update mask: True for blocks that need denoising update at this iteration
            # Exclude blocks that haven't started (new_row != pre_row) or are finished (new_row != num_iterations)
            # Final state example: [False, ..., False, True, True, True, True, True]
            # where first 20 frames are done (False) and last 5 frames still need updates (True)
            update_mask.append((new_row != pre_row) & (new_row != num_iterations))

            # Store the iteration state
            step_index.append(new_row)  # Index into step_template
            step_matrix.append(step_template[new_row])  # Actual timestep values
            pre_row = new_row  # Update for next iteration

        # For videos longer than model capacity, we process in sliding windows
        terminal_flag = base_num_blocks

        # Optional optimization: shrink interval based on first update mask
        if shrink_interval_with_mask:
            idx_sequence = mint.arange(num_blocks, dtype=ms.int64)
            update_mask = update_mask[0]
            update_mask_idx = idx_sequence[update_mask]
            last_update_idx = update_mask_idx[-1].item()
            terminal_flag = last_update_idx + 1

        # Each interval defines which frames to process in the current forward pass
        for curr_mask in update_mask:
            # Extend terminal flag if current mask has updates beyond current terminal
            if terminal_flag < num_blocks and curr_mask[terminal_flag]:
                terminal_flag += 1
            # Create interval: [start, end) where start ensures we don't exceed model capacity
            valid_interval.append((max(terminal_flag - base_num_blocks, 0), terminal_flag))

        # Convert lists to tensors for efficient processing
        step_update_mask = mint.stack(update_mask, dim=0)
        step_index = mint.stack(step_index, dim=0)
        step_matrix = mint.stack(step_matrix, dim=0)

        # Each block's schedule is replicated to all frames within that block
        if causal_block_size > 1:
            # Expand each block to causal_block_size frames
            step_update_mask = step_update_mask.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
            step_index = step_index.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
            step_matrix = step_matrix.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
            # Scale intervals from block-level to frame-level
            valid_interval = [(s * causal_block_size, e * causal_block_size) for s, e in valid_interval]

        return step_matrix, step_index, step_update_mask, valid_interval

    @property
    def guidance_scale(self):
        return self._guidance_scale

    @property
    def do_classifier_free_guidance(self):
        return self._guidance_scale > 1.0

    @property
    def num_timesteps(self):
        return self._num_timesteps

    @property
    def current_timestep(self):
        return self._current_timestep

    @property
    def interrupt(self):
        return self._interrupt

    @property
    def attention_kwargs(self):
        return self._attention_kwargs

    def __call__(
        self,
        video: List[Image.Image],
        prompt: Union[str, List[str]] = None,
        negative_prompt: Union[str, List[str]] = None,
        height: int = 544,
        width: int = 960,
        num_frames: int = 120,
        num_inference_steps: int = 50,
        guidance_scale: float = 6.0,
        num_videos_per_prompt: Optional[int] = 1,
        generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
        latents: Optional[ms.Tensor] = None,
        prompt_embeds: Optional[ms.Tensor] = None,
        negative_prompt_embeds: Optional[ms.Tensor] = None,
        output_type: Optional[str] = "np",
        return_dict: bool = False,
        attention_kwargs: Optional[Dict[str, Any]] = None,
        callback_on_step_end: Optional[
            Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
        ] = None,
        callback_on_step_end_tensor_inputs: List[str] = ["latents"],
        max_sequence_length: int = 512,
        overlap_history: Optional[int] = None,
        addnoise_condition: float = 0,
        base_num_frames: int = 97,
        ar_step: int = 0,
        causal_block_size: Optional[int] = None,
        fps: int = 24,
    ):
        r"""
        The call function to the pipeline for generation.

        Args:
            video (`List[Image.Image]`):
                The video to guide the video generation.
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the video generation. If not defined, one has to pass `prompt_embeds`.
                instead.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the video generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            height (`int`, defaults to `544`):
                The height of the generated video.
            width (`int`, defaults to `960`):
                The width of the generated video.
            num_frames (`int`, defaults to `120`):
                The number of frames in the generated video.
            num_inference_steps (`int`, defaults to `50`):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            guidance_scale (`float`, defaults to `6.0`):
                Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
                `guidance_scale` is defined as `w` of equation 2. of [Imagen
                Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
                1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
                usually at the expense of lower image quality. (**6.0 for T2V**, **5.0 for I2V**)
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            generator (`np.random.Generator` or `List[np.random.Generator]`, *optional*):
                A [`np.random.Generator`](https://numpy.org/doc/stable/reference/random/generator.html) to make
                generation deterministic.
            latents (`ms.Tensor`, *optional*):
                Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor is generated by sampling using the supplied random `generator`.
            prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `prompt` input argument.
            negative_prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `negative_prompt` input argument.
            output_type (`str`, *optional*, defaults to `"np"`):
                The output format of the generated image. Choose between `PIL.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `False`):
                Whether or not to return a [`SkyReelsV2PipelineOutput`] instead of a plain tuple.
            attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
                `self.processor` in
                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
                A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
                each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
                DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
                list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
            callback_on_step_end_tensor_inputs (`List`, *optional*):
                The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
                will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
                `._callback_tensor_inputs` attribute of your pipeline class.
            max_sequence_length (`int`, *optional*, defaults to `512`):
                The maximum sequence length of the prompt.
            overlap_history (`int`, *optional*, defaults to `None`):
                Number of frames to overlap for smooth transitions in long videos. If `None`, the pipeline assumes
                short video generation mode, and no overlap is applied. 17 and 37 are recommended to set.
            addnoise_condition (`float`, *optional*, defaults to `0`):
                This is used to help smooth the long video generation by adding some noise to the clean condition. Too
                large noise can cause the inconsistency as well. 20 is a recommended value, and you may try larger
                ones, but it is recommended to not exceed 50.
            base_num_frames (`int`, *optional*, defaults to `97`):
                97 or 121 | Base frame count (**97 for 540P**, **121 for 720P**)
            ar_step (`int`, *optional*, defaults to `0`):
                Controls asynchronous inference (0 for synchronous mode) You can set `ar_step=5` to enable asynchronous
                inference. When asynchronous inference, `causal_block_size=5` is recommended while it is not supposed
                to be set for synchronous generation. Asynchronous inference will take more steps to diffuse the whole
                sequence which means it will be SLOWER than synchronous mode. In our experiments, asynchronous
                inference may improve the instruction following and visual consistent performance.
            causal_block_size (`int`, *optional*, defaults to `None`):
                The number of frames in each block/chunk. Recommended when using asynchronous inference (when ar_step >
                0)
            fps (`int`, *optional*, defaults to `24`):
                Frame rate of the generated video

        Examples:

        Returns:
            [`~SkyReelsV2PipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`SkyReelsV2PipelineOutput`] is returned, otherwise a `tuple` is returned
                where the first element is a list with the generated images and the second element is a list of `bool`s
                indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
        """

        if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
            callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs

        height = height or self.transformer.config.sample_height * self.vae_scale_factor_spatial
        width = width or self.transformer.config.sample_width * self.vae_scale_factor_spatial
        num_videos_per_prompt = 1

        # 1. Check inputs. Raise error if not correct
        self.check_inputs(
            prompt,
            negative_prompt,
            height,
            width,
            video,
            latents,
            prompt_embeds,
            negative_prompt_embeds,
            callback_on_step_end_tensor_inputs,
            overlap_history,
            num_frames,
            base_num_frames,
        )

        if addnoise_condition > 60:
            logger.warning(
                f"The value of 'addnoise_condition' is too large ({addnoise_condition}) and may cause inconsistencies in long video generation. A value of 20 is recommended."  # noqa: E501
            )

        if num_frames % self.vae_scale_factor_temporal != 1:
            logger.warning(
                f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
            )
            num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
        num_frames = max(num_frames, 1)

        self._guidance_scale = guidance_scale
        self._attention_kwargs = attention_kwargs
        self._current_timestep = None
        self._interrupt = False

        # 2. Define call parameters
        if prompt is not None and isinstance(prompt, str):
            batch_size = 1
        elif prompt is not None and isinstance(prompt, list):
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        # 3. Encode input prompt
        prompt_embeds, negative_prompt_embeds = self.encode_prompt(
            prompt=prompt,
            negative_prompt=negative_prompt,
            do_classifier_free_guidance=self.do_classifier_free_guidance,
            num_videos_per_prompt=num_videos_per_prompt,
            prompt_embeds=prompt_embeds,
            negative_prompt_embeds=negative_prompt_embeds,
            max_sequence_length=max_sequence_length,
        )

        transformer_dtype = self.transformer.dtype
        prompt_embeds = prompt_embeds.to(transformer_dtype)
        if negative_prompt_embeds is not None:
            negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)

        # 4. Prepare timesteps
        self.scheduler.set_timesteps(num_inference_steps)
        timesteps = self.scheduler.timesteps

        if latents is None:
            video_original = self.video_processor.preprocess_video(video, height=height, width=width).to(
                dtype=ms.float32
            )

        if causal_block_size is None:
            causal_block_size = self.transformer.config.num_frame_per_block
        else:
            self.transformer._set_ar_attention(causal_block_size)

        fps_embeds = [fps] * prompt_embeds.shape[0]
        fps_embeds = [0 if i == 16 else 1 for i in fps_embeds]
        # TODO: adapt to graph mode. List[int] is not supported in graph mode unless wrapped in ms.mutable
        fps_embeds = tuple(fps_embeds)

        # Long video generation
        accumulated_latents = None
        overlap_history_latent_frames = (overlap_history - 1) // self.vae_scale_factor_temporal + 1
        num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
        base_latent_num_frames = (
            (base_num_frames - 1) // self.vae_scale_factor_temporal + 1
            if base_num_frames is not None
            else num_latent_frames
        )
        n_iter = (
            1
            + (num_latent_frames - base_latent_num_frames - 1)
            // (base_latent_num_frames - overlap_history_latent_frames)
            + 1
        )
        for long_video_iter in range(n_iter):
            logger.debug(f"Processing iteration {long_video_iter + 1}/{n_iter} for long video generation...")

            # 5. Prepare latent variables
            num_channels_latents = self.transformer.config.in_channels
            (
                latents,
                current_num_latent_frames,
                prefix_video_latents,
                prefix_video_latents_frames,
            ) = self.prepare_latents(
                video_original,
                batch_size * num_videos_per_prompt,
                num_channels_latents,
                height,
                width,
                num_frames,
                ms.float32,
                generator,
                latents if long_video_iter == 0 else None,
                video_latents=accumulated_latents,  # Pass latents directly instead of decoded video
                overlap_history=overlap_history,
                base_latent_num_frames=base_latent_num_frames,
                causal_block_size=causal_block_size,
                overlap_history_latent_frames=overlap_history_latent_frames,
                long_video_iter=long_video_iter,
            )

            if prefix_video_latents_frames > 0:
                latents[:, :, :prefix_video_latents_frames, :, :] = prefix_video_latents.to(transformer_dtype)

            # 4. Prepare sample schedulers and timestep matrix
            sample_schedulers = []
            for _ in range(current_num_latent_frames):
                sample_scheduler = deepcopy(self.scheduler)
                sample_scheduler.set_timesteps(num_inference_steps)
                sample_schedulers.append(sample_scheduler)
            step_matrix, _, step_update_mask, valid_interval = self.generate_timestep_matrix(
                current_num_latent_frames,
                timesteps,
                current_num_latent_frames,
                ar_step,
                prefix_video_latents_frames,
                causal_block_size,
            )

            # 6. Denoising loop
            num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
            self._num_timesteps = len(step_matrix)

            with self.progress_bar(total=len(step_matrix)) as progress_bar:
                for i, t in enumerate(step_matrix):
                    if self.interrupt:
                        continue

                    self._current_timestep = t
                    valid_interval_start, valid_interval_end = valid_interval[i]
                    latent_model_input = (
                        latents[:, :, valid_interval_start:valid_interval_end, :, :].to(transformer_dtype).clone()
                    )
                    timestep = t.broadcast_to((latents.shape[0], -1))[
                        :, valid_interval_start:valid_interval_end
                    ].clone()

                    if addnoise_condition > 0 and valid_interval_start < prefix_video_latents_frames:
                        noise_factor = 0.001 * addnoise_condition
                        latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :] = (
                            latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                            * (1.0 - noise_factor)
                            + mint.randn_like(
                                latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                            )
                            * noise_factor
                        )
                        timestep[:, valid_interval_start:prefix_video_latents_frames] = addnoise_condition

                    noise_pred = self.transformer(
                        hidden_states=latent_model_input,
                        timestep=timestep,
                        encoder_hidden_states=prompt_embeds,
                        enable_diffusion_forcing=True,
                        fps=fps_embeds,
                        attention_kwargs=attention_kwargs,
                        return_dict=False,
                    )[0]
                    if self.do_classifier_free_guidance:
                        noise_uncond = self.transformer(
                            hidden_states=latent_model_input,
                            timestep=timestep,
                            encoder_hidden_states=negative_prompt_embeds,
                            enable_diffusion_forcing=True,
                            fps=fps_embeds,
                            attention_kwargs=attention_kwargs,
                            return_dict=False,
                        )[0]
                        noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)

                    update_mask_i = step_update_mask[i]
                    for idx in range(valid_interval_start, valid_interval_end):
                        if update_mask_i[idx].item():
                            latents[:, :, idx, :, :] = sample_schedulers[idx].step(
                                noise_pred[:, :, idx - valid_interval_start, :, :],
                                t[idx],
                                latents[:, :, idx, :, :],
                                return_dict=False,
                            )[0]

                    if callback_on_step_end is not None:
                        callback_kwargs = {}
                        for k in callback_on_step_end_tensor_inputs:
                            callback_kwargs[k] = locals()[k]
                        callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)

                        latents = callback_outputs.pop("latents", latents)
                        prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
                        negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)

                    # call the callback, if provided
                    if i == len(step_matrix) - 1 or (
                        (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
                    ):
                        progress_bar.update()

            if accumulated_latents is None:
                accumulated_latents = latents
            else:
                # Keep overlap frames for conditioning but don't include them in final output
                accumulated_latents = mint.cat(
                    [accumulated_latents, latents[:, :, overlap_history_latent_frames:]], dim=2
                )

        latents = accumulated_latents

        self._current_timestep = None

        # Final decoding step - convert latents to pixels
        if not output_type == "latent":
            latents = latents.to(self.vae.dtype)
            latents_mean = (
                ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
            )
            latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
                latents.dtype
            )
            latents = latents / latents_std + latents_mean
            # TODO: we use pynative mode here since cache in vae.decode which not supported in graph mode
            with pynative_context():
                video_generated = self.vae.decode(latents, return_dict=False)[0]
            video = mint.cat([video_original, video_generated], dim=2)
            video = self.video_processor.postprocess_video(video, output_type=output_type)
        else:
            video = latents

        if not return_dict:
            return (video,)

        return SkyReelsV2PipelineOutput(frames=video)

mindone.diffusers.SkyReelsV2DiffusionForcingVideoToVideoPipeline.__call__(video, prompt=None, negative_prompt=None, height=544, width=960, num_frames=120, num_inference_steps=50, guidance_scale=6.0, num_videos_per_prompt=1, generator=None, latents=None, prompt_embeds=None, negative_prompt_embeds=None, output_type='np', return_dict=False, attention_kwargs=None, callback_on_step_end=None, callback_on_step_end_tensor_inputs=['latents'], max_sequence_length=512, overlap_history=None, addnoise_condition=0, base_num_frames=97, ar_step=0, causal_block_size=None, fps=24)

The call function to the pipeline for generation.

PARAMETER DESCRIPTION
video

The video to guide the video generation.

TYPE: `List[Image.Image]`

prompt

The prompt or prompts to guide the video generation. If not defined, one has to pass prompt_embeds. instead.

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

negative_prompt

The prompt or prompts not to guide the video generation. If not defined, one has to pass negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is less than 1).

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

height

The height of the generated video.

TYPE: `int`, defaults to `544` DEFAULT: 544

width

The width of the generated video.

TYPE: `int`, defaults to `960` DEFAULT: 960

num_frames

The number of frames in the generated video.

TYPE: `int`, defaults to `120` DEFAULT: 120

num_inference_steps

The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.

TYPE: `int`, defaults to `50` DEFAULT: 50

guidance_scale

Guidance scale as defined in Classifier-Free Diffusion Guidance. guidance_scale is defined as w of equation 2. of Imagen Paper. Guidance scale is enabled by setting guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to the text prompt, usually at the expense of lower image quality. (6.0 for T2V, 5.0 for I2V)

TYPE: `float`, defaults to `6.0` DEFAULT: 6.0

num_videos_per_prompt

The number of images to generate per prompt.

TYPE: `int`, *optional*, defaults to 1 DEFAULT: 1

generator

A np.random.Generator to make generation deterministic.

TYPE: `np.random.Generator` or `List[np.random.Generator]`, *optional* DEFAULT: None

latents

Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor is generated by sampling using the supplied random generator.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

negative_prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the negative_prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

output_type

The output format of the generated image. Choose between PIL.Image or np.array.

TYPE: `str`, *optional*, defaults to `"np"` DEFAULT: 'np'

return_dict

Whether or not to return a [SkyReelsV2PipelineOutput] instead of a plain tuple.

TYPE: `bool`, *optional*, defaults to `False` DEFAULT: False

attention_kwargs

A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under self.processor in diffusers.models.attention_processor.

TYPE: `dict`, *optional* DEFAULT: None

callback_on_step_end

A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a list of all tensors as specified by callback_on_step_end_tensor_inputs.

TYPE: `Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional* DEFAULT: None

callback_on_step_end_tensor_inputs

The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list will be passed as callback_kwargs argument. You will only be able to include variables listed in the ._callback_tensor_inputs attribute of your pipeline class.

TYPE: `List`, *optional* DEFAULT: ['latents']

max_sequence_length

The maximum sequence length of the prompt.

TYPE: `int`, *optional*, defaults to `512` DEFAULT: 512

overlap_history

Number of frames to overlap for smooth transitions in long videos. If None, the pipeline assumes short video generation mode, and no overlap is applied. 17 and 37 are recommended to set.

TYPE: `int`, *optional*, defaults to `None` DEFAULT: None

addnoise_condition

This is used to help smooth the long video generation by adding some noise to the clean condition. Too large noise can cause the inconsistency as well. 20 is a recommended value, and you may try larger ones, but it is recommended to not exceed 50.

TYPE: `float`, *optional*, defaults to `0` DEFAULT: 0

base_num_frames

97 or 121 | Base frame count (97 for 540P, 121 for 720P)

TYPE: `int`, *optional*, defaults to `97` DEFAULT: 97

ar_step

Controls asynchronous inference (0 for synchronous mode) You can set ar_step=5 to enable asynchronous inference. When asynchronous inference, causal_block_size=5 is recommended while it is not supposed to be set for synchronous generation. Asynchronous inference will take more steps to diffuse the whole sequence which means it will be SLOWER than synchronous mode. In our experiments, asynchronous inference may improve the instruction following and visual consistent performance.

TYPE: `int`, *optional*, defaults to `0` DEFAULT: 0

causal_block_size

The number of frames in each block/chunk. Recommended when using asynchronous inference (when ar_step > 0)

TYPE: `int`, *optional*, defaults to `None` DEFAULT: None

fps

Frame rate of the generated video

TYPE: `int`, *optional*, defaults to `24` DEFAULT: 24

RETURNS DESCRIPTION

[~SkyReelsV2PipelineOutput] or tuple: If return_dict is True, [SkyReelsV2PipelineOutput] is returned, otherwise a tuple is returned where the first element is a list with the generated images and the second element is a list of bools indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_v2v.py
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
def __call__(
    self,
    video: List[Image.Image],
    prompt: Union[str, List[str]] = None,
    negative_prompt: Union[str, List[str]] = None,
    height: int = 544,
    width: int = 960,
    num_frames: int = 120,
    num_inference_steps: int = 50,
    guidance_scale: float = 6.0,
    num_videos_per_prompt: Optional[int] = 1,
    generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
    latents: Optional[ms.Tensor] = None,
    prompt_embeds: Optional[ms.Tensor] = None,
    negative_prompt_embeds: Optional[ms.Tensor] = None,
    output_type: Optional[str] = "np",
    return_dict: bool = False,
    attention_kwargs: Optional[Dict[str, Any]] = None,
    callback_on_step_end: Optional[
        Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
    ] = None,
    callback_on_step_end_tensor_inputs: List[str] = ["latents"],
    max_sequence_length: int = 512,
    overlap_history: Optional[int] = None,
    addnoise_condition: float = 0,
    base_num_frames: int = 97,
    ar_step: int = 0,
    causal_block_size: Optional[int] = None,
    fps: int = 24,
):
    r"""
    The call function to the pipeline for generation.

    Args:
        video (`List[Image.Image]`):
            The video to guide the video generation.
        prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts to guide the video generation. If not defined, one has to pass `prompt_embeds`.
            instead.
        negative_prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts not to guide the video generation. If not defined, one has to pass
            `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
            less than `1`).
        height (`int`, defaults to `544`):
            The height of the generated video.
        width (`int`, defaults to `960`):
            The width of the generated video.
        num_frames (`int`, defaults to `120`):
            The number of frames in the generated video.
        num_inference_steps (`int`, defaults to `50`):
            The number of denoising steps. More denoising steps usually lead to a higher quality image at the
            expense of slower inference.
        guidance_scale (`float`, defaults to `6.0`):
            Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
            `guidance_scale` is defined as `w` of equation 2. of [Imagen
            Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
            1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
            usually at the expense of lower image quality. (**6.0 for T2V**, **5.0 for I2V**)
        num_videos_per_prompt (`int`, *optional*, defaults to 1):
            The number of images to generate per prompt.
        generator (`np.random.Generator` or `List[np.random.Generator]`, *optional*):
            A [`np.random.Generator`](https://numpy.org/doc/stable/reference/random/generator.html) to make
            generation deterministic.
        latents (`ms.Tensor`, *optional*):
            Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
            generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
            tensor is generated by sampling using the supplied random `generator`.
        prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
            provided, text embeddings are generated from the `prompt` input argument.
        negative_prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
            provided, text embeddings are generated from the `negative_prompt` input argument.
        output_type (`str`, *optional*, defaults to `"np"`):
            The output format of the generated image. Choose between `PIL.Image` or `np.array`.
        return_dict (`bool`, *optional*, defaults to `False`):
            Whether or not to return a [`SkyReelsV2PipelineOutput`] instead of a plain tuple.
        attention_kwargs (`dict`, *optional*):
            A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
            `self.processor` in
            [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
        callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
            A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
            each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
            DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
            list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
        callback_on_step_end_tensor_inputs (`List`, *optional*):
            The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
            will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
            `._callback_tensor_inputs` attribute of your pipeline class.
        max_sequence_length (`int`, *optional*, defaults to `512`):
            The maximum sequence length of the prompt.
        overlap_history (`int`, *optional*, defaults to `None`):
            Number of frames to overlap for smooth transitions in long videos. If `None`, the pipeline assumes
            short video generation mode, and no overlap is applied. 17 and 37 are recommended to set.
        addnoise_condition (`float`, *optional*, defaults to `0`):
            This is used to help smooth the long video generation by adding some noise to the clean condition. Too
            large noise can cause the inconsistency as well. 20 is a recommended value, and you may try larger
            ones, but it is recommended to not exceed 50.
        base_num_frames (`int`, *optional*, defaults to `97`):
            97 or 121 | Base frame count (**97 for 540P**, **121 for 720P**)
        ar_step (`int`, *optional*, defaults to `0`):
            Controls asynchronous inference (0 for synchronous mode) You can set `ar_step=5` to enable asynchronous
            inference. When asynchronous inference, `causal_block_size=5` is recommended while it is not supposed
            to be set for synchronous generation. Asynchronous inference will take more steps to diffuse the whole
            sequence which means it will be SLOWER than synchronous mode. In our experiments, asynchronous
            inference may improve the instruction following and visual consistent performance.
        causal_block_size (`int`, *optional*, defaults to `None`):
            The number of frames in each block/chunk. Recommended when using asynchronous inference (when ar_step >
            0)
        fps (`int`, *optional*, defaults to `24`):
            Frame rate of the generated video

    Examples:

    Returns:
        [`~SkyReelsV2PipelineOutput`] or `tuple`:
            If `return_dict` is `True`, [`SkyReelsV2PipelineOutput`] is returned, otherwise a `tuple` is returned
            where the first element is a list with the generated images and the second element is a list of `bool`s
            indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
    """

    if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
        callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs

    height = height or self.transformer.config.sample_height * self.vae_scale_factor_spatial
    width = width or self.transformer.config.sample_width * self.vae_scale_factor_spatial
    num_videos_per_prompt = 1

    # 1. Check inputs. Raise error if not correct
    self.check_inputs(
        prompt,
        negative_prompt,
        height,
        width,
        video,
        latents,
        prompt_embeds,
        negative_prompt_embeds,
        callback_on_step_end_tensor_inputs,
        overlap_history,
        num_frames,
        base_num_frames,
    )

    if addnoise_condition > 60:
        logger.warning(
            f"The value of 'addnoise_condition' is too large ({addnoise_condition}) and may cause inconsistencies in long video generation. A value of 20 is recommended."  # noqa: E501
        )

    if num_frames % self.vae_scale_factor_temporal != 1:
        logger.warning(
            f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
        )
        num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
    num_frames = max(num_frames, 1)

    self._guidance_scale = guidance_scale
    self._attention_kwargs = attention_kwargs
    self._current_timestep = None
    self._interrupt = False

    # 2. Define call parameters
    if prompt is not None and isinstance(prompt, str):
        batch_size = 1
    elif prompt is not None and isinstance(prompt, list):
        batch_size = len(prompt)
    else:
        batch_size = prompt_embeds.shape[0]

    # 3. Encode input prompt
    prompt_embeds, negative_prompt_embeds = self.encode_prompt(
        prompt=prompt,
        negative_prompt=negative_prompt,
        do_classifier_free_guidance=self.do_classifier_free_guidance,
        num_videos_per_prompt=num_videos_per_prompt,
        prompt_embeds=prompt_embeds,
        negative_prompt_embeds=negative_prompt_embeds,
        max_sequence_length=max_sequence_length,
    )

    transformer_dtype = self.transformer.dtype
    prompt_embeds = prompt_embeds.to(transformer_dtype)
    if negative_prompt_embeds is not None:
        negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)

    # 4. Prepare timesteps
    self.scheduler.set_timesteps(num_inference_steps)
    timesteps = self.scheduler.timesteps

    if latents is None:
        video_original = self.video_processor.preprocess_video(video, height=height, width=width).to(
            dtype=ms.float32
        )

    if causal_block_size is None:
        causal_block_size = self.transformer.config.num_frame_per_block
    else:
        self.transformer._set_ar_attention(causal_block_size)

    fps_embeds = [fps] * prompt_embeds.shape[0]
    fps_embeds = [0 if i == 16 else 1 for i in fps_embeds]
    # TODO: adapt to graph mode. List[int] is not supported in graph mode unless wrapped in ms.mutable
    fps_embeds = tuple(fps_embeds)

    # Long video generation
    accumulated_latents = None
    overlap_history_latent_frames = (overlap_history - 1) // self.vae_scale_factor_temporal + 1
    num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
    base_latent_num_frames = (
        (base_num_frames - 1) // self.vae_scale_factor_temporal + 1
        if base_num_frames is not None
        else num_latent_frames
    )
    n_iter = (
        1
        + (num_latent_frames - base_latent_num_frames - 1)
        // (base_latent_num_frames - overlap_history_latent_frames)
        + 1
    )
    for long_video_iter in range(n_iter):
        logger.debug(f"Processing iteration {long_video_iter + 1}/{n_iter} for long video generation...")

        # 5. Prepare latent variables
        num_channels_latents = self.transformer.config.in_channels
        (
            latents,
            current_num_latent_frames,
            prefix_video_latents,
            prefix_video_latents_frames,
        ) = self.prepare_latents(
            video_original,
            batch_size * num_videos_per_prompt,
            num_channels_latents,
            height,
            width,
            num_frames,
            ms.float32,
            generator,
            latents if long_video_iter == 0 else None,
            video_latents=accumulated_latents,  # Pass latents directly instead of decoded video
            overlap_history=overlap_history,
            base_latent_num_frames=base_latent_num_frames,
            causal_block_size=causal_block_size,
            overlap_history_latent_frames=overlap_history_latent_frames,
            long_video_iter=long_video_iter,
        )

        if prefix_video_latents_frames > 0:
            latents[:, :, :prefix_video_latents_frames, :, :] = prefix_video_latents.to(transformer_dtype)

        # 4. Prepare sample schedulers and timestep matrix
        sample_schedulers = []
        for _ in range(current_num_latent_frames):
            sample_scheduler = deepcopy(self.scheduler)
            sample_scheduler.set_timesteps(num_inference_steps)
            sample_schedulers.append(sample_scheduler)
        step_matrix, _, step_update_mask, valid_interval = self.generate_timestep_matrix(
            current_num_latent_frames,
            timesteps,
            current_num_latent_frames,
            ar_step,
            prefix_video_latents_frames,
            causal_block_size,
        )

        # 6. Denoising loop
        num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
        self._num_timesteps = len(step_matrix)

        with self.progress_bar(total=len(step_matrix)) as progress_bar:
            for i, t in enumerate(step_matrix):
                if self.interrupt:
                    continue

                self._current_timestep = t
                valid_interval_start, valid_interval_end = valid_interval[i]
                latent_model_input = (
                    latents[:, :, valid_interval_start:valid_interval_end, :, :].to(transformer_dtype).clone()
                )
                timestep = t.broadcast_to((latents.shape[0], -1))[
                    :, valid_interval_start:valid_interval_end
                ].clone()

                if addnoise_condition > 0 and valid_interval_start < prefix_video_latents_frames:
                    noise_factor = 0.001 * addnoise_condition
                    latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :] = (
                        latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                        * (1.0 - noise_factor)
                        + mint.randn_like(
                            latent_model_input[:, :, valid_interval_start:prefix_video_latents_frames, :, :]
                        )
                        * noise_factor
                    )
                    timestep[:, valid_interval_start:prefix_video_latents_frames] = addnoise_condition

                noise_pred = self.transformer(
                    hidden_states=latent_model_input,
                    timestep=timestep,
                    encoder_hidden_states=prompt_embeds,
                    enable_diffusion_forcing=True,
                    fps=fps_embeds,
                    attention_kwargs=attention_kwargs,
                    return_dict=False,
                )[0]
                if self.do_classifier_free_guidance:
                    noise_uncond = self.transformer(
                        hidden_states=latent_model_input,
                        timestep=timestep,
                        encoder_hidden_states=negative_prompt_embeds,
                        enable_diffusion_forcing=True,
                        fps=fps_embeds,
                        attention_kwargs=attention_kwargs,
                        return_dict=False,
                    )[0]
                    noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)

                update_mask_i = step_update_mask[i]
                for idx in range(valid_interval_start, valid_interval_end):
                    if update_mask_i[idx].item():
                        latents[:, :, idx, :, :] = sample_schedulers[idx].step(
                            noise_pred[:, :, idx - valid_interval_start, :, :],
                            t[idx],
                            latents[:, :, idx, :, :],
                            return_dict=False,
                        )[0]

                if callback_on_step_end is not None:
                    callback_kwargs = {}
                    for k in callback_on_step_end_tensor_inputs:
                        callback_kwargs[k] = locals()[k]
                    callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)

                    latents = callback_outputs.pop("latents", latents)
                    prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
                    negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)

                # call the callback, if provided
                if i == len(step_matrix) - 1 or (
                    (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
                ):
                    progress_bar.update()

        if accumulated_latents is None:
            accumulated_latents = latents
        else:
            # Keep overlap frames for conditioning but don't include them in final output
            accumulated_latents = mint.cat(
                [accumulated_latents, latents[:, :, overlap_history_latent_frames:]], dim=2
            )

    latents = accumulated_latents

    self._current_timestep = None

    # Final decoding step - convert latents to pixels
    if not output_type == "latent":
        latents = latents.to(self.vae.dtype)
        latents_mean = (
            ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
        )
        latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
            latents.dtype
        )
        latents = latents / latents_std + latents_mean
        # TODO: we use pynative mode here since cache in vae.decode which not supported in graph mode
        with pynative_context():
            video_generated = self.vae.decode(latents, return_dict=False)[0]
        video = mint.cat([video_original, video_generated], dim=2)
        video = self.video_processor.postprocess_video(video, output_type=output_type)
    else:
        video = latents

    if not return_dict:
        return (video,)

    return SkyReelsV2PipelineOutput(frames=video)

mindone.diffusers.SkyReelsV2DiffusionForcingVideoToVideoPipeline.encode_prompt(prompt, negative_prompt=None, do_classifier_free_guidance=True, num_videos_per_prompt=1, prompt_embeds=None, negative_prompt_embeds=None, max_sequence_length=226, dtype=None)

Encodes the prompt into text encoder hidden states.

PARAMETER DESCRIPTION
prompt

prompt to be encoded

TYPE: `str` or `List[str]`, *optional*

negative_prompt

The prompt or prompts not to guide the image generation. If not defined, one has to pass negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is less than 1).

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

do_classifier_free_guidance

Whether to use classifier free guidance or not.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

num_videos_per_prompt

Number of videos that should be generated per prompt.

TYPE: `int`, *optional*, defaults to 1 DEFAULT: 1

prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, text embeddings will be generated from prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

negative_prompt_embeds

Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

dtype

(ms.Type, optional): mindspore dtype

TYPE: Optional[Type] DEFAULT: None

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_v2v.py
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
def encode_prompt(
    self,
    prompt: Union[str, List[str]],
    negative_prompt: Optional[Union[str, List[str]]] = None,
    do_classifier_free_guidance: bool = True,
    num_videos_per_prompt: int = 1,
    prompt_embeds: Optional[ms.Tensor] = None,
    negative_prompt_embeds: Optional[ms.Tensor] = None,
    max_sequence_length: int = 226,
    dtype: Optional[ms.Type] = None,
):
    r"""
    Encodes the prompt into text encoder hidden states.

    Args:
        prompt (`str` or `List[str]`, *optional*):
            prompt to be encoded
        negative_prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts not to guide the image generation. If not defined, one has to pass
            `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
            less than `1`).
        do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
            Whether to use classifier free guidance or not.
        num_videos_per_prompt (`int`, *optional*, defaults to 1):
            Number of videos that should be generated per prompt.
        prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
            provided, text embeddings will be generated from `prompt` input argument.
        negative_prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
            weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
            argument.
        dtype: (`ms.Type`, *optional*):
            mindspore dtype
    """
    prompt = [prompt] if isinstance(prompt, str) else prompt
    if prompt is not None:
        batch_size = len(prompt)
    else:
        batch_size = prompt_embeds.shape[0]

    if prompt_embeds is None:
        prompt_embeds = self._get_t5_prompt_embeds(
            prompt=prompt,
            num_videos_per_prompt=num_videos_per_prompt,
            max_sequence_length=max_sequence_length,
            dtype=dtype,
        )

    if do_classifier_free_guidance and negative_prompt_embeds is None:
        negative_prompt = negative_prompt or ""
        negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt

        if prompt is not None and type(prompt) is not type(negative_prompt):
            raise TypeError(
                f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
                f" {type(prompt)}."
            )
        elif batch_size != len(negative_prompt):
            raise ValueError(
                f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
                f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                " the batch size of `prompt`."
            )

        negative_prompt_embeds = self._get_t5_prompt_embeds(
            prompt=negative_prompt,
            num_videos_per_prompt=num_videos_per_prompt,
            max_sequence_length=max_sequence_length,
            dtype=dtype,
        )

    return prompt_embeds, negative_prompt_embeds

mindone.diffusers.SkyReelsV2DiffusionForcingVideoToVideoPipeline.generate_timestep_matrix(num_latent_frames, step_template, base_num_latent_frames, ar_step=5, num_pre_ready=0, causal_block_size=1, shrink_interval_with_mask=False)

This function implements the core diffusion forcing algorithm that creates a coordinated denoising schedule across temporal frames. It supports both synchronous and asynchronous generation modes:

Synchronous Mode (ar_step=0, causal_block_size=1): - All frames are denoised simultaneously at each timestep - Each frame follows the same denoising trajectory: [1000, 800, 600, ..., 0] - Simpler but may have less temporal consistency for long videos

Asynchronous Mode (ar_step>0, causal_block_size>1): - Frames are grouped into causal blocks and processed block/chunk-wise - Each block is denoised in a staggered pattern creating a "denoising wave" - Earlier blocks are more denoised, later blocks lag behind by ar_step timesteps - Creates stronger temporal dependencies and better consistency

PARAMETER DESCRIPTION
num_latent_frames

Total number of latent frames to generate

TYPE: int

step_template

Base timestep schedule (e.g., [1000, 800, 600, ..., 0])

TYPE: Tensor

base_num_latent_frames

Maximum frames the model can process in one forward pass

TYPE: int

ar_step

Autoregressive step size for temporal lag. 0 = synchronous, >0 = asynchronous. Defaults to 5.

TYPE: int DEFAULT: 5

num_pre_ready
                     Number of frames already denoised (e.g., from prefix in a video2video task).
                     Defaults to 0.

TYPE: int DEFAULT: 0

causal_block_size

Number of frames processed as a causal block. Defaults to 1.

TYPE: int DEFAULT: 1

shrink_interval_with_mask

Whether to optimize processing intervals. Defaults to False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
tuple[Tensor, Tensor, Tensor, list[tuple]]

tuple containing: - step_matrix (ms.Tensor): Matrix of timesteps for each frame at each iteration Shape: [num_iterations, num_latent_frames] - step_index (ms.Tensor): Index matrix for timestep lookup Shape: [num_iterations, num_latent_frames] - step_update_mask (ms.Tensor): Boolean mask indicating which frames to update Shape: [num_iterations, num_latent_frames] - valid_interval (list[tuple]): List of (start, end) intervals for each iteration

RAISES DESCRIPTION
ValueError

If ar_step is too small for the given configuration

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_diffusion_forcing_v2v.py
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
def generate_timestep_matrix(
    self,
    num_latent_frames: int,
    step_template: ms.Tensor,
    base_num_latent_frames: int,
    ar_step: int = 5,
    num_pre_ready: int = 0,
    causal_block_size: int = 1,
    shrink_interval_with_mask: bool = False,
) -> tuple[ms.Tensor, ms.Tensor, ms.Tensor, list[tuple]]:
    """
    This function implements the core diffusion forcing algorithm that creates a coordinated denoising schedule
    across temporal frames. It supports both synchronous and asynchronous generation modes:

    **Synchronous Mode** (ar_step=0, causal_block_size=1):
    - All frames are denoised simultaneously at each timestep
    - Each frame follows the same denoising trajectory: [1000, 800, 600, ..., 0]
    - Simpler but may have less temporal consistency for long videos

    **Asynchronous Mode** (ar_step>0, causal_block_size>1):
    - Frames are grouped into causal blocks and processed block/chunk-wise
    - Each block is denoised in a staggered pattern creating a "denoising wave"
    - Earlier blocks are more denoised, later blocks lag behind by ar_step timesteps
    - Creates stronger temporal dependencies and better consistency

    Args:
        num_latent_frames (int): Total number of latent frames to generate
        step_template (ms.Tensor): Base timestep schedule (e.g., [1000, 800, 600, ..., 0])
        base_num_latent_frames (int): Maximum frames the model can process in one forward pass
        ar_step (int, optional): Autoregressive step size for temporal lag.
                               0 = synchronous, >0 = asynchronous. Defaults to 5.
        num_pre_ready (int, optional):
                                     Number of frames already denoised (e.g., from prefix in a video2video task).
                                     Defaults to 0.
        causal_block_size (int, optional): Number of frames processed as a causal block.
                                         Defaults to 1.
        shrink_interval_with_mask (bool, optional): Whether to optimize processing intervals.
                                                  Defaults to False.

    Returns:
        tuple containing:
            - step_matrix (ms.Tensor): Matrix of timesteps for each frame at each iteration Shape:
              [num_iterations, num_latent_frames]
            - step_index (ms.Tensor): Index matrix for timestep lookup Shape: [num_iterations,
              num_latent_frames]
            - step_update_mask (ms.Tensor): Boolean mask indicating which frames to update Shape:
              [num_iterations, num_latent_frames]
            - valid_interval (list[tuple]): List of (start, end) intervals for each iteration

    Raises:
        ValueError: If ar_step is too small for the given configuration
    """
    # Initialize lists to store the scheduling matrices and metadata
    step_matrix, step_index = [], []  # Will store timestep values and indices for each iteration
    update_mask, valid_interval = [], []  # Will store update masks and processing intervals

    # Calculate total number of denoising iterations (add 1 for initial noise state)
    num_iterations = len(step_template) + 1

    # Convert frame counts to block counts for causal processing
    # Each block contains causal_block_size frames that are processed together
    # E.g.: 25 frames ÷ 5 = 5 blocks total
    num_blocks = num_latent_frames // causal_block_size
    base_num_blocks = base_num_latent_frames // causal_block_size

    # Validate ar_step is sufficient for the given configuration
    # In asynchronous mode, we need enough timesteps to create the staggered pattern
    if base_num_blocks < num_blocks:
        min_ar_step = len(step_template) / base_num_blocks
        if ar_step < min_ar_step:
            raise ValueError(f"`ar_step` should be at least {math.ceil(min_ar_step)} in your setting")

    # Extend step_template with boundary values for easier indexing
    # 999: dummy value for counter starting from 1
    # 0: final timestep (completely denoised)
    step_template = mint.cat(
        [ms.tensor([999], dtype=ms.int64), step_template.long(), ms.tensor([0], dtype=ms.int64)]
    )

    # Initialize the previous row state (tracks denoising progress for each block)
    # 0 means not started, num_iterations means fully denoised
    pre_row = mint.zeros(num_blocks, dtype=ms.int64)

    # Mark pre-ready frames (e.g., from prefix video for a video2video task) as already at final denoising state
    if num_pre_ready > 0:
        pre_row[: num_pre_ready // causal_block_size] = num_iterations

    # Main loop: Generate denoising schedule until all frames are fully denoised
    while not mint.all(pre_row >= (num_iterations - 1)):
        # Create new row representing the next denoising step
        new_row = mint.zeros(num_blocks, dtype=ms.int64)

        # Apply diffusion forcing logic for each block
        for i in range(num_blocks):
            if i == 0 or pre_row[i - 1] >= (
                num_iterations - 1
            ):  # the first frame or the last frame is completely denoised
                new_row[i] = pre_row[i] + 1
            else:
                # Asynchronous mode: lag behind previous block by ar_step timesteps
                # This creates the "diffusion forcing" staggered pattern
                new_row[i] = new_row[i - 1] - ar_step

        # Clamp values to valid range [0, num_iterations]
        new_row = new_row.clamp(0, num_iterations)

        # Create update mask: True for blocks that need denoising update at this iteration
        # Exclude blocks that haven't started (new_row != pre_row) or are finished (new_row != num_iterations)
        # Final state example: [False, ..., False, True, True, True, True, True]
        # where first 20 frames are done (False) and last 5 frames still need updates (True)
        update_mask.append((new_row != pre_row) & (new_row != num_iterations))

        # Store the iteration state
        step_index.append(new_row)  # Index into step_template
        step_matrix.append(step_template[new_row])  # Actual timestep values
        pre_row = new_row  # Update for next iteration

    # For videos longer than model capacity, we process in sliding windows
    terminal_flag = base_num_blocks

    # Optional optimization: shrink interval based on first update mask
    if shrink_interval_with_mask:
        idx_sequence = mint.arange(num_blocks, dtype=ms.int64)
        update_mask = update_mask[0]
        update_mask_idx = idx_sequence[update_mask]
        last_update_idx = update_mask_idx[-1].item()
        terminal_flag = last_update_idx + 1

    # Each interval defines which frames to process in the current forward pass
    for curr_mask in update_mask:
        # Extend terminal flag if current mask has updates beyond current terminal
        if terminal_flag < num_blocks and curr_mask[terminal_flag]:
            terminal_flag += 1
        # Create interval: [start, end) where start ensures we don't exceed model capacity
        valid_interval.append((max(terminal_flag - base_num_blocks, 0), terminal_flag))

    # Convert lists to tensors for efficient processing
    step_update_mask = mint.stack(update_mask, dim=0)
    step_index = mint.stack(step_index, dim=0)
    step_matrix = mint.stack(step_matrix, dim=0)

    # Each block's schedule is replicated to all frames within that block
    if causal_block_size > 1:
        # Expand each block to causal_block_size frames
        step_update_mask = step_update_mask.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
        step_index = step_index.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
        step_matrix = step_matrix.unsqueeze(-1).tile((1, 1, causal_block_size)).flatten(1).contiguous()
        # Scale intervals from block-level to frame-level
        valid_interval = [(s * causal_block_size, e * causal_block_size) for s, e in valid_interval]

    return step_matrix, step_index, step_update_mask, valid_interval

mindone.diffusers.SkyReelsV2Pipeline

Bases: DiffusionPipeline, SkyReelsV2LoraLoaderMixin

Pipeline for Text-to-Video (t2v) generation using SkyReels-V2.

This model inherits from [DiffusionPipeline]. Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a particular device, etc.).

PARAMETER DESCRIPTION
tokenizer

Tokenizer from T5, specifically the google/umt5-xxl variant.

TYPE: [`T5Tokenizer`]

text_encoder

T5, specifically the google/umt5-xxl variant.

TYPE: [`T5EncoderModel`]

transformer

Conditional Transformer to denoise the input latents.

TYPE: [`SkyReelsV2Transformer3DModel`]

scheduler

A scheduler to be used in combination with transformer to denoise the encoded image latents.

TYPE: [`UniPCMultistepScheduler`]

vae

Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.

TYPE: [`AutoencoderKLWan`]

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2.py
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
class SkyReelsV2Pipeline(DiffusionPipeline, SkyReelsV2LoraLoaderMixin):
    r"""
    Pipeline for Text-to-Video (t2v) generation using SkyReels-V2.

    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
    implemented for all pipelines (downloading, saving, running on a particular device, etc.).

    Args:
        tokenizer ([`T5Tokenizer`]):
            Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
            specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        text_encoder ([`T5EncoderModel`]):
            [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
            the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        transformer ([`SkyReelsV2Transformer3DModel`]):
            Conditional Transformer to denoise the input latents.
        scheduler ([`UniPCMultistepScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
        vae ([`AutoencoderKLWan`]):
            Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
    """

    model_cpu_offload_seq = "text_encoder->transformer->vae"
    _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]

    def __init__(
        self,
        tokenizer: AutoTokenizer,
        text_encoder: UMT5EncoderModel,
        transformer: SkyReelsV2Transformer3DModel,
        vae: AutoencoderKLWan,
        scheduler: UniPCMultistepScheduler,
    ):
        super().__init__()

        self.register_modules(
            vae=vae,
            text_encoder=text_encoder,
            tokenizer=tokenizer,
            transformer=transformer,
            scheduler=scheduler,
        )

        self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
        self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
        self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)

    # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline._get_t5_prompt_embeds
    def _get_t5_prompt_embeds(
        self,
        prompt: Union[str, List[str]] = None,
        num_videos_per_prompt: int = 1,
        max_sequence_length: int = 226,
        dtype: Optional[ms.Type] = None,
    ):
        dtype = dtype or self.text_encoder.dtype

        prompt = [prompt] if isinstance(prompt, str) else prompt
        prompt = [prompt_clean(u) for u in prompt]
        batch_size = len(prompt)

        text_inputs = self.tokenizer(
            prompt,
            padding="max_length",
            max_length=max_sequence_length,
            truncation=True,
            add_special_tokens=True,
            return_attention_mask=True,
            return_tensors="np",
        )
        text_input_ids, mask = ms.tensor(text_inputs.input_ids), ms.tensor(text_inputs.attention_mask)
        seq_lens = mask.gt(0).sum(dim=1).long()

        prompt_embeds = self.text_encoder(text_input_ids, mask)[0]
        prompt_embeds = prompt_embeds.to(dtype=dtype)
        prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
        prompt_embeds = mint.stack(
            [mint.cat([u, u.new_zeros((max_sequence_length - u.shape[0], u.shape[1]))]) for u in prompt_embeds], dim=0
        )

        # duplicate text embeddings for each generation per prompt, using mps friendly method
        _, seq_len, _ = prompt_embeds.shape
        prompt_embeds = prompt_embeds.tile((1, num_videos_per_prompt, 1))
        prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)

        return prompt_embeds

    # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
    def encode_prompt(
        self,
        prompt: Union[str, List[str]],
        negative_prompt: Optional[Union[str, List[str]]] = None,
        do_classifier_free_guidance: bool = True,
        num_videos_per_prompt: int = 1,
        prompt_embeds: Optional[ms.Tensor] = None,
        negative_prompt_embeds: Optional[ms.Tensor] = None,
        max_sequence_length: int = 226,
        dtype: Optional[ms.Type] = None,
    ):
        r"""
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
                Whether to use classifier free guidance or not.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                Number of videos that should be generated per prompt.
            prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            negative_prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            dtype: (`ms.Type`, *optional*):
                mindspore dtype
        """
        prompt = [prompt] if isinstance(prompt, str) else prompt
        if prompt is not None:
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        if prompt_embeds is None:
            prompt_embeds = self._get_t5_prompt_embeds(
                prompt=prompt,
                num_videos_per_prompt=num_videos_per_prompt,
                max_sequence_length=max_sequence_length,
                dtype=dtype,
            )

        if do_classifier_free_guidance and negative_prompt_embeds is None:
            negative_prompt = negative_prompt or ""
            negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt

            if prompt is not None and type(prompt) is not type(negative_prompt):
                raise TypeError(
                    f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
                    f" {type(prompt)}."
                )
            elif batch_size != len(negative_prompt):
                raise ValueError(
                    f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
                    f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                    " the batch size of `prompt`."
                )

            negative_prompt_embeds = self._get_t5_prompt_embeds(
                prompt=negative_prompt,
                num_videos_per_prompt=num_videos_per_prompt,
                max_sequence_length=max_sequence_length,
                dtype=dtype,
            )

        return prompt_embeds, negative_prompt_embeds

    def check_inputs(
        self,
        prompt,
        negative_prompt,
        height,
        width,
        prompt_embeds=None,
        negative_prompt_embeds=None,
        callback_on_step_end_tensor_inputs=None,
    ):
        if height % 16 != 0 or width % 16 != 0:
            raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")

        if callback_on_step_end_tensor_inputs is not None and not all(
            k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
        ):
            raise ValueError(
                f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"  # noqa: E501
            )

        if prompt is not None and prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
                " only forward one of the two."
            )
        elif negative_prompt is not None and negative_prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
                " only forward one of the two."
            )
        elif prompt is None and prompt_embeds is None:
            raise ValueError(
                "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
            )
        elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
            raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
        elif negative_prompt is not None and (
            not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
        ):
            raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")

    # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.prepare_latents
    def prepare_latents(
        self,
        batch_size: int,
        num_channels_latents: int = 16,
        height: int = 480,
        width: int = 832,
        num_frames: int = 81,
        dtype: Optional[ms.Type] = None,
        generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
        latents: Optional[ms.Tensor] = None,
    ) -> ms.Tensor:
        if latents is not None:
            return latents.to(dtype=dtype)

        num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
        shape = (
            batch_size,
            num_channels_latents,
            num_latent_frames,
            int(height) // self.vae_scale_factor_spatial,
            int(width) // self.vae_scale_factor_spatial,
        )
        if isinstance(generator, list) and len(generator) != batch_size:
            raise ValueError(
                f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
                f" size of {batch_size}. Make sure the batch size matches the length of the generators."
            )

        latents = randn_tensor(shape, generator=generator, dtype=dtype)
        return latents

    @property
    def guidance_scale(self):
        return self._guidance_scale

    @property
    def do_classifier_free_guidance(self):
        return self._guidance_scale > 1.0

    @property
    def num_timesteps(self):
        return self._num_timesteps

    @property
    def current_timestep(self):
        return self._current_timestep

    @property
    def interrupt(self):
        return self._interrupt

    @property
    def attention_kwargs(self):
        return self._attention_kwargs

    def __call__(
        self,
        prompt: Union[str, List[str]] = None,
        negative_prompt: Union[str, List[str]] = None,
        height: int = 544,
        width: int = 960,
        num_frames: int = 97,
        num_inference_steps: int = 50,
        guidance_scale: float = 6.0,
        num_videos_per_prompt: Optional[int] = 1,
        generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
        latents: Optional[ms.Tensor] = None,
        prompt_embeds: Optional[ms.Tensor] = None,
        negative_prompt_embeds: Optional[ms.Tensor] = None,
        output_type: Optional[str] = "np",
        return_dict: bool = False,
        attention_kwargs: Optional[Dict[str, Any]] = None,
        callback_on_step_end: Optional[
            Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
        ] = None,
        callback_on_step_end_tensor_inputs: List[str] = ["latents"],
        max_sequence_length: int = 512,
    ):
        r"""
        The call function to the pipeline for generation.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
                instead.
            height (`int`, defaults to `544`):
                The height in pixels of the generated image.
            width (`int`, defaults to `960`):
                The width in pixels of the generated image.
            num_frames (`int`, defaults to `97`):
                The number of frames in the generated video.
            num_inference_steps (`int`, defaults to `50`):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            guidance_scale (`float`, defaults to `6.0`):
                Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
                `guidance_scale` is defined as `w` of equation 2. of [Imagen
                Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
                1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
                usually at the expense of lower image quality.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            generator (`np.random.Generator` or `List[np.random.Generator]`, *optional*):
                A [`np.random.Generator`](https://numpy.org/doc/stable/reference/random/generator.html) to make
                generation deterministic.
            latents (`ms.Tensor`, *optional*):
                Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor is generated by sampling using the supplied random `generator`.
            prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `prompt` input argument.
            output_type (`str`, *optional*, defaults to `"np"`):
                The output format of the generated image. Choose between `PIL.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `False`):
                Whether or not to return a [`SkyReelsV2PipelineOutput`] instead of a plain tuple.
            attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
                `self.processor` in
                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
                A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
                each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
                DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
                list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
            callback_on_step_end_tensor_inputs (`List`, *optional*):
                The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
                will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
                `._callback_tensor_inputs` attribute of your pipeline class.
            max_sequence_length (`int`, *optional*, defaults to `512`):
                The maximum sequence length for the text encoder.

        Examples:

        Returns:
            [`~SkyReelsV2PipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`SkyReelsV2PipelineOutput`] is returned, otherwise a `tuple` is returned
                where the first element is a list with the generated images and the second element is a list of `bool`s
                indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
        """

        if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
            callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs

        # 1. Check inputs. Raise error if not correct
        self.check_inputs(
            prompt,
            negative_prompt,
            height,
            width,
            prompt_embeds,
            negative_prompt_embeds,
            callback_on_step_end_tensor_inputs,
        )

        if num_frames % self.vae_scale_factor_temporal != 1:
            logger.warning(
                f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
            )
            num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
        num_frames = max(num_frames, 1)

        self._guidance_scale = guidance_scale
        self._attention_kwargs = attention_kwargs
        self._current_timestep = None
        self._interrupt = False

        # 2. Define call parameters
        if prompt is not None and isinstance(prompt, str):
            batch_size = 1
        elif prompt is not None and isinstance(prompt, list):
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        # 3. Encode input prompt
        prompt_embeds, negative_prompt_embeds = self.encode_prompt(
            prompt=prompt,
            negative_prompt=negative_prompt,
            do_classifier_free_guidance=self.do_classifier_free_guidance,
            num_videos_per_prompt=num_videos_per_prompt,
            prompt_embeds=prompt_embeds,
            negative_prompt_embeds=negative_prompt_embeds,
            max_sequence_length=max_sequence_length,
        )

        transformer_dtype = self.transformer.dtype
        prompt_embeds = prompt_embeds.to(transformer_dtype)
        if negative_prompt_embeds is not None:
            negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)

        # 4. Prepare timesteps
        self.scheduler.set_timesteps(num_inference_steps)
        timesteps = self.scheduler.timesteps

        # 5. Prepare latent variables
        num_channels_latents = self.transformer.config.in_channels
        latents = self.prepare_latents(
            batch_size * num_videos_per_prompt,
            num_channels_latents,
            height,
            width,
            num_frames,
            ms.float32,
            generator,
            latents,
        )

        # 6. Denoising loop
        num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
        self._num_timesteps = len(timesteps)

        with self.progress_bar(total=num_inference_steps) as progress_bar:
            for i, t in enumerate(timesteps):
                if self.interrupt:
                    continue

                self._current_timestep = t
                latent_model_input = latents.to(transformer_dtype)
                timestep = t.broadcast_to((latents.shape[0],))

                noise_pred = self.transformer(
                    hidden_states=latent_model_input,
                    timestep=timestep,
                    encoder_hidden_states=prompt_embeds,
                    attention_kwargs=attention_kwargs,
                    return_dict=False,
                )[0]

                if self.do_classifier_free_guidance:
                    noise_uncond = self.transformer(
                        hidden_states=latent_model_input,
                        timestep=timestep,
                        encoder_hidden_states=negative_prompt_embeds,
                        attention_kwargs=attention_kwargs,
                        return_dict=False,
                    )[0]
                    noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)

                # compute the previous noisy sample x_t -> x_t-1
                latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]

                if callback_on_step_end is not None:
                    callback_kwargs = {}
                    for k in callback_on_step_end_tensor_inputs:
                        callback_kwargs[k] = locals()[k]
                    callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)

                    latents = callback_outputs.pop("latents", latents)
                    prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
                    negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)

                # call the callback, if provided
                if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
                    progress_bar.update()

        self._current_timestep = None

        if not output_type == "latent":
            latents = latents.to(self.vae.dtype)
            latents_mean = (
                ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
            )
            latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
                latents.dtype
            )
            latents = latents / latents_std + latents_mean
            # TODO: we use pynative mode here since cache in vae.decode which not supported in graph mode
            with pynative_context():
                video = self.vae.decode(latents, return_dict=False)[0]
            video = self.video_processor.postprocess_video(video, output_type=output_type)
        else:
            video = latents

        if not return_dict:
            return (video,)

        return SkyReelsV2PipelineOutput(frames=video)

mindone.diffusers.SkyReelsV2Pipeline.__call__(prompt=None, negative_prompt=None, height=544, width=960, num_frames=97, num_inference_steps=50, guidance_scale=6.0, num_videos_per_prompt=1, generator=None, latents=None, prompt_embeds=None, negative_prompt_embeds=None, output_type='np', return_dict=False, attention_kwargs=None, callback_on_step_end=None, callback_on_step_end_tensor_inputs=['latents'], max_sequence_length=512)

The call function to the pipeline for generation.

PARAMETER DESCRIPTION
prompt

The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds. instead.

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

height

The height in pixels of the generated image.

TYPE: `int`, defaults to `544` DEFAULT: 544

width

The width in pixels of the generated image.

TYPE: `int`, defaults to `960` DEFAULT: 960

num_frames

The number of frames in the generated video.

TYPE: `int`, defaults to `97` DEFAULT: 97

num_inference_steps

The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.

TYPE: `int`, defaults to `50` DEFAULT: 50

guidance_scale

Guidance scale as defined in Classifier-Free Diffusion Guidance. guidance_scale is defined as w of equation 2. of Imagen Paper. Guidance scale is enabled by setting guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to the text prompt, usually at the expense of lower image quality.

TYPE: `float`, defaults to `6.0` DEFAULT: 6.0

num_videos_per_prompt

The number of images to generate per prompt.

TYPE: `int`, *optional*, defaults to 1 DEFAULT: 1

generator

A np.random.Generator to make generation deterministic.

TYPE: `np.random.Generator` or `List[np.random.Generator]`, *optional* DEFAULT: None

latents

Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor is generated by sampling using the supplied random generator.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

output_type

The output format of the generated image. Choose between PIL.Image or np.array.

TYPE: `str`, *optional*, defaults to `"np"` DEFAULT: 'np'

return_dict

Whether or not to return a [SkyReelsV2PipelineOutput] instead of a plain tuple.

TYPE: `bool`, *optional*, defaults to `False` DEFAULT: False

attention_kwargs

A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under self.processor in diffusers.models.attention_processor.

TYPE: `dict`, *optional* DEFAULT: None

callback_on_step_end

A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a list of all tensors as specified by callback_on_step_end_tensor_inputs.

TYPE: `Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional* DEFAULT: None

callback_on_step_end_tensor_inputs

The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list will be passed as callback_kwargs argument. You will only be able to include variables listed in the ._callback_tensor_inputs attribute of your pipeline class.

TYPE: `List`, *optional* DEFAULT: ['latents']

max_sequence_length

The maximum sequence length for the text encoder.

TYPE: `int`, *optional*, defaults to `512` DEFAULT: 512

RETURNS DESCRIPTION

[~SkyReelsV2PipelineOutput] or tuple: If return_dict is True, [SkyReelsV2PipelineOutput] is returned, otherwise a tuple is returned where the first element is a list with the generated images and the second element is a list of bools indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2.py
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
def __call__(
    self,
    prompt: Union[str, List[str]] = None,
    negative_prompt: Union[str, List[str]] = None,
    height: int = 544,
    width: int = 960,
    num_frames: int = 97,
    num_inference_steps: int = 50,
    guidance_scale: float = 6.0,
    num_videos_per_prompt: Optional[int] = 1,
    generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
    latents: Optional[ms.Tensor] = None,
    prompt_embeds: Optional[ms.Tensor] = None,
    negative_prompt_embeds: Optional[ms.Tensor] = None,
    output_type: Optional[str] = "np",
    return_dict: bool = False,
    attention_kwargs: Optional[Dict[str, Any]] = None,
    callback_on_step_end: Optional[
        Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
    ] = None,
    callback_on_step_end_tensor_inputs: List[str] = ["latents"],
    max_sequence_length: int = 512,
):
    r"""
    The call function to the pipeline for generation.

    Args:
        prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
            instead.
        height (`int`, defaults to `544`):
            The height in pixels of the generated image.
        width (`int`, defaults to `960`):
            The width in pixels of the generated image.
        num_frames (`int`, defaults to `97`):
            The number of frames in the generated video.
        num_inference_steps (`int`, defaults to `50`):
            The number of denoising steps. More denoising steps usually lead to a higher quality image at the
            expense of slower inference.
        guidance_scale (`float`, defaults to `6.0`):
            Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
            `guidance_scale` is defined as `w` of equation 2. of [Imagen
            Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
            1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
            usually at the expense of lower image quality.
        num_videos_per_prompt (`int`, *optional*, defaults to 1):
            The number of images to generate per prompt.
        generator (`np.random.Generator` or `List[np.random.Generator]`, *optional*):
            A [`np.random.Generator`](https://numpy.org/doc/stable/reference/random/generator.html) to make
            generation deterministic.
        latents (`ms.Tensor`, *optional*):
            Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
            generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
            tensor is generated by sampling using the supplied random `generator`.
        prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
            provided, text embeddings are generated from the `prompt` input argument.
        output_type (`str`, *optional*, defaults to `"np"`):
            The output format of the generated image. Choose between `PIL.Image` or `np.array`.
        return_dict (`bool`, *optional*, defaults to `False`):
            Whether or not to return a [`SkyReelsV2PipelineOutput`] instead of a plain tuple.
        attention_kwargs (`dict`, *optional*):
            A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
            `self.processor` in
            [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
        callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
            A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
            each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
            DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
            list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
        callback_on_step_end_tensor_inputs (`List`, *optional*):
            The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
            will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
            `._callback_tensor_inputs` attribute of your pipeline class.
        max_sequence_length (`int`, *optional*, defaults to `512`):
            The maximum sequence length for the text encoder.

    Examples:

    Returns:
        [`~SkyReelsV2PipelineOutput`] or `tuple`:
            If `return_dict` is `True`, [`SkyReelsV2PipelineOutput`] is returned, otherwise a `tuple` is returned
            where the first element is a list with the generated images and the second element is a list of `bool`s
            indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
    """

    if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
        callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs

    # 1. Check inputs. Raise error if not correct
    self.check_inputs(
        prompt,
        negative_prompt,
        height,
        width,
        prompt_embeds,
        negative_prompt_embeds,
        callback_on_step_end_tensor_inputs,
    )

    if num_frames % self.vae_scale_factor_temporal != 1:
        logger.warning(
            f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
        )
        num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
    num_frames = max(num_frames, 1)

    self._guidance_scale = guidance_scale
    self._attention_kwargs = attention_kwargs
    self._current_timestep = None
    self._interrupt = False

    # 2. Define call parameters
    if prompt is not None and isinstance(prompt, str):
        batch_size = 1
    elif prompt is not None and isinstance(prompt, list):
        batch_size = len(prompt)
    else:
        batch_size = prompt_embeds.shape[0]

    # 3. Encode input prompt
    prompt_embeds, negative_prompt_embeds = self.encode_prompt(
        prompt=prompt,
        negative_prompt=negative_prompt,
        do_classifier_free_guidance=self.do_classifier_free_guidance,
        num_videos_per_prompt=num_videos_per_prompt,
        prompt_embeds=prompt_embeds,
        negative_prompt_embeds=negative_prompt_embeds,
        max_sequence_length=max_sequence_length,
    )

    transformer_dtype = self.transformer.dtype
    prompt_embeds = prompt_embeds.to(transformer_dtype)
    if negative_prompt_embeds is not None:
        negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)

    # 4. Prepare timesteps
    self.scheduler.set_timesteps(num_inference_steps)
    timesteps = self.scheduler.timesteps

    # 5. Prepare latent variables
    num_channels_latents = self.transformer.config.in_channels
    latents = self.prepare_latents(
        batch_size * num_videos_per_prompt,
        num_channels_latents,
        height,
        width,
        num_frames,
        ms.float32,
        generator,
        latents,
    )

    # 6. Denoising loop
    num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
    self._num_timesteps = len(timesteps)

    with self.progress_bar(total=num_inference_steps) as progress_bar:
        for i, t in enumerate(timesteps):
            if self.interrupt:
                continue

            self._current_timestep = t
            latent_model_input = latents.to(transformer_dtype)
            timestep = t.broadcast_to((latents.shape[0],))

            noise_pred = self.transformer(
                hidden_states=latent_model_input,
                timestep=timestep,
                encoder_hidden_states=prompt_embeds,
                attention_kwargs=attention_kwargs,
                return_dict=False,
            )[0]

            if self.do_classifier_free_guidance:
                noise_uncond = self.transformer(
                    hidden_states=latent_model_input,
                    timestep=timestep,
                    encoder_hidden_states=negative_prompt_embeds,
                    attention_kwargs=attention_kwargs,
                    return_dict=False,
                )[0]
                noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)

            # compute the previous noisy sample x_t -> x_t-1
            latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]

            if callback_on_step_end is not None:
                callback_kwargs = {}
                for k in callback_on_step_end_tensor_inputs:
                    callback_kwargs[k] = locals()[k]
                callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)

                latents = callback_outputs.pop("latents", latents)
                prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
                negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)

            # call the callback, if provided
            if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
                progress_bar.update()

    self._current_timestep = None

    if not output_type == "latent":
        latents = latents.to(self.vae.dtype)
        latents_mean = (
            ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
        )
        latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
            latents.dtype
        )
        latents = latents / latents_std + latents_mean
        # TODO: we use pynative mode here since cache in vae.decode which not supported in graph mode
        with pynative_context():
            video = self.vae.decode(latents, return_dict=False)[0]
        video = self.video_processor.postprocess_video(video, output_type=output_type)
    else:
        video = latents

    if not return_dict:
        return (video,)

    return SkyReelsV2PipelineOutput(frames=video)

mindone.diffusers.SkyReelsV2Pipeline.encode_prompt(prompt, negative_prompt=None, do_classifier_free_guidance=True, num_videos_per_prompt=1, prompt_embeds=None, negative_prompt_embeds=None, max_sequence_length=226, dtype=None)

Encodes the prompt into text encoder hidden states.

PARAMETER DESCRIPTION
prompt

prompt to be encoded

TYPE: `str` or `List[str]`, *optional*

negative_prompt

The prompt or prompts not to guide the image generation. If not defined, one has to pass negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is less than 1).

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

do_classifier_free_guidance

Whether to use classifier free guidance or not.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

num_videos_per_prompt

Number of videos that should be generated per prompt.

TYPE: `int`, *optional*, defaults to 1 DEFAULT: 1

prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, text embeddings will be generated from prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

negative_prompt_embeds

Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

dtype

(ms.Type, optional): mindspore dtype

TYPE: Optional[Type] DEFAULT: None

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2.py
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
def encode_prompt(
    self,
    prompt: Union[str, List[str]],
    negative_prompt: Optional[Union[str, List[str]]] = None,
    do_classifier_free_guidance: bool = True,
    num_videos_per_prompt: int = 1,
    prompt_embeds: Optional[ms.Tensor] = None,
    negative_prompt_embeds: Optional[ms.Tensor] = None,
    max_sequence_length: int = 226,
    dtype: Optional[ms.Type] = None,
):
    r"""
    Encodes the prompt into text encoder hidden states.

    Args:
        prompt (`str` or `List[str]`, *optional*):
            prompt to be encoded
        negative_prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts not to guide the image generation. If not defined, one has to pass
            `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
            less than `1`).
        do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
            Whether to use classifier free guidance or not.
        num_videos_per_prompt (`int`, *optional*, defaults to 1):
            Number of videos that should be generated per prompt.
        prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
            provided, text embeddings will be generated from `prompt` input argument.
        negative_prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
            weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
            argument.
        dtype: (`ms.Type`, *optional*):
            mindspore dtype
    """
    prompt = [prompt] if isinstance(prompt, str) else prompt
    if prompt is not None:
        batch_size = len(prompt)
    else:
        batch_size = prompt_embeds.shape[0]

    if prompt_embeds is None:
        prompt_embeds = self._get_t5_prompt_embeds(
            prompt=prompt,
            num_videos_per_prompt=num_videos_per_prompt,
            max_sequence_length=max_sequence_length,
            dtype=dtype,
        )

    if do_classifier_free_guidance and negative_prompt_embeds is None:
        negative_prompt = negative_prompt or ""
        negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt

        if prompt is not None and type(prompt) is not type(negative_prompt):
            raise TypeError(
                f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
                f" {type(prompt)}."
            )
        elif batch_size != len(negative_prompt):
            raise ValueError(
                f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
                f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                " the batch size of `prompt`."
            )

        negative_prompt_embeds = self._get_t5_prompt_embeds(
            prompt=negative_prompt,
            num_videos_per_prompt=num_videos_per_prompt,
            max_sequence_length=max_sequence_length,
            dtype=dtype,
        )

    return prompt_embeds, negative_prompt_embeds

mindone.diffusers.SkyReelsV2ImageToVideoPipeline

Bases: DiffusionPipeline, SkyReelsV2LoraLoaderMixin

Pipeline for Image-to-Video (i2v) generation using SkyReels-V2.

This model inherits from [DiffusionPipeline]. Check the superclass documentation for the generic methods implemented for all pipelines (downloading, saving, running on a particular device, etc.).

PARAMETER DESCRIPTION
tokenizer

Tokenizer from T5, specifically the google/umt5-xxl variant.

TYPE: [`T5Tokenizer`]

text_encoder

T5, specifically the google/umt5-xxl variant.

TYPE: [`T5EncoderModel`]

image_encoder

CLIP, specifically the clip-vit-huge-patch14 variant.

TYPE: [`CLIPVisionModelWithProjection`]

transformer

Conditional Transformer to denoise the input latents.

TYPE: [`SkyReelsV2Transformer3DModel`]

scheduler

A scheduler to be used in combination with transformer to denoise the encoded image latents.

TYPE: [`UniPCMultistepScheduler`]

vae

Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.

TYPE: [`AutoencoderKLWan`]

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_i2v.py
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
class SkyReelsV2ImageToVideoPipeline(DiffusionPipeline, SkyReelsV2LoraLoaderMixin):
    r"""
    Pipeline for Image-to-Video (i2v) generation using SkyReels-V2.

    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
    implemented for all pipelines (downloading, saving, running on a particular device, etc.).

    Args:
        tokenizer ([`T5Tokenizer`]):
            Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
            specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        text_encoder ([`T5EncoderModel`]):
            [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
            the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
        image_encoder ([`CLIPVisionModelWithProjection`]):
            [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPVisionModelWithProjection),
            specifically the
            [clip-vit-huge-patch14](https://github.com/mlfoundations/open_clip/blob/main/docs/PRETRAINED.md#vit-h14-xlm-roberta-large)
            variant.
        transformer ([`SkyReelsV2Transformer3DModel`]):
            Conditional Transformer to denoise the input latents.
        scheduler ([`UniPCMultistepScheduler`]):
            A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
        vae ([`AutoencoderKLWan`]):
            Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
    """

    model_cpu_offload_seq = "text_encoder->image_encoder->transformer->vae"
    _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]

    def __init__(
        self,
        tokenizer: AutoTokenizer,
        text_encoder: UMT5EncoderModel,
        image_encoder: CLIPVisionModelWithProjection,
        image_processor: CLIPProcessor,
        transformer: SkyReelsV2Transformer3DModel,
        vae: AutoencoderKLWan,
        scheduler: UniPCMultistepScheduler,
    ):
        super().__init__()

        self.register_modules(
            vae=vae,
            text_encoder=text_encoder,
            tokenizer=tokenizer,
            image_encoder=image_encoder,
            transformer=transformer,
            scheduler=scheduler,
            image_processor=image_processor,
        )

        self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
        self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
        self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
        self.image_processor = image_processor

    # Copied from diffusers.pipelines.wan.pipeline_wan_i2v.WanImageToVideoPipeline._get_t5_prompt_embeds
    def _get_t5_prompt_embeds(
        self,
        prompt: Union[str, List[str]] = None,
        num_videos_per_prompt: int = 1,
        max_sequence_length: int = 512,
        dtype: Optional[ms.Type] = None,
    ):
        dtype = dtype or self.text_encoder.dtype

        prompt = [prompt] if isinstance(prompt, str) else prompt
        prompt = [prompt_clean(u) for u in prompt]
        batch_size = len(prompt)

        text_inputs = self.tokenizer(
            prompt,
            padding="max_length",
            max_length=max_sequence_length,
            truncation=True,
            add_special_tokens=True,
            return_attention_mask=True,
            return_tensors="np",
        )
        text_input_ids, mask = ms.tensor(text_inputs.input_ids), ms.tensor(text_inputs.attention_mask)
        seq_lens = mask.gt(0).sum(dim=1).long()

        prompt_embeds = self.text_encoder(text_input_ids, mask)[0]
        prompt_embeds = prompt_embeds.to(dtype=dtype)
        prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
        prompt_embeds = mint.stack(
            [mint.cat([u, u.new_zeros((max_sequence_length - u.shape[0], u.shape[1]))]) for u in prompt_embeds], dim=0
        )

        # duplicate text embeddings for each generation per prompt, using mps friendly method
        _, seq_len, _ = prompt_embeds.shape
        prompt_embeds = prompt_embeds.tile((1, num_videos_per_prompt, 1))
        prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)

        return prompt_embeds

    # Copied from diffusers.pipelines.wan.pipeline_wan_i2v.WanImageToVideoPipeline.encode_image
    def encode_image(
        self,
        image: PipelineImageInput,
    ):
        image = self.image_processor(images=image, return_tensors="np")
        for key in image.keys():
            image[key] = ms.tensor(image[key])
        image_embeds = self.image_encoder(**image, output_hidden_states=True)
        return image_embeds[2][-2]

    # Copied from diffusers.pipelines.wan.pipeline_wan_i2v.WanImageToVideoPipeline.encode_prompt
    def encode_prompt(
        self,
        prompt: Union[str, List[str]],
        negative_prompt: Optional[Union[str, List[str]]] = None,
        do_classifier_free_guidance: bool = True,
        num_videos_per_prompt: int = 1,
        prompt_embeds: Optional[ms.Tensor] = None,
        negative_prompt_embeds: Optional[ms.Tensor] = None,
        max_sequence_length: int = 226,
        dtype: Optional[ms.Type] = None,
    ):
        r"""
        Encodes the prompt into text encoder hidden states.

        Args:
            prompt (`str` or `List[str]`, *optional*):
                prompt to be encoded
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
                Whether to use classifier free guidance or not.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                Number of videos that should be generated per prompt.
            prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
                provided, text embeddings will be generated from `prompt` input argument.
            negative_prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
                weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
                argument.
            dtype: (`ms.Type`, *optional*):
                mindspore dtype
        """
        prompt = [prompt] if isinstance(prompt, str) else prompt
        if prompt is not None:
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        if prompt_embeds is None:
            prompt_embeds = self._get_t5_prompt_embeds(
                prompt=prompt,
                num_videos_per_prompt=num_videos_per_prompt,
                max_sequence_length=max_sequence_length,
                dtype=dtype,
            )

        if do_classifier_free_guidance and negative_prompt_embeds is None:
            negative_prompt = negative_prompt or ""
            negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt

            if prompt is not None and type(prompt) is not type(negative_prompt):
                raise TypeError(
                    f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
                    f" {type(prompt)}."
                )
            elif batch_size != len(negative_prompt):
                raise ValueError(
                    f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
                    f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                    " the batch size of `prompt`."
                )

            negative_prompt_embeds = self._get_t5_prompt_embeds(
                prompt=negative_prompt,
                num_videos_per_prompt=num_videos_per_prompt,
                max_sequence_length=max_sequence_length,
                dtype=dtype,
            )

        return prompt_embeds, negative_prompt_embeds

    def check_inputs(
        self,
        prompt,
        negative_prompt,
        image,
        height,
        width,
        prompt_embeds=None,
        negative_prompt_embeds=None,
        image_embeds=None,
        callback_on_step_end_tensor_inputs=None,
    ):
        if image is not None and image_embeds is not None:
            raise ValueError(
                f"Cannot forward both `image`: {image} and `image_embeds`: {image_embeds}. Please make sure to"
                " only forward one of the two."
            )
        if image is None and image_embeds is None:
            raise ValueError(
                "Provide either `image` or `prompt_embeds`. Cannot leave both `image` and `image_embeds` undefined."
            )
        if image is not None and not isinstance(image, ms.Tensor) and not isinstance(image, PIL.Image.Image):
            raise ValueError(f"`image` has to be of type `ms.Tensor` or `PIL.Image.Image` but is {type(image)}")
        if height % 16 != 0 or width % 16 != 0:
            raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")

        if callback_on_step_end_tensor_inputs is not None and not all(
            k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
        ):
            raise ValueError(
                f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"  # noqa: E501
            )

        if prompt is not None and prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
                " only forward one of the two."
            )
        elif negative_prompt is not None and negative_prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
                " only forward one of the two."
            )
        elif prompt is None and prompt_embeds is None:
            raise ValueError(
                "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
            )
        elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
            raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
        elif negative_prompt is not None and (
            not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
        ):
            raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")

    def prepare_latents(
        self,
        image: PipelineImageInput,
        batch_size: int,
        num_channels_latents: int = 16,
        height: int = 480,
        width: int = 832,
        num_frames: int = 81,
        dtype: Optional[ms.Type] = None,
        generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
        latents: Optional[ms.Tensor] = None,
        last_image: Optional[ms.Tensor] = None,
    ) -> Tuple[ms.Tensor, ms.Tensor]:
        num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
        latent_height = height // self.vae_scale_factor_spatial
        latent_width = width // self.vae_scale_factor_spatial

        shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
        if isinstance(generator, list) and len(generator) != batch_size:
            raise ValueError(
                f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
                f" size of {batch_size}. Make sure the batch size matches the length of the generators."
            )

        if latents is None:
            latents = randn_tensor(shape, generator=generator, dtype=dtype)
        else:
            latents = latents.to(dtype=dtype)

        image = image.unsqueeze(2)
        if last_image is None:
            video_condition = mint.cat(
                [image, image.new_zeros((image.shape[0], image.shape[1], num_frames - 1, height, width))], dim=2
            )
        else:
            last_image = last_image.unsqueeze(2)
            video_condition = mint.cat(
                [image, image.new_zeros(image.shape[0], image.shape[1], num_frames - 2, height, width), last_image],
                dim=2,
            )
        video_condition = video_condition.to(dtype=self.vae.dtype)

        latents_mean = ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
        latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
            latents.dtype
        )

        with pynative_context():
            if isinstance(generator, list):
                latent_condition = [
                    retrieve_latents(self.vae, self.vae.encode(video_condition)[0], sample_mode="argmax")
                    for _ in generator
                ]
                latent_condition = mint.cat(latent_condition)
            else:
                latent_condition = retrieve_latents(self.vae, self.vae.encode(video_condition)[0], sample_mode="argmax")
                latent_condition = latent_condition.tile((batch_size, 1, 1, 1, 1))

        latent_condition = latent_condition.to(dtype)
        latent_condition = (latent_condition - latents_mean) * latents_std

        mask_lat_size = mint.ones((batch_size, 1, num_frames, latent_height, latent_width))

        if last_image is None:
            mask_lat_size[:, :, list(range(1, num_frames))] = 0
        else:
            mask_lat_size[:, :, list(range(1, num_frames - 1))] = 0
        first_frame_mask = mask_lat_size[:, :, 0:1]
        first_frame_mask = mint.repeat_interleave(first_frame_mask, dim=2, repeats=self.vae_scale_factor_temporal)
        mask_lat_size = mint.concat([first_frame_mask, mask_lat_size[:, :, 1:, :]], dim=2)
        mask_lat_size = mask_lat_size.view(batch_size, -1, self.vae_scale_factor_temporal, latent_height, latent_width)
        mask_lat_size = mask_lat_size.swapaxes(1, 2)

        return latents, mint.concat([mask_lat_size, latent_condition], dim=1)

    @property
    def guidance_scale(self):
        return self._guidance_scale

    @property
    def do_classifier_free_guidance(self):
        return self._guidance_scale > 1

    @property
    def num_timesteps(self):
        return self._num_timesteps

    @property
    def current_timestep(self):
        return self._current_timestep

    @property
    def interrupt(self):
        return self._interrupt

    @property
    def attention_kwargs(self):
        return self._attention_kwargs

    def __call__(
        self,
        image: PipelineImageInput,
        prompt: Union[str, List[str]] = None,
        negative_prompt: Union[str, List[str]] = None,
        height: int = 544,
        width: int = 960,
        num_frames: int = 97,
        num_inference_steps: int = 50,
        guidance_scale: float = 5.0,
        num_videos_per_prompt: Optional[int] = 1,
        generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
        latents: Optional[ms.Tensor] = None,
        prompt_embeds: Optional[ms.Tensor] = None,
        negative_prompt_embeds: Optional[ms.Tensor] = None,
        image_embeds: Optional[ms.Tensor] = None,
        last_image: Optional[ms.Tensor] = None,
        output_type: Optional[str] = "np",
        return_dict: bool = False,
        attention_kwargs: Optional[Dict[str, Any]] = None,
        callback_on_step_end: Optional[
            Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
        ] = None,
        callback_on_step_end_tensor_inputs: List[str] = ["latents"],
        max_sequence_length: int = 512,
    ):
        r"""
        The call function to the pipeline for generation.

        Args:
            image (`PipelineImageInput`):
                The input image to condition the generation on. Must be an image, a list of images or a `ms.Tensor`.
            prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
                instead.
            negative_prompt (`str` or `List[str]`, *optional*):
                The prompt or prompts not to guide the image generation. If not defined, one has to pass
                `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
                less than `1`).
            height (`int`, defaults to `544`):
                The height of the generated video.
            width (`int`, defaults to `960`):
                The width of the generated video.
            num_frames (`int`, defaults to `97`):
                The number of frames in the generated video.
            num_inference_steps (`int`, defaults to `50`):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            guidance_scale (`float`, defaults to `5.0`):
                Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
                `guidance_scale` is defined as `w` of equation 2. of [Imagen
                Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
                1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
                usually at the expense of lower image quality.
            num_videos_per_prompt (`int`, *optional*, defaults to 1):
                The number of images to generate per prompt.
            generator (`np.random.Generator` or `List[np.random.Generator]`, *optional*):
                A [`np.random.Generator`](https://numpy.org/doc/stable/reference/random/generator.html) to make
                generation deterministic.
            latents (`ms.Tensor`, *optional*):
                Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
                generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
                tensor is generated by sampling using the supplied random `generator`.
            prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `prompt` input argument.
            negative_prompt_embeds (`ms.Tensor`, *optional*):
                Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
                provided, text embeddings are generated from the `negative_prompt` input argument.
            image_embeds (`ms.Tensor`, *optional*):
                Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
                image embeddings are generated from the `image` input argument.
            output_type (`str`, *optional*, defaults to `"np"`):
                The output format of the generated image. Choose between `PIL.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `False`):
                Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
            attention_kwargs (`dict`, *optional*):
                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
                `self.processor` in
                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
            callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
                A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
                each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
                DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
                list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
            callback_on_step_end_tensor_inputs (`List`, *optional*):
                The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
                will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
                `._callback_tensor_inputs` attribute of your pipeline class.
            max_sequence_length (`int`, *optional*, defaults to `512`):
                The maximum sequence length of the prompt.

        Examples:

        Returns:
            [`~SkyReelsV2PipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`SkyReelsV2PipelineOutput`] is returned, otherwise a `tuple` is returned
                where the first element is a list with the generated images and the second element is a list of `bool`s
                indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
        """

        if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
            callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs

        # 1. Check inputs. Raise error if not correct
        self.check_inputs(
            prompt,
            negative_prompt,
            image,
            height,
            width,
            prompt_embeds,
            negative_prompt_embeds,
            image_embeds,
            callback_on_step_end_tensor_inputs,
        )

        if num_frames % self.vae_scale_factor_temporal != 1:
            logger.warning(
                f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
            )
            num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
        num_frames = max(num_frames, 1)

        self._guidance_scale = guidance_scale
        self._attention_kwargs = attention_kwargs
        self._current_timestep = None
        self._interrupt = False

        # 2. Define call parameters
        if prompt is not None and isinstance(prompt, str):
            batch_size = 1
        elif prompt is not None and isinstance(prompt, list):
            batch_size = len(prompt)
        else:
            batch_size = prompt_embeds.shape[0]

        # 3. Encode input prompt
        prompt_embeds, negative_prompt_embeds = self.encode_prompt(
            prompt=prompt,
            negative_prompt=negative_prompt,
            do_classifier_free_guidance=self.do_classifier_free_guidance,
            num_videos_per_prompt=num_videos_per_prompt,
            prompt_embeds=prompt_embeds,
            negative_prompt_embeds=negative_prompt_embeds,
            max_sequence_length=max_sequence_length,
        )

        # Encode image embedding
        transformer_dtype = self.transformer.dtype
        prompt_embeds = prompt_embeds.to(transformer_dtype)
        if negative_prompt_embeds is not None:
            negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)

        if image_embeds is None:
            if last_image is None:
                image_embeds = self.encode_image(image)
            else:
                image_embeds = self.encode_image([image, last_image])
        image_embeds = image_embeds.tile((batch_size, 1, 1))
        image_embeds = image_embeds.to(transformer_dtype)

        # 4. Prepare timesteps
        self.scheduler.set_timesteps(num_inference_steps)
        timesteps = self.scheduler.timesteps

        # 5. Prepare latent variables
        num_channels_latents = self.vae.config.z_dim
        image = self.video_processor.preprocess(image, height=height, width=width).to(dtype=ms.float32)
        if last_image is not None:
            last_image = self.video_processor.preprocess(last_image, height=height, width=width).to(dtype=ms.float32)
        latents, condition = self.prepare_latents(
            image,
            batch_size * num_videos_per_prompt,
            num_channels_latents,
            height,
            width,
            num_frames,
            ms.float32,
            generator,
            latents,
            last_image,
        )

        # 6. Denoising loop
        num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
        self._num_timesteps = len(timesteps)

        with self.progress_bar(total=num_inference_steps) as progress_bar:
            for i, t in enumerate(timesteps):
                if self.interrupt:
                    continue

                self._current_timestep = t
                latent_model_input = mint.cat([latents, condition], dim=1).to(transformer_dtype)
                timestep = t.broadcast_to((latents.shape[0],))

                noise_pred = self.transformer(
                    hidden_states=latent_model_input,
                    timestep=timestep,
                    encoder_hidden_states=prompt_embeds,
                    encoder_hidden_states_image=image_embeds,
                    attention_kwargs=attention_kwargs,
                    return_dict=False,
                )[0]

                if self.do_classifier_free_guidance:
                    noise_uncond = self.transformer(
                        hidden_states=latent_model_input,
                        timestep=timestep,
                        encoder_hidden_states=negative_prompt_embeds,
                        encoder_hidden_states_image=image_embeds,
                        attention_kwargs=attention_kwargs,
                        return_dict=False,
                    )[0]
                    noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)

                # compute the previous noisy sample x_t -> x_t-1
                latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]

                if callback_on_step_end is not None:
                    callback_kwargs = {}
                    for k in callback_on_step_end_tensor_inputs:
                        callback_kwargs[k] = locals()[k]
                    callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)

                    latents = callback_outputs.pop("latents", latents)
                    prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
                    negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)

                # call the callback, if provided
                if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
                    progress_bar.update()

        self._current_timestep = None

        if not output_type == "latent":
            latents = latents.to(self.vae.dtype)
            latents_mean = (
                ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
            )
            latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
                latents.dtype
            )
            latents = latents / latents_std + latents_mean
            # TODO: we use pynative mode here since cache in vae.decode which not supported in graph mode
            with pynative_context():
                video = self.vae.decode(latents, return_dict=False)[0]
            video = self.video_processor.postprocess_video(video, output_type=output_type)
        else:
            video = latents

        if not return_dict:
            return (video,)

        return SkyReelsV2PipelineOutput(frames=video)

mindone.diffusers.SkyReelsV2ImageToVideoPipeline.__call__(image, prompt=None, negative_prompt=None, height=544, width=960, num_frames=97, num_inference_steps=50, guidance_scale=5.0, num_videos_per_prompt=1, generator=None, latents=None, prompt_embeds=None, negative_prompt_embeds=None, image_embeds=None, last_image=None, output_type='np', return_dict=False, attention_kwargs=None, callback_on_step_end=None, callback_on_step_end_tensor_inputs=['latents'], max_sequence_length=512)

The call function to the pipeline for generation.

PARAMETER DESCRIPTION
image

The input image to condition the generation on. Must be an image, a list of images or a ms.Tensor.

TYPE: `PipelineImageInput`

prompt

The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds. instead.

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

negative_prompt

The prompt or prompts not to guide the image generation. If not defined, one has to pass negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is less than 1).

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

height

The height of the generated video.

TYPE: `int`, defaults to `544` DEFAULT: 544

width

The width of the generated video.

TYPE: `int`, defaults to `960` DEFAULT: 960

num_frames

The number of frames in the generated video.

TYPE: `int`, defaults to `97` DEFAULT: 97

num_inference_steps

The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.

TYPE: `int`, defaults to `50` DEFAULT: 50

guidance_scale

Guidance scale as defined in Classifier-Free Diffusion Guidance. guidance_scale is defined as w of equation 2. of Imagen Paper. Guidance scale is enabled by setting guidance_scale > 1. Higher guidance scale encourages to generate images that are closely linked to the text prompt, usually at the expense of lower image quality.

TYPE: `float`, defaults to `5.0` DEFAULT: 5.0

num_videos_per_prompt

The number of images to generate per prompt.

TYPE: `int`, *optional*, defaults to 1 DEFAULT: 1

generator

A np.random.Generator to make generation deterministic.

TYPE: `np.random.Generator` or `List[np.random.Generator]`, *optional* DEFAULT: None

latents

Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor is generated by sampling using the supplied random generator.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

negative_prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not provided, text embeddings are generated from the negative_prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

image_embeds

Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided, image embeddings are generated from the image input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

output_type

The output format of the generated image. Choose between PIL.Image or np.array.

TYPE: `str`, *optional*, defaults to `"np"` DEFAULT: 'np'

return_dict

Whether or not to return a [WanPipelineOutput] instead of a plain tuple.

TYPE: `bool`, *optional*, defaults to `False` DEFAULT: False

attention_kwargs

A kwargs dictionary that if specified is passed along to the AttentionProcessor as defined under self.processor in diffusers.models.attention_processor.

TYPE: `dict`, *optional* DEFAULT: None

callback_on_step_end

A function or a subclass of PipelineCallback or MultiPipelineCallbacks that is called at the end of each denoising step during the inference. with the following arguments: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs will include a list of all tensors as specified by callback_on_step_end_tensor_inputs.

TYPE: `Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional* DEFAULT: None

callback_on_step_end_tensor_inputs

The list of tensor inputs for the callback_on_step_end function. The tensors specified in the list will be passed as callback_kwargs argument. You will only be able to include variables listed in the ._callback_tensor_inputs attribute of your pipeline class.

TYPE: `List`, *optional* DEFAULT: ['latents']

max_sequence_length

The maximum sequence length of the prompt.

TYPE: `int`, *optional*, defaults to `512` DEFAULT: 512

RETURNS DESCRIPTION

[~SkyReelsV2PipelineOutput] or tuple: If return_dict is True, [SkyReelsV2PipelineOutput] is returned, otherwise a tuple is returned where the first element is a list with the generated images and the second element is a list of bools indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_i2v.py
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
def __call__(
    self,
    image: PipelineImageInput,
    prompt: Union[str, List[str]] = None,
    negative_prompt: Union[str, List[str]] = None,
    height: int = 544,
    width: int = 960,
    num_frames: int = 97,
    num_inference_steps: int = 50,
    guidance_scale: float = 5.0,
    num_videos_per_prompt: Optional[int] = 1,
    generator: Optional[Union[np.random.Generator, List[np.random.Generator]]] = None,
    latents: Optional[ms.Tensor] = None,
    prompt_embeds: Optional[ms.Tensor] = None,
    negative_prompt_embeds: Optional[ms.Tensor] = None,
    image_embeds: Optional[ms.Tensor] = None,
    last_image: Optional[ms.Tensor] = None,
    output_type: Optional[str] = "np",
    return_dict: bool = False,
    attention_kwargs: Optional[Dict[str, Any]] = None,
    callback_on_step_end: Optional[
        Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
    ] = None,
    callback_on_step_end_tensor_inputs: List[str] = ["latents"],
    max_sequence_length: int = 512,
):
    r"""
    The call function to the pipeline for generation.

    Args:
        image (`PipelineImageInput`):
            The input image to condition the generation on. Must be an image, a list of images or a `ms.Tensor`.
        prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
            instead.
        negative_prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts not to guide the image generation. If not defined, one has to pass
            `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
            less than `1`).
        height (`int`, defaults to `544`):
            The height of the generated video.
        width (`int`, defaults to `960`):
            The width of the generated video.
        num_frames (`int`, defaults to `97`):
            The number of frames in the generated video.
        num_inference_steps (`int`, defaults to `50`):
            The number of denoising steps. More denoising steps usually lead to a higher quality image at the
            expense of slower inference.
        guidance_scale (`float`, defaults to `5.0`):
            Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
            `guidance_scale` is defined as `w` of equation 2. of [Imagen
            Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
            1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
            usually at the expense of lower image quality.
        num_videos_per_prompt (`int`, *optional*, defaults to 1):
            The number of images to generate per prompt.
        generator (`np.random.Generator` or `List[np.random.Generator]`, *optional*):
            A [`np.random.Generator`](https://numpy.org/doc/stable/reference/random/generator.html) to make
            generation deterministic.
        latents (`ms.Tensor`, *optional*):
            Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
            generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
            tensor is generated by sampling using the supplied random `generator`.
        prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
            provided, text embeddings are generated from the `prompt` input argument.
        negative_prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
            provided, text embeddings are generated from the `negative_prompt` input argument.
        image_embeds (`ms.Tensor`, *optional*):
            Pre-generated image embeddings. Can be used to easily tweak image inputs (weighting). If not provided,
            image embeddings are generated from the `image` input argument.
        output_type (`str`, *optional*, defaults to `"np"`):
            The output format of the generated image. Choose between `PIL.Image` or `np.array`.
        return_dict (`bool`, *optional*, defaults to `False`):
            Whether or not to return a [`WanPipelineOutput`] instead of a plain tuple.
        attention_kwargs (`dict`, *optional*):
            A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
            `self.processor` in
            [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
        callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
            A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
            each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
            DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
            list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
        callback_on_step_end_tensor_inputs (`List`, *optional*):
            The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
            will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
            `._callback_tensor_inputs` attribute of your pipeline class.
        max_sequence_length (`int`, *optional*, defaults to `512`):
            The maximum sequence length of the prompt.

    Examples:

    Returns:
        [`~SkyReelsV2PipelineOutput`] or `tuple`:
            If `return_dict` is `True`, [`SkyReelsV2PipelineOutput`] is returned, otherwise a `tuple` is returned
            where the first element is a list with the generated images and the second element is a list of `bool`s
            indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
    """

    if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
        callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs

    # 1. Check inputs. Raise error if not correct
    self.check_inputs(
        prompt,
        negative_prompt,
        image,
        height,
        width,
        prompt_embeds,
        negative_prompt_embeds,
        image_embeds,
        callback_on_step_end_tensor_inputs,
    )

    if num_frames % self.vae_scale_factor_temporal != 1:
        logger.warning(
            f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
        )
        num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
    num_frames = max(num_frames, 1)

    self._guidance_scale = guidance_scale
    self._attention_kwargs = attention_kwargs
    self._current_timestep = None
    self._interrupt = False

    # 2. Define call parameters
    if prompt is not None and isinstance(prompt, str):
        batch_size = 1
    elif prompt is not None and isinstance(prompt, list):
        batch_size = len(prompt)
    else:
        batch_size = prompt_embeds.shape[0]

    # 3. Encode input prompt
    prompt_embeds, negative_prompt_embeds = self.encode_prompt(
        prompt=prompt,
        negative_prompt=negative_prompt,
        do_classifier_free_guidance=self.do_classifier_free_guidance,
        num_videos_per_prompt=num_videos_per_prompt,
        prompt_embeds=prompt_embeds,
        negative_prompt_embeds=negative_prompt_embeds,
        max_sequence_length=max_sequence_length,
    )

    # Encode image embedding
    transformer_dtype = self.transformer.dtype
    prompt_embeds = prompt_embeds.to(transformer_dtype)
    if negative_prompt_embeds is not None:
        negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)

    if image_embeds is None:
        if last_image is None:
            image_embeds = self.encode_image(image)
        else:
            image_embeds = self.encode_image([image, last_image])
    image_embeds = image_embeds.tile((batch_size, 1, 1))
    image_embeds = image_embeds.to(transformer_dtype)

    # 4. Prepare timesteps
    self.scheduler.set_timesteps(num_inference_steps)
    timesteps = self.scheduler.timesteps

    # 5. Prepare latent variables
    num_channels_latents = self.vae.config.z_dim
    image = self.video_processor.preprocess(image, height=height, width=width).to(dtype=ms.float32)
    if last_image is not None:
        last_image = self.video_processor.preprocess(last_image, height=height, width=width).to(dtype=ms.float32)
    latents, condition = self.prepare_latents(
        image,
        batch_size * num_videos_per_prompt,
        num_channels_latents,
        height,
        width,
        num_frames,
        ms.float32,
        generator,
        latents,
        last_image,
    )

    # 6. Denoising loop
    num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
    self._num_timesteps = len(timesteps)

    with self.progress_bar(total=num_inference_steps) as progress_bar:
        for i, t in enumerate(timesteps):
            if self.interrupt:
                continue

            self._current_timestep = t
            latent_model_input = mint.cat([latents, condition], dim=1).to(transformer_dtype)
            timestep = t.broadcast_to((latents.shape[0],))

            noise_pred = self.transformer(
                hidden_states=latent_model_input,
                timestep=timestep,
                encoder_hidden_states=prompt_embeds,
                encoder_hidden_states_image=image_embeds,
                attention_kwargs=attention_kwargs,
                return_dict=False,
            )[0]

            if self.do_classifier_free_guidance:
                noise_uncond = self.transformer(
                    hidden_states=latent_model_input,
                    timestep=timestep,
                    encoder_hidden_states=negative_prompt_embeds,
                    encoder_hidden_states_image=image_embeds,
                    attention_kwargs=attention_kwargs,
                    return_dict=False,
                )[0]
                noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)

            # compute the previous noisy sample x_t -> x_t-1
            latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]

            if callback_on_step_end is not None:
                callback_kwargs = {}
                for k in callback_on_step_end_tensor_inputs:
                    callback_kwargs[k] = locals()[k]
                callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)

                latents = callback_outputs.pop("latents", latents)
                prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
                negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)

            # call the callback, if provided
            if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
                progress_bar.update()

    self._current_timestep = None

    if not output_type == "latent":
        latents = latents.to(self.vae.dtype)
        latents_mean = (
            ms.tensor(self.vae.config.latents_mean).view(1, self.vae.config.z_dim, 1, 1, 1).to(latents.dtype)
        )
        latents_std = 1.0 / ms.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
            latents.dtype
        )
        latents = latents / latents_std + latents_mean
        # TODO: we use pynative mode here since cache in vae.decode which not supported in graph mode
        with pynative_context():
            video = self.vae.decode(latents, return_dict=False)[0]
        video = self.video_processor.postprocess_video(video, output_type=output_type)
    else:
        video = latents

    if not return_dict:
        return (video,)

    return SkyReelsV2PipelineOutput(frames=video)

mindone.diffusers.SkyReelsV2ImageToVideoPipeline.encode_prompt(prompt, negative_prompt=None, do_classifier_free_guidance=True, num_videos_per_prompt=1, prompt_embeds=None, negative_prompt_embeds=None, max_sequence_length=226, dtype=None)

Encodes the prompt into text encoder hidden states.

PARAMETER DESCRIPTION
prompt

prompt to be encoded

TYPE: `str` or `List[str]`, *optional*

negative_prompt

The prompt or prompts not to guide the image generation. If not defined, one has to pass negative_prompt_embeds instead. Ignored when not using guidance (i.e., ignored if guidance_scale is less than 1).

TYPE: `str` or `List[str]`, *optional* DEFAULT: None

do_classifier_free_guidance

Whether to use classifier free guidance or not.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

num_videos_per_prompt

Number of videos that should be generated per prompt.

TYPE: `int`, *optional*, defaults to 1 DEFAULT: 1

prompt_embeds

Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, text embeddings will be generated from prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

negative_prompt_embeds

Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt input argument.

TYPE: `ms.Tensor`, *optional* DEFAULT: None

dtype

(ms.Type, optional): mindspore dtype

TYPE: Optional[Type] DEFAULT: None

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_skyreels_v2_i2v.py
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
def encode_prompt(
    self,
    prompt: Union[str, List[str]],
    negative_prompt: Optional[Union[str, List[str]]] = None,
    do_classifier_free_guidance: bool = True,
    num_videos_per_prompt: int = 1,
    prompt_embeds: Optional[ms.Tensor] = None,
    negative_prompt_embeds: Optional[ms.Tensor] = None,
    max_sequence_length: int = 226,
    dtype: Optional[ms.Type] = None,
):
    r"""
    Encodes the prompt into text encoder hidden states.

    Args:
        prompt (`str` or `List[str]`, *optional*):
            prompt to be encoded
        negative_prompt (`str` or `List[str]`, *optional*):
            The prompt or prompts not to guide the image generation. If not defined, one has to pass
            `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
            less than `1`).
        do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
            Whether to use classifier free guidance or not.
        num_videos_per_prompt (`int`, *optional*, defaults to 1):
            Number of videos that should be generated per prompt.
        prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
            provided, text embeddings will be generated from `prompt` input argument.
        negative_prompt_embeds (`ms.Tensor`, *optional*):
            Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
            weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
            argument.
        dtype: (`ms.Type`, *optional*):
            mindspore dtype
    """
    prompt = [prompt] if isinstance(prompt, str) else prompt
    if prompt is not None:
        batch_size = len(prompt)
    else:
        batch_size = prompt_embeds.shape[0]

    if prompt_embeds is None:
        prompt_embeds = self._get_t5_prompt_embeds(
            prompt=prompt,
            num_videos_per_prompt=num_videos_per_prompt,
            max_sequence_length=max_sequence_length,
            dtype=dtype,
        )

    if do_classifier_free_guidance and negative_prompt_embeds is None:
        negative_prompt = negative_prompt or ""
        negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt

        if prompt is not None and type(prompt) is not type(negative_prompt):
            raise TypeError(
                f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
                f" {type(prompt)}."
            )
        elif batch_size != len(negative_prompt):
            raise ValueError(
                f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
                f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
                " the batch size of `prompt`."
            )

        negative_prompt_embeds = self._get_t5_prompt_embeds(
            prompt=negative_prompt,
            num_videos_per_prompt=num_videos_per_prompt,
            max_sequence_length=max_sequence_length,
            dtype=dtype,
        )

    return prompt_embeds, negative_prompt_embeds

mindone.diffusers.pipelines.skyreels_v2.pipeline_output.SkyReelsV2PipelineOutput dataclass

Bases: BaseOutput

Output class for SkyReelsV2 pipelines.

PARAMETER DESCRIPTION
frames

List of video outputs - It can be a nested list of length batch_size, with each sub-list containing denoised PIL image sequences of length num_frames. It can also be a NumPy array or MindSpore tensor of shape (batch_size, num_frames, channels, height, width).

TYPE: `ms.Tensor`, `np.ndarray`, or List[List[PIL.Image.Image]]

Source code in mindone/diffusers/pipelines/skyreels_v2/pipeline_output.py
11
12
13
14
15
16
17
18
19
20
21
22
23
@dataclass
class SkyReelsV2PipelineOutput(BaseOutput):
    r"""
    Output class for SkyReelsV2 pipelines.

    Args:
        frames (`ms.Tensor`, `np.ndarray`, or List[List[PIL.Image.Image]]):
            List of video outputs - It can be a nested list of length `batch_size,` with each sub-list containing
            denoised PIL image sequences of length `num_frames.` It can also be a NumPy array or MindSpore tensor of
            shape `(batch_size, num_frames, channels, height, width)`.
    """

    frames: ms.Tensor