Buckets:
| # Generación de video | |
| Los modelos de generación de video extienden la generación de imágenes (que puede considerarse un video de un solo fotograma) para procesar también datos relacionados con el espacio y el tiempo. Asegurar que todos estos datos, texto, espacio y tiempo, permanezcan consistentes y alineados de un fotograma a otro es un gran desafío a la hora de generar videos largos y de alta resolución. | |
| Los modelos de video modernos abordan este desafío con la arquitectura de transformador de difusión (DiT). Esto reduce los costos computacionales y permite una escalabilidad más eficiente hacia datos de imágenes y videos más grandes y de mayor calidad. | |
| A continuación, echa un vistazo a lo que son capaces de hacer algunos de estos modelos de video. | |
| ```py | |
| # pip install ftfy | |
| import torch | |
| import numpy as np | |
| from diffusers import AutoModel, WanPipeline | |
| 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", dtype=torch.bfloat16) | |
| vae = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32) | |
| transformer = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", 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, | |
| dtype=torch.bfloat16 | |
| ) | |
| pipeline.to("cuda") # or "mps", "xpu", "cpu" | |
| 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) | |
| ``` | |
| ```py | |
| import torch | |
| from diffusers importAutoModel, HunyuanVideoPipeline | |
| from diffusers.quantizers import PipelineQuantizationConfig | |
| from diffusers.utils import export_to_video | |
| # quantize weights to int4 with bitsandbytes | |
| pipeline_quant_config = PipelineQuantizationConfig( | |
| quant_backend="bitsandbytes_4bit", | |
| quant_kwargs={ | |
| "load_in_4bit": True, | |
| "bnb_4bit_quant_type": "nf4", | |
| "bnb_4bit_compute_dtype": torch.bfloat16 | |
| }, | |
| components_to_quantize="transformer" | |
| ) | |
| pipeline = HunyuanVideoPipeline.from_pretrained( | |
| "hunyuanvideo-community/HunyuanVideo", | |
| quantization_config=pipeline_quant_config, | |
| dtype=torch.bfloat16, | |
| ) | |
| # model-offloading and tiling | |
| pipeline.enable_model_cpu_offload() | |
| pipeline.vae.enable_tiling() | |
| prompt = "A fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys." | |
| video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0] | |
| export_to_video(video, "output.mp4", fps=15) | |
| ``` | |
| ```py | |
| import torch | |
| from diffusers import LTXPipeline, AutoModel | |
| from diffusers.hooks import apply_group_offloading | |
| from diffusers.utils import export_to_video | |
| # fp8 layerwise weight-casting | |
| transformer = AutoModel.from_pretrained( | |
| "Lightricks/LTX-Video", | |
| subfolder="transformer", | |
| dtype=torch.bfloat16 | |
| ) | |
| transformer.enable_layerwise_casting( | |
| storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16 | |
| ) | |
| pipeline = LTXPipeline.from_pretrained("Lightricks/LTX-Video", transformer=transformer, dtype=torch.bfloat16) | |
| # group-offloading | |
| onload_device = torch.device("cuda") | |
| offload_device = torch.device("cpu") | |
| pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_device=offload_device, offload_type="leaf_level", use_stream=True) | |
| apply_group_offloading(pipeline.text_encoder, onload_device=onload_device, offload_type="block_level", num_blocks_per_group=2) | |
| apply_group_offloading(pipeline.vae, onload_device=onload_device, offload_type="leaf_level") | |
| prompt = """ | |
| A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage | |
| """ | |
| negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted" | |
| video = pipeline( | |
| prompt=prompt, | |
| negative_prompt=negative_prompt, | |
| width=768, | |
| height=512, | |
| num_frames=161, | |
| decode_timestep=0.03, | |
| decode_noise_scale=0.025, | |
| num_inference_steps=50, | |
| ).frames[0] | |
| export_to_video(video, "output.mp4", fps=24) | |
| ``` | |
| Esta guía cubrirá los fundamentos de la generación de video, como qué parámetros configurar y cómo reducir su uso de memoria. | |
| > [!TIP] | |
| > Si te interesa aprender más sobre cómo usar un modelo específico, consulta la tarjeta de modelo de su API de pipeline. | |
| ## Parámetros de la pipeline | |
| Hay varios parámetros que configurar en el pipeline que afectarán a la calidad o la velocidad de la generación de video. Experimentar con diferentes valores de parámetros es importante para descubrir el equilibrio adecuado entre calidad y velocidad. | |
| ### num_frames | |
| Un fotograma es una imagen fija que se reproduce en una secuencia de otros fotogramas para crear movimiento o un video. Controle el número de fotogramas generados por segundo con `num_frames`. Aumentar `num_frames` mejora la suavidad percibida del movimiento y la coherencia visual, lo que es especialmente importante para videos con contenido dinámico. Un valor más alto de `num_frames` también aumenta la duración del video. | |
| Algunos modelos de vídeo requieren valores más específicos de `num_frames` para la inferencia. Por ejemplo, [HunyuanVideoPipeline](/docs/diffusers/main/es/api/pipelines/hunyuan_video#diffusers.HunyuanVideoPipeline) recomienda calcular `num_frames` con `(4 * num_frames) +1`. Consulta siempre la tarjeta de modelo de la API de un pipeline para ver si hay un valor recomendado. | |
| ```py | |
| import torch | |
| from diffusers import LTXPipeline | |
| from diffusers.utils import export_to_video | |
| pipeline = LTXPipeline.from_pretrained( | |
| "Lightricks/LTX-Video", dtype=torch.bfloat16 | |
| ).to("cuda") # or "mps", "xpu", "cpu" | |
| prompt = """ | |
| A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman | |
| with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The | |
| camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and | |
| natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be | |
| real-life footage | |
| """ | |
| video = pipeline( | |
| prompt=prompt, | |
| negative_prompt=negative_prompt, | |
| width=768, | |
| height=512, | |
| num_frames=161, | |
| decode_timestep=0.03, | |
| decode_noise_scale=0.025, | |
| num_inference_steps=50, | |
| ).frames[0] | |
| export_to_video(video, "output.mp4", fps=24) | |
| ``` | |
| ### guidance_scale | |
| La escala de guía o "cfg" controla hasta qué punto los fotogramas generados se ajustan a la condición de entrada (texto, imagen o ambos). Aumentar `guidance_scale` genera fotogramas que se asemejan más a las condiciones de entrada e incluyen detalles más finos, pero con el riesgo de introducir artefactos y reducir la diversidad de la salida. Valores más bajos de `guidance_scale` fomentan un ajuste más laxo al prompt y una mayor variedad en la salida, aunque los detalles pueden no ser tan buenos. Si es demasiado bajo, es posible que ignore por completo el prompt y genere ruido aleatorio. | |
| ```py | |
| import torch | |
| from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel | |
| from diffusers.utils import export_to_video | |
| pipeline = CogVideoXPipeline.from_pretrained( | |
| "THUDM/CogVideoX-2b", | |
| dtype=torch.float16 | |
| ).to("cuda") # or "mps", "xpu", "cpu" | |
| prompt = """ | |
| A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over | |
| a plush, blue carpet that mimics the waves of the sea. The ship's hull is painted a rich brown, | |
| with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an | |
| oceanic expanse. Surrounding the ship are various other toys and children's items, hinting at | |
| a playful environment. The scene captures the innocence and imagination of childhood, | |
| with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting. | |
| """ | |
| video = pipeline( | |
| prompt=prompt, | |
| guidance_scale=6, | |
| num_inference_steps=50 | |
| ).frames[0] | |
| export_to_video(video, "output.mp4", fps=8) | |
| ``` | |
| ### negative_prompt | |
| Un prompt negativo es útil para excluir elementos que no deseas ver en el video generado. Se utiliza comúnmente para refinar la calidad y la alineación del video generado, alejando al modelo de elementos no deseados como "blurry, distorted, ugly". Esto puede crear videos más limpios y enfocados. | |
| ```py | |
| # pip install ftfy | |
| import torch | |
| from diffusers import WanPipeline | |
| from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler | |
| from diffusers.utils import export_to_video | |
| vae = AutoencoderKLWan.from_pretrained( | |
| "Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32 | |
| ) | |
| pipeline = WanPipeline.from_pretrained( | |
| "Wan-AI/Wan2.1-T2V-14B-Diffusers", vae=vae, dtype=torch.bfloat16 | |
| ) | |
| pipeline.scheduler = UniPCMultistepScheduler.from_config( | |
| pipeline.scheduler.config, flow_shift=5.0 | |
| ) | |
| pipeline.to("cuda") # or "mps", "xpu", "cpu" | |
| pipeline.load_lora_weights("benjamin-paine/steamboat-willie-14b", 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) | |
| ``` | |
| ## Reducir el uso de memoria | |
| Los modelos de video recientes, como [HunyuanVideoPipeline](/docs/diffusers/main/es/api/pipelines/hunyuan_video#diffusers.HunyuanVideoPipeline) y [WanPipeline](/docs/diffusers/main/es/api/pipelines/wan#diffusers.WanPipeline), que tienen más de 10 mil millones de parámetros, requieren mucha memoria y a menudo superan la memoria disponible en el hardware de consumo. Diffusers ofrece varias técnicas para reducir los requisitos de memoria de estos modelos grandes. | |
| > [!TIP] | |
| > Consulte la guía [Reduce memory usage](../optimization/memory) para obtener más detalles sobre otras técnicas de ahorro de memoria. | |
| Una de estas técnicas es [group-offloading](../optimization/memory#group-offloading), que descarga grupos de capas internas del modelo (como `torch.nn.Sequential`) a la CPU cuando no se están utilizando. Estas capas solo se cargan cuando son necesarias para el cálculo, evitando así almacenar **todos** los componentes del modelo en la GPU. Para un modelo de 14B parámetros como [WanPipeline](/docs/diffusers/main/es/api/pipelines/wan#diffusers.WanPipeline), el group-offloading puede reducir la memoria requerida a ~13GB de VRAM. | |
| ```py | |
| # pip install ftfy | |
| import torch | |
| import numpy as np | |
| from diffusers import AutoModel, WanPipeline | |
| 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", dtype=torch.bfloat16) | |
| vae = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32) | |
| transformer = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", 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, | |
| dtype=torch.bfloat16 | |
| ) | |
| pipeline.to("cuda") # or "mps", "xpu", "cpu" | |
| 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) | |
| ``` | |
| Otra opción para reducir la memoria es considerar la cuantización de un modelo, que almacena los pesos del modelo en un tipo de datos de menor precisión. Sin embargo, la cuantización puede afectar la calidad del vídeo dependiendo del modelo de vídeo específico. Consulte el [Resumen](../quantization/overview) de la cuantización para obtener más información sobre los diferentes backends de cuantización admitidos. | |
| El ejemplo siguiente utiliza [bitsandbytes](../quantization/bitsandbytes) para cuantizar un modelo. | |
| ```py | |
| # pip install ftfy | |
| import torch | |
| from diffusers import WanPipeline | |
| from diffusers import AutoModel, WanPipeline | |
| from diffusers.quantizers import PipelineQuantizationConfig | |
| from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler | |
| from transformers import UMT5EncoderModel | |
| from diffusers.utils import export_to_video | |
| # quantize transformer and text encoder weights with bitsandbytes | |
| pipeline_quant_config = PipelineQuantizationConfig( | |
| quant_backend="bitsandbytes_4bit", | |
| quant_kwargs={"load_in_4bit": True}, | |
| components_to_quantize=["transformer", "text_encoder"] | |
| ) | |
| vae = AutoModel.from_pretrained( | |
| "Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32 | |
| ) | |
| pipeline = WanPipeline.from_pretrained( | |
| "Wan-AI/Wan2.1-T2V-14B-Diffusers", vae=vae, quantization_config=pipeline_quant_config, dtype=torch.bfloat16 | |
| ) | |
| pipeline.scheduler = UniPCMultistepScheduler.from_config( | |
| pipeline.scheduler.config, flow_shift=5.0 | |
| ) | |
| pipeline.to("cuda") # or "mps", "xpu", "cpu" | |
| pipeline.load_lora_weights("benjamin-paine/steamboat-willie-14b", 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) | |
| ``` | |
| ## Velocidad de inferencia | |
| [torch.compile](https://docs.pytorch.org/tutorials/intermediate/torch_compile_tutorial.html) puede acelerar la inferencia mediante el uso de kernels optimizados. La compilación tarda más la primera vez, pero una vez compilado, es mucho más rápido. Lo ideal es compilar el pipeline una sola vez y luego usarlo múltiples veces sin cambiar nada. Un cambio, como en el tamaño de la imagen, provoca una recompilación. | |
| El siguiente ejemplo compila el transformer en el pipeline y usa el modo `"max-autotune"` para maximizar el rendimiento. | |
| ```py | |
| import torch | |
| from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel | |
| from diffusers.utils import export_to_video | |
| pipeline = CogVideoXPipeline.from_pretrained( | |
| "THUDM/CogVideoX-2b", | |
| dtype=torch.float16 | |
| ).to("cuda") # or "mps", "xpu", "cpu" | |
| # torch.compile | |
| pipeline.transformer.to(memory_format=torch.channels_last) | |
| pipeline.transformer = torch.compile( | |
| pipeline.transformer, mode="max-autotune", fullgraph=True | |
| ) | |
| prompt = """ | |
| A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. | |
| The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. | |
| Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, | |
| with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting. | |
| """ | |
| video = pipeline( | |
| prompt=prompt, | |
| guidance_scale=6, | |
| num_inference_steps=50 | |
| ).frames[0] | |
| export_to_video(video, "output.mp4", fps=8) | |
| ``` | |
Xet Storage Details
- Size:
- 19.3 kB
- Xet hash:
- 1e8879e6e433cd3cdd54923205e2c6b9b0859e66e8efb8b0e36389827254e0ca
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.