Buckets:

mishig's picture
|
download
raw
7.7 kB
# Introducción
Diffusers es una biblioteca para desarrolladores e investigadores que proporciona una API de inferencia sencilla para generar imágenes, videos y audio, así como los bloques de construcción para implementar nuevos flujos de trabajo.
Diffusers ofrece muchas optimizaciones de serie que permiten cargar y ejecutar modelos grandes en configuraciones con memoria limitada o acelerar la inferencia.
Este tutorial de iniciación te dará una visión general de Diffusers y te permitirá empezar a generar contenido rápidamente.
> [!TIP]
> Antes de comenzar, asegúrate de tener una [cuenta](https://huggingface.co/join) de Hugging Face para usar modelos con acceso restringido como [Flux](https://huggingface.co/black-forest-labs/FLUX.1-dev). ¿Prefieres construir un pipeline personalizado? Consulta la [introducción rápida a Modular Diffusers](./modular_diffusers/quickstart) y el [resumen](./modular_diffusers/overview).
Sigue la guía de [Instalación](./installation) para instalar Diffusers si aún no está instalado.
## Prompt del agente
Pega esto en tu agente de codificación para configurar Diffusers para inferencia.
```text
Help me get set up with Hugging Face Diffusers for inference.
1. Install Diffusers for my environment with `uv pip install "diffusers[torch]"`.
2. If I need gated Hub models, help me authenticate to the Hugging Face Hub.
3. Install Diffusers coding agent skills with `diffusers-cli skills add diffusers-cli`. Pass `--cursor`, `--claude`, or `--codex` if auto-detect fails. Optionally pass `--all` to install every skill in the registry.
4. Run a first text-to-image with DiffusionPipeline or `diffusers-cli run`, using a small or current Quickstart model and the right `device_map` for my machine.
5. Ask what I want next and point me at the matching docs.
```
## DiffusionPipeline
[DiffusionPipeline](/docs/diffusers/v0.43.0/es/api/pipelines/overview#diffusers.DiffusionPipeline) agrupa los componentes de un modelo de difusión (codificador de texto, programador, UNet o DiT y VAE) en una sola clase para la inferencia. Cargue con [from_pretrained()](/docs/diffusers/v0.43.0/es/api/pipelines/overview#diffusers.DiffusionPipeline.from_pretrained) y luego llame a la tubería.
Los argumentos de `__call__()` como `num_inference_steps` cambian la calidad y la velocidad. Para ver los detalles de carga y los componentes combinables, consulte [Cargar pipelines](./using-diffusers/loading). Para cambiar el programador, consulte [Programadores](./using-diffusers/schedulers).
Los ejemplos a continuación utilizan los valores de argumento predeterminados.
Use `.images[0]` para acceder a la imagen generada.
```py
import torch
from diffusers import DiffusionPipeline
pipeline = DiffusionPipeline.from_pretrained(
"Qwen/Qwen-Image", dtype=torch.bfloat16, device_map="cuda" # or "mps", "xpu", "cpu"
)
prompt = """
cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
"""
pipeline(prompt).images[0]
```
Use `.frames[0]` para acceder a la salida del video generado y [export_to_video()](/docs/diffusers/v0.43.0/es/api/utilities#diffusers.utils.export_to_video) para guardar el video.
```py
import torch
from diffusers import AutoencoderKLWan, DiffusionPipeline
from diffusers.utils import export_to_video
vae = AutoencoderKLWan.from_pretrained(
"Wan-AI/Wan2.2-T2V-A14B-Diffusers",
subfolder="vae",
dtype=torch.float32
)
pipeline = DiffusionPipeline.from_pretrained(
"Wan-AI/Wan2.2-T2V-A14B-Diffusers",
vae=vae,
dtype=torch.bfloat16,
device_map="cuda" # or "mps", "xpu", "cpu"
)
prompt = """
Cinematic video of a sleek cat lounging on a colorful inflatable in a crystal-clear turquoise pool in Palm Springs,
sipping a salt-rimmed margarita through a straw. Golden-hour sunlight glows over mid-century modern homes and swaying palms.
Shot in rich Sony a7S III: with moody, glamorous color grading, subtle lens flares, and soft vintage film grain.
Ripples shimmer as a warm desert breeze stirs the water, blending luxury and playful charm in an epic, gorgeously composed frame.
"""
video = pipeline(prompt=prompt, num_frames=81, num_inference_steps=40).frames[0]
export_to_video(video, "output.mp4", fps=16)
```
## LoRA
Los adaptadores [LoRA](./tutorials/using_peft_for_inference) añaden un punto de control de estilo o sujeto pequeño sobre un pipeline base. Carga uno con [load_lora_weights()](/docs/diffusers/v0.43.0/es/api/loaders/lora#diffusers.loaders.QwenImageLoraLoaderMixin.load_lora_weights). Algunos LoRA requieren una frase de activación. Consulta la tarjeta de modelo del LoRA.
```py
import torch
from diffusers import DiffusionPipeline
pipeline = DiffusionPipeline.from_pretrained(
"Qwen/Qwen-Image", dtype=torch.bfloat16, device_map="cuda" # or "mps", "xpu", "cpu"
)
pipeline.load_lora_weights(
"threecrowco/VolkClipartQwen",
weight_name="pytorch_lora_weights.safetensors",
)
prompt = """
Volk clipart style drawing of a cat sipping a margarita in a pool in Palm Springs, California, flat colors, bold outlines, simple shapes
"""
pipeline(prompt).images[0]
```
## Cuantización y optimizaciones
Los modelos grandes a menudo requieren menos memoria o más velocidad. Utilice [cuantización](./quantization/overview) para reducir los pesos en memoria y [compile_repeated_blocks()](/docs/diffusers/v0.43.0/es/api/models/overview#diffusers.ModelMixin.compile_repeated_blocks) para acelerar las generaciones posteriores. Para [descarga de modelos](./optimization/memory#model-offloading) y otras opciones, consulte [Optimizar y escalar](./stable_diffusion).
Para usar menos memoria, cargue en 4 bits con bitsandbytes.
```py
import torch
from diffusers import DiffusionPipeline
from diffusers.quantizers import PipelineQuantizationConfig
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", "text_encoder"],
)
pipeline = DiffusionPipeline.from_pretrained(
"Qwen/Qwen-Image",
dtype=torch.bfloat16,
quantization_config=quant_config,
device_map="cuda" # or "mps", "xpu", "cpu"
)
prompt = """
cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
"""
pipeline(prompt).images[0]
```
Para acelerar las ejecuciones posteriores, compile los bloques repetidos del transformer. El primer generate después de la compilación es un arranque en frío y es lento. Los generates posteriores son más rápidos.
```py
import torch
from diffusers import DiffusionPipeline
pipeline = DiffusionPipeline.from_pretrained(
"Qwen/Qwen-Image", dtype=torch.bfloat16, device_map="cuda" # or "mps", "xpu", "cpu"
)
pipeline.transformer.compile_repeated_blocks(fullgraph=True)
prompt = """
cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
"""
pipeline(prompt).images[0]
```
## Próximos pasos
- [Inferencia](./using-diffusers/loading) — pipelines, prompting y adaptadores
- [Optimizar y escalar](./stable_diffusion) — memoria, velocidad, cuantización y servicio
- [Diffusers modulares](./modular_diffusers/overview) — bloques componibles y pipelines personalizados
- [Entrenar y ajustar](./training/overview) — scripts de entrenamiento y adaptadores
- [CLI](./using-diffusers/cli) — generar desde la línea de comandos

Xet Storage Details

Size:
7.7 kB
·
Xet hash:
baf5ade4564181612892a43503a0a74caa604976dabb92abeba681bcf7864686

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.