# Bria Fibo 编辑

Fibo Edit 是一个 8B 参数的图像到图像模型，引入了结构化控制的新范式。它基于与源图像配对的 JSON 输入进行操作，从而实现确定性和可重复的编辑工作流。凭借用于精细控制的本地掩码功能，它超越了简单的基于提示的扩散，为生产环境提供了显式且可解释的控制。其轻量级架构专为深度定制而设计，使研究人员能够针对特定领域任务构建专用的“Edit”模型，同时提供一流的美学质量。

请参阅 Bria Fibo Edit 的 Hugging Face [页面](https://huggingface.co/briaai/Fibo-Edit-1.5-base)以了解更多信息。蒸馏检查点可在 [Fibo-Edit-1.5-turbo](https://huggingface.co/briaai/Fibo-Edit-1.5-turbo) 处获取。

## 用法

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

使用以下命令登录：

```bash
hf auth login
```

## BriaFiboEditPipeline[[diffusers.BriaFiboEditPipeline]]

#### diffusers.BriaFiboEditPipeline[[diffusers.BriaFiboEditPipeline]]

```python
diffusers.BriaFiboEditPipeline(transformer: BriaFiboTransformer2DModel, scheduler: typing.Union[diffusers.schedulers.scheduling_flow_match_euler_discrete.FlowMatchEulerDiscreteScheduler, diffusers.schedulers.scheduling_utils.KarrasDiffusionSchedulers], vae: AutoencoderKLWan, text_encoder: SmolLM3ForCausalLM, tokenizer: AutoTokenizer)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/bria_fibo/pipeline_bria_fibo_edit.py#L240)

**参数：**

transformer (`BriaFiboTransformer2DModel`)：用于 2D 扩散建模的 transformer 模型。

scheduler (`FlowMatchEulerDiscreteScheduler` 或 `KarrasDiffusionSchedulers`)：用于配合 `transformer` 对编码后的潜变量进行去噪的调度器。

vae (`AutoencoderKLWan`)：变分自编码器，用于将图像编码为潜在表示以及从潜在表示解码为图像。

text_encoder (`SmolLM3ForCausalLM`)：用于处理输入提示的文本编码器。

tokenizer (`AutoTokenizer`)：用于处理输入文本提示词以配合 text_encoder 的 Tokenizer。

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

```python
__call__(prompt: typing.Union[str, typing.List[str]] = None, image: typing.Union[PIL.Image.Image, typing.List[PIL.Image.Image], NoneType] = None, mask: typing.Union[torch.FloatTensor, PIL.Image.Image, typing.List[PIL.Image.Image], typing.List[torch.FloatTensor], numpy.ndarray, typing.List[numpy.ndarray], NoneType] = None, height: int | None = None, width: int | None = None, num_inference_steps: int = 30, timesteps: typing.List[int] = None, seed: int | None = None, guidance_scale: float = 5, negative_prompt: typing.Union[str, typing.List[str], NoneType] = None, num_images_per_prompt: typing.Optional[int] = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.FloatTensor] = None, output_type: str = 'pil', return_dict: bool = True, joint_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None, callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None, callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'], max_sequence_length: int = 3000, do_patching = False, _auto_resize: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/bria_fibo/pipeline_bria_fibo_edit.py#L599)

**参数：**

prompt (`str` 或 `List[str]`) : 用于引导图像生成的提示词或提示词列表。

image (`PIL.Image.Image` 或 `List[PIL.Image.Image]`，*可选*)：用于引导图像生成的一张或多张参考图像。列表被视为多个参考（而非一个批次）：每个参考都会按其自身的宽高比进行 VAE 编码，并放置在各自的 RoPE 时间平面 1、2、... 上。如果未定义，流水线将从零开始生成图像。

mask (`PipelineMaskInput`，*可选*)：可选的掩码，用于定义 `image` 中需要编辑的区域。掩码覆盖的像素将被重新生成，而图像的其余部分将保持不变。

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`，*可选*，默认值为 30)：去噪步数。更多的去噪步数通常能生成更高质量的图像，但代价是推理速度变慢。

seed (`int`, *可选*) : 用于使生成过程确定性的随机种子。

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

guidance_scale (`float`，*可选*，默认值为 5.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` 紧密关联的图像，但通常以牺牲图像质量为代价。

negative_prompt (`str` 或 `List[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。当未使用引导时（即 `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`进行采样来生成潜变量张量。

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

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

joint_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` 默认值为 3000)：用于 `prompt` 的最大序列长度。

do_patching (`bool`，*可选*，默认为 `False`)：是否使用 patching。

_auto_resize (`bool`，*可选*，默认为 `True`)：是否将默认输出分辨率（取自第一张参考图像）对齐到首选分辨率。

**返回：** `~pipelines.flux.BriaFiboPipelineOutput` 或 `tuple`

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

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

示例：
```python
import torch
from PIL import Image

from diffusers import BriaFiboEditPipeline
from diffusers.modular_pipelines import ModularPipelineBlocks

# This prompt-to-JSON block calls Gemini and needs GEMINI_API_KEY in the environment.
vlm_pipe = ModularPipelineBlocks.from_pretrained("briaai/FIBO-edit-gemini-prompt-to-JSON", trust_remote_code=True)
vlm_pipe = vlm_pipe.init_pipeline()

pipe = BriaFiboEditPipeline.from_pretrained(
    "briaai/Fibo-Edit-1.5-base",
    torch_dtype=torch.bfloat16,
)
pipe.to("cuda")

image = Image.open("owl.png")
json_prompt = vlm_pipe(image=image, prompt="Make the owl into a cat").values["json_prompt"]

result = pipe(prompt=json_prompt, image=image, num_inference_steps=30, guidance_scale=5)

# Multiple reference images: pass a list. Each reference conditions the edit at its
# own aspect ratio; the output resolution follows the first reference.
owl, forest = Image.open("owl.png"), Image.open("forest.png")
json_prompt = vlm_pipe(
    image=[owl, forest], prompt="Place the owl from the first image in the forest from the second image"
).values["json_prompt"]
result = pipe(
    prompt=json_prompt,
    image=[owl, forest],
    num_inference_steps=30,
    guidance_scale=5,
)

# The distilled Turbo checkpoint edits in 4 steps without classifier-free guidance.
pipe = BriaFiboEditPipeline.from_pretrained("briaai/Fibo-Edit-1.5-turbo", torch_dtype=torch.bfloat16)
pipe.to("cuda")
result = pipe(prompt=json_prompt, image=[owl, forest], num_inference_steps=4, guidance_scale=1)
```

#### encode_prompt[[diffusers.BriaFiboEditPipeline.encode_prompt]]

```python
encode_prompt(prompt: typing.Union[str, typing.List[str]], device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, guidance_scale: float = 5, negative_prompt: typing.Union[str, typing.List[str], NoneType] = None, max_sequence_length: int = 3000, lora_scale: bool | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/bria_fibo/pipeline_bria_fibo_edit.py#L365)

**参数：**

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

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

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

guidance_scale (`float`) : 无分类器引导的引导比例。

negative_prompt (`str` 或 `List[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。当未使用引导时（即 `guidance_scale` 小于 `1` 时）将被忽略。

#### prepare_reference_latents[[diffusers.BriaFiboEditPipeline.prepare_reference_latents]]

```python
prepare_reference_latents(image: Image, num_channels_latents: int, dtype: dtype, device: device, do_patching: bool = False, reference_index: int = 1)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/bria_fibo/pipeline_bria_fibo_edit.py#L992)

使用 VAE 以原始尺寸对一张 PIL 参考图像进行编码，并将其打包为编辑上下文 token 流。

