Diffusers documentation
Krea 2
Krea 2
Krea 2 (K2) là mô hình text-to-image dựa trên flow-matching, được xây dựng quanh một MMDiT single-stream với grouped-query attention. Bộ mã hóa văn bản Qwen3-VL cung cấp điều kiện: thay vì sử dụng hidden state cuối cùng, các hidden state từ mười hai lớp decoder được lấy theo từng token và được kết hợp bên trong transformer bởi một giai đoạn text-fusion nhỏ. Ảnh được giải mã bằng Qwen-Image VAE.
Hai checkpoint được phát hành, chia sẻ cùng một kiến trúc nhưng với các cài đặt sampler khuyến nghị khác nhau:
- Cơ bản (midtrain) — sử dụng bộ lấy mẫu đầy đủ với classifier-free guidance:
num_inference_steps=28,guidance_scale=4.5. - TDM (distilled) — được chưng cất để lấy mẫu trong vài bước, chạy với
num_inference_steps=8và tắt hướng dẫn (guidance_scale=0.0).
guidance_scale tuân theo quy ước của Krea 2: velocity được tính bằng cond + guidance_scale * (cond - uncond) và guidance được kích hoạt khi guidance_scale > 0 (điều này tương đương với công thức CFG thông thường với scale là 1 + guidance_scale).
Văn bản sang hình ảnh
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")Ngoài ra, chúng tôi còn cung cấp một ví dụ về việc sử dụng 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")Tải checkpoint dạng tệp đơn
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
lớp 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 )
Tham số
- scheduler (FlowMatchEulerDiscreteScheduler) —
Trình lập lịch Euler flow-matching. Lịch sigma của Krea 2 là sự dịch chuyển thời gian mũ nhận thức độ phân giải, do đó
cấu hình trình lập lịch được kỳ vọng sẽ đặt
use_dynamic_shifting=Truecùng với các tham số dịch chuyển của Krea 2 (base_shift=0.5,max_shift=1.15,base_image_seq_len=256,max_image_seq_len=6400). - vae (AutoencoderKLQwenImage) — Biến thể tự mã hóa (variational auto-encoder) của Qwen-Image (f8, 16 kênh tiềm ẩn) được dùng để giải mã các giá trị tiềm ẩn thành ảnh.
- text_encoder (PreTrainedModel) —
Một mô hình Qwen3-VL (ví dụ
Qwen3VLModelcủaQwen/Qwen3-VL-4B-Instruct). Pipeline sử dụng một chồng hidden states được lấy từ nhiều lớp decoder khác nhau thay vì hidden state cuối cùng. - tokenizer (AutoTokenizer) — Bộ phân từ đi kèm với bộ mã hóa văn bản.
- transformer (Krea2Transformer2DModel) — MMDiT single-stream của Krea 2, dự đoán vận tốc flow-matching.
- text_encoder_select_layers (
tuple[int, ...], tuỳ chọn) — Các chỉ số trong tuplehidden_statescủa text encoder (0 là đầu ra embedding) mà trạng thái của chúng được xếp chồng theo từng token để làm điều kiện văn bản cho transformer. Phải cótransformer.config.num_text_layersmục. - is_distilled (
bool, tùy chọn, mặc định làFalse) — Xác định xem transformer có phải là checkpoint distilled (TDM/turbo) ít bước hay không. KhiTrue, một mức dịch chuyển bước thời gian cố địnhmu=1.15sẽ được sử dụng; ngược lại,musẽ được tính toán từ độ phân giải của hình ảnh. - patch_size (
int, tùy chọn, mặc định là 2) — Độ dài cạnh của các ô vuông mà các latents được đóng gói vào trước khi đi vào transformer. Hệ số giảm mẫu từ pixel xuống token hiệu dụng làvae_scale_factor * patch_size.
Pipeline Krea 2 cho việc tạo ảnh từ văn bản.
__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
Tham số
- prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyềnprompt_embeds. - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Bỏ qua khiguidance_scale <= 0; mặc định là prompt rỗng khi guidance được bật. - height (
int, mặc định là 1024) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. Làm tròn lên thành bội số của 16 nếu cần. - width (
int, mặc định là 1024) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. Làm tròn lên thành bội số của 16 nếu cần. - num_inference_steps (
int, mặc định là 28) — Số bước khử nhiễu. Sử dụng 28 cho checkpoint cơ bản (midtrain) và 8 cho checkpoint chưng cất ít bước (TDM). - sigmas (
list[float], tùy chọn) — Các sigma tùy chỉnh cho trình lập lịch. Nếu không được định nghĩa, lưới mặc địnhlinspace(1.0, 1/num_inference_steps, num_inference_steps)sẽ được sử dụng (sự dịch chuyển nhận thức độ phân giải được áp dụng bên trong trình lập lịch). - guidance_scale (
float, mặc định là 4.5) — Thang độ hướng dẫn không phân loại (classifier-free guidance scale), tuân theo quy ước của Krea 2: vận tốc được tính bằngcond + guidance_scale * (cond - uncond)và hướng dẫn được kích hoạt khiguidance_scale > 0(điều này tương đương với công thức CFG thông thường với thang độ1 + guidance_scale). Đặt thành0.0để tắt (ví dụ: cho checkpoint TDM). - num_images_per_prompt (
int, mặc định là 1) — Số lượng hình ảnh cần tạo cho mỗi prompt. - generator (
torch.Generatorhoặclist[torch.Generator], tuỳ chọn) — Một hoặc nhiều torch generator để làm cho quá trình sinh ra kết quả tất định. - latents (
torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước ở dạng đóng gói(batch_size, image_seq_len, in_channels), được lấy mẫu từ một phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã tạo trước có hình dạng(batch_size, text_seq_len, num_text_layers, text_hidden_dim). Nếu không được cung cấp, các embedding sẽ được tạo từprompt. - prompt_embeds_mask (
torch.Tensor, tùy chọn) — Mặt nạ Boolean choprompt_embeds; bắt buộc khiprompt_embedsđược truyền vào. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước; cùng bố cục vớiprompt_embeds. - negative_prompt_embeds_mask (
torch.Tensor, tùy chọn) — Mặt nạ Boolean chonegative_prompt_embeds; bắt buộc khinegative_prompt_embedsđược truyền vào. - output_type (
str, tùy chọn, mặc định là"pil") — Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữa"pil","np","pt"hoặc"latent". - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về một Krea2PipelineOutput thay vì một tuple thông thường hay không. - callback_on_step_end (
Callable, tùy chọn) — Một hàm được gọi vào cuối mỗi bước khử nhiễu vớicallback_on_step_end(self, step, timestep, callback_kwargs). - callback_on_step_end_tensor_inputs (
list[str], tùy chọn, mặc định là["latents"]) — Danh sách các đầu vào tensor cho hàmcallback_on_step_end. Phải là một tập con của._callback_tensor_inputs. - attention_kwargs (
dict, tùy chọn) — Một từ điển kwargs, nếu được chỉ định, sẽ được truyền đếnAttentionProcessornhư đã định nghĩa dướiself.processortrong diffusers.models.attention_processor. - max_sequence_length (
int, mặc định là 512) — Chiều dài chuỗi văn bản cố định được transformer tiêu thụ; các prompt sẽ được đệm hoặc cắt ngắn để đạt chiều dài này.
Trả về
Krea2PipelineOutput hoặc tuple
Krea2PipelineOutput nếu
return_dict là True, ngược lại là một tuple, trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh đã tạo.
Hàm được gọi khi gọi pipeline cho việc sinh.
Ví dụ:
>>> 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 )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - device — (
torch.device): thiết bị torch - num_images_per_prompt (
int) — số lượng hình ảnh cần được tạo cho mỗi prompt - prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding văn bản đã tạo trước có hình dạng(batch_size, text_seq_len, num_text_layers, text_hidden_dim). Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, ví dụ như trọng số prompt. Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vàoprompt. - prompt_embeds_mask (
torch.Tensor, tuỳ chọn) — Mặt nạ boolean được tạo trước, đánh dấu các token văn bản hợp lệ, có hình dạng(batch_size, text_seq_len). Bắt buộc khi truyềnprompt_embeds. - max_sequence_length (
int, mặc định là 512) — Chiều dài chuỗi văn bản cố định được transformer tiêu thụ; các prompt sẽ được đệm hoặc cắt ngắn để đạt chiều dài này.
( prompt: str | list[str]max_sequence_length: int = 512device: typing.Optional[torch.device] = None )
Tokenize prompt thành bố cục Krea 2 có độ dài cố định và lấy các trạng thái ẩn của encoder đã chọn.
Trả về một tuple (hidden_states, attention_mask) có hình dạng (batch_size, text_seq_len, num_text_layers, text_hidden_dim) và (batch_size, text_seq_len) (bool).
Xây dựng tọa độ rotary (text_seq_len + grid_height * grid_width, 3) cho chuỗi kết hợp:
các token văn bản nằm tại gốc tọa độ, các token ảnh mang tọa độ lưới tiềm ẩn (0, h, w) của chúng.
Krea2PipelineOutput
lớp diffusers.pipelines.krea2.Krea2PipelineOutput
< source >( images: list[PIL.Image.Image] | numpy.ndarray )
Lớp đầu ra cho pipeline Krea 2.
Modular
Krea 2 cũng có sẵn dưới dạng pipeline module hóa. Classifier-free guidance được cấu hình thông qua thành phần guider thay vì tham số gọi guidance_scale. Krea 2 sử dụng CFG neo điều kiện (cond-anchored CFG), tức là ClassifierFreeGuidance với use_original_formulation=True.
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")Ngoài ra, chúng tôi cung cấp một ví dụ về việc sử dụng Krea2 Turbo. Checkpoint đã được chưng cất (distilled) được ánh xạ đến một bộ khối riêng của nó (Krea2TurboAutoBlocks): nó chạy không có guidance (không có guider), không nhận negative prompt và lấy mẫu trong vài bước. ModularPipeline.from_pretrained tự động chọn các khối turbo từ cấu hình is_distilled của checkpoint, do đó không cần cấu hình guidance:
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
lớp 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 )
Một ModularPipeline cho Krea 2.
Krea2AutoBlocks
Auto Modular pipeline cho việc tạo ảnh từ văn bản sử dụng Krea 2: mã hóa văn bản -> khử nhiễu lõi (CFG đối xứng) -> giải mã.
Các quy trình làm việc được hỗ trợ:
text2image: yêu cầuprompt
Các thành phần:
text_encoder (Qwen3VLModel): Bộ mã hóa văn bản Qwen3-VL. tokenizer (AutoTokenizer): Bộ phân từ đi kèm
với bộ mã hóa văn bản. guider (ClassifierFreeGuidance) transformer (Krea2Transformer2DModel) scheduler
(FlowMatchEulerDiscreteScheduler) vae (AutoencoderKLQwenImage) image_processor (VaeImageProcessor)
Đầu vào:
prompt (str):
Prompt hoặc các prompt để định hướng việc tạo ảnh.
negative_prompt (str, tùy chọn):
Prompt âm (negative prompt) cho CFG.
max_sequence_length (int, tùy chọn, mặc định là 512):
Độ dài chuỗi tối đa cho việc mã hóa prompt.
num_images_per_prompt (int, tùy chọn, mặc định là 1):
Số lượng ảnh cần tạo cho mỗi prompt.
latents (Tensor, tùy chọn):
Các latents nhiễu đã tạo sẵn cho việc tạo ảnh.
height (int, tùy chọn, mặc định là 1024):
Chiều cao của ảnh được tạo, tính bằng pixel.
width (int, tùy chọn, mặc định là 1024):
Chiều rộng của ảnh được tạo, tính bằng pixel.
generator (Generator, tùy chọn):
Torch generator cho việc tạo ra kết quả xác định.
num_inference_steps (int, tùy chọn, mặc định là 28):
Số bước khử nhiễu.
sigmas (list, tùy chọn):
Lịch sigma tùy chỉnh (mặc định là một đường dốc tuyến tính).
attention_kwargs (dict, tùy chọn):
Các kwargs bổ sung cho các bộ xử lý attention.
output_type (str, tùy chọn, mặc định là pil):
Định dạng đầu ra: ‘pil’, ‘np’, ‘pt’.
Đầu ra:
images (list):
Các hình ảnh được tạo.
Krea2TurboModularPipeline
lớp 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 )
ModularPipeline cho checkpoint Krea 2 turbo (TDM) đã được chưng cất. Nó chạy mà không cần classifier-free guidance, do đó không nhận negative prompt và không có guider.
Krea2TurboAutoBlocks
Auto Modular pipeline để tạo ảnh từ văn bản sử dụng checkpoint Krea 2 turbo đã được chưng cất: mã hóa văn bản -> khử nhiễu lõi (không có hướng dẫn) -> giải mã.
Các quy trình làm việc được hỗ trợ:
text2image: yêu cầuprompt
Các thành phần:
text_encoder (Qwen3VLModel): Bộ mã hóa văn bản Qwen3-VL. tokenizer (AutoTokenizer): Bộ phân từ đi kèm
với bộ mã hóa văn bản. transformer (Krea2Transformer2DModel) scheduler (FlowMatchEulerDiscreteScheduler)
vae (AutoencoderKLQwenImage) image_processor (VaeImageProcessor)
Đầu vào:
prompt (str):
Prompt hoặc các prompt để định hướng việc tạo ảnh.
max_sequence_length (int, tùy chọn, mặc định là 512):
Độ dài chuỗi tối đa cho việc mã hóa prompt.
num_images_per_prompt (int, tùy chọn, mặc định là 1):
Số lượng ảnh cần tạo cho mỗi prompt.
latents (Tensor, tùy chọn):
Các latents nhiễu đã tạo trước cho việc tạo ảnh.
height (int, tùy chọn, mặc định là 1024):
Chiều cao của ảnh được tạo, tính bằng pixel.
width (int, tùy chọn, mặc định là 1024):
Chiều rộng của ảnh được tạo, tính bằng pixel.
generator (Generator, tùy chọn):
Torch generator cho việc tạo ra kết quả xác định.
num_inference_steps (int, tùy chọn, mặc định là 8):
Số bước khử nhiễu.
sigmas (list, tùy chọn):
Lịch trình sigma tùy chỉnh (mặc định là một đường dốc tuyến tính).
attention_kwargs (dict, tùy chọn):
Các kwargs bổ sung cho các bộ xử lý attention.
output_type (str, tùy chọn, mặc định là pil):
Định dạng đầu ra: ‘pil’, ‘np’, ‘pt’.
Đầu ra:
images (list):
Các hình ảnh được tạo.