# Bria 3.2

Bria 3.2는 차세대 상용화 가능한 텍스트-이미지 생성 모델입니다. 단 40억 개의 파라미터로 뛰어난 미적 품질과 텍스트 렌더링을 제공하며, 주요 오픈소스 모델과 동등한 결과를 내는 것으로 평가받고 있고, 다른 라이선스 기반 모델보다 우수한 성능을 보입니다. 전적으로 라이선스된 데이터로 구축된 것 외에도, 3.2는 기업 및 상업적 사용에 다음과 같은 여러 이점을 제공합니다:

- Efficient Compute - 해당 모델은 시장에서 동등한 모델보다 X3배 더 작습니다(다른 오픈 소스 모델의 12B 파라미터 대비 4B 파라미터)
- Architecture Consistency: 3.1과 동일한 아키텍처—중단 없이 업그레이드를 원하는 사용자에게 이상적입니다.
- Fine-tuning 속도 향상: L40S 및 A100에서 2배 빠른 fine-tuning.

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/main/src/diffusers/pipelines/bria/pipeline_bria.py#L89)

**매개변수:**

transformer ([BriaTransformer2DModel](/docs/diffusers/main/ko/api/models/bria_transformer#diffusers.BriaTransformer2DModel)) : 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer (MMDiT) 아키텍처.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/ko/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : `transformer`와 함께 사용하여 인코딩된 이미지 라텐트를 디노이즈하는 데 사용되는 스케줄러입니다.

vae ([AutoencoderKL](/docs/diffusers/main/ko/api/models/autoencoderkl#diffusers.AutoencoderKL)) : 이미지를 잠재 표현으로 인코딩하고 잠재 표현에서 이미지로 디코딩하는 Variational Auto-Encoder (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 기반:
- 풀링된 임베딩 없음
- 프롬프트에는 zero padding을 사용합니다
- 이것은 증류된 버전이 아니므로 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 = 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 = ['latents'], max_sequence_length: int = 128, clip_value: None | float = None, normalize: bool = False)
```

[소스](https://github.com/huggingface/diffusers/blob/main/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`입니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지의 목록입니다.

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

<<<<<<< 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
The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). num_images_per_prompt (`int`, *optional*, defaults to 1): The number of images to generate per prompt. generator (`torch.Generator` or `list[torch.Generator]`, *optional*): One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation deterministic. latents (`torch.FloatTensor`, *optional*): Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will be generated by sampling using the supplied random `generator`. prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument. negative_prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input argument. output_type (`str`, *optional*, defaults to `"pil"`): The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a `~pipelines.bria.BriaPipelineOutput` instead of a plain tuple. attention_kwargs (`dict`, *optional*): A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under `self.processor` in [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). callback_on_step_end (`Callable`, *optional*): A function that calls at the end of each denoising steps during the inference. The function is called with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by `callback_on_step_end_tensor_inputs`. callback_on_step_end_tensor_inputs (`list`, *optional*): The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the `._callback_tensor_inputs` attribute of your pipeline class. max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`. clip_value (`float`, *optional*): If set, the predicted noise is clipped to the range `[-clip_value, clip_value]` at each denoising step. normalize (`bool`, *optional*, defaults to `False`): Whether to normalize the predicted noise at each denoising step.

예:
```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/main/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` 입력 인수에서 negative_prompt_embeds가 생성됩니다.

