Skip to content

Commit 87f0c39

Browse files
authored
Merge branch 'main' into integrations/wan2.2-s2v
2 parents 74c1553 + 94c9613 commit 87f0c39

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+10111
-45
lines changed

docs/source/en/_toctree.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,8 @@
349349
title: DiTTransformer2DModel
350350
- local: api/models/easyanimate_transformer3d
351351
title: EasyAnimateTransformer3DModel
352+
- local: api/models/flux2_transformer
353+
title: Flux2Transformer2DModel
352354
- local: api/models/flux_transformer
353355
title: FluxTransformer2DModel
354356
- local: api/models/hidream_image_transformer
@@ -525,6 +527,8 @@
525527
title: EasyAnimate
526528
- local: api/pipelines/flux
527529
title: Flux
530+
- local: api/pipelines/flux2
531+
title: Flux2
528532
- local: api/pipelines/control_flux_inpaint
529533
title: FluxControlInpaint
530534
- local: api/pipelines/hidream

docs/source/en/api/loaders/lora.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@ LoRA is a fast and lightweight training method that inserts and trains a signifi
3030
- [`CogView4LoraLoaderMixin`] provides similar functions for [CogView4](https://huggingface.co/docs/diffusers/main/en/api/pipelines/cogview4).
3131
- [`AmusedLoraLoaderMixin`] is for the [`AmusedPipeline`].
3232
- [`HiDreamImageLoraLoaderMixin`] provides similar functions for [HiDream Image](https://huggingface.co/docs/diffusers/main/en/api/pipelines/hidream)
33-
- [`QwenImageLoraLoaderMixin`] provides similar functions for [Qwen Image](https://huggingface.co/docs/diffusers/main/en/api/pipelines/qwen)
33+
- [`QwenImageLoraLoaderMixin`] provides similar functions for [Qwen Image](https://huggingface.co/docs/diffusers/main/en/api/pipelines/qwen).
34+
- [`Flux2LoraLoaderMixin`] provides similar functions for [Flux2](https://huggingface.co/docs/diffusers/main/en/api/pipelines/flux2).
3435
- [`LoraBaseMixin`] provides a base class with several utility methods to fuse, unfuse, unload, LoRAs and more.
3536

3637
> [!TIP]
@@ -56,6 +57,10 @@ LoRA is a fast and lightweight training method that inserts and trains a signifi
5657

5758
[[autodoc]] loaders.lora_pipeline.FluxLoraLoaderMixin
5859

60+
## Flux2LoraLoaderMixin
61+
62+
[[autodoc]] loaders.lora_pipeline.Flux2LoraLoaderMixin
63+
5964
## CogVideoXLoraLoaderMixin
6065

6166
[[autodoc]] loaders.lora_pipeline.CogVideoXLoraLoaderMixin
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4+
the License. You may obtain a copy of the License at
5+
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
8+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10+
specific language governing permissions and limitations under the License.
11+
-->
12+
13+
# Flux2Transformer2DModel
14+
15+
A Transformer model for image-like data from [Flux2](https://hf.co/black-forest-labs/FLUX.2-dev).
16+
17+
## Flux2Transformer2DModel
18+
19+
[[autodoc]] Flux2Transformer2DModel
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4+
the License. You may obtain a copy of the License at
5+
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
8+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10+
specific language governing permissions and limitations under the License.
11+
-->
12+
13+
# Flux2
14+
15+
<div class="flex flex-wrap space-x-1">
16+
<img alt="LoRA" src="https://img.shields.io/badge/LoRA-d8b4fe?style=flat"/>
17+
<img alt="MPS" src="https://img.shields.io/badge/MPS-000000?style=flat&logo=apple&logoColor=white%22">
18+
</div>
19+
20+
Flux.2 is the recent series of image generation models from Black Forest Labs, preceded by the [Flux.1](./flux.md) series. It is an entirely new model with a new architecture and pre-training done from scratch!
21+
22+
Original model checkpoints for Flux can be found [here](https://huggingface.co/black-forest-labs). Original inference code can be found [here](https://github.com/black-forest-labs/flux2).
23+
24+
> [!TIP]
25+
> Flux2 can be quite expensive to run on consumer hardware devices. However, you can perform a suite of optimizations to run it faster and in a more memory-friendly manner. Check out [this section](https://huggingface.co/blog/sd3#memory-optimizations-for-sd3) for more details. Additionally, Flux can benefit from quantization for memory efficiency with a trade-off in inference latency. Refer to [this blog post](https://huggingface.co/blog/quanto-diffusers) to learn more.
26+
>
27+
> [Caching](../../optimization/cache) may also speed up inference by storing and reusing intermediate outputs.
28+
29+
## Flux2Pipeline
30+
31+
[[autodoc]] Flux2Pipeline
32+
- all
33+
- __call__

docs/source/en/api/pipelines/sana_video.md

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,13 @@ Note: The recommended dtype mentioned is for the transformer weights. The text e
4343
<hfoptions id="generation pipelines">`
4444
<hfoption id="Text-to-Video">
4545

46-
The example below demonstrates how to use the text-to-video pipeline to generate a video using a text descriptio and a starting frame.
46+
The example below demonstrates how to use the text-to-video pipeline to generate a video using a text description.
4747

4848
```python
49-
model_id =
50-
pipe = SanaVideoPipeline.from_pretrained("Efficient-Large-Model/SANA-Video_2B_480p_diffusers", torch_dtype=torch.bfloat16)
49+
pipe = SanaVideoPipeline.from_pretrained(
50+
"Efficient-Large-Model/SANA-Video_2B_480p_diffusers",
51+
torch_dtype=torch.bfloat16,
52+
)
5153
pipe.text_encoder.to(torch.bfloat16)
5254
pipe.vae.to(torch.float32)
5355
pipe.to("cuda")
@@ -75,12 +77,11 @@ export_to_video(video, "sana_video.mp4", fps=16)
7577
</hfoption>
7678
<hfoption id="Image-to-Video">
7779

78-
The example below demonstrates how to use the image-to-video pipeline to generate a video using a text descriptio and a starting frame.
80+
The example below demonstrates how to use the image-to-video pipeline to generate a video using a text description and a starting frame.
7981

8082
```python
81-
model_id = "Efficient-Large-Model/SANA-Video_2B_480p_diffusers"
8283
pipe = SanaImageToVideoPipeline.from_pretrained(
83-
model_id,
84+
"Efficient-Large-Model/SANA-Video_2B_480p_diffusers",
8485
torch_dtype=torch.bfloat16,
8586
)
8687
pipe.scheduler = FlowMatchEulerDiscreteScheduler.from_config(pipe.scheduler.config, flow_shift=8.0)

docs/source/en/optimization/attention_backends.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,12 +139,14 @@ Refer to the table below for a complete list of available attention backends and
139139
| `_native_npu` | [PyTorch native](https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend) | NPU-optimized attention |
140140
| `_native_xla` | [PyTorch native](https://docs.pytorch.org/docs/stable/generated/torch.nn.attention.SDPBackend.html#torch.nn.attention.SDPBackend) | XLA-optimized attention |
141141
| `flash` | [FlashAttention](https://github.com/Dao-AILab/flash-attention) | FlashAttention-2 |
142+
| `flash_hub` | [FlashAttention](https://github.com/Dao-AILab/flash-attention) | FlashAttention-2 from kernels |
142143
| `flash_varlen` | [FlashAttention](https://github.com/Dao-AILab/flash-attention) | Variable length FlashAttention |
143144
| `aiter` | [AI Tensor Engine for ROCm](https://github.com/ROCm/aiter) | FlashAttention for AMD ROCm |
144145
| `_flash_3` | [FlashAttention](https://github.com/Dao-AILab/flash-attention) | FlashAttention-3 |
145146
| `_flash_varlen_3` | [FlashAttention](https://github.com/Dao-AILab/flash-attention) | Variable length FlashAttention-3 |
146147
| `_flash_3_hub` | [FlashAttention](https://github.com/Dao-AILab/flash-attention) | FlashAttention-3 from kernels |
147148
| `sage` | [SageAttention](https://github.com/thu-ml/SageAttention) | Quantized attention (INT8 QK) |
149+
| `sage_hub` | [SageAttention](https://github.com/thu-ml/SageAttention) | Quantized attention (INT8 QK) from kernels |
148150
| `sage_varlen` | [SageAttention](https://github.com/thu-ml/SageAttention) | Variable length SageAttention |
149151
| `_sage_qk_int8_pv_fp8_cuda` | [SageAttention](https://github.com/thu-ml/SageAttention) | INT8 QK + FP8 PV (CUDA) |
150152
| `_sage_qk_int8_pv_fp8_cuda_sm90` | [SageAttention](https://github.com/thu-ml/SageAttention) | INT8 QK + FP8 PV (SM90) |

docs/source/pt/_toctree.yml

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
- sections:
2-
- local: index
3-
title: 🧨 Diffusers
4-
- local: quicktour
5-
title: Tour rápido
6-
- local: installation
7-
title: Instalação
2+
- local: index
3+
title: Diffusers
4+
- local: installation
5+
title: Instalação
6+
- local: quicktour
7+
title: Tour rápido
8+
- local: stable_diffusion
9+
title: Desempenho básico
810
title: Primeiros passos

docs/source/pt/index.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,11 @@ specific language governing permissions and limitations under the License.
1818

1919
# Diffusers
2020

21-
🤗 Diffusers é uma biblioteca de modelos de difusão de última geração para geração de imagens, áudio e até mesmo estruturas 3D de moléculas. Se você está procurando uma solução de geração simples ou queira treinar seu próprio modelo de difusão, 🤗 Diffusers é uma modular caixa de ferramentas que suporta ambos. Nossa biblioteca é desenhada com foco em [usabilidade em vez de desempenho](conceptual/philosophy#usability-over-performance), [simples em vez de fácil](conceptual/philosophy#simple-over-easy) e [customizável em vez de abstrações](conceptual/philosophy#tweakable-contributorfriendly-over-abstraction).
21+
🤗 Diffusers é uma biblioteca de modelos de difusão de última geração para geração de imagens, áudio e até mesmo estruturas 3D de moléculas. Se você está procurando uma solução de geração simples ou quer treinar seu próprio modelo de difusão, 🤗 Diffusers é uma caixa de ferramentas modular que suporta ambos. Nossa biblioteca é desenhada com foco em [usabilidade em vez de desempenho](conceptual/philosophy#usability-over-performance), [simples em vez de fácil](conceptual/philosophy#simple-over-easy) e [customizável em vez de abstrações](conceptual/philosophy#tweakable-contributorfriendly-over-abstraction).
2222

2323
A Biblioteca tem três componentes principais:
2424

25-
- Pipelines de última geração para a geração em poucas linhas de código. Têm muitos pipelines no 🤗 Diffusers, veja a tabela no pipeline [Visão geral](api/pipelines/overview) para uma lista completa de pipelines disponíveis e as tarefas que eles resolvem.
25+
- Pipelines de última geração para a geração em poucas linhas de código. muitos pipelines no 🤗 Diffusers, veja a tabela no pipeline [Visão geral](api/pipelines/overview) para uma lista completa de pipelines disponíveis e as tarefas que eles resolvem.
2626
- Intercambiáveis [agendadores de ruído](api/schedulers/overview) para balancear as compensações entre velocidade e qualidade de geração.
2727
- [Modelos](api/models) pré-treinados que podem ser usados como se fossem blocos de construção, e combinados com agendadores, para criar seu próprio sistema de difusão de ponta a ponta.
2828

docs/source/pt/installation.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ specific language governing permissions and limitations under the License.
2121

2222
Recomenda-se instalar 🤗 Diffusers em um [ambiente virtual](https://docs.python.org/3/library/venv.html).
2323
Se você não está familiarizado com ambiente virtuals, veja o [guia](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
24-
Um ambiente virtual deixa mais fácil gerenciar diferentes projetos e evitar problemas de compatibilidade entre dependências.
24+
Um ambiente virtual facilita gerenciar diferentes projetos e evitar problemas de compatibilidade entre dependências.
2525

2626
Comece criando um ambiente virtual no diretório do projeto:
2727

@@ -100,12 +100,12 @@ pip install -e ".[flax]"
100100
</jax>
101101
</frameworkcontent>
102102

103-
Esses comandos irá linkar a pasta que você clonou o repositório e os caminhos das suas bibliotecas Python.
103+
Esses comandos irão vincular a pasta que você clonou o repositório e os caminhos das suas bibliotecas Python.
104104
Python então irá procurar dentro da pasta que você clonou além dos caminhos normais das bibliotecas.
105105
Por exemplo, se o pacote python for tipicamente instalado no `~/anaconda3/envs/main/lib/python3.10/site-packages/`, o Python também irá procurar na pasta `~/diffusers/` que você clonou.
106106

107107
> [!WARNING]
108-
> Você deve deixar a pasta `diffusers` se você quiser continuar usando a biblioteca.
108+
> Você deve manter a pasta `diffusers` se quiser continuar usando a biblioteca.
109109
110110
Agora você pode facilmente atualizar seu clone para a última versão do 🤗 Diffusers com o seguinte comando:
111111

docs/source/pt/stable_diffusion.md

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
<!--Copyright 2025 The HuggingFace Team. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4+
the License. You may obtain a copy of the License at
5+
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
8+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10+
specific language governing permissions and limitations under the License.
11+
-->
12+
13+
[[open-in-colab]]
14+
15+
# Desempenho básico
16+
17+
Difusão é um processo aleatório que demanda muito processamento. Você pode precisar executar o [`DiffusionPipeline`] várias vezes antes de obter o resultado desejado. Por isso é importante equilibrar cuidadosamente a velocidade de geração e o uso de memória para iterar mais rápido.
18+
19+
Este guia recomenda algumas dicas básicas de desempenho para usar o [`DiffusionPipeline`]. Consulte a seção de documentação sobre Otimização de Inferência, como [Acelerar inferência](./optimization/fp16) ou [Reduzir uso de memória](./optimization/memory) para guias de desempenho mais detalhados.
20+
21+
## Uso de memória
22+
23+
Reduzir a quantidade de memória usada indiretamente acelera a geração e pode ajudar um modelo a caber no dispositivo.
24+
25+
O método [`~DiffusionPipeline.enable_model_cpu_offload`] move um modelo para a CPU quando não está em uso para economizar memória da GPU.
26+
27+
```py
28+
import torch
29+
from diffusers import DiffusionPipeline
30+
31+
pipeline = DiffusionPipeline.from_pretrained(
32+
"stabilityai/stable-diffusion-xl-base-1.0",
33+
torch_dtype=torch.bfloat16,
34+
device_map="cuda"
35+
)
36+
pipeline.enable_model_cpu_offload()
37+
38+
prompt = """
39+
cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
40+
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
41+
"""
42+
pipeline(prompt).images[0]
43+
print(f"Memória máxima reservada: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB")
44+
```
45+
46+
## Velocidade de inferência
47+
48+
O processo de remoção de ruído é o mais exigente computacionalmente durante a difusão. Métodos que otimizam este processo aceleram a velocidade de inferência. Experimente os seguintes métodos para acelerar.
49+
50+
- Adicione `device_map="cuda"` para colocar o pipeline em uma GPU. Colocar um modelo em um acelerador, como uma GPU, aumenta a velocidade porque realiza computações em paralelo.
51+
- Defina `torch_dtype=torch.bfloat16` para executar o pipeline em meia-precisão. Reduzir a precisão do tipo de dado aumenta a velocidade porque leva menos tempo para realizar computações em precisão mais baixa.
52+
53+
```py
54+
import torch
55+
import time
56+
from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
57+
58+
pipeline = DiffusionPipeline.from_pretrained(
59+
"stabilityai/stable-diffusion-xl-base-1.0",
60+
torch_dtype=torch.bfloat16,
61+
device_map="cuda"
62+
)
63+
```
64+
65+
- Use um agendador mais rápido, como [`DPMSolverMultistepScheduler`], que requer apenas ~20-25 passos.
66+
- Defina `num_inference_steps` para um valor menor. Reduzir o número de passos de inferência reduz o número total de computações. No entanto, isso pode resultar em menor qualidade de geração.
67+
68+
```py
69+
pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
70+
71+
prompt = """
72+
cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
73+
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
74+
"""
75+
76+
start_time = time.perf_counter()
77+
image = pipeline(prompt).images[0]
78+
end_time = time.perf_counter()
79+
80+
print(f"Geração de imagem levou {end_time - start_time:.3f} segundos")
81+
```
82+
83+
## Qualidade de geração
84+
85+
Muitos modelos de difusão modernos entregam imagens de alta qualidade imediatamente. No entanto, você ainda pode melhorar a qualidade de geração experimentando o seguinte.
86+
87+
- Experimente um prompt mais detalhado e descritivo. Inclua detalhes como o meio da imagem, assunto, estilo e estética. Um prompt negativo também pode ajudar, guiando um modelo para longe de características indesejáveis usando palavras como baixa qualidade ou desfocado.
88+
89+
```py
90+
import torch
91+
from diffusers import DiffusionPipeline
92+
93+
pipeline = DiffusionPipeline.from_pretrained(
94+
"stabilityai/stable-diffusion-xl-base-1.0",
95+
torch_dtype=torch.bfloat16,
96+
device_map="cuda"
97+
)
98+
99+
prompt = """
100+
cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
101+
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
102+
"""
103+
negative_prompt = "low quality, blurry, ugly, poor details"
104+
pipeline(prompt, negative_prompt=negative_prompt).images[0]
105+
```
106+
107+
Para mais detalhes sobre como criar prompts melhores, consulte a documentação sobre [Técnicas de prompt](./using-diffusers/weighted_prompts).
108+
109+
- Experimente um agendador diferente, como [`HeunDiscreteScheduler`] ou [`LMSDiscreteScheduler`], que sacrifica velocidade de geração por qualidade.
110+
111+
```py
112+
import torch
113+
from diffusers import DiffusionPipeline, HeunDiscreteScheduler
114+
115+
pipeline = DiffusionPipeline.from_pretrained(
116+
"stabilityai/stable-diffusion-xl-base-1.0",
117+
torch_dtype=torch.bfloat16,
118+
device_map="cuda"
119+
)
120+
pipeline.scheduler = HeunDiscreteScheduler.from_config(pipeline.scheduler.config)
121+
122+
prompt = """
123+
cinematic film still of a cat sipping a margarita in a pool in Palm Springs, California
124+
highly detailed, high budget hollywood movie, cinemascope, moody, epic, gorgeous, film grain
125+
"""
126+
negative_prompt = "low quality, blurry, ugly, poor details"
127+
pipeline(prompt, negative_prompt=negative_prompt).images[0]
128+
```
129+
130+
## Próximos passos
131+
132+
Diffusers oferece otimizações mais avançadas e poderosas, como [group-offloading](./optimization/memory#group-offloading) e [compilação regional](./optimization/fp16#regional-compilation). Para saber mais sobre como maximizar o desempenho, consulte a seção sobre Otimização de Inferência.

0 commit comments

Comments
 (0)