import inspect
import math
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Tuple, Union

import numpy as np
import torch
import torch.nn.functional as F
import torchvision.transforms.functional as TF
from diffusers import FlowMatchEulerDiscreteScheduler
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
from diffusers.image_processor import VaeImageProcessor
from diffusers.models.embeddings import get_1d_rotary_pos_embed
from diffusers.models.autoencoders.vae import DiagonalGaussianDistribution
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
from diffusers.utils import BaseOutput, logging, replace_example_docstring
from diffusers.utils.torch_utils import randn_tensor
from diffusers.video_processor import VideoProcessor
from einops import rearrange
from PIL import Image
from transformers import T5Tokenizer
import time

from ..models import (AutoencoderKLWan, AutoTokenizer, CLIPModel,
                              WanT5EncoderModel, WanTransformer3DModel)

import random

logger = logging.get_logger(__name__)  # pylint: disable=invalid-name


EXAMPLE_DOC_STRING = """
    Examples:
        ```python
        pass
        ```
"""


# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
def retrieve_timesteps(
    scheduler,
    num_inference_steps: Optional[int] = None,
    device: Optional[Union[str, torch.device]] = None,
    timesteps: Optional[List[int]] = None,
    sigmas: Optional[List[float]] = None,
    **kwargs,
):
    """
    Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
    custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.

    Args:
        scheduler (`SchedulerMixin`):
            The scheduler to get timesteps from.
        num_inference_steps (`int`):
            The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
            must be `None`.
        device (`str` or `torch.device`, *optional*):
            The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
        timesteps (`List[int]`, *optional*):
            Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
            `num_inference_steps` and `sigmas` must be `None`.
        sigmas (`List[float]`, *optional*):
            Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
            `num_inference_steps` and `timesteps` must be `None`.

    Returns:
        `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
        second element is the number of inference steps.
    """
    if timesteps is not None and sigmas is not None:
        raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
    if timesteps is not None:
        accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
        if not accepts_timesteps:
            raise ValueError(
                f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
                f" timestep schedules. Please check whether you are using the correct scheduler."
            )
        scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
        timesteps = scheduler.timesteps
        num_inference_steps = len(timesteps)
    elif sigmas is not None:
        accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
        if not accept_sigmas:
            raise ValueError(
                f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
                f" sigmas schedules. Please check whether you are using the correct scheduler."
            )
        scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
        timesteps = scheduler.timesteps
        num_inference_steps = len(timesteps)
    else:
        scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
        timesteps = scheduler.timesteps
    return timesteps, num_inference_steps


def resize_mask(mask, latent, process_first_frame_only=True):
    latent_size = latent.size()
    batch_size, channels, num_frames, height, width = mask.shape

    if process_first_frame_only:
        target_size = list(latent_size[2:])
        target_size[0] = 1
        first_frame_resized = F.interpolate(
            mask[:, :, 0:1, :, :],
            size=target_size,
            mode='trilinear',
            align_corners=False
        )
        
        target_size = list(latent_size[2:])
        target_size[0] = target_size[0] - 1
        if target_size[0] != 0:
            remaining_frames_resized = F.interpolate(
                mask[:, :, 1:, :, :],
                size=target_size,
                mode='trilinear',
                align_corners=False
            )
            resized_mask = torch.cat([first_frame_resized, remaining_frames_resized], dim=2)
        else:
            resized_mask = first_frame_resized
    else:
        target_size = list(latent_size[2:])
        resized_mask = F.interpolate(
            mask,
            size=target_size,
            mode='trilinear',
            align_corners=False
        )
    return resized_mask


@dataclass
class WanPipelineOutput(BaseOutput):
    r"""
    Output class for CogVideo pipelines.

    Args:
        video (`torch.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 Torch tensor of shape
            `(batch_size, num_frames, channels, height, width)`.
    """

    videos: torch.Tensor


class WanFunCausalRLControlPipeline(DiffusionPipeline):
    r"""
    Pipeline for text-to-video generation using Wan.

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

    _optional_components = []
    model_cpu_offload_seq = "text_encoder->clip_image_encoder->transformer->vae"

    _callback_tensor_inputs = [
        "latents",
        "prompt_embeds",
        "negative_prompt_embeds",
    ]

    def __init__(
        self,
        tokenizer: AutoTokenizer,
        text_encoder: WanT5EncoderModel,
        vae: AutoencoderKLWan,
        transformer: WanTransformer3DModel,
        clip_image_encoder: CLIPModel,
        scheduler: FlowMatchEulerDiscreteScheduler,
    ):
        super().__init__()

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

        self.video_processor = VideoProcessor(vae_scale_factor=self.vae.config.spacial_compression_ratio)
        self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae.config.spacial_compression_ratio)
        self.mask_processor = VaeImageProcessor(
            vae_scale_factor=self.vae.config.spacial_compression_ratio, do_normalize=False, do_binarize=True, do_convert_grayscale=True
        )

        # for wan 1.3b
        self.num_transformer_blocks = 30
        self.num_frame_per_block = 1
        
        denoising_step_list = [1000, 757, 522, 0]
        self.denoising_step_list = torch.tensor(denoising_step_list[:-1], dtype=torch.long)


    def _get_t5_prompt_embeds(
        self,
        prompt: Union[str, List[str]] = None,
        num_videos_per_prompt: int = 1,
        max_sequence_length: int = 512,
        device: Optional[torch.device] = None,
        dtype: Optional[torch.dtype] = None,
    ):
        device = device or self._execution_device
        dtype = dtype or self.text_encoder.dtype

        prompt = [prompt] if isinstance(prompt, str) else 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_tensors="pt",
        )
        text_input_ids = text_inputs.input_ids
        prompt_attention_mask = text_inputs.attention_mask
        untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids

        if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
            removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
            logger.warning(
                "The following part of your input was truncated because `max_sequence_length` is set to "
                f" {max_sequence_length} tokens: {removed_text}"
            )

        seq_lens = prompt_attention_mask.gt(0).sum(dim=1).long()
        prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=prompt_attention_mask.to(device))[0]
        prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)

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

        return [u[:v] for u, v in zip(prompt_embeds, seq_lens)]

    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[torch.Tensor] = None,
        negative_prompt_embeds: Optional[torch.Tensor] = None,
        max_sequence_length: int = 512,
        device: Optional[torch.device] = None,
        dtype: Optional[torch.dtype] = 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. torch device to place the resulting embeddings on
            prompt_embeds (`torch.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 (`torch.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.
            device: (`torch.device`, *optional*):
                torch device
            dtype: (`torch.dtype`, *optional*):
                torch dtype
        """
        device = device or self._execution_device

        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,
                device=device,
                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,
                device=device,
                dtype=dtype,
            )

        return prompt_embeds, negative_prompt_embeds

    def prepare_latents(
        self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None
    ):
        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."
            )

        shape = (
            batch_size,
            num_channels_latents,
            (num_frames - 1) // self.vae.config.temporal_compression_ratio + 1,
            height // self.vae.config.spacial_compression_ratio,
            width // self.vae.config.spacial_compression_ratio,
        )

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

        # scale the initial noise by the standard deviation required by the scheduler
        if hasattr(self.scheduler, "init_noise_sigma"):
            latents = latents * self.scheduler.init_noise_sigma
        return latents

    def prepare_control_latents(
        self, control, control_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
    ):
        # resize the control to latents shape as we concatenate the control to the latents
        # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
        # and half precision

        if control is not None:
            control = control.to(device=device, dtype=dtype)
            bs = 1
            new_control = []
            for i in range(0, control.shape[0], bs):
                control_bs = control[i : i + bs]
                control_bs = self.vae.encode(control_bs)[0]
                if isinstance(control_bs, DiagonalGaussianDistribution):
                    control_bs = control_bs.mode()
                new_control.append(control_bs)
            control = torch.cat(new_control, dim = 0)

        if control_image is not None:
            control_image = control_image.to(device=device, dtype=dtype)
            bs = 1
            new_control_pixel_values = []
            for i in range(0, control_image.shape[0], bs):
                control_pixel_values_bs = control_image[i : i + bs]
                control_pixel_values_bs = self.vae.encode(control_pixel_values_bs)[0]
                if isinstance(control_pixel_values_bs, DiagonalGaussianDistribution):
                    control_pixel_values_bs = control_pixel_values_bs.mode()
                new_control_pixel_values.append(control_pixel_values_bs)
            control_image_latents = torch.cat(new_control_pixel_values, dim = 0)
        else:
            control_image_latents = None

        return control, control_image_latents

    def decode_latents(self, latents: torch.Tensor, vae_cache = None) -> torch.Tensor:
        frames, vae_cache = self.vae.decode(latents.to(self.vae.dtype), cache=vae_cache, return_dict=False)
        frames = (frames / 2 + 0.5).clamp(0, 1)
        # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
        frames = frames.cpu().float()
        return frames, vae_cache

    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
    def prepare_extra_step_kwargs(self, generator, eta):

        accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
        extra_step_kwargs = {}
        if accepts_eta:
            extra_step_kwargs["eta"] = eta

        # check if the scheduler accepts generator
        accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
        if accepts_generator:
            extra_step_kwargs["generator"] = generator
        return extra_step_kwargs

    # Copied from diffusers.pipelines.latte.pipeline_latte.LattePipeline.check_inputs
    def check_inputs(
        self,
        prompt,
        height,
        width,
        negative_prompt,
        callback_on_step_end_tensor_inputs,
        prompt_embeds=None,
        negative_prompt_embeds=None,
    ):
        if height % 8 != 0 or width % 8 != 0:
            raise ValueError(f"`height` and `width` have to be divisible by 8 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]}"
            )
        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 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)}")

        if prompt is not None and negative_prompt_embeds is not None:
            raise ValueError(
                f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
                f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
            )

        if 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`:"
                f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
            )

        if prompt_embeds is not None and negative_prompt_embeds is not None:
            if prompt_embeds.shape != negative_prompt_embeds.shape:
                raise ValueError(
                    "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
                    f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
                    f" {negative_prompt_embeds.shape}."
                )

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

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

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

    @property
    def interrupt(self):
        return self._interrupt
    
    def _initialize_kv_cache(self, batch_size, dtype, device):
        """
        Initialize a Per-GPU KV cache for the Wan model.
        """
        kv_cache = []

        for _ in range(self.num_transformer_blocks):
            kv_cache.append({
                "k": torch.zeros([batch_size, 32760, 12, 128], dtype=dtype, device=device),
                "v": torch.zeros([batch_size, 32760, 12, 128], dtype=dtype, device=device)
            })

        return kv_cache

    def _initialize_crossattn_cache(self, batch_size, dtype, device):
        """
        Initialize a Per-GPU cross-attention cache for the Wan model.
        """
        crossattn_cache = []

        for _ in range(self.num_transformer_blocks):
            crossattn_cache.append({
                "k": torch.zeros([batch_size, 512, 12, 128], dtype=dtype, device=device),
                "v": torch.zeros([batch_size, 512, 12, 128], dtype=dtype, device=device),
                "is_init": False
            })

        return crossattn_cache

    def _convert_flow_pred_to_x0(self, flow_pred: torch.Tensor, xt: torch.Tensor, timestep: torch.Tensor) -> torch.Tensor:
        """
        Convert flow matching's prediction to x0 prediction.
        flow_pred: the prediction with shape [B, C, F, H, W]
        xt: the input noisy data with shape [B, C, F, H, W]
        timestep: the timestep with shape [B, F]

        pred = noise - x0
        x_t = (1-sigma_t) * x0 + sigma_t * noise
        we have x0 = x_t - sigma_t * pred
        see derivations https://chatgpt.com/share/67bf8589-3d04-8008-bc6e-4cf1a24e2d0e
        """
        # use higher precision for calculations
        original_dtype = flow_pred.dtype
        flow_pred, xt, sigmas, timesteps = map(
            lambda x: x.double().to(flow_pred.device), [flow_pred, xt,
                                                        self.scheduler.sigmas,
                                                        self.scheduler.timesteps]
        )

        batch_size, num_frames = timestep.shape
        timestep = timestep.flatten()
        timestep_id = torch.argmin(
            (timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1)
        sigma_t = sigmas[timestep_id].reshape(batch_size, 1, num_frames, 1, 1)
        x0_pred = xt - sigma_t * flow_pred
        return x0_pred.to(original_dtype)

    def _convert_flow_pred_to_next_step(self, flow_pred, xt, timestep, next_timestep):
        original_dtype = flow_pred.dtype
        flow_pred, xt, sigmas, timesteps = map(
            lambda x: x.double().to(flow_pred.device), [flow_pred, xt,
                                                        self.scheduler.sigmas,
                                                        self.scheduler.timesteps]
        )

        batch_size, num_frames = timestep.shape
        timestep = timestep.flatten()
        timestep_id = torch.argmin(
            (timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1)
        sigma_t = sigmas[timestep_id].reshape(batch_size, 1, num_frames, 1, 1)

        next_timestep = next_timestep.flatten()
        next_timestep_id = torch.argmin(
            (timesteps.unsqueeze(0) - next_timestep.unsqueeze(1)).abs(), dim=1)
        sigma_next = sigmas[next_timestep_id].reshape(batch_size, 1, num_frames, 1, 1)

        prev_sample = xt + (sigma_next - sigma_t) * flow_pred
        return prev_sample.to(original_dtype)

    def _add_noise(self, x0, noise, timestep):
        original_dtype = x0.dtype
        x0, noise, sigmas, timesteps = map(
            lambda x: x.double().to(x0.device), [x0, noise,
                                                        self.scheduler.sigmas,
                                                        self.scheduler.timesteps]
        )

        batch_size, num_frames = timestep.shape
        timestep = timestep.flatten()
        timestep_id = torch.argmin(
            (timesteps.unsqueeze(0) - timestep.unsqueeze(1)).abs(), dim=1)
        sigma_t = sigmas[timestep_id].reshape(batch_size, 1, num_frames, 1, 1)
        xt = (1.0 - sigma_t) * x0 + sigma_t * noise
        return xt.to(original_dtype)

    @torch.no_grad()
    @replace_example_docstring(EXAMPLE_DOC_STRING)
    def __call__(
        self,
        prompt: Optional[Union[str, List[str]]] = None,
        negative_prompt: Optional[Union[str, List[str]]] = None,
        height: int = 480,
        width: int = 720,
        control_video: Union[torch.FloatTensor] = None,
        ref_image: Union[torch.FloatTensor] = None,
        num_frames: int = 49,
        num_inference_steps: int = 50,
        timesteps: Optional[List[int]] = None,
        guidance_scale: float = 6,
        num_videos_per_prompt: int = 1,
        eta: float = 0.0,
        generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
        latents: Optional[torch.FloatTensor] = None,
        prompt_embeds: Optional[torch.FloatTensor] = None,
        negative_prompt_embeds: Optional[torch.FloatTensor] = None,
        output_type: str = "numpy",
        return_dict: bool = False,
        callback_on_step_end: Optional[
            Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
        ] = None,
        attention_kwargs: Optional[Dict[str, Any]] = None,
        callback_on_step_end_tensor_inputs: List[str] = ["latents"],
        clip_image: Image = None,
        max_sequence_length: int = 512,
        comfyui_progressbar: bool = False,
        mode: str = "control_ref",
        context_perturbation: float = 0.0,
        mini_num_image_per_prompt: int = 4,
        noise_level: float = 0.7,
        train_num_steps: int = 1,
        process_index: int = 0,
        random_timestep: Optional[int] = None,
    ) -> Union[WanPipelineOutput, Tuple]:
        """
        Function invoked when calling the pipeline for generation.
        Args:

        Examples:

        Returns:

        """
        tic = time.time()
        if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
            callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
        num_videos_per_prompt = 1

        # 1. Check inputs. Raise error if not correct
        self.check_inputs(
            prompt,
            height,
            width,
            negative_prompt,
            callback_on_step_end_tensor_inputs,
            prompt_embeds,
            negative_prompt_embeds,
        )
        self._guidance_scale = guidance_scale
        self._attention_kwargs = attention_kwargs
        self._interrupt = False

        # 2. Default 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]

        device = self._execution_device
        weight_dtype = self.text_encoder.dtype

        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
        # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
        # corresponds to doing no classifier free guidance.
        do_classifier_free_guidance = guidance_scale > 1.0

        # 3. Encode input prompt
        prompt_embeds, negative_prompt_embeds = self.encode_prompt(
            prompt,
            negative_prompt,
            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,
            device=device,
        )
        if do_classifier_free_guidance:
            prompt_embeds = negative_prompt_embeds + prompt_embeds

        # 4. Prepare timesteps
        timesteps = None
        if isinstance(self.scheduler, FlowMatchEulerDiscreteScheduler):
            timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps, mu=1)
        else:
            timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
        self._num_timesteps = len(timesteps)
        if comfyui_progressbar:
            from comfy.utils import ProgressBar
            pbar = ProgressBar(num_inference_steps + 2)

        # 5. Prepare latents.
        latent_channels = self.vae.config.latent_channels
        latents = self.prepare_latents(
            batch_size * num_videos_per_prompt,
            latent_channels,
            num_frames,
            height,
            width,
            weight_dtype,
            device,
            generator,
            latents,
        )
        if comfyui_progressbar:
            pbar.update(1)

        # Prepare mask latent variables
        if control_video is not None:
            video_length = control_video.shape[2]
            control_video = self.image_processor.preprocess(rearrange(control_video, "b c f h w -> (b f) c h w"), height=height, width=width) 
            control_video = control_video.to(dtype=torch.float32)
            control_video = rearrange(control_video, "(b f) c h w -> b c f h w", f=video_length)
            control_video_latents = self.prepare_control_latents(
                None,
                control_video,
                batch_size,
                height,
                width,
                weight_dtype,
                device,
                generator,
                do_classifier_free_guidance
            )[1]
            control_video_latents[:, :, :1] = 0  # Make first frame control to zero
            control_latents = (
                torch.cat([control_video_latents] * 2) if do_classifier_free_guidance else control_video_latents
            ).to(device, weight_dtype)
        else:
            control_video_latents = torch.zeros_like(latents).to(device, weight_dtype)
            control_latents = (
                torch.cat([control_video_latents] * 2) if do_classifier_free_guidance else control_video_latents
            ).to(device, weight_dtype)
            
        if ref_image is not None:
            video_length = ref_image.shape[2]
            ref_image = self.image_processor.preprocess(rearrange(ref_image, "b c f h w -> (b f) c h w"), height=height, width=width) 
            ref_image = ref_image.to(dtype=torch.float32)
            ref_image = rearrange(ref_image, "(b f) c h w -> b c f h w", f=video_length)
            
            ref_image_latents = self.prepare_control_latents(
                None,
                ref_image,
                batch_size,
                height,
                width,
                weight_dtype,
                device,
                generator,
                do_classifier_free_guidance
            )[1]

            if mode == "control_ref_repeat":
                ref_image_latents_conv_in = ref_image_latents.repeat(1, 1, latents.size(2), 1, 1)
            else:
                ref_image_latents_conv_in = torch.zeros_like(latents)
                if latents.size()[2] != 1:
                    ref_image_latents_conv_in[:, :, :1] = ref_image_latents
            ref_image_latents_conv_input = (
                torch.cat([ref_image_latents_conv_in] * 2) if do_classifier_free_guidance else ref_image_latents_conv_in
            ).to(device, weight_dtype)
            control_latents = torch.cat([control_latents, ref_image_latents_conv_input], dim = 1)
        else:
            ref_image_latents_conv_in = torch.zeros_like(latents)
            ref_image_latents_conv_input = (
                torch.cat([ref_image_latents_conv_in] * 2) if do_classifier_free_guidance else ref_image_latents_conv_in
            ).to(device, weight_dtype)
            control_latents = torch.cat([control_latents, ref_image_latents_conv_input], dim = 1)
        y = control_latents

        # Prepare clip latent variables
        if clip_image is not None:
            clip_image = TF.to_tensor(clip_image).sub_(0.5).div_(0.5).to(device, weight_dtype) 
            clip_context = self.clip_image_encoder([clip_image[:, None, :, :]])
            clip_context = (
                torch.cat([clip_context] * 2) if do_classifier_free_guidance else clip_context
            )
        else:
            clip_image = Image.new("RGB", (512, 512), color=(0, 0, 0))  
            clip_image = TF.to_tensor(clip_image).sub_(0.5).div_(0.5).to(device, weight_dtype) 
            clip_context = self.clip_image_encoder([clip_image[:, None, :, :]])
            clip_context = (
                torch.cat([clip_context] * 2) if do_classifier_free_guidance else clip_context
            )
            clip_context = torch.zeros_like(clip_context)
        if comfyui_progressbar:
            pbar.update(1)

        # prepare cache and output placeholder
        kv_cache = self._initialize_kv_cache(batch_size * 2 if do_classifier_free_guidance else batch_size, weight_dtype, device)
        crossattn_cache = self._initialize_crossattn_cache(batch_size * 2 if do_classifier_free_guidance else batch_size, weight_dtype, device)
        output = torch.zeros_like(latents)
        output_video = []
        vae_cache = None

        # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
        extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)

        num_latent_frames = (num_frames - 1) // self.vae.config.temporal_compression_ratio + 1
        target_shape = (self.vae.config.latent_channels, (num_frames - 1) // self.vae.config.temporal_compression_ratio + 1, 
                width // self.vae.config.spacial_compression_ratio, height // self.vae.config.spacial_compression_ratio)
        seq_len = math.ceil((target_shape[2] * target_shape[3]) / (self.transformer.config.patch_size[1] * self.transformer.config.patch_size[2]))  # token sequence length per frame
        num_input_blocks = 1
        assert ref_image is not None, "Only support control over a start frame"
        num_blocks = num_latent_frames // self.num_frame_per_block
        shift_cache_length = 0
        torch.cuda.synchronize()
        print(f"Time taken to prepare inputs: {time.time() - tic:.2f} seconds")

        random.seed(process_index)
        if random_timestep is None:
            random_timestep = random.randint(0, len(self.denoising_step_list)-1)
        
        all_latents = []
        all_log_probs = []
        all_timesteps = []
        for block_index in range(num_blocks):
            tic = time.time()
            print(f"Block {block_index + 1}/{num_blocks}")
            block_latents = latents[:, :, block_index * self.num_frame_per_block:(block_index + 1) * self.num_frame_per_block]
            block_y = y[:, :, block_index * self.num_frame_per_block:(block_index + 1) * self.num_frame_per_block] if y is not None else None

            # 如果超出 cache 最大长度，则整体左移，丢弃最左边的部分
            current_start = block_index * self.num_frame_per_block * seq_len - shift_cache_length
            current_end = (block_index + 1) * self.num_frame_per_block * seq_len - shift_cache_length
            block_len =  current_end - current_start
            while current_end > kv_cache[0]["k"].shape[1]:
                shift_cache_length += block_len
                current_end -= block_len
                current_start -= block_len
                for layer_kv_cache in kv_cache:
                    layer_kv_cache["k"][:, :-block_len] = layer_kv_cache["k"][:, block_len:].clone()
                    layer_kv_cache["v"][:, :-block_len] = layer_kv_cache["v"][:, block_len:].clone()
                print(f"Shift cache length: {shift_cache_length}, current_start: {current_start}, current_end: {current_end}")

            # fetch the clean first frame
            if block_index < num_input_blocks:
                block_latents = ref_image_latents_conv_in[:, :, block_index * self.num_frame_per_block:(block_index + 1) * self.num_frame_per_block]
            
            # denoising loop
            else:
                timesteps = self.denoising_step_list.to(device=device)
                for i, t in enumerate(timesteps):
                    latent_model_input = torch.cat([block_latents] * 2) if do_classifier_free_guidance else block_latents
                    timestep = torch.ones([batch_size * 2 if do_classifier_free_guidance else batch_size, self.num_frame_per_block], device=device, dtype=latents.dtype) * t
                    
                    if i < random_timestep:
                        cur_noise_level = 0
                    elif i == random_timestep:
                        cur_noise_level= noise_level
                        # 将latents repeat mini_num_image_per_prompt次
                        latent_model_input = latent_model_input.repeat(mini_num_image_per_prompt, 1, 1, 1)
                        prompt_embeds = prompt_embeds.repeat(mini_num_image_per_prompt, 1, 1)
                        timestep = timestep.repeat(mini_num_image_per_prompt, 1)
                        block_y = block_y.repeat(mini_num_image_per_prompt, 1, 1)
                        clip_context = clip_context.repeat(mini_num_image_per_prompt, 1, 1)
                    elif i > random_timestep and i < random_timestep + train_num_steps:
                        cur_noise_level = noise_level
                    else:
                        cur_noise_level= 0
                    # predict noise model_output
                    with torch.autocast(str(device), dtype=weight_dtype):
                        noise_pred = self.transformer(
                            x=latent_model_input,
                            context=prompt_embeds,
                            t=timestep,
                            seq_len=seq_len * self.num_frame_per_block,
                            y=block_y,
                            clip_fea=clip_context,
                            kv_cache=kv_cache,
                            crossattn_cache=crossattn_cache,
                            current_start=current_start,
                            current_end=current_end,
                            shift_cache_length=shift_cache_length,
                        )

                    # perform guidance
                    if do_classifier_free_guidance:
                        noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
                        noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)

                    # compute the previous noisy sample x_t -> x_t-1
                    # block_latents = self.scheduler.step(noise_pred, t, block_latents, **extra_step_kwargs, return_dict=False)[0]
                    latents_dtype = latents.dtype
                    latents, log_prob, prev_latents_mean, std_dev_t = sde_step_with_logprob(
                        self,
                        noise_pred.float(), 
                        t.unsqueeze(0), 
                        latents.float(),
                        noise_level=cur_noise_level,
                    )   

                    if latents.dtype != latents_dtype:
                        latents = latents.to(latents_dtype)

                    if i >= random_timestep and i < random_timestep + train_num_steps:
                        all_latents.append(latents)
                        all_log_probs.append(log_prob)
                        all_timesteps.append(t.repeat(len(latents)))
                    
                    if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
                        progress_bar.update()
            
            if block_index < num_input_blocks:
                # update cache with clean latents and timestep=0
                latent_model_input = torch.cat([block_latents] * 2) if do_classifier_free_guidance else block_latents
                timestep = torch.ones([batch_size * 2 if do_classifier_free_guidance else batch_size, self.num_frame_per_block], device=device, dtype=torch.int64) * 0
            else:
                latents_with_minor_noise = block_latents * (1 - context_perturbation) + torch.randn_like(block_latents) * context_perturbation
                latent_model_input = torch.cat([latents_with_minor_noise] * 2) if do_classifier_free_guidance else latents_with_minor_noise
                timestep = torch.ones([batch_size * 2 if do_classifier_free_guidance else batch_size, self.num_frame_per_block], device=device, dtype=torch.int64) * (context_perturbation * 1000)
            with torch.autocast(str(device), dtype=weight_dtype):
                self.transformer(
                    x=latent_model_input,
                    context=prompt_embeds,
                    t=timestep,
                    seq_len=seq_len * self.num_frame_per_block,
                    y=block_y,
                    clip_fea=clip_context,
                    kv_cache=kv_cache,
                    crossattn_cache=crossattn_cache,
                    current_start=current_start,
                    current_end=current_end,
                    shift_cache_length=shift_cache_length,
                )
            torch.cuda.synchronize()
            print(f"Time taken to denoise block {block_index + 1}: {time.time() - tic:.2f} seconds")

            # decode the latest block
            tic = time.time()
            block_video, vae_cache = self.decode_latents(block_latents, vae_cache=vae_cache)
            output_video.append(block_video)  # (b c f h w), [0, 1]
            torch.cuda.synchronize()
            print(f"Time taken to decode block {block_index + 1}: {time.time() - tic:.2f} seconds")
            # output[:, :, block_index * self.num_frame_per_block:(block_index + 1) * self.num_frame_per_block] = block_latents
        
        output_video = torch.cat(output_video, dim=2)
        print(f"Final output shape: {output_video.shape}")
        # output_video = self.decode_latents(output)
        # video = self.video_processor.postprocess_video(video=video, output_type="pil")

        # Offload all models
        self.maybe_free_model_hooks()

        return WanPipelineOutput(videos=output_video)

        
    def sde_step_with_logprob(
        self,
        model_output: torch.FloatTensor,
        timestep: Union[float, torch.FloatTensor],
        sample: torch.FloatTensor,
        noise_level: float = 0.7,
        prev_sample: Optional[torch.FloatTensor] = None,
        generator: Optional[torch.Generator] = None,
    ):
        """
        Predict the sample from the previous timestep by reversing the SDE. This function propagates the flow
        process from the learned model outputs (most often the predicted velocity).

        Args:
            model_output (`torch.FloatTensor`):
                The direct output from learned flow model.
            timestep (`float`):
                The current discrete timestep in the diffusion chain.
            sample (`torch.FloatTensor`):
                A current instance of a sample created by the diffusion process.
            generator (`torch.Generator`, *optional*):
                A random number generator.
        """
        # bf16 can overflow here when compute prev_sample_mean, we must convert all variable to fp32
        model_output=model_output.float()
        sample=sample.float()
        if prev_sample is not None:
            prev_sample=prev_sample.float()

        step_index = [self.scheduler.index_for_timestep(t) for t in timestep]
        prev_step_index = [step+1 for step in step_index]
        sigma = self.scheduler.sigmas[step_index].view(-1, *([1] * (len(sample.shape) - 1)))
        sigma_prev = self.scheduler.sigmas[prev_step_index].view(-1, *([1] * (len(sample.shape) - 1)))
        sigma_max = self.scheduler.sigmas[1].item()
        dt = sigma_prev - sigma

        std_dev_t = torch.sqrt(sigma / (1 - torch.where(sigma == 1, sigma_max, sigma)))*noise_level
        
        # our sde
        prev_sample_mean = sample*(1+std_dev_t**2/(2*sigma)*dt)+model_output*(1+std_dev_t**2*(1-sigma)/(2*sigma))*dt
        
        if prev_sample is None:
            variance_noise = randn_tensor(
                model_output.shape,
                generator=generator,
                device=model_output.device,
                dtype=model_output.dtype,
            )
            prev_sample = prev_sample_mean + std_dev_t * torch.sqrt(-1*dt) * variance_noise

        log_prob = (
            -((prev_sample.detach() - prev_sample_mean) ** 2) / (2 * ((std_dev_t * torch.sqrt(-1*dt))**2))
            - torch.log(std_dev_t * torch.sqrt(-1*dt))
            - torch.log(torch.sqrt(2 * torch.as_tensor(math.pi)))
        )

        # mean along all but batch dimension
        log_prob = log_prob.mean(dim=tuple(range(1, log_prob.ndim)))
        
        return prev_sample, log_prob, prev_sample_mean, std_dev_t
                    

    @torch.no_grad()
    def stream_generate(
        self,
        block_index: int,
        prompt: Optional[Union[str, List[str]]] = None,
        negative_prompt: Optional[Union[str, List[str]]] = None,
        height: int = 480,
        width: int = 720,
        control_video: Union[torch.FloatTensor] = None,
        ref_image: Union[torch.FloatTensor] = None,
        clip_image: Image = None,
        num_frames: int = 4,  # number of frames per block, 1 for first block
        num_inference_steps: int = 50,
        timesteps: Optional[List[int]] = None,
        guidance_scale: float = 6,
        num_videos_per_prompt: int = 1,
        eta: float = 0.0,
        generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
        latents: Optional[torch.FloatTensor] = None,
        max_sequence_length: int = 512,
        mode: str = 'control_ref', 
        context_perturbation: float = 0.0,
        history_guidance_scale: float = 0.0,

        # cache
        prompt_embeds: Optional[torch.FloatTensor] = None,
        negative_prompt_embeds: Optional[torch.FloatTensor] = None,
        ref_image_latents = None,
        clip_context = None,
        control_enc_cache = None,
        video_dec_cache = None,
        kv_cache = None,
        crossattn_cache = None,
        shift_cache_length: int = 0,
    ) -> Union[WanPipelineOutput, Tuple]:
        print(f"> Process block: {block_index + 1}")
        tic0 = time.time()
        is_first_block = block_index == 0

        tic = time.time()
        num_videos_per_prompt = 1

        # 1. Check inputs. Raise error if not correct
        self._guidance_scale = guidance_scale
        self._interrupt = False

        # 2. Default 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]

        device = self._execution_device
        weight_dtype = self.text_encoder.dtype

        # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
        # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
        # corresponds to doing no classifier free guidance.
        do_classifier_free_guidance = guidance_scale > 1.0
        do_history_guidance = history_guidance_scale > 1.0

        # 3. Encode input prompt
        if is_first_block:
            prompt_embeds, negative_prompt_embeds = self.encode_prompt(
                prompt,
                negative_prompt,
                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,
                device=device,
            )
            if do_history_guidance:
                prompt_embeds = prompt_embeds + prompt_embeds
            if do_classifier_free_guidance:
                prompt_embeds = negative_prompt_embeds + prompt_embeds
        else:
            assert prompt_embeds is not None

        # 4. Prepare timesteps
        timesteps = None
        if isinstance(self.scheduler, FlowMatchEulerDiscreteScheduler):
            timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps, mu=1)
        else:
            timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
        self._num_timesteps = len(timesteps)

        # 5. Prepare latents.
        latent_channels = self.vae.config.latent_channels
        latents = self.prepare_latents(
            batch_size * num_videos_per_prompt,
            latent_channels,
            num_frames,
            height,
            width,
            weight_dtype,
            device,
            generator,
            latents,
        )

        # Encode control video for every block
        if control_video is not None:
            video_length = control_video.shape[2]
            control_video = self.image_processor.preprocess(rearrange(control_video, "b c f h w -> (b f) c h w"), height=height, width=width) 
            control_video = control_video.to(device=device, dtype=weight_dtype)
            control_video = rearrange(control_video, "(b f) c h w -> b c f h w", f=video_length)
            control_video_latents, control_enc_cache = self.vae.encode(control_video, cache=control_enc_cache, return_dict=False)
            if isinstance(control_video_latents, DiagonalGaussianDistribution):
                control_video_latents = control_video_latents.mode()
        # first frame should be zero control, but we encode a black image to get the encoder cache
        else:
            control_video = torch.ones_like(ref_image).to(device=device, dtype=weight_dtype) * -1
            control_video_latents, control_enc_cache = self.vae.encode(control_video, cache=control_enc_cache, return_dict=False)
            if isinstance(control_video_latents, DiagonalGaussianDistribution):
                control_video_latents = control_video_latents.mode()
        control_latents = (
            torch.cat([control_video_latents] * 2) if do_classifier_free_guidance or do_history_guidance else control_video_latents
        ).to(device, weight_dtype)
        
        # Encode ref_image for first block
        if is_first_block:
            video_length = ref_image.shape[2]
            ref_image = self.image_processor.preprocess(rearrange(ref_image, "b c f h w -> (b f) c h w"), height=height, width=width) 
            ref_image = ref_image.to(device=device, dtype=weight_dtype)
            ref_image = rearrange(ref_image, "(b f) c h w -> b c f h w", f=video_length)
            ref_image_latents, _ = self.vae.encode(ref_image, return_dict=False)
            if isinstance(ref_image_latents, DiagonalGaussianDistribution):
                ref_image_latents = ref_image_latents.mode()
            ref_image_latents_conv_in = ref_image_latents
        else:
            if mode == 'control_ref_repeat':
                ref_image_latents_conv_in = ref_image_latents
            else:
                ref_image_latents_conv_in = torch.zeros_like(latents)
        ref_image_latents_conv_input = (
            torch.cat([ref_image_latents_conv_in] * 2) if do_classifier_free_guidance or do_history_guidance else ref_image_latents_conv_in
        ).to(device, weight_dtype)

        control_latents = torch.cat([control_latents, ref_image_latents_conv_input], dim = 1)

        # Prepare clip latent variables
        if is_first_block:
            clip_image = TF.to_tensor(clip_image).sub_(0.5).div_(0.5).to(device, weight_dtype) 
            clip_context = self.clip_image_encoder([clip_image[:, None, :, :]])
            clip_context = (
                torch.cat([clip_context] * 2) if do_classifier_free_guidance or do_history_guidance else clip_context
            )
        else:
            assert clip_context is not None

        # prepare cache and output placeholder
        if is_first_block:
            kv_cache = self._initialize_kv_cache(batch_size * 2 if do_classifier_free_guidance or do_history_guidance else batch_size, weight_dtype, device)
            crossattn_cache = self._initialize_crossattn_cache(batch_size * 2 if do_classifier_free_guidance or do_history_guidance else batch_size, weight_dtype, device)
            video_dec_cache = None
            shift_cache_length = 0
        
        num_latent_frames = (num_frames - 1) // self.vae.config.temporal_compression_ratio + 1
        target_shape = (self.vae.config.latent_channels, (num_frames - 1) // self.vae.config.temporal_compression_ratio + 1, 
                width // self.vae.config.spacial_compression_ratio, height // self.vae.config.spacial_compression_ratio)
        seq_len = math.ceil((target_shape[2] * target_shape[3]) / (self.transformer.config.patch_size[1] * self.transformer.config.patch_size[2]))  # token sequence length per frame

        # 如果超出 cache 最大长度，则整体左移，丢弃最左边的部分
        current_start = block_index * self.num_frame_per_block * seq_len - shift_cache_length
        current_end = (block_index + 1) * self.num_frame_per_block * seq_len - shift_cache_length
        block_len =  current_end - current_start
        while current_end > kv_cache[0]["k"].shape[1]:
            shift_cache_length += block_len
            current_end -= block_len
            current_start -= block_len
            for layer_kv_cache in kv_cache:
                layer_kv_cache["k"][:, :-block_len] = layer_kv_cache["k"][:, block_len:].clone()
                layer_kv_cache["v"][:, :-block_len] = layer_kv_cache["v"][:, block_len:].clone()
            print(f"Shift cache length: {shift_cache_length}, current_start: {current_start}, current_end: {current_end}")

        torch.cuda.synchronize()
        print(f"Time taken to prepare inputs block {block_index + 1}: {time.time() - tic:.2f} seconds")

        tic = time.time()
        if is_first_block:
            latents = ref_image_latents_conv_in
        else:
            # denoising loop
            timesteps = self.denoising_step_list.to(device=device)
            for i, t in enumerate(timesteps):
                latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance or do_history_guidance else latents
                timestep = torch.ones([batch_size * 2 if do_classifier_free_guidance or do_history_guidance else batch_size, self.num_frame_per_block], device=device, dtype=latents.dtype) * t
                
                # predict noise model_output
                with torch.autocast(str(device), dtype=weight_dtype):
                    noise_pred = self.transformer(
                        x=latent_model_input,
                        context=prompt_embeds,
                        t=timestep,
                        seq_len=seq_len * self.num_frame_per_block,
                        y=control_latents,
                        clip_fea=clip_context,
                        kv_cache=kv_cache,
                        crossattn_cache=crossattn_cache,
                        current_start=current_start,
                        current_end=current_end,
                        shift_cache_length=shift_cache_length,
                    )

                # perform guidance
                if do_history_guidance:
                    noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2)
                    noise_pred = noise_pred_uncond + history_guidance_scale * (noise_pred_cond - noise_pred_uncond)
                if do_classifier_free_guidance:
                    noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
                    noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)

                if i < len(timesteps) - 1:
                    next_timestep = torch.ones([batch_size, self.num_frame_per_block], device=device, dtype=latents.dtype) * timesteps[i + 1]
                    latents = self._convert_flow_pred_to_next_step(
                        noise_pred, latents, timestep[:batch_size], next_timestep
                    )
                else:
                    latents = self._convert_flow_pred_to_x0(
                        noise_pred, latents, timestep[:batch_size]
                    )
                print(f"step {i + 1}/{len(timesteps)}, timestep {t}")

        # update cache with clean latents and timestep=0
        if do_history_guidance:
            print(f"do history guidance with w = {history_guidance_scale}")
            if is_first_block:
                latent_model_input = torch.cat([latents] * 2)
                timestep = torch.ones([batch_size * 2, self.num_frame_per_block], device=device, dtype=torch.int64) * 0
            else:
                # apply condition to previous history
                for cache in kv_cache:
                    cache["k"][:batch_size] = cache["k"][batch_size:]
                    cache["v"][:batch_size] = cache["v"][batch_size:]
                for cache in crossattn_cache:
                    cache["k"][:batch_size] = cache["k"][batch_size:]
                    cache["v"][:batch_size] = cache["v"][batch_size:]
                latent_model_input = torch.cat([torch.randn_like(latents), latents])
                timestep = torch.cat([
                    torch.ones([batch_size, self.num_frame_per_block], device=device, dtype=torch.int64) * 1000,
                    torch.ones([batch_size, self.num_frame_per_block], device=device, dtype=torch.int64) * 0
                ], dim=0)
        else:
            if is_first_block or context_perturbation == 0.0:
                latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
                timestep = torch.ones([batch_size * 2 if do_classifier_free_guidance else batch_size, self.num_frame_per_block], device=device, dtype=torch.int64) * 0
            else:
                latents_with_minor_noise = latents * (1 - context_perturbation) + torch.randn_like(latents) * context_perturbation
                latent_model_input = torch.cat([latents_with_minor_noise] * 2) if do_classifier_free_guidance else latents_with_minor_noise
                timestep = torch.ones([batch_size * 2 if do_classifier_free_guidance else batch_size, self.num_frame_per_block], device=device, dtype=torch.int64) * (context_perturbation * 1000)
        
        with torch.autocast(str(device), dtype=weight_dtype):
            self.transformer(
                x=latent_model_input,
                context=prompt_embeds,
                t=timestep,
                seq_len=seq_len * self.num_frame_per_block,
                y=control_latents,
                clip_fea=clip_context,
                kv_cache=kv_cache,
                crossattn_cache=crossattn_cache,
                current_start=current_start,
                current_end=current_end,
                shift_cache_length=shift_cache_length,
            )
        torch.cuda.synchronize()
        print(f"Time taken to denoise block {block_index + 1}: {time.time() - tic:.2f} seconds")

        # decode the latest block
        tic = time.time()
        output_video, video_dec_cache = self.decode_latents(latents, vae_cache=video_dec_cache)  # (b c f h w), [0, 1]
        torch.cuda.synchronize()
        print(f"Time taken to decode block {block_index + 1}: {time.time() - tic:.2f} seconds")
        print(f"> Total time taken to process block {block_index + 1}: {time.time() - tic0:.2f} seconds")

        return output_video, prompt_embeds, negative_prompt_embeds, ref_image_latents, clip_context, control_enc_cache, video_dec_cache, kv_cache, crossattn_cache, shift_cache_length