Diffusers documentation
Krea 2
Krea 2
Krea 2 (K2)는 그룹 쿼리 어텐션을 갖춘 단일 스트림 MMDiT를 기반으로 구축된 플로우 매칭 텍스트-이미지 모델입니다. Qwen3-VL 텍스트 인코더가 조건을 제공합니다. 마지막 히든 상태 대신, 토큰당 12개의 디코더 레이어에서 히든 상태를 추출하여 작은 텍스트 퓨전 단계에서 트랜스포머 내부에서 융합합니다. 이미지는 Qwen-Image VAE로 디코딩됩니다.
두 개의 체크포인트가 릴리스되며, 동일한 아키텍처를 공유하지만 권장 샘플러 설정이 다릅니다:
- Base (midtrain) — classifier-free guidance를 사용하는 전체 sampler를 사용하세요:
num_inference_steps=28,guidance_scale=4.5. - TDM (distilled) — few-step sampling을 위해 증류된 모델로,
num_inference_steps=8로 실행하고 guidance를 비활성화합니다(guidance_scale=0.0).
guidance_scale는 Krea 2 규약을 따릅니다: velocity는 cond + guidance_scale * (cond - uncond)로 계산되며, guidance_scale > 0인 경우에만 guidance가 활성화됩니다(이는 scale이 1 + guidance_scale인 일반적인 CFG 수식과 동일합니다).
텍스트-이미지
import torch
from diffusers import Krea2Pipeline
# Load from a local directory produced by the Krea 2 conversion (no hub repo yet).
pipe = Krea2Pipeline.from_pretrained("krea/Krea-2-Raw", dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
prompt = "a fox in the snow"
image = pipe(
prompt,
height=1024,
width=1024,
num_inference_steps=28,
guidance_scale=4.5,
generator=torch.Generator("cuda").manual_seed(0),
).images[0]
image.save("krea2.png")Krea2 Turbo를 사용하는 예제도 추가로 제공합니다:
import torch
from diffusers import Krea2Pipeline
pipe = Krea2Pipeline.from_pretrained("krea/Krea-2-Turbo", dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image = pipe(
"a fox in the snow",
height=1024,
width=1024,
num_inference_steps=8,
guidance_scale=0.0,
generator=torch.Generator("cuda").manual_seed(0),
).images[0]
image.save("krea2_turbo.png")단일 파일 체크포인트 로드
import torch
from diffusers import Krea2Pipeline, Krea2Transformer2DModel
transformer = Krea2Transformer2DModel.from_single_file(
"https://huggingface.co/krea/Krea-2-Turbo/blob/main/turbo.safetensors", dtype=torch.bfloat16
)
pipe = Krea2Pipeline.from_pretrained("krea/Krea-2-Turbo", transformer=transformer, dtype=torch.bfloat16).to("cuda")Krea2Pipeline
클래스 diffusers.Krea2Pipeline
< source >( scheduler: FlowMatchEulerDiscreteSchedulervae: AutoencoderKLQwenImagetext_encoder: Qwen3VLModeltokenizer: AutoTokenizertransformer: Krea2Transformer2DModeltext_encoder_select_layers: tuple[int, ...] | list[int] | None = Noneis_distilled: bool = Falsepatch_size: int = 2 )
매개변수
- scheduler (FlowMatchEulerDiscreteScheduler) —
Euler flow-matching 스케줄러입니다. Krea 2의 시그마 스케줄은 해상도 인식 지수 시간 시프트이므로,
스케줄러 설정에서 Krea 2 시프트 매개변수(
base_shift=0.5,max_shift=1.15,base_image_seq_len=256,max_image_seq_len=6400)와 함께use_dynamic_shifting=True가 설정되어 있어야 합니다. - vae (AutoencoderKLQwenImage) — latent를 이미지로 디코딩하는 데 사용되는 Qwen-Image 변분 오토인코더(f8, 16 latent 채널)
- text_encoder (PreTrainedModel) —
Qwen3-VL 모델(예:
Qwen/Qwen3-VL-4B-Instruct의Qwen3VLModel). 파이프라인은 마지막 hidden state가 아니라 여러 decoder layer에서 추출된 hidden states 스택을 사용합니다. - tokenizer (AutoTokenizer) — 텍스트 인코더와 짝을 이루는 토크나이저.
- transformer (Krea2Transformer2DModel) — flow-matching 속도를 예측하는 Krea 2 단일 스트림 MMDiT입니다.
- text_encoder_select_layers (
tuple[int, ...], 선택 사항) — 텍스트 인코더의hidden_states튜플(0은 임베딩 출력)에서, 토큰별로 스택되어 transformer의 텍스트 조건으로 사용되는 상태의 인덱스입니다.transformer.config.num_text_layers개의 항목을 가져야 합니다. - is_distilled (
bool, 선택 사항, 기본값False) — transformer가 few-step distilled (TDM/turbo) 체크포인트인지 여부입니다.True인 경우 고정 타임스텝 시프트mu=1.15가 사용되며, 그렇지 않으면mu가 이미지 해상도로부터 계산됩니다. - patch_size (
int, 선택 사항, 기본값 2) — transformer에 입력되기 전에 latents가 패킹되는 정사각형 패치의 한 변 길이. 실제 픽셀 대 토큰 다운샘플링 계수는vae_scale_factor * patch_size입니다.
텍스트-이미지 생성을 위한 Krea 2 파이프라인.
__call__
< source >( prompt: str | list[str] | None = Nonenegative_prompt: str | list[str] | None = Noneheight: int = 1024width: int = 1024num_inference_steps: int = 28sigmas: list[float] | None = Noneguidance_scale: float = 4.5num_images_per_prompt: int = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_embeds_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds_mask: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecallback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']attention_kwargs: dict[str, typing.Any] | None = Nonemax_sequence_length: int = 512 ) → Krea2PipelineOutput or tuple
매개변수
- prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내할 프롬프트입니다. 정의되지 않은 경우prompt_embeds를 전달해야 합니다. - negative_prompt (
str또는list[str], 선택 사항) — 이미지 생성을 안내하지 않을 프롬프트입니다.guidance_scale <= 0인 경우 무시되며, 가이던스가 활성화된 경우 기본값은 빈 프롬프트입니다. - height (
int, 기본값 1024) — 생성된 이미지의 픽셀 단위 높이입니다. 필요 시 16의 배수로 올림됩니다. - width (
int, 기본값 1024) — 생성된 이미지의 픽셀 단위 너비입니다. 필요 시 16의 배수로 올림됩니다. - num_inference_steps (
int, 기본값 28) — 디노이징 단계 수입니다. base(midtrain) 체크포인트에는 28을, few-step distilled(TDM) 체크포인트에는 8을 사용하십시오. - sigmas (
list[float], 선택 사항) — 스케줄러에 사용할 커스텀 시그마입니다. 정의되지 않은 경우, 기본linspace(1.0, 1/num_inference_steps, num_inference_steps)그리드가 사용됩니다(해상도 인식 시프트는 스케줄러 내부에서 적용됩니다). - guidance_scale (
float, 기본값 4.5) — Krea 2 규약을 따르는 Classifier-free guidance scale입니다. velocity는cond + guidance_scale * (cond - uncond)로 계산되며,guidance_scale > 0인 경우 항상 guidance가 활성화됩니다(이는 scale이1 + guidance_scale인 일반적인 CFG 수식과 동일합니다). 비활성화하려면0.0으로 설정하세요(예: TDM checkpoint). - num_images_per_prompt (
int, 기본값 1) — 프롬프트당 생성할 이미지의 수입니다. - generator (
torch.Generator또는list[torch.Generator], 선택 사항) — 생성을 결정적으로 만들기 위한 하나 이상의 torch generator. - latents (
torch.Tensor, 선택 사항) — 이미지 생성의 입력으로 사용할 가우시안 분포에서 샘플링된, 패킹된 형태(batch_size, image_seq_len, in_channels)의 사전 생성된 노이즈 latents입니다. - prompt_embeds (
torch.Tensor, 선택 사항) —(batch_size, text_seq_len, num_text_layers, text_hidden_dim)형태의 사전 생성된 텍스트 임베딩입니다. 제공되지 않으면prompt에서 임베딩이 생성됩니다. - prompt_embeds_mask (
torch.Tensor, 선택 사항) —prompt_embeds에 대한 불리언 마스크입니다.prompt_embeds가 전달될 때 필수입니다. - negative_prompt_embeds (
torch.Tensor, 선택 사항) — 미리 생성된 부정 텍스트 임베딩.prompt_embeds와 동일한 레이아웃을 가집니다. - negative_prompt_embeds_mask (
torch.Tensor, 선택 사항) —negative_prompt_embeds에 대한 Boolean 마스크입니다.negative_prompt_embeds가 전달될 때 필수입니다. - output_type (
str, 선택 사항, 기본값"pil") — 생성된 이미지의 출력 형식입니다."pil","np","pt"또는"latent"중 하나를 선택합니다. - return_dict (
bool, 선택 사항, 기본값True) — 일반 튜플 대신 Krea2PipelineOutput를 반환할지 여부. - callback_on_step_end (
Callable, 선택 사항) — 각 노이즈 제거 단계의 끝에서callback_on_step_end(self, step, timestep, callback_kwargs)로 호출되는 함수입니다. - callback_on_step_end_tensor_inputs (
list[str], 선택 사항, 기본값["latents"]) —callback_on_step_end함수의 텐서 입력 목록입니다.._callback_tensor_inputs의 부분집합이어야 합니다. - attention_kwargs (
dict, 선택 사항) — 지정된 경우 diffusers.models.attention_processor의self.processor에서 정의된AttentionProcessor로 전달되는 kwargs 사전입니다. - max_sequence_length (
int, 기본값 512) — Transformer가 소비하는 고정된 텍스트 시퀀스 길이입니다. 프롬프트는 이 길이에 맞게 패딩되거나 잘립니다.
반환값
Krea2PipelineOutput 또는 tuple
return_dict가 True이면 Krea2PipelineOutput, 그렇지 않으면 생성된 이미지가 포함된 리스트가 첫 번째 요소인 tuple
생성을 위해 파이프라인을 호출할 때 호출되는 함수.
예:
>>> import torch
>>> from diffusers import Krea2Pipeline
>>> # Load from a local directory produced by the Krea 2 conversion (no hub repo yet).
>>> pipe = Krea2Pipeline.from_pretrained("path/to/krea2-diffusers", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> prompt = "a fox in the snow"
>>> # Base (midtrain) checkpoint defaults. For the few-step distilled (TDM) checkpoint use
>>> # `num_inference_steps=8, guidance_scale=0.0` instead.
>>> image = pipe(prompt, num_inference_steps=28, guidance_scale=4.5).images[0]
>>> image.save("krea2.png")encode_prompt
< source >( prompt: str | list[str]device: typing.Optional[torch.device] = Nonenum_images_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_embeds_mask: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 512 )
매개변수
- prompt (
str또는list[str], 선택 사항) — 인코딩할 프롬프트 - device — (
torch.device): torch device - num_images_per_prompt (
int) — 프롬프트당 생성할 이미지 수 - prompt_embeds (
torch.Tensor, 선택 사항) —(batch_size, text_seq_len, num_text_layers, text_hidden_dim)모양의 사전 생성된 텍스트 임베딩입니다. 텍스트 입력을 쉽게 조정하는 데 사용할 수 있으며, 예를 들어 프롬프트 가중치 설정에 활용할 수 있습니다. 제공되지 않으면prompt입력 인자로부터 텍스트 임베딩이 생성됩니다. - prompt_embeds_mask (
torch.Tensor, 선택 사항) — 유효한 텍스트 토큰을 표시하는 사전 생성된 불리언 마스크로, 모양은(batch_size, text_seq_len)입니다.prompt_embeds가 전달될 때 필수입니다. - max_sequence_length (
int, 기본값 512) — Transformer가 소비하는 고정된 텍스트 시퀀스 길이입니다. 프롬프트는 이 길이에 맞게 패딩되거나 잘립니다.
( prompt: str | list[str]max_sequence_length: int = 512device: typing.Optional[torch.device] = None )
prompt을 고정 길이의 Krea 2 레이아웃으로 토큰화하고 선택된 인코더의 숨겨진 상태를 가져옵니다.
(hidden_states, attention_mask) 튜플을 반환합니다. 각 요소의 형태는 각각 (batch_size, text_seq_len, num_text_layers, text_hidden_dim)과 (batch_size, text_seq_len)(bool)입니다.
결합된 시퀀스에 대한 (text_seq_len + grid_height * grid_width, 3) 회전 좌표를 구성합니다:
텍스트 토큰은 원점에 위치하고, 이미지 토큰은 (0, h, w) 잠재 그리드 좌표를 가집니다.
Krea2PipelineOutput
클래스 diffusers.pipelines.krea2.Krea2PipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarray )
Krea 2 파이프라인의 출력 클래스입니다.
모듈형
Krea 2는 모듈형 파이프라인으로도 사용할 수 있습니다. Classifier-free guidance는 guidance_scale 호출 인수가 아닌 guider 구성 요소를 통해 설정됩니다. Krea 2는 cond-anchored CFG를 사용하며, 이는 use_original_formulation=True가 적용된 ClassifierFreeGuidance입니다.
import torch
from diffusers import ClassifierFreeGuidance, ModularPipeline
pipe = ModularPipeline.from_pretrained("krea/Krea-2-Raw")
pipe.load_components(dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image = pipe(
prompt="a fox in the snow",
height=1024,
width=1024,
num_inference_steps=28,
generator=torch.Generator("cuda").manual_seed(0),
).images[0]
image.save("krea2.png")Krea2 Turbo 사용 예제도 함께 제공합니다. 증류된 체크포인트는 자체 블록 세트(Krea2TurboAutoBlocks)에 매핑됩니다: 가이던스 없이 실행되며(guider 없음), 부정 프롬프트를 받지 않고, 몇 단계 만에 샘플링합니다. ModularPipeline.from_pretrained는 체크포인트의 is_distilled 설정을 기반으로 터보 블록을 자동으로 선택하므로 가이던스 설정이 필요하지 않습니다:
import torch
from diffusers import ModularPipeline
pipe = ModularPipeline.from_pretrained("krea/Krea-2-Turbo")
pipe.load_components(dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image = pipe(
prompt="a fox in the snow",
height=1024,
width=1024,
num_inference_steps=8,
generator=torch.Generator("cuda").manual_seed(0),
).images[0]
image.save("krea2_turbo.png")Krea2ModularPipeline
클래스 diffusers.Krea2ModularPipeline
< source >( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )
Krea 2용 ModularPipeline.
Krea2AutoBlocks
Krea 2를 사용한 텍스트-이미지 생성을 위한 Auto Modular 파이프라인: 텍스트 인코딩 -> 코어 디노이즈(대칭 CFG) -> 디코딩.
지원되는 워크플로:
text2image:prompt필수
Components:
text_encoder (Qwen3VLModel): Qwen3-VL 텍스트 인코더. tokenizer (AutoTokenizer): 텍스트 인코더와 짝을 이루는 토크나이저. guider (ClassifierFreeGuidance) transformer (Krea2Transformer2DModel) scheduler (FlowMatchEulerDiscreteScheduler) vae (AutoencoderKLQwenImage) image_processor (VaeImageProcessor)
입력:
prompt (str):
이미지 생성을 안내하는 프롬프트입니다.
negative_prompt (str, 선택 사항):
CFG를 위한 음의 프롬프트입니다.
max_sequence_length (int, 선택 사항, 기본값 512):
프롬프트 인코딩을 위한 최대 시퀀스 길이입니다.
num_images_per_prompt (int, 선택 사항, 기본값 1):
프롬프트당 생성할 이미지의 수입니다.
latents (Tensor, 선택 사항):
이미지 생성을 위한 사전 생성된 노이즈된 잠재 변수입니다.
height (int, 선택 사항, 기본값 1024):
생성된 이미지의 픽셀 단위 높이입니다.
width (int, 선택 사항, 기본값 1024):
생성된 이미지의 픽셀 단위 너비입니다.
generator (Generator, 선택 사항):
결정론적 생성을 위한 Torch 생성기입니다.
num_inference_steps (int, 선택 사항, 기본값 28):
노이즈 제거 단계의 수입니다.
sigmas (list, 선택 사항):
사용자 정의 시그마 스케줄입니다(기본값은 선형 램프).
attention_kwargs (dict, 선택 사항):
어텐션 프로세서에 대한 추가 kwargs입니다.
output_type (str, 선택 사항, 기본값 pil):
출력 형식: ‘pil’, ‘np’, ‘pt’.
출력:
images (list):
생성된 이미지.
Krea2TurboModularPipeline
클래스 diffusers.Krea2TurboModularPipeline
< source >( blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = Nonepretrained_model_name_or_path: str | os.PathLike | None = Nonecomponents_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = Nonecollection: str | None = Noneworkflow: str | None = Nonemodular_config_dict: dict[str, typing.Any] | None = Noneconfig_dict: dict[str, typing.Any] | None = None**kwargs )
디스틸된 Krea 2 turbo(TDM) 체크포인트를 위한 ModularPipeline입니다. classifier-free guidance 없이 실행되므로 negative prompt를 받지 않으며 guider가 없습니다.
Krea2TurboAutoBlocks
Auto 모듈러 파이프라인을 사용하여 디스틸된 Krea 2 turbo 체크포인트로 텍스트-이미지 생성을 수행합니다: 텍스트 인코딩 -> 코어 디노이즈(가이던스 없음) -> 디코딩.
지원되는 워크플로:
text2image:prompt필수
Components:
text_encoder (Qwen3VLModel): Qwen3-VL 텍스트 인코더. tokenizer (AutoTokenizer): 텍스트 인코더와 짝을 이루는 토크나이저. transformer (Krea2Transformer2DModel) scheduler (FlowMatchEulerDiscreteScheduler)
vae (AutoencoderKLQwenImage) image_processor (VaeImageProcessor)
입력:
prompt (str):
이미지 생성을 안내하는 프롬프트입니다.
max_sequence_length (int, 선택 사항, 기본값 512):
프롬프트 인코딩을 위한 최대 시퀀스 길이입니다.
num_images_per_prompt (int, 선택 사항, 기본값 1):
프롬프트당 생성할 이미지의 수입니다.
latents (Tensor, 선택 사항):
이미지 생성을 위한 사전 생성된 노이즈 latents입니다.
height (int, 선택 사항, 기본값 1024):
생성된 이미지의 픽셀 단위 높이입니다.
width (int, 선택 사항, 기본값 1024):
생성된 이미지의 픽셀 단위 너비입니다.
generator (Generator, 선택 사항):
결정론적 생성을 위한 Torch generator입니다.
num_inference_steps (int, 선택 사항, 기본값 8):
디노이징 단계의 수입니다.
sigmas (list, 선택 사항):
사용자 정의 sigma 스케줄입니다(기본값은 선형 램프).
attention_kwargs (dict, 선택 사항):
attention 프로세서에 대한 추가 kwargs입니다.
output_type (str, 선택 사항, 기본값 pil):
출력 형식: ‘pil’, ‘np’, ‘pt’.
출력:
images (list):
생성된 이미지.