# Bria Fibo Edit

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/main/src/diffusers/pipelines/bria_fibo/pipeline_bria_fibo_edit.py#L240)

**매개변수:**

transformer (`BriaFiboTransformer2DModel`) : 2D 확산 모델링을 위한 transformer 모델입니다.

scheduler (`FlowMatchEulerDiscreteScheduler` 또는 `KarrasDiffusionSchedulers`) : `transformer`와 함께 인코딩된 latents의 노이즈를 제거하는 데 사용되는 Scheduler입니다.

vae (`AutoencoderKLWan`) : 이미지를 잠재 표현으로 인코딩하고 잠재 표현에서 이미지로 디코딩하는 변분 오토인코더(Variational Auto-Encoder)입니다.

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/main/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 generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) 하나 또는 목록.

latents (`torch.FloatTensor`, *선택 사항*) : 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈된 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤 `generator`를 사용하여 샘플링을 통해 latents 텐서가 생성됩니다.

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`, *선택 사항*) : 지정된 경우 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)의 `self.processor` 아래에서 정의된 `AttentionProcessor`로 전달되는 kwargs 사전입니다.

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`) : 패칭을 사용할지 여부.

_auto_resize (`bool`, *선택 사항*, 기본값 `True`) : 기본 출력 해상도(첫 번째 참조 이미지에서 가져옴)를 권장 해상도에 맞출지 여부.

**반환값:** `~pipelines.flux.BriaFiboPipelineOutput` 또는 `tuple`

`return_dict`가 True인 경우 `~pipelines.flux.BriaFiboPipelineOutput`, 그렇지 않으면 `tuple`입니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지의 목록입니다.

생성을 위해 파이프라인을 호출할 때 호출되는 함수.

예:
```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/main/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`) : classifier free guidance의 guidance scale입니다.

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/main/src/diffusers/pipelines/bria_fibo/pipeline_bria_fibo_edit.py#L992)

VAE를 사용하여 PIL 참조 이미지를 자체 크기로 인코딩하고, 이를 편집 컨텍스트 토큰 스트림으로 패키징합니다.

