#
# 根据 Apache 许可证 2.0 版本（“许可证”）授权
# 您只能在遵守许可证的情况下使用本文件。
# 您可以在以下位置获取许可证副本
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 除非适用法律要求或双方书面同意，软件
# 根据许可证分发，本软件按“原样”
# 不附带任何明示或暗示的保证或条件。
# 请参阅许可证中关于权限的具体语言
# 许可证下的限制。-->

# Lumina2

  

[Lumina Image 2.0: A Unified and Efficient Image Generative Model](https://huggingface.co/Alpha-VLLM/Lumina-Image-2.0) 是一个拥有 20 亿参数的基于流的扩散 Transformer，能够根据文本描述生成多样化的图像。

该论文的摘要如下：

*我们推出了 Lumina-Image 2.0，这是一款先进的文本生成图像模型，它在多个基准测试中超越了此前的最先进方法，同时也揭示了其演变为通用视觉智能模型的潜力。Lumina-Image 2.0 具备三个关键特性：(1) 统一性——它采用统一架构，将文本和图像标记视为一个联合序列，从而实现自然的跨模态交互并促进任务扩展。此外，由于高质量的描述器能够提供语义对齐更好的文本-图像训练对，我们引入了一个统一的描述系统 UniCaptioner，为模型生成全面且精确的描述。这不仅加速了模型收敛，还通过提示模板增强了提示遵循能力、变长提示处理以及任务泛化能力。(2) 高效性——为了提高统一架构的效率，我们开发了一系列优化技术，在训练过程中改善语义学习和细粒度纹理生成，同时在不牺牲图像质量的前提下引入推理时加速策略。(3) 透明性——我们开源了所有训练细节、代码和模型，以确保完全可复现性，旨在弥合资源充足的闭源研究团队与独立开发者之间的差距。*

> [!TIP]
> 请务必参阅 [调度器指南](../../using-diffusers/schedulers)，了解如何探索调度器速度与质量之间的权衡，并查看 [跨流水线复用组件](../../using-diffusers/loading#reusing-models-in-multiple-pipelines) 部分，了解如何高效地将相同组件加载到多个流水线中。

## 使用单文件加载方式加载 Lumina Image 2.0

`Lumina2Transformer2DModel` 现已支持 Lumina Image 2.0 的单文件加载

```python
import torch
from diffusers import Lumina2Transformer2DModel, Lumina2Pipeline

ckpt_path = "https://huggingface.co/Alpha-VLLM/Lumina-Image-2.0/blob/main/consolidated.00-of-01.pth"
transformer = Lumina2Transformer2DModel.from_single_file(
    ckpt_path, dtype=torch.bfloat16
)

pipe = Lumina2Pipeline.from_pretrained(
    "Alpha-VLLM/Lumina-Image-2.0", transformer=transformer, dtype=torch.bfloat16
)
pipe.enable_model_cpu_offload()
image = pipe(
    "a cat holding a sign that says hello",
    generator=torch.Generator("cpu").manual_seed(0),
).images[0]
image.save("lumina-single-file.png")

```

## 使用 GGUF 量化检查点与 Lumina Image 2.0

`Lumina2Transformer2DModel` 的 GGUF 量化检查点可以通过 `from_single_file` 配合 `GGUFQuantizationConfig` 进行加载。

```python
from diffusers import Lumina2Transformer2DModel, Lumina2Pipeline, GGUFQuantizationConfig 

ckpt_path = "https://huggingface.co/calcuis/lumina-gguf/blob/main/lumina2-q4_0.gguf"
transformer = Lumina2Transformer2DModel.from_single_file(
    ckpt_path,
    quantization_config=GGUFQuantizationConfig(compute_dtype=torch.bfloat16),
    dtype=torch.bfloat16,
)

pipe = Lumina2Pipeline.from_pretrained(
    "Alpha-VLLM/Lumina-Image-2.0", transformer=transformer, dtype=torch.bfloat16
)
pipe.enable_model_cpu_offload()
image = pipe(
    "a cat holding a sign that says hello",
    generator=torch.Generator("cpu").manual_seed(0),
).images[0]
image.save("lumina-gguf.png")
```

## Lumina2Pipeline[[diffusers.Lumina2Pipeline]]

#### diffusers.Lumina2Pipeline[[diffusers.Lumina2Pipeline]]

```python
diffusers.Lumina2Pipeline(transformer: Lumina2Transformer2DModel, scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKL, text_encoder: Gemma2PreTrainedModel, tokenizer: GemmaTokenizer)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/lumina2/pipeline_lumina2.py#L136)

**参数：**

vae ([AutoencoderKL](/docs/diffusers/v0.43.0/zh/api/models/autoencoderkl#diffusers.AutoencoderKL))：变分自编码器（VAE）模型，用于将图像编码为潜在表示，并从潜在表示解码回图像。

text_encoder (`Gemma2PreTrainedModel`)：冻结的 Gemma2 文本编码器。

tokenizer (`GemmaTokenizer` 或 `GemmaTokenizerFast`)：Gemma 分词器。

transformer ([Transformer2DModel](/docs/diffusers/v0.43.0/zh/api/models/transformer2d#diffusers.Transformer2DModel))：一个以文本为条件的 `Transformer2DModel`，用于对编码后的图像潜变量进行去噪。

scheduler ([SchedulerMixin](/docs/diffusers/v0.43.0/zh/api/schedulers/overview#diffusers.SchedulerMixin))：用于与 `transformer` 配合，对编码后的图像潜变量进行去噪的调度器。

使用 Lumina-T2I 进行文本到图像生成的 Pipeline。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。请查阅父类文档，了解该库为所有 pipeline 实现的通用方法（例如下载或保存、在特定设备上运行等）。

#### __调用__[[diffusers.Lumina2Pipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, width: int | None = None, height: int | None = None, num_inference_steps: int = 30, guidance_scale: float = 4.0, negative_prompt: str | list[str] = None, sigmas: list[float] = None, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'], system_prompt: str | None = None, cfg_trunc_ratio: float = 1.0, cfg_normalization: bool = True, max_sequence_length: int = 256)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/lumina2/pipeline_lumina2.py#L470)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须改为传入 `prompt_embeds`。

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时），此参数将被忽略。

num_inference_steps (`int`，*可选*，默认值为 30)：去噪步数。更多的去噪步数通常能生成更高质量的图像，但代价是推理速度变慢。

sigmas (`list[float]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `sigmas` 参数的调度器的去噪过程的自定义 sigmas。如果未定义，将使用传入 `num_inference_steps` 时的默认行为。

guidance_scale (`float`，*可选*，默认值为 4.0)：如[Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

height (`int`，*可选*，默认为 self.unet.config.sample_size)：生成图像的高度（以像素为单位）。

width (`int`，*可选*，默认为 self.unet.config.sample_size)：生成图像的像素宽度。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或一组 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.Tensor`, *可选*) : 预先生成的噪声潜变量，从高斯分布中采样得到，用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

prompt_attention_mask (`torch.Tensor`, *可选*) : 为文本嵌入预生成的注意力掩码。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负向文本嵌入。对于 Lumina-T2I，此负向提示应为 ""。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

negative_prompt_attention_mask (`torch.Tensor`, *可选*) : 为负文本嵌入预生成的注意力掩码。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.stable_diffusion.IFPipelineOutput` 而不是普通元组。

attention_kwargs : 一个 kwargs 字典，如果指定，将传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

callback_on_step_end (`Callable`，*可选*)：一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用：`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`list`，*可选*)：`callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传递。您只能包含流水线类的 `._callback_tensor_inputs` 属性中列出的变量。

system_prompt (`str`, *可选*) : 用于图像生成的系统提示词。

cfg_trunc_ratio (`float`, *可选*，默认为 `1.0`)：应用基于归一化的 guidance scale 的时间步间隔比例。

cfg_normalization (`bool`，*可选*，默认为 `True`)：是否应用基于归一化的引导尺度。

max_sequence_length (`int`，默认为 `256`) : 与 `prompt` 一起使用的最大序列长度。

**返回：** [ImagePipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/consistency_models#diffusers.ImagePipelineOutput) 或 `tuple`

如果 `return_dict` 为 `True`，则返回 [ImagePipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/consistency_models#diffusers.ImagePipelineOutput)，否则返回一个 `tuple`，其中第一个元素是包含生成图像的列表

调用生成 pipeline 时调用的函数。

示例：
```py
>>> import torch
>>> from diffusers import Lumina2Pipeline

>>> pipe = Lumina2Pipeline.from_pretrained("Alpha-VLLM/Lumina-Image-2.0", torch_dtype=torch.bfloat16)
>>> # Enable memory optimizations.
>>> pipe.enable_model_cpu_offload()

>>> prompt = "Upper body of a young woman in a Victorian-era outfit with brass goggles and leather straps. Background shows an industrial revolution cityscape with smoky skies and tall, metal structures"
>>> image = pipe(prompt).images[0]
```

#### encode_prompt[[diffusers.Lumina2Pipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], do_classifier_free_guidance: bool = True, negative_prompt: str | list[str] = None, num_images_per_prompt: int = 1, device: typing.Optional[torch.device] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_attention_mask: typing.Optional[torch.Tensor] = None, negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None, system_prompt: str | None = None, max_sequence_length: int = 256)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/lumina2/pipeline_lumina2.py#L237)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

negative_prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的负面提示词。如果未定义，则必须传入 `negative_prompt_embeds`。在未使用引导时会被忽略（即当 `guidance_scale` 小于 `1` 时会被忽略）。对于 Lumina-T2I，此值应为 ""。

do_classifier_free_guidance (`bool`，*可选*，默认为 `True`)：是否使用无分类器引导

num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词应生成的图像数量

device : (`torch.device`, *可选*): 用于放置生成的嵌入的 torch 设备

prompt_embeds (`torch.Tensor`, *可选*) : 预生成的文本嵌入。可用于轻松调整文本输入，*例如* 提示词加权。如果未提供，文本嵌入将从 `prompt` 输入参数生成。

negative_prompt_embeds (`torch.Tensor`, *可选*) : 预生成的负文本嵌入。对于 Lumina-T2I，它应该是 "" 字符串的嵌入。

max_sequence_length (`int`，默认为 `256`)：用于提示词的最大序列长度。

将提示词编码为文本编码器的隐藏状态。

