# Bria 3.2

Bria 3.2 是下一代可商用的文本生成图像模型。它仅拥有 40 亿参数，却提供了卓越的审美效果和文本渲染能力，经评估，其表现与领先的开源模型相当，并优于其他授权模型。除了完全基于授权数据构建外，3.2 还为企业和商用场景提供了多项优势：

- 高效计算 - 该模型比市场上同等水平的模型小 3 倍（4B 参数，而其他开源模型为 12B 参数）
- 架构一致性：与 3.1 版本采用相同的架构——非常适合希望在不中断的情况下进行升级的用户。
- 微调加速：在 L40S 和 A100 上，微调速度提升 2 倍。

Bria 3.2 的原始模型检查点可在[此处](https://huggingface.co/briaai/BRIA-3.2)找到。Bria 3.2 的 Github 仓库可在[此处](https://github.com/Bria-AI/BRIA-3.2)找到。

如果您想了解更多关于 Bria 平台的信息，并获取免费试用访问权限，请访问 [bria.ai](https://bria.ai)。

## 用法

_由于该模型受访问限制，在使用 diffusers 之前，您需要先前往 [Bria 3.2 Hugging Face 页面](https://huggingface.co/briaai/BRIA-3.2)，填写表单并接受访问限制。进入后，您需要登录，以便系统确认您已接受该访问限制。_

使用以下命令登录：

```bash
hf auth login
```

## BriaPipeline[[diffusers.BriaPipeline]]

#### diffusers.BriaPipeline[[diffusers.BriaPipeline]]

```python
diffusers.BriaPipeline(transformer: BriaTransformer2DModel, scheduler: diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler | diffusers.schedulers.scheduling_utils.KarrasDiffusionSchedulers, vae: AutoencoderKL, text_encoder: T5EncoderModel, tokenizer: T5Tokenizer, image_encoder: CLIPVisionModelWithProjection = None, feature_extractor: CLIPImageProcessorPil = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/bria/pipeline_bria.py#L89)

**参数：**

transformer ([BriaTransformer2DModel](/docs/diffusers/v0.43.0/zh/api/models/bria_transformer#diffusers.BriaTransformer2DModel))：用于对编码后的图像潜变量进行去噪的条件 Transformer (MMDiT) 架构。

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

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

text_encoder (`T5EncoderModel`)：冻结的文本编码器。Bria 使用的是 [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel)，具体为 [t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) 变体。

tokenizer (`T5TokenizerFast`)：[T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer) 类的分词器。

基于 FluxPipeline，并进行了若干修改：
- 没有池化嵌入
- 我们对提示词使用零填充
- 由于这不是蒸馏版本，因此没有 guidance embedding

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

```python
__call__(prompt: str | list[str] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 30, timesteps: list[int] = None, guidance_scale: float = 5, negative_prompt: str | list[str] | None = None, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = 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'], max_sequence_length: int = 128, clip_value: None | float = None, normalize: bool = False)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/bria/pipeline_bria.py#L448)

**参数：**

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

height (`int`，*可选*，默认为 self.unet.config.sample_size * self.vae_scale_factor)：生成图像的高度（以像素为单位）。默认设置为 1024，以获得最佳效果。

width (`int`，*可选*，默认为 self.unet.config.sample_size * self.vae_scale_factor)：生成图像的像素宽度。默认设置为 1024 以获得最佳效果。

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

timesteps (`list[int]`，*可选*)：用于在支持 `set_timesteps` 方法中 `timesteps` 参数的调度器中，指定去噪过程所使用的自定义时间步。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。

guidance_scale (`float`，*可选*，默认值为 5.0) --

**返回：** `~pipelines.bria.BriaPipelineOutput` 或 `tuple`

如果 `return_dict` 为 True，则返回 `~pipelines.bria.BriaPipelineOutput`，否则返回 `tuple`。当返回元组时，第一个元素是一个包含生成图像的列表。

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

<<<<<<< HEAD 如 [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598) 中定义的 Guidance scale。`guidance_scale` 定义为 [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用 Guidance scale。较高的 guidance scale 会促使生成与文本 `prompt` 紧密相关的图像，通常以牺牲图像质量为代价。negative_prompt (`str` 或 `list[str]`，*可选*)： ======= 如 [Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598) 中定义的 Guidance scale。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用 Guidance scale。较高的 guidance scale 会促使生成与文本 `prompt` 紧密相关的图像，通常以牺牲图像质量为代价。negative_prompt (`str` 或 `list[str]`，*可选*)：
>>>>>>> main
用于引导图像生成的提示词或提示词列表。如果未定义，则必须传入 `negative_prompt_embeds`。当不使用引导时（即 `guidance_scale` 小于 `1` 时）将被忽略。num_images_per_prompt (`int`，*可选*，默认为 1)：每个提示词要生成的图像数量。generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或多个 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。latents (`torch.FloatTensor`，*可选*)：预生成的噪声潜变量，从高斯分布中采样，用作图像生成的输入。可用于使用不同的提示词微调相同的生成过程。如果未提供，将通过使用提供的随机 `generator` 进行采样来生成一个潜变量张量。prompt_embeds (`torch.FloatTensor`，*可选*)：预生成的文本嵌入。可用于轻松微调文本输入，*例如* 提示词加权。如果未提供，将从 `prompt` 输入参数生成文本嵌入。negative_prompt_embeds (`torch.FloatTensor`，*可选*)：预生成的负向文本嵌入。可用于轻松微调文本输入，*例如* 提示词加权。如果未提供，将从 `negative_prompt` 输入参数生成 negative_prompt_embeds。output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。在 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array` 之间进行选择。return_dict (`bool`，*可选*，默认为 `True`)：是否返回 `~pipelines.bria.BriaPipelineOutput` 而不是普通元组。attention_kwargs (`dict`，*可选*)：一个 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` 属性中列出的变量。max_sequence_length (`int`，默认为 256)：与 `prompt` 一起使用的最大序列长度。clip_value (`float`，*可选*)：如果设置，预测的噪声将在每个去噪步骤中被裁剪到范围 `[-clip_value, clip_value]`。normalize (`bool`，*可选*，默认为 `False`)：是否在每个去噪步骤中归一化预测的噪声。

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

>>> pipe = BriaPipeline.from_pretrained("briaai/BRIA-3.2", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
# BRIA's T5 text encoder is sensitive to precision. We need to cast it to bfloat16 and keep the final layer in float32.

>>> pipe.text_encoder = pipe.text_encoder.to(dtype=torch.bfloat16)
>>> for block in pipe.text_encoder.encoder.block:
...     block.layer[-1].DenseReluDense.wo.to(dtype=torch.float32)
# BRIA's VAE is not supported in mixed precision, so we use float32.

>>> if pipe.vae.config.shift_factor == 0:
...     pipe.vae.to(dtype=torch.float32)

>>> prompt = "Photorealistic food photography of a stack of fluffy pancakes on a white plate, with maple syrup being poured over them. On top of the pancakes are the words 'BRIA 3.2' in bold, yellow, 3D letters. The background is dark and out of focus."
>>> image = pipe(prompt).images[0]
>>> image.save("bria.png")
```

#### encode_prompt[[diffusers.BriaPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, do_classifier_free_guidance: bool = True, negative_prompt: str | list[str] | None = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, max_sequence_length: int = 128, lora_scale: float | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/bria/pipeline_bria.py#L146)

**参数：**

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

device : (`torch.device`): torch 设备

num_images_per_prompt (`int`) : 每个提示词应生成的图像数量

do_classifier_free_guidance (`bool`) : 是否使用 classifier free guidance

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

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

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如*提示词权重。如果未提供，negative_prompt_embeds 将根据 `negative_prompt` 输入参数生成。

