Diffusers documentation
Flux2
Flux2
Flux.2는 Black Forest Labs의 최신 이미지 생성 모델 시리즈로, Flux.1 시리즈에 이어 출시되었습니다. 완전히 새로운 아키텍처를 갖춘 새로운 모델이며, 처음부터 사전 학습을 수행했습니다!
Flux의 원래 모델 체크포인트는 여기에서 찾을 수 있습니다. 원래 추론 코드는 여기에서 찾을 수 있습니다.
Flux2는 소비자용 하드웨어에서 실행할 때 비용이 상당히 높을 수 있습니다. 그러나 일련의 최적화를 수행하여 더 빠르고 메모리에 부담이 적은 방식으로 실행할 수 있습니다. 자세한 내용은 이 섹션을 확인하세요. 또한, Flux는 추론 지연 시간의 트레이드오프를 감수하고 메모리 효율성을 위해 양자화를 활용할 수 있습니다. 더 자세한 내용은 이 블로그 게시물을 참고하세요.
Caching은 중간 결과를 저장하고 재사용하여 추론 속도를 높이는 데에도 도움이 될 수 있습니다.
캡션 업샘플링
Flux.2는 더 나은 프롬프트를 사용하면 더 좋은 출력을 생성할 수 있습니다. 파이프라인 호출 인수로 caption_upsample_temperature 인수를 설정하여 입력 프롬프트를 “업샘플링”할 수 있습니다. 공식 구현에서는 이 값을 0.15로 권장합니다.
Flux2Pipeline
클래스 diffusers.Flux2Pipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLFlux2text_encoder: Mistral3ForConditionalGenerationtokenizer: AutoProcessortransformer: Flux2Transformer2DModel )
매개변수
- transformer (Flux2Transformer2DModel) — 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer (MMDiT) 아키텍처.
- scheduler (FlowMatchEulerDiscreteScheduler) —
transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러. - vae (
AutoencoderKLFlux2) — 잠재 표현으로 이미지를 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델입니다. - text_encoder (
Mistral3ForConditionalGeneration) — Mistral3ForConditionalGeneration - tokenizer (
AutoProcessor) — PixtralProcessor 클래스의 토크나이저.
텍스트-이미지 생성을 위한 Flux2 파이프라인.
참고: https://bfl.ai/blog/flux-2
__call__
< source >( image: PIL.Image.Image | list[PIL.Image.Image] | None = Noneprompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float | None = 4.0num_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512text_encoder_out_layers: tuple = (10, 20, 30)caption_upsample_temperature: float = None ) → ~pipelines.flux2.Flux2PipelineOutput or tuple
매개변수
- image (
torch.Tensor,PIL.Image.Image,np.ndarray,list[torch.Tensor],list[PIL.Image.Image]또는list[np.ndarray]) — 시작점으로 사용할 이미지 배치의Image, numpy 배열 또는 텐서를 나타냅니다. numpy 배열과 pytorch 텐서 모두에서 예상 값 범위는[0, 1]입니다. 텐서 또는 텐서 목록인 경우 예상 shape은(B, C, H, W)또는(C, H, W)여야 합니다. numpy 배열 또는 배열 목록인 경우 예상 shape은(B, H, W, C)또는(H, W, C)여야 합니다.image로 이미지 latents도 받을 수 있지만, latents를 직접 전달하는 경우 다시 인코딩되지 않습니다. - prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우prompt_embeds를 대신 전달해야 합니다. - guidance_scale (
float, 선택 사항, 기본값 1.0) — 임베디드 가이던스 스케일은guidance_scale> 1. 을 더 높이면guidance_scale모델이prompt에 더 부합하는 이미지를 생성하도록 장려하지만, 이미지 품질이 낮아지는 대가를 치릅니다.Guidance-distilled 모델은
guidance_scale> 1인 경우 true classifer-free guidance를 근사합니다. 자세한 내용은 논문을 참고하세요. - 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) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다. - sigmas (
list[float], 선택 사항) —set_timesteps메서드에sigmas인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우,num_inference_steps가 전달될 때의 기본 동작이 사용됩니다. - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다. - generator (
torch.Generator또는list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록 - latents (
torch.Tensor, 선택 사항) — 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다. - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - output_type (
str, 선택 사항, 기본값"pil") — 이미지 생성의 출력 형식입니다. PIL:PIL.Image.Image또는np.array중 하나를 선택합니다. - return_dict (
bool, 선택 사항, 기본값True) — 일반 튜플 대신~pipelines.qwenimage.QwenImagePipelineOutput를 반환할지 여부. - attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의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, 기본값 512) —prompt에 사용할 최대 시퀀스 길이입니다. - text_encoder_out_layers (
tuple[int]) — 최종 프롬프트 임베딩을 유도하기 위해text_encoder에서 사용할 레이어 인덱스입니다. - caption_upsample_temperature (
float) — 지정된 경우, 출력을 개선하기 위해 캡션 업샘플링을 수행하려고 합니다. 캡션 업샘플링을 수행할 경우 0.15로 설정하는 것을 권장합니다.
반환값
~pipelines.flux2.Flux2PipelineOutput 또는 tuple
return_dict가 True인 경우 ~pipelines.flux2.Flux2PipelineOutput, 그렇지 않으면 tuple입니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지 목록입니다.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> import torch
>>> from diffusers import Flux2Pipeline
>>> pipe = Flux2Pipeline.from_pretrained("black-forest-labs/FLUX.2-dev", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> # Depending on the variant being used, the pipeline call will slightly vary.
>>> # Refer to the pipeline documentation for more details.
>>> image = pipe(prompt, num_inference_steps=50, guidance_scale=2.5).images[0]
>>> image.save("flux.png")Flux2KleinPipeline
클래스 diffusers.Flux2KleinPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLFlux2text_encoder: Qwen3ForCausalLMtokenizer: Qwen2Tokenizertransformer: Flux2Transformer2DModelis_distilled: bool = False )
매개변수
- transformer (Flux2Transformer2DModel) — 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer (MMDiT) 아키텍처.
- scheduler (FlowMatchEulerDiscreteScheduler) —
transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러. - vae (
AutoencoderKLFlux2) — 잠재 표현으로 이미지를 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델입니다. - text_encoder (
Qwen3ForCausalLM) — Qwen3ForCausalLM - tokenizer (
Qwen2TokenizerFast) — Qwen2TokenizerFast 클래스의 토크나이저.
텍스트-이미지 생성을 위한 Flux2 Klein 파이프라인.
참고: https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence
__call__
< source >( image: list[PIL.Image.Image] | PIL.Image.Image | None = Noneprompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50sigmas: list[float] | None = Noneguidance_scale: float = 4.0num_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: str | list[str] | None = Noneoutput_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512text_encoder_out_layers: tuple = (9, 18, 27) ) → ~pipelines.flux2.Flux2PipelineOutput or tuple
매개변수
- image (
torch.Tensor,PIL.Image.Image,np.ndarray,List[torch.Tensor],List[PIL.Image.Image]또는List[np.ndarray]) — 시작점으로 사용할 이미지 배치의Image, numpy 배열 또는 텐서를 나타냅니다. numpy 배열과 pytorch 텐서 모두에서 예상 값 범위는[0, 1]입니다. 텐서 또는 텐서 목록인 경우, 예상 shape은(B, C, H, W)또는(C, H, W)여야 합니다. numpy 배열 또는 배열 목록인 경우, 예상 shape은(B, H, W, C)또는(H, W, C)여야 합니다.image로 이미지 latents도 받을 수 있지만, latents를 직접 전달하는 경우 다시 인코딩되지 않습니다. - prompt (
str또는List[str], 선택) — 이미지 생성을 안내하는 프롬프트입니다. 정의되지 않은 경우prompt_embeds를 대신 전달해야 합니다. - guidance_scale (
float, 선택 사항, 기본값 4.0) — Classifier-Free Diffusion Guidance에서 정의한 가이던스 스케일입니다.guidance_scale은 Imagen Paper의 방정식 2의w로 정의됩니다.guidance_scale > 1로 설정하면 가이던스 스케일이 활성화됩니다. 가이던스 스케일이 높을수록prompt텍스트와 밀접하게 연결된 이미지를 생성하도록 장려하지만, 일반적으로 이미지 품질이 낮아지는 대가를 치릅니다. 단계별 증류된 모델의 경우guidance_scale은 무시됩니다. - 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) — 디노이징 단계의 수입니다. 디노이징 단계가 많을수록 일반적으로 더 높은 품질의 이미지를 생성하지만, 추론 속도가 느려집니다. - sigmas (
List[float], 선택 사항) —set_timesteps메서드에sigmas인수를 지원하는 스케줄러의 노이즈 제거 과정에 사용할 커스텀 시그마입니다. 정의되지 않은 경우,num_inference_steps가 전달될 때의 기본 동작이 사용됩니다. - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다. - generator (
torch.Generator또는List[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 torch generator 하나 또는 목록 - latents (
torch.Tensor, 선택 사항) — 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된 사전 생성된 노이즈 latents입니다. 동일한 생성을 다른 프롬프트로 조정하는 데 사용할 수 있습니다. 제공되지 않으면, 제공된 랜덤generator를 사용하여 샘플링하여 latents 텐서가 생성됩니다. - prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - negative_prompt_embeds (
torch.Tensor, 선택) — 미리 생성된 부정 텍스트 임베딩입니다. 이 파이프라인에서는 ""가 부정 프롬프트로 사용됩니다. 제공되지 않으면 ""에서 생성됩니다. - output_type (
str, 선택 사항, 기본값"pil") — 이미지 생성의 출력 형식입니다. PIL:PIL.Image.Image또는np.array중 하나를 선택합니다. - return_dict (
bool, 선택 사항, 기본값True) — 일반 튜플 대신~pipelines.qwenimage.QwenImagePipelineOutput를 반환할지 여부. - attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의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, 기본값 512) —prompt에 사용할 최대 시퀀스 길이입니다. - text_encoder_out_layers (
tuple[int]) — 최종 프롬프트 임베딩을 유도하기 위해text_encoder에서 사용할 레이어 인덱스입니다.
반환값
~pipelines.flux2.Flux2PipelineOutput 또는 tuple
return_dict가 True인 경우 ~pipelines.flux2.Flux2PipelineOutput, 그렇지 않으면 tuple입니다. tuple을 반환할 경우 첫 번째 요소는 생성된 이미지 목록입니다.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> import torch
>>> from diffusers import Flux2KleinPipeline
>>> pipe = Flux2KleinPipeline.from_pretrained(
... "black-forest-labs/FLUX.2-klein-base-9B", torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> prompt = "A cat holding a sign that says hello world"
>>> # Depending on the variant being used, the pipeline call will slightly vary.
>>> # Refer to the pipeline documentation for more details.
>>> image = pipe(prompt, num_inference_steps=50, guidance_scale=4.0).images[0]
>>> image.save("flux2_output.png")Flux2KleinKVPipeline
class diffusers.Flux2KleinKVPipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLFlux2text_encoder: Qwen3ForCausalLMtokenizer: Qwen2Tokenizertransformer: Flux2Transformer2DModelis_distilled: bool = True )
매개변수
- transformer (Flux2Transformer2DModel) — 인코딩된 이미지 레이턴트를 디노이즈하기 위한 조건부 Transformer (MMDiT) 아키텍처.
- scheduler (FlowMatchEulerDiscreteScheduler) —
transformer와 함께 사용하여 인코딩된 이미지 latents의 노이즈를 제거하는 데 사용되는 스케줄러. - vae (
AutoencoderKLFlux2) — 잠재 표현으로 이미지를 인코딩하고 디코딩하는 Variational Auto-Encoder (VAE) 모델입니다. - text_encoder (
Qwen3ForCausalLM) — Qwen3ForCausalLM - tokenizer (
Qwen2TokenizerFast) — Qwen2TokenizerFast 클래스의 토크나이저.
KV 캐시 기반 참조 이미지 조건부 텍스트-이미지 생성을 위한 Flux2 Klein KV 파이프라인
첫 번째 노이즈 제거 단계에서 참조 이미지 토큰이 forward pass에 포함되며, 해당 attention K/V 투영이 캐시됩니다. 이후 단계에서는 재계산 없이 캐시된 K/V를 재사용하여 참조 이미지를 사용할 때 더 빠른 추론을 제공합니다.
참고: https://bfl.ai/blog/flux2-klein-towards-interactive-visual-intelligence
__call__
< source >( image: list[PIL.Image.Image] | PIL.Image.Image | None = Noneprompt: str | list[str] = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 4sigmas: list[float] | None = Nonenum_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512text_encoder_out_layers: tuple = (9, 18, 27) )
매개변수
- image (
PIL.Image.Image또는List[PIL.Image.Image], 선택 사항) — 조건부 생성을 위한 참조 이미지입니다. 첫 번째 디노이징 단계에서 참조 토큰이 포워드 패스에 포함되며, 해당 주의 K/V가 캐시됩니다. 이후 단계에서는 재계산 없이 캐시된 K/V를 재사용합니다. - prompt (
str또는List[str], 선택 사항) — 이미지 생성을 안내하는 프롬프트입니다. - height (
int, 선택 사항) — 생성된 이미지의 픽셀 단위 높이입니다. - width (
int, 선택 사항) — 생성된 이미지의 픽셀 단위 너비입니다. - num_inference_steps (
int, 선택 사항, 기본값 4) — 디노이징 단계 수입니다. - sigmas (
List[float], 선택 사항) — 디노이징 스케줄에 사용할 커스텀 시그마입니다. - num_images_per_prompt (
int, 선택 사항, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다. - generator (
torch.Generator또는List[torch.Generator], 선택 사항) — 결정론적 생성을 위한 Generator입니다. - latents (
torch.Tensor, 선택 사항) — 미리 생성된 노이즈가 포함된 latents. - prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 텍스트 임베딩입니다. - output_type (
str, 선택 사항, 기본값"pil") — 출력 형식:"pil"또는"np". - return_dict (
bool, 선택 사항, 기본값True) —Flux2PipelineOutput을 반환할지, 아니면 일반 튜플을 반환할지를 결정합니다. - attention_kwargs (
dict, 선택 사항) — attention processor에 전달되는 추가 kwargs입니다. - callback_on_step_end (
Callable, 선택 사항) — 각 디노이징 단계의 끝에서 호출되는 콜백 함수입니다. - callback_on_step_end_tensor_inputs (
List, 선택 사항) — 콜백 함수에 전달되는 텐서 입력입니다. - max_sequence_length (
int, 기본값 512) — 프롬프트의 최대 시퀀스 길이입니다. - text_encoder_out_layers (
tuple[int]) — 텍스트 인코더 히든 상태 추출을 위한 레이어 인덱스.
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> import torch
>>> from PIL import Image
>>> from diffusers import Flux2KleinKVPipeline
>>> pipe = Flux2KleinKVPipeline.from_pretrained(
... "black-forest-labs/FLUX.2-klein-9b-kv", torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> ref_image = Image.open("reference.png")
>>> image = pipe("A cat dressed like a wizard", image=ref_image, num_inference_steps=4).images[0]
>>> image.save("flux2_kv_output.png")