# Krea 2

Krea 2 (K2) 是一个基于单流 MMDiT 和分组查询注意力机制的流匹配文本生成图像模型。Qwen3-VL 文本编码器提供条件信息：对于每个 token，不再使用最后一个隐藏状态，而是从十二个解码器层中提取隐藏状态，并通过 transformer 内部的一个小型文本融合阶段进行融合。图像通过 Qwen-Image VAE 进行解码。

发布了两个检查点，它们共享相同的架构，但具有不同的推荐采样器设置：

- **基础（中期训练）** — 使用完整的采样器并配合无分类器引导：`num_inference_steps=28`，`guidance_scale=4.5`。
- **TDM（蒸馏版）** — 专为少步采样而蒸馏，运行时使用 `num_inference_steps=8` 并禁用引导（`guidance_scale=0.0`）。

`guidance_scale` 遵循 Krea 2 的约定：速度计算为 `cond + guidance_scale * (cond - uncond)`，并且只要 `guidance_scale > 0` 就会启用 guidance（这等同于使用 scale `1 + guidance_scale` 的常规 CFG 公式）。

## 文本到图像

```python
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 的示例：

```python
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")
```

## 加载单文件检查点

```python
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]]

#### diffusers.Krea2Pipeline[[diffusers.Krea2Pipeline]]

```python
diffusers.Krea2Pipeline(scheduler: FlowMatchEulerDiscreteScheduler, vae: AutoencoderKLQwenImage, text_encoder: Qwen3VLModel, tokenizer: AutoTokenizer, transformer: Krea2Transformer2DModel, text_encoder_select_layers: tuple[int, ...] | list[int] | None = None, is_distilled: bool = False, patch_size: int = 2)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/krea2/pipeline_krea2.py#L134)

**参数：**

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/main/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：Euler 流匹配调度器。Krea 2 的 sigma 调度采用分辨率感知的指数时间偏移，因此调度器配置预期会设置 `use_dynamic_shifting=True`，并同时配置 Krea 2 的偏移参数（`base_shift=0.5`、`max_shift=1.15`、`base_image_seq_len=256`、`max_image_seq_len=6400`）。

vae ([AutoencoderKLQwenImage](/docs/diffusers/main/zh/api/models/autoencoderkl_qwenimage#diffusers.AutoencoderKLQwenImage))：用于将潜在变量解码为图像的 Qwen-Image 变分自编码器（f8，16 个潜在通道）。

text_encoder ([PreTrainedModel](https://huggingface.co/docs/transformers/main/en/main_classes/model#transformers.PreTrainedModel))：一个 Qwen3-VL 模型（例如 `Qwen/Qwen3-VL-4B-Instruct` 的 `Qwen3VLModel`）。该 pipeline 消费的是从多个解码器层中提取的隐藏状态堆栈，而非最后一个隐藏状态。

tokenizer ([AutoTokenizer](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoTokenizer))：与文本编码器配对的 tokenizer。

transformer ([Krea2Transformer2DModel](/docs/diffusers/main/zh/api/models/krea2_transformer2d#diffusers.Krea2Transformer2DModel))：Krea 2 单流 MMDiT，用于预测流匹配速度。

text_encoder_select_layers (`tuple[int, ...]`，*可选*)：文本编码器 `hidden_states` 元组（0 为嵌入输出）的索引，这些状态将按 token 堆叠，作为 transformer 的文本条件。必须包含 `transformer.config.num_text_layers` 个条目。

is_distilled (`bool`，*可选*，默认为 `False`)：transformer 是否为少步蒸馏（TDM/turbo）检查点。当 `True` 时，使用固定的时间步偏移 `mu=1.15`；否则 `mu` 根据图像分辨率计算得出。

patch_size (`int`, *可选*，默认为 2)：在潜在表示进入 Transformer 之前，将其打包成的方形 patch 的边长。有效的像素到 token 的下采样因子为 `vae_scale_factor * patch_size`。

用于文本到图像生成的 Krea 2 流水线。

#### __调用__[[diffusers.Krea2Pipeline.__call__]]

```python
__call__(prompt: str | list[str] | None = None, negative_prompt: str | list[str] | None = None, height: int = 1024, width: int = 1024, num_inference_steps: int = 28, sigmas: list[float] | None = None, guidance_scale: float = 4.5, num_images_per_prompt: int = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_embeds_mask: typing.Optional[torch.Tensor] = None, negative_prompt_embeds: typing.Optional[torch.Tensor] = None, negative_prompt_embeds_mask: typing.Optional[torch.Tensor] = None, output_type: str | None = 'pil', return_dict: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int, dict], NoneType]] = None, callback_on_step_end_tensor_inputs: list = ['latents'], attention_kwargs: dict[str, typing.Any] | None = None, max_sequence_length: int = 512)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/krea2/pipeline_krea2.py#L445)

**参数：**

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)：去噪步数。对于基础（midtrain）检查点，请使用 28；对于少步蒸馏（TDM）检查点，请使用 8。

sigmas (`list[float]`, *可选*) : 调度器的自定义 sigmas。如果未定义，则使用默认的 `linspace(1.0, 1/num_inference_steps, num_inference_steps)` 网格（分辨率感知的 shift 在调度器内部应用）。

guidance_scale (`float`，默认值为 4.5) : 无分类器引导（Classifier-free guidance）的缩放系数，遵循 Krea 2 的约定：速度计算方式为 `cond + guidance_scale * (cond - uncond)`，且只要 `guidance_scale > 0` 即启用引导（这等同于常规 CFG 公式中缩放系数为 `1 + guidance_scale` 的情况）。将其设置为 `0.0` 可禁用引导（例如用于 TDM 检查点）。

num_images_per_prompt (`int`，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：一个或多个 [torch 生成器](https://pytorch.org/docs/stable/generated/torch.Generator.html)，用于使生成过程具有确定性。

latents (`torch.Tensor`, *可选*) : 以打包形式预生成的噪声潜变量 `(batch_size, image_seq_len, in_channels)`，从高斯分布中采样，用作图像生成的输入。

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` 的布尔掩码；当传入 `negative_prompt_embeds` 时必填。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 `"pil"`、`"np"`、`"pt"` 或 `"latent"`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [Krea2PipelineOutput](/docs/diffusers/main/zh/api/pipelines/krea2#diffusers.pipelines.krea2.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`, *可选*) : 一个 kwargs 字典，如果指定，将作为参数传递给 [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

max_sequence_length (`int`，默认值为 512)：Transformer 消耗的固定文本序列长度；提示词会被填充或截断至该长度。

**返回：** [Krea2PipelineOutput](/docs/diffusers/main/zh/api/pipelines/krea2#diffusers.pipelines.krea2.Krea2PipelineOutput) 或 `tuple`

如果 `return_dict` 为 True，则返回 [Krea2PipelineOutput](/docs/diffusers/main/zh/api/pipelines/krea2#diffusers.pipelines.krea2.Krea2PipelineOutput)；否则返回一个 `tuple`，其第一个元素是包含生成图像的列表。

调用生成 pipeline 时调用的函数。

示例：
```py
>>> 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[[diffusers.Krea2Pipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], device: typing.Optional[torch.device] = None, num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.Tensor] = None, prompt_embeds_mask: typing.Optional[torch.Tensor] = None, max_sequence_length: int = 512)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/krea2/pipeline_krea2.py#L263)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：要编码的提示

device : (`torch.device`): torch 设备

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`, *可选*) : 预生成的布尔掩码，用于标记有效的文本 token，形状为 `(batch_size, text_seq_len)`。当传入 `prompt_embeds` 时必填。

max_sequence_length (`int`，默认值为 512)：Transformer 消耗的固定文本序列长度；提示词会被填充或截断至该长度。

#### get_text_hidden_states[[diffusers.Krea2Pipeline.get_text_hidden_states]]

```python
get_text_hidden_states(prompt: str | list[str], max_sequence_length: int = 512, device: typing.Optional[torch.device] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/krea2/pipeline_krea2.py#L214)

将 `prompt` 分词为固定长度的 Krea 2 布局，并获取所选编码器的隐藏状态。

返回一个 `(hidden_states, attention_mask)` 元组，其形状分别为 `(batch_size, text_seq_len, num_text_layers, text_hidden_dim)` 和 `(batch_size, text_seq_len)`（bool 类型）。

#### prepare_position_ids[[diffusers.Krea2Pipeline.prepare_position_ids]]

```python
prepare_position_ids(text_seq_len: int, grid_height: int, grid_width: int, device: device)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/krea2/pipeline_krea2.py#L381)

构建合并序列的 `(text_seq_len + grid_height * grid_width, 3)` 旋转坐标：文本 token 位于原点，图像 token 携带其 `(0, h, w)` 潜在网格坐标。

## Krea2PipelineOutput[[diffusers.pipelines.krea2.Krea2PipelineOutput]]

#### diffusers.pipelines.krea2.Krea2PipelineOutput[[diffusers.pipelines.krea2.Krea2PipelineOutput]]

```python
diffusers.pipelines.krea2.Krea2PipelineOutput(images: list[PIL.Image.Image] | numpy.ndarray)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/krea2/pipeline_output.py#L24)

**参数：**

images (`list[PIL.Image.Image]` 或 `np.ndarray`)：长度为 `batch_size` 的去噪 PIL 图像列表，或形状为 `(batch_size, height, width, num_channels)` 的 numpy 数组。

Krea 2 流水线的输出类。

## 模块化

Krea 2 也可作为[模块化流水线](../../modular_diffusers/overview)使用。无分类器引导通过`guider`组件进行配置，而不是通过`guidance_scale`调用参数。Krea 2 使用基于条件锚定的 CFG，即`use_original_formulation=True`的[ClassifierFreeGuidance](/docs/diffusers/main/zh/api/modular_diffusers/guiders#diffusers.ClassifierFreeGuidance)。

```python
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](/docs/diffusers/main/zh/api/pipelines/krea2#diffusers.Krea2TurboAutoBlocks)）：它以无引导方式运行（不使用 `guider`），不接受负面提示词，并且只需少量步骤即可完成采样。`ModularPipeline.from_pretrained` 会根据检查点的 `is_distilled` 配置自动选择 turbo 块，因此无需配置引导：

```python
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]]

#### diffusers.Krea2ModularPipeline[[diffusers.Krea2ModularPipeline]]

```python
diffusers.Krea2ModularPipeline(blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = None, pretrained_model_name_or_path: str | os.PathLike | None = None, components_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = None, collection: str | None = None, workflow: str | None = None, modular_config_dict: dict[str, typing.Any] | None = None, config_dict: dict[str, typing.Any] | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/krea2/modular_pipeline.py#L19)

用于 Krea 2 的 ModularPipeline。

## Krea2AutoBlocks[[diffusers.Krea2AutoBlocks]]

#### diffusers.Krea2AutoBlocks[[diffusers.Krea2AutoBlocks]]

```python
diffusers.Krea2AutoBlocks()
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/krea2/modular_blocks_krea2.py#L106)

使用 Krea 2 进行文本到图像生成的 Auto Modular 流水线：编码文本 -> 核心去噪（对称 CFG） -> 解码。

支持的工作流：
- `text2image`：需要 `prompt`

组件：text_encoder (`Qwen3VLModel`)：Qwen3-VL 文本编码器。tokenizer (`AutoTokenizer`)：与文本编码器配套的 tokenizer。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`，*可选*)：自定义 sigma 调度（默认为线性斜坡）。attention_kwargs (`dict`，*可选*)：注意力处理器的额外 kwargs。output_type (`str`，*可选*，默认为 pil)：输出格式：'pil'、'np'、'pt'。

输出：图像（`list`）：生成的图像。

## Krea2TurboModularPipeline[[diffusers.Krea2TurboModularPipeline]]

#### diffusers.Krea2TurboModularPipeline[[diffusers.Krea2TurboModularPipeline]]

```python
diffusers.Krea2TurboModularPipeline(blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = None, pretrained_model_name_or_path: str | os.PathLike | None = None, components_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = None, collection: str | None = None, workflow: str | None = None, modular_config_dict: dict[str, typing.Any] | None = None, config_dict: dict[str, typing.Any] | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/krea2/modular_pipeline.py#L54)

用于蒸馏版 Krea 2 turbo (TDM) 检查点的 ModularPipeline。它在运行时不使用无分类器引导，因此不接受负面提示，也没有引导器。

## Krea2TurboAutoBlocks[[diffusers.Krea2TurboAutoBlocks]]

#### diffusers.Krea2TurboAutoBlocks[[diffusers.Krea2TurboAutoBlocks]]

```python
diffusers.Krea2TurboAutoBlocks()
```

[源代码](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/krea2/modular_blocks_krea2_turbo.py#L102)

使用蒸馏版 Krea 2 turbo 检查点的 Auto Modular 文本生成图像流水线：文本编码 -> 核心去噪（无引导） -> 解码。

支持的工作流：
- `text2image`：需要 `prompt`

组件：text_encoder (`Qwen3VLModel`)：Qwen3-VL 文本编码器。tokenizer (`AutoTokenizer`)：与文本编码器配套的 tokenizer。transformer (`Krea2Transformer2DModel`) scheduler (`FlowMatchEulerDiscreteScheduler`) vae (`AutoencoderKLQwenImage`) image_processor (`VaeImageProcessor`)

输入：prompt (`str`)：用于引导图像生成的提示词或提示词列表。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`，*可选*，默认为 8)：去噪步骤数。sigmas (`list`，*可选*)：自定义 sigma 调度（默认为线性斜坡）。attention_kwargs (`dict`，*可选*)：注意力处理器的额外 kwargs。output_type (`str`，*可选*，默认为 pil)：输出格式：'pil'、'np'、'pt'。

输出：图像（`list`）：生成的图像。

