#
Wan

Wan-2.1 by the Wan Team.

This report presents Wan, a comprehensive and open suite of video foundation models designed to push the boundaries of video generation. Built upon the mainstream diffusion transformer paradigm, Wan achieves significant advancements in generative capabilities through a series of innovations, including our novel VAE, scalable pre-training strategies, large-scale data curation, and automated evaluation metrics. These contributions collectively enhance the model’s performance and versatility. Specifically, Wan is characterized by four key features: Leading Performance: The 14B model of Wan, trained on a vast dataset comprising billions of images and videos, demonstrates the scaling laws of video generation with respect to both data and model size. It consistently outperforms the existing open-source models as well as state-of-the-art commercial solutions across multiple internal and external benchmarks, demonstrating a clear and significant performance superiority. Comprehensiveness: Wan offers two capable models, i.e., 1.3B and 14B parameters, for efficiency and effectiveness respectively. It also covers multiple downstream applications, including image-to-video, instruction-guided video editing, and personal video generation, encompassing up to eight tasks. Consumer-Grade Efficiency: The 1.3B model demonstrates exceptional resource efficiency, requiring only 8.19 GB VRAM, making it compatible with a wide range of consumer-grade GPUs. Openness: We open-source the entire series of Wan, including source code and all models, with the goal of fostering the growth of the video generation community. This openness seeks to significantly expand the creative possibilities of video production in the industry and provide academia with high-quality video foundation models. All the code and models are available at this https URL.

You can find all the original Wan2.1 checkpoints under the Wan-AI organization.

The following Wan models are supported in Diffusers:

- Wan 2.1 T2V 1.3B
- Wan 2.1 T2V 14B
- Wan 2.1 I2V 14B - 480P
- Wan 2.1 I2V 14B - 720P
- Wan 2.1 FLF2V 14B - 720P
- Wan 2.1 VACE 1.3B
- Wan 2.1 VACE 14B
- Wan 2.2 T2V 14B
- Wan 2.2 I2V 14B
- Wan 2.2 TI2V 5B

> Click on the Wan models in the right sidebar for more examples of video generation.

###
Text-to-Video Generation

The example below demonstrates how to generate a video from text optimized for memory or inference speed.

T2V memory
T2V inference speed

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

The Wan2.1 text-to-video model below requires ~13GB of VRAM.

    # pip install ftfy
    import torch
    import numpy as np
    from diffusers import AutoModel, WanPipeline
    from diffusers.quantizers import PipelineQuantizationConfig
    from diffusers.hooks.group_offloading import apply_group_offloading
    from diffusers.utils import export_to_video, load_image
    from transformers import UMT5EncoderModel

    text_encoder = UMT5EncoderModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", torch_dtype=torch.bfloat16)
    vae = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", torch_dtype=torch.float32)
    transformer = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", torch_dtype=torch.bfloat16)

    # group-offloading
    onload_device = torch.device("cuda")
    offload_device = torch.device("cpu")
    apply_group_offloading(text_encoder,
        onload_device=onload_device,
        offload_device=offload_device,
        offload_type="block_level",
        num_blocks_per_group=4
    )
    transformer.enable_group_offload(
        onload_device=onload_device,
        offload_device=offload_device,
        offload_type="leaf_level",
        use_stream=True
    )

    pipeline = WanPipeline.from_pretrained(
        "Wan-AI/Wan2.1-T2V-14B-Diffusers",
        vae=vae,
        transformer=transformer,
        text_encoder=text_encoder,
        torch_dtype=torch.bfloat16
    )
    pipeline.to("cuda")

    prompt = """
    The camera rushes from far to near in a low-angle shot,
    revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
    for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
    Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic
    shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
    """
    negative_prompt = """
    Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
    low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
    misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
    """

    output = pipeline(
        prompt=prompt,
        negative_prompt=negative_prompt,
        num_frames=81,
        guidance_scale=5.0,
    ).frames[0]
    export_to_video(output, "output.mp4", fps=16)

###
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.

usage

    import numpy as np
    import torch
    import torchvision.transforms.functional as TF
    from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
    from diffusers.utils import export_to_video, load_image
    from transformers import CLIPVisionModel

    model_id = "Wan-AI/Wan2.1-FLF2V-14B-720P-diffusers"
    image_encoder = CLIPVisionModel.from_pretrained(model_id, subfolder="image_encoder", torch_dtype=torch.float32)
    vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
    pipe = WanImageToVideoPipeline.from_pretrained(
        model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16
    )
    pipe.to("cuda")

    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, pipe, max_area=720 * 1280):
        aspect_ratio = image.height / image.width
        mod_value = pipe.vae_scale_factor_spatial * pipe.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_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 = TF.center_crop(image, size)

        return image, height, width

    first_frame, height, width = aspect_ratio_resize(first_frame, pipe)
    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 = pipe(
        image=first_frame, last_image=last_frame, prompt=prompt, height=height, width=width, guidance_scale=5.5
    ).frames[0]
    export_to_video(output, "output.mp4", fps=16)

###
Any-to-Video Controllable Generation

Wan VACE supports various generation techniques which achieve controllable video generation. Some of the capabilities include:

- Control to Video (Depth, Pose, Sketch, Flow, Grayscale, Scribble, Layout, Boundary Box, etc.). Recommended library for preprocessing videos to obtain control videos: huggingface/controlnet_aux
- Image/Video to Video (first frame, last frame, starting clip, ending clip, random clips)
- Inpainting and Outpainting
- Subject to Video (faces, object, characters, etc.)
- Composition to Video (reference anything, animate anything, swap anything, expand anything, move anything, etc.)

The code snippets available in this pull request demonstrate some examples of how videos can be generated with controllability signals.

The general rule of thumb to keep in mind when preparing inputs for the VACE pipeline is that the input images, or frames of a video that you want to use for conditioning, should have a corresponding mask that is black in color. The black mask signifies that the model will not generate new content for that area, and only use those parts for conditioning the generation process. For parts/frames that should be generated by the model, the mask should be white in color.

##
Notes

- Wan2.1 supports LoRAs with load_lora_weights().

  Show example code

      # pip install ftfy
      import torch
      from diffusers import AutoModel, WanPipeline
      from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
      from diffusers.utils import export_to_video

      vae = AutoModel.from_pretrained(
          "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", subfolder="vae", torch_dtype=torch.float32
      )
      pipeline = WanPipeline.from_pretrained(
          "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", vae=vae, torch_dtype=torch.bfloat16
      )
      pipeline.scheduler = UniPCMultistepScheduler.from_config(
          pipeline.scheduler.config, flow_shift=5.0
      )
      pipeline.to("cuda")

      pipeline.load_lora_weights("benjamin-paine/steamboat-willie-1.3b", adapter_name="steamboat-willie")
      pipeline.set_adapters("steamboat-willie")

      pipeline.enable_model_cpu_offload()

      # use "steamboat willie style" to trigger the LoRA
      prompt = """
      steamboat willie style, golden era animation, The camera rushes from far to near in a low-angle shot,
      revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in
      for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground.
      Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic
      shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
      """

      output = pipeline(
          prompt=prompt,
          num_frames=81,
          guidance_scale=5.0,
      ).frames[0]
      export_to_video(output, "output.mp4", fps=16)

- WanTransformer3DModel and AutoencoderKLWan supports loading from single files with from_single_file().

  Show example code

      # pip install ftfy
      import torch
      from diffusers import WanPipeline, WanTransformer3DModel, AutoencoderKLWan

      vae = AutoencoderKLWan.from_single_file(
          "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/blob/main/split_files/vae/wan_2.1_vae.safetensors"
      )
      transformer = WanTransformer3DModel.from_single_file(
          "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/blob/main/split_files/diffusion_models/wan2.1_t2v_1.3B_bf16.safetensors",
          torch_dtype=torch.bfloat16
      )
      pipeline = WanPipeline.from_pretrained(
          "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
          vae=vae,
          transformer=transformer,
          torch_dtype=torch.bfloat16
      )

- Set the AutoencoderKLWan dtype to `torch.float32` for better decoding quality.

- The number of frames per second (fps) or `k` should be calculated by `4 * k + 1`.

- Try lower `shift` values (`2.0` to `5.0`) for lower resolution videos and higher `shift` values (`7.0` to `12.0`) for higher resolution images.

- Wan 2.1 and 2.2 support using LightX2V LoRAs to speed up inference. Using them on Wan 2.2 is slightly more involed. Refer to this code snippet to learn more.

- Wan 2.2 has two denoisers. By default, LoRAs are only loaded into the first denoiser. One can set `load_into_transformer_2=True` to load LoRAs into the second denoiser. Refer to this and this examples to learn more.

##
WanPipeline

###
class diffusers.WanPipeline

< source >

( tokenizer: AutoTokenizer text_encoder: UMT5EncoderModel vae: AutoencoderKLWan scheduler: FlowMatchEulerDiscreteScheduler transformer: typing.Optional[diffusers.models.transformers.transformer_wan.WanTransformer3DModel] = None transformer_2: typing.Optional[diffusers.models.transformers.transformer_wan.WanTransformer3DModel] = None boundary_ratio: typing.Optional[float] = None expand_timesteps: bool = False )

Parameters

- tokenizer (`T5Tokenizer`) — Tokenizer from T5, specifically the google/umt5-xxl variant.
- text_encoder (`T5EncoderModel`) — T5, specifically the google/umt5-xxl variant.
- transformer (WanTransformer3DModel) — 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.
- transformer_2 (WanTransformer3DModel, optional) — Conditional Transformer to denoise the input latents during the low-noise stage. If provided, enables two-stage denoising where `transformer` handles high-noise stages and `transformer_2` handles low-noise stages. If not provided, only `transformer` is used.
- boundary_ratio (`float`, optional, defaults to `None`) — Ratio of total timesteps to use as the boundary for switching between transformers in two-stage denoising. The actual boundary timestep is calculated as `boundary_ratio * num_train_timesteps`. When provided, `transformer` handles timesteps >= boundary_timestep and `transformer_2` handles timesteps < boundary_timestep. If `None`, only `transformer` is used for the entire denoising process.

Pipeline for text-to-video generation using Wan.

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.).

####
__call__

< source >

( prompt: typing.Union[str, typing.List[str]] = None negative_prompt: typing.Union[str, typing.List[str]] = None height: int = 480 width: int = 832 num_frames: int = 81 num_inference_steps: int = 50 guidance_scale: float = 5.0 guidance_scale_2: typing.Optional[float] = None num_videos_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'np' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) →
`~WanPipelineOutput` or `tuple`

Parameters

- prompt (`str` or `List[str]`, optional) — The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
- negative_prompt (`str` or `List[str]`, optional) — The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale` < `1`).
- height (`int`, defaults to `480`) — The height in pixels of the generated image.
- width (`int`, defaults to `832`) — The width in pixels of the generated image.
- num_frames (`int`, defaults to `81`) — 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. `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.
- guidance_scale_2 (`float`, optional, defaults to `None`) — Guidance scale for the low-noise stage transformer (`transformer_2`). If `None` and the pipeline’s `boundary_ratio` is not None, uses the same value as `guidance_scale`. Only used when `transformer_2` and the pipeline’s `boundary_ratio` are not None.
- num_videos_per_prompt (`int`, optional, defaults to 1) — The number of images to generate per prompt.
- generator (`torch.Generator` or `List[torch.Generator]`, optional) — A `torch.Generator` to make generation deterministic.
- latents (`torch.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 (`torch.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 `True`) — 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.
- 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`, defaults to `512`) — The maximum sequence length of the text encoder. If the prompt is longer than this, it will be truncated. If the prompt is shorter, it will be padded to this length.

Returns

`~WanPipelineOutput` or `tuple`

If `return_dict` is `True`, `WanPipelineOutput` 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.

The call function to the pipeline for generation.

Examples:

    >>> import torch
    >>> from diffusers.utils import export_to_video
    >>> from diffusers import AutoencoderKLWan, WanPipeline
    >>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler

    >>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
    >>> model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
    >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
    >>> pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
    >>> flow_shift = 5.0  # 5.0 for 720P, 3.0 for 480P
    >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
    >>> pipe.to("cuda")

    >>> 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."
    >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"

    >>> output = pipe(
    ...     prompt=prompt,
    ...     negative_prompt=negative_prompt,
    ...     height=720,
    ...     width=1280,
    ...     num_frames=81,
    ...     guidance_scale=5.0,
    ... ).frames[0]
    >>> export_to_video(output, "output.mp4", fps=16)

####
encode_prompt

< source >

( prompt: typing.Union[str, typing.List[str]] negative_prompt: typing.Union[str, typing.List[str], NoneType] = None do_classifier_free_guidance: bool = True num_videos_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None max_sequence_length: int = 226 device: typing.Optional[torch.device] = None dtype: typing.Optional[torch.dtype] = None )

Parameters

- 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

Encodes the prompt into text encoder hidden states.

##
WanImageToVideoPipeline

###
class diffusers.WanImageToVideoPipeline

< source >

( tokenizer: AutoTokenizer text_encoder: UMT5EncoderModel vae: AutoencoderKLWan scheduler: FlowMatchEulerDiscreteScheduler image_processor: CLIPImageProcessor = None image_encoder: CLIPVisionModel = None transformer: WanTransformer3DModel = None transformer_2: WanTransformer3DModel = None boundary_ratio: typing.Optional[float] = None expand_timesteps: bool = False )

Parameters

- tokenizer (`T5Tokenizer`) — Tokenizer from T5, specifically the google/umt5-xxl variant.
- text_encoder (`T5EncoderModel`) — T5, specifically the google/umt5-xxl variant.
- image_encoder (`CLIPVisionModel`) — CLIP, specifically the clip-vit-huge-patch14 variant.
- transformer (WanTransformer3DModel) — 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.
- transformer_2 (WanTransformer3DModel, optional) — Conditional Transformer to denoise the input latents during the low-noise stage. In two-stage denoising, `transformer` handles high-noise stages and `transformer_2` handles low-noise stages. If not provided, only `transformer` is used.
- boundary_ratio (`float`, optional, defaults to `None`) — Ratio of total timesteps to use as the boundary for switching between transformers in two-stage denoising. The actual boundary timestep is calculated as `boundary_ratio * num_train_timesteps`. When provided, `transformer` handles timesteps >= boundary_timestep and `transformer_2` handles timesteps < boundary_timestep. If `None`, only `transformer` is used for the entire denoising process.

Pipeline for image-to-video generation using Wan.

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.).

####
__call__

< source >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] prompt: typing.Union[str, typing.List[str]] = None negative_prompt: typing.Union[str, typing.List[str]] = None height: int = 480 width: int = 832 num_frames: int = 81 num_inference_steps: int = 50 guidance_scale: float = 5.0 guidance_scale_2: typing.Optional[float] = None num_videos_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None image_embeds: typing.Optional[torch.Tensor] = None last_image: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'np' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) →
`~WanPipelineOutput` or `tuple`

Parameters

- image (`PipelineImageInput`) — The input image to condition the generation on. Must be an image, a list of images or a `torch.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 `480`) — The height of the generated video.
- width (`int`, defaults to `832`) — The width of the generated video.
- num_frames (`int`, defaults to `81`) — 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. `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.
- guidance_scale_2 (`float`, optional, defaults to `None`) — Guidance scale for the low-noise stage transformer (`transformer_2`). If `None` and the pipeline’s `boundary_ratio` is not None, uses the same value as `guidance_scale`. Only used when `transformer_2` and the pipeline’s `boundary_ratio` are not None.
- num_videos_per_prompt (`int`, optional, defaults to 1) — The number of images to generate per prompt.
- generator (`torch.Generator` or `List[torch.Generator]`, optional) — A `torch.Generator` to make generation deterministic.
- latents (`torch.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 (`torch.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 (`torch.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 (`torch.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 `True`) — 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.
- 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`, defaults to `512`) — The maximum sequence length of the text encoder. If the prompt is longer than this, it will be truncated. If the prompt is shorter, it will be padded to this length.

Returns

`~WanPipelineOutput` or `tuple`

If `return_dict` is `True`, `WanPipelineOutput` 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.

The call function to the pipeline for generation.

Examples:

    >>> import torch
    >>> import numpy as np
    >>> from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
    >>> from diffusers.utils import export_to_video, load_image
    >>> from transformers import CLIPVisionModel

    >>> # Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers
    >>> model_id = "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers"
    >>> image_encoder = CLIPVisionModel.from_pretrained(
    ...     model_id, subfolder="image_encoder", torch_dtype=torch.float32
    ... )
    >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
    >>> pipe = WanImageToVideoPipeline.from_pretrained(
    ...     model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16
    ... )
    >>> pipe.to("cuda")

    >>> image = load_image(
    ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
    ... )
    >>> max_area = 480 * 832
    >>> aspect_ratio = image.height / image.width
    >>> mod_value = pipe.vae_scale_factor_spatial * pipe.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))
    >>> prompt = (
    ...     "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
    ...     "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
    ... )
    >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"

    >>> output = pipe(
    ...     image=image,
    ...     prompt=prompt,
    ...     negative_prompt=negative_prompt,
    ...     height=height,
    ...     width=width,
    ...     num_frames=81,
    ...     guidance_scale=5.0,
    ... ).frames[0]
    >>> export_to_video(output, "output.mp4", fps=16)

####
encode_prompt

< source >

( prompt: typing.Union[str, typing.List[str]] negative_prompt: typing.Union[str, typing.List[str], NoneType] = None do_classifier_free_guidance: bool = True num_videos_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None max_sequence_length: int = 226 device: typing.Optional[torch.device] = None dtype: typing.Optional[torch.dtype] = None )

Parameters

- 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

Encodes the prompt into text encoder hidden states.

##
WanVACEPipeline

###
class diffusers.WanVACEPipeline

< source >

( tokenizer: AutoTokenizer text_encoder: UMT5EncoderModel transformer: WanVACETransformer3DModel vae: AutoencoderKLWan scheduler: FlowMatchEulerDiscreteScheduler transformer_2: WanVACETransformer3DModel = None boundary_ratio: typing.Optional[float] = None )

Parameters

- tokenizer (`T5Tokenizer`) — Tokenizer from T5, specifically the google/umt5-xxl variant.
- text_encoder (`T5EncoderModel`) — T5, specifically the google/umt5-xxl variant.
- transformer (`WanVACETransformer3DModel`) — Conditional Transformer to denoise the input latents.
- transformer_2 (`WanVACETransformer3DModel`, optional) — Conditional Transformer to denoise the input latents during the low-noise stage. In two-stage denoising, `transformer` handles high-noise stages and `transformer_2` handles low-noise stages. If not provided, only `transformer` is used.
- 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.
- boundary_ratio (`float`, optional, defaults to `None`) — Ratio of total timesteps to use as the boundary for switching between transformers in two-stage denoising. The actual boundary timestep is calculated as `boundary_ratio * num_train_timesteps`. When provided, `transformer` handles timesteps >= boundary_timestep and `transformer_2` handles timesteps < boundary_timestep. If `None`, only `transformer` is used for the entire denoising process.

Pipeline for controllable generation using Wan.

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.).

####
__call__

< source >

( prompt: typing.Union[str, typing.List[str]] = None negative_prompt: typing.Union[str, typing.List[str]] = None video: typing.Optional[typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]]] = None mask: typing.Optional[typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]]] = None reference_images: typing.Optional[typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]]] = None conditioning_scale: typing.Union[float, typing.List[float], torch.Tensor] = 1.0 height: int = 480 width: int = 832 num_frames: int = 81 num_inference_steps: int = 50 guidance_scale: float = 5.0 guidance_scale_2: typing.Optional[float] = None num_videos_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'np' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) →
`~WanPipelineOutput` or `tuple`

Parameters

- 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`).
- video (`List[PIL.Image.Image]`, optional) — The input video or videos to be used as a starting point for the generation. The video should be a list of PIL images, a numpy array, or a torch tensor. Currently, the pipeline only supports generating one video at a time.
- mask (`List[PIL.Image.Image]`, optional) — The input mask defines which video regions to condition on and which to generate. Black areas in the mask indicate conditioning regions, while white areas indicate regions for generation. The mask should be a list of PIL images, a numpy array, or a torch tensor. Currently supports generating a single video at a time.
- reference_images (`List[PIL.Image.Image]`, optional) — A list of one or more reference images as extra conditioning for the generation. For example, if you are trying to inpaint a video to change the character, you can pass reference images of the new character here. Refer to the Diffusers examples and original user guide for a full list of supported tasks and use cases.
- conditioning_scale (`float`, `List[float]`, `torch.Tensor`, defaults to `1.0`) — The conditioning scale to be applied when adding the control conditioning latent stream to the denoising latent stream in each control layer of the model. If a float is provided, it will be applied uniformly to all layers. If a list or tensor is provided, it should have the same length as the number of control layers in the model (`len(transformer.config.vace_layers)`).
- height (`int`, defaults to `480`) — The height in pixels of the generated image.
- width (`int`, defaults to `832`) — The width in pixels of the generated image.
- num_frames (`int`, defaults to `81`) — 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. `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.
- guidance_scale_2 (`float`, optional, defaults to `None`) — Guidance scale for the low-noise stage transformer (`transformer_2`). If `None` and the pipeline’s `boundary_ratio` is not None, uses the same value as `guidance_scale`. Only used when `transformer_2` and the pipeline’s `boundary_ratio` are not None.
- num_videos_per_prompt (`int`, optional, defaults to 1) — The number of images to generate per prompt.
- generator (`torch.Generator` or `List[torch.Generator]`, optional) — A `torch.Generator` to make generation deterministic.
- latents (`torch.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 (`torch.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 `True`) — 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.
- 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`, defaults to `512`) — The maximum sequence length of the text encoder. If the prompt is longer than this, it will be truncated. If the prompt is shorter, it will be padded to this length.

Returns

`~WanPipelineOutput` or `tuple`

If `return_dict` is `True`, `WanPipelineOutput` 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.

The call function to the pipeline for generation.

Examples:

    >>> import torch
    >>> import PIL.Image
    >>> from diffusers import AutoencoderKLWan, WanVACEPipeline
    >>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
    >>> from diffusers.utils import export_to_video, load_image
    def prepare_video_and_mask(first_img: PIL.Image.Image, last_img: PIL.Image.Image, height: int, width: int, num_frames: int):
        first_img = first_img.resize((width, height))
        last_img = last_img.resize((width, height))
        frames = []
        frames.append(first_img)
        # Ideally, this should be 127.5 to match original code, but they perform computation on numpy arrays
        # whereas we are passing PIL images. If you choose to pass numpy arrays, you can set it to 127.5 to
        # match the original code.
        frames.extend([PIL.Image.new("RGB", (width, height), (128, 128, 128))] * (num_frames - 2))
        frames.append(last_img)
        mask_black = PIL.Image.new("L", (width, height), 0)
        mask_white = PIL.Image.new("L", (width, height), 255)
        mask = [mask_black, *[mask_white] * (num_frames - 2), mask_black]
        return frames, mask

    >>> # Available checkpoints: Wan-AI/Wan2.1-VACE-1.3B-diffusers, Wan-AI/Wan2.1-VACE-14B-diffusers
    >>> model_id = "Wan-AI/Wan2.1-VACE-1.3B-diffusers"
    >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
    >>> pipe = WanVACEPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
    >>> flow_shift = 3.0  # 5.0 for 720P, 3.0 for 480P
    >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
    >>> pipe.to("cuda")

    >>> 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."
    >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
    >>> 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>>> "
    ... )

    >>> height = 512
    >>> width = 512
    >>> num_frames = 81
    >>> video, mask = prepare_video_and_mask(first_frame, last_frame, height, width, num_frames)

    >>> output = pipe(
    ...     video=video,
    ...     mask=mask,
    ...     prompt=prompt,
    ...     negative_prompt=negative_prompt,
    ...     height=height,
    ...     width=width,
    ...     num_frames=num_frames,
    ...     num_inference_steps=30,
    ...     guidance_scale=5.0,
    ...     generator=torch.Generator().manual_seed(42),
    ... ).frames[0]
    >>> export_to_video(output, "output.mp4", fps=16)

####
encode_prompt

< source >

( prompt: typing.Union[str, typing.List[str]] negative_prompt: typing.Union[str, typing.List[str], NoneType] = None do_classifier_free_guidance: bool = True num_videos_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None max_sequence_length: int = 226 device: typing.Optional[torch.device] = None dtype: typing.Optional[torch.dtype] = None )

Parameters

- 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

Encodes the prompt into text encoder hidden states.

##
WanVideoToVideoPipeline

###
class diffusers.WanVideoToVideoPipeline

< source >

( tokenizer: AutoTokenizer text_encoder: UMT5EncoderModel transformer: WanTransformer3DModel vae: AutoencoderKLWan scheduler: FlowMatchEulerDiscreteScheduler )

Parameters

- tokenizer (`T5Tokenizer`) — Tokenizer from T5, specifically the google/umt5-xxl variant.
- text_encoder (`T5EncoderModel`) — T5, specifically the google/umt5-xxl variant.
- transformer (WanTransformer3DModel) — 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.

Pipeline for video-to-video generation using Wan.

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.).

####
__call__

< source >

( video: typing.List[PIL.Image.Image] = None prompt: typing.Union[str, typing.List[str]] = None negative_prompt: typing.Union[str, typing.List[str]] = None height: int = 480 width: int = 832 num_inference_steps: int = 50 timesteps: typing.Optional[typing.List[int]] = None guidance_scale: float = 5.0 strength: float = 0.8 num_videos_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'np' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 512 ) →
`~WanPipelineOutput` or `tuple`

Parameters

- 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 `480`) — The height in pixels of the generated image.
- width (`int`, defaults to `832`) — The width in pixels of the generated image.
- num_frames (`int`, defaults to `81`) — 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. `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.
- strength (`float`, defaults to `0.8`) — Higher strength leads to more differences between original image and generated video.
- num_videos_per_prompt (`int`, optional, defaults to 1) — The number of images to generate per prompt.
- generator (`torch.Generator` or `List[torch.Generator]`, optional) — A `torch.Generator` to make generation deterministic.
- latents (`torch.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 (`torch.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 `True`) — 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.
- 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`, defaults to `512`) — The maximum sequence length of the text encoder. If the prompt is longer than this, it will be truncated. If the prompt is shorter, it will be padded to this length.

Returns

`~WanPipelineOutput` or `tuple`

If `return_dict` is `True`, `WanPipelineOutput` 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.

The call function to the pipeline for generation.

Examples:

    >>> import torch
    >>> from diffusers.utils import export_to_video
    >>> from diffusers import AutoencoderKLWan, WanVideoToVideoPipeline
    >>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler

    >>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
    >>> model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
    >>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
    >>> pipe = WanVideoToVideoPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
    >>> flow_shift = 3.0  # 5.0 for 720P, 3.0 for 480P
    >>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
    >>> pipe.to("cuda")

    >>> prompt = "A robot standing on a mountain top. The sun is setting in the background"
    >>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
    >>> video = load_video(
    ...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
    ... )
    >>> output = pipe(
    ...     video=video,
    ...     prompt=prompt,
    ...     negative_prompt=negative_prompt,
    ...     height=480,
    ...     width=720,
    ...     guidance_scale=5.0,
    ...     strength=0.7,
    ... ).frames[0]
    >>> export_to_video(output, "output.mp4", fps=16)

####
encode_prompt

< source >

( prompt: typing.Union[str, typing.List[str]] negative_prompt: typing.Union[str, typing.List[str], NoneType] = None do_classifier_free_guidance: bool = True num_videos_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None max_sequence_length: int = 226 device: typing.Optional[torch.device] = None dtype: typing.Optional[torch.dtype] = None )

Parameters

- 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

Encodes the prompt into text encoder hidden states.

##
WanPipelineOutput

###
class diffusers.pipelines.wan.pipeline_output.WanPipelineOutput

< source >

( frames: Tensor )

Parameters

- frames (`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)`.

Output class for Wan pipelines.

Update on GitHub