#
# 根据 Apache 许可证 2.0 版本（“许可证”）授权
# 您只能在遵守许可证的情况下使用本文件。
# 您可以在以下位置获取许可证副本
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 除非适用法律要求或双方书面同意，软件
# 根据许可证分发，本软件按“原样”
# 不附带任何明示或暗示的保证或条件。
# 请参阅许可证中关于权限的具体语言
# 许可证下的限制。-->

# PRX Pixel

PRXPixel 是 Photoroom 推出的像素空间文本生成图像模型。一个约 7B 的 `PRXTransformer2DModel` 直接对原始 RGB 图像进行去噪——无需 VAE。该模型以 Qwen3-VL 文本编码器作为条件，并采用 flow matching，其中 transformer 在每一步预测干净图像（x-prediction）。生成分辨率会被输入到时间步调制中，使模型能够感知目标尺寸。

## 可用模型

| 模型 | 分辨率 | 描述 | 建议参数 | 推荐的 dtype |
|:-----:|:---------:|:----------:|:----------:|:----------:|
| [`Photoroom/prxpixel-t2i`](https://huggingface.co/Photoroom/prxpixel-t2i) | 1024 | 采用 Qwen3-VL 文本编码器的像素空间 ~7B 模型 | 28 步，cfg=5.0 | `torch.bfloat16` |

## 加载 pipeline

[PRXPixelPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/prx_pixel#diffusers.PRXPixelPipeline) 需要 `transformers >= 4.57`（即引入 `Qwen3VLTextModel` 的版本）。请使用 [from_pretrained()](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline.from_pretrained) 加载：

```py
import torch
from diffusers import PRXPixelPipeline

pipe = PRXPixelPipeline.from_pretrained("Photoroom/prxpixel-t2i", dtype=torch.bfloat16)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

prompt = "A front-facing portrait of a lion in the golden savanna at sunset."
image = pipe(prompt, num_inference_steps=28, guidance_scale=5.0).images[0]
image.save("prxpixel_output.png")
```

## 内存优化

对于内存受限的环境：

```py
import torch
from diffusers import PRXPixelPipeline

pipe = PRXPixelPipeline.from_pretrained("Photoroom/prxpixel-t2i", dtype=torch.bfloat16)
pipe.enable_model_cpu_offload()

# Or use sequential CPU offload for even lower memory
pipe.enable_sequential_cpu_offload()
```

## PRXPixelPipeline[[diffusers.PRXPixelPipeline]]

#### diffusers.PRXPixelPipeline[[diffusers.PRXPixelPipeline]]

```python
diffusers.PRXPixelPipeline(transformer: PRXTransformer2DModel, scheduler: FlowMatchEulerDiscreteScheduler, text_encoder: PreTrainedModel, tokenizer: transformers.models.auto.tokenization_auto.AutoTokenizer | transformers.tokenization_utils_base.PreTrainedTokenizerBase, default_sample_size: int | None = 1024, prompt_max_tokens: int = 256, noise_scale: float = 2.0)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/prx/pipeline_prx_pixel.py#L98)

**参数：**

transformer (`PRXTransformer2DModel`)：约 70 亿参数的 PRX 去噪器。对于 PRXPixel，该模型以 `in_channels=3` 构建，包含瓶颈层 `img_in`，并设置 `resolution_embeds=True`，其训练目标是预测干净图像 `x0`。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于对（像素空间）潜在变量进行去噪的流匹配调度器。

text_encoder (`PreTrainedModel`)：用于编码提示词的 Qwen3-VL 文本主干（视觉塔将被丢弃）。必须返回 `last_hidden_state`。

tokenizer (`PreTrainedTokenizerBase`)：`text_encoder` 的分词器（通常通过 `AutoTokenizer` 加载）。

default_sample_size (`int`，*可选*，默认值为 1024)：当未向 `__call__` 提供值时使用的默认高度/宽度。

prompt_max_tokens (`int`，*可选*，默认值为 256)：在编码之前，提示词将被填充或截断到的文本 token 数量。

noise_scale (`float`，*可选*，默认值为 2.0)：应用于初始高斯噪声的缩放系数。PRXPixel 使用非单位初始噪声尺度进行训练，因此采样必须从 `randn * noise_scale` 开始。

用于使用 PRXPixel 模型进行文本到图像生成的 Pipeline。

PRXPixel 是一个独立的像素空间文生图流水线。它直接使用约 70 亿参数的 `PRXTransformer2DModel` 对原始 RGB 进行去噪，且不包含 VAE（生成过程完全在像素空间中进行，因此去噪后的输出*就是*图像）。提示词通过 Qwen3-VL 文本编码器进行编码（视觉塔部分被丢弃）。与 [PRXPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/prx#diffusers.PRXPipeline) 不同，该 Transformer 采用 x-prediction 进行训练：在每一步中，它预测干净图像 `x0`，然后将其转换为 flow-matching 速度，再执行调度器步骤。采样从 `randn * noise_scale` 开始（默认 `noise_scale=2.0`），默认分辨率为 1024px。

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。请查阅父类文档，了解该库为所有 pipeline 实现的通用方法（例如下载或保存、在特定设备上运行等）。

示例：
```py
>>> import torch
>>> from diffusers import PRXPixelPipeline

>>> pipe = PRXPixelPipeline.from_pretrained("Photoroom/prxpixel-t2i", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "A front-facing portrait of a lion in the golden savanna at sunset."
>>> image = pipe(prompt, num_inference_steps=28, guidance_scale=5.0).images[0]
>>> image.save("prxpixel_output.png")
```

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

```python
__call__(prompt: str | list[str] = None, negative_prompt: str = '', height: int | None = None, width: int | None = None, num_inference_steps: int = 28, timesteps: list[int] = None, guidance_scale: float = 4.0, num_images_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = None, latents: typing.Optional[torch.Tensor] = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, prompt_attention_mask: typing.Optional[torch.BoolTensor] = None, negative_prompt_attention_mask: typing.Optional[torch.BoolTensor] = None, output_type: str | None = 'pil', return_dict: bool = True, use_resolution_binning: bool = True, callback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = None, callback_on_step_end_tensor_inputs: list[str] = ['latents'])
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/prx/pipeline_prx_pixel.py#L406)

**参数：**

prompt (`str` 或 `list[str]`，*可选*)：用于引导图像生成的提示词或提示词列表。如果未定义，则必须传入 `prompt_embeds`。

negative_prompt (`str`，*可选*，默认为 `""`)：用于引导图像生成的提示词或提示词列表。在未使用引导时会被忽略（即当 `guidance_scale` 小于 `1` 时会被忽略）。

height (`int`，*可选*，默认为 `default_sample_size`)：生成图像的高度（以像素为单位）。

width (`int`，*可选*，默认为 `default_sample_size`)：生成图像的像素宽度。

num_inference_steps (`int`，*可选*，默认值为 28)：去噪步数。更多的去噪步数通常能带来更高质量的图像，但代价是推理速度变慢。

timesteps (`list[int]`，*可选*)：用于在支持 `set_timesteps` 方法中 `timesteps` 参数的调度器中，指定去噪过程所使用的自定义时间步。如果未定义，则使用传入 `num_inference_steps` 时的默认行为。必须按降序排列。

guidance_scale (`float`，*可选*，默认值为 4.0)：如[Classifier-Free Diffusion Guidance](https://huggingface.co/papers/2207.12598)中定义的引导尺度。`guidance_scale` 定义为 [Imagen Paper](https://huggingface.co/papers/2205.11487) 中公式 2 的 `w`。通过设置 `guidance_scale > 1` 来启用引导尺度。较高的引导尺度会促使生成与文本 `prompt` 紧密关联的图像，但通常以牺牲图像质量为代价。

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`, *可选*) : 预先生成的噪声潜变量，从高斯分布中采样得到，用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供，将通过使用提供的随机`generator`进行采样来生成潜变量张量。

prompt_embeds (`torch.FloatTensor`，*可选*)：预生成的文本嵌入。可用于轻松调整文本输入，*例如*提示词加权。如果未提供，则将从 `prompt` 输入参数生成文本嵌入。

negative_prompt_embeds (`torch.FloatTensor`, *可选*) : 预生成的负向文本嵌入。可用于轻松调整文本输入，*例如*提示词加权。如果未提供且 `guidance_scale > 1`，将从空字符串生成负向嵌入。

prompt_attention_mask (`torch.BoolTensor`, *可选*) : 为 `prompt_embeds` 预生成的注意力掩码。如果未提供，则会根据 `prompt` 输入参数生成注意力掩码。

negative_prompt_attention_mask (`torch.BoolTensor`, *可选*) : 为 `negative_prompt_embeds` 预生成的注意力掩码。如果未提供且 `guidance_scale > 1`，则将从空字符串生成注意力掩码。

output_type (`str`，*可选*，默认为 `"pil"`)：生成图像的输出格式。可选 [PIL](https://pillow.readthedocs.io/en/stable/)：`PIL.Image.Image` 或 `np.array`。

return_dict (`bool`，*可选*，默认为 `True`)：是否返回 [PRXPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/prx#diffusers.pipelines.prx.PRXPipelineOutput) 而不是普通元组。

use_resolution_binning (`bool`，*可选*，默认为 `True`)：如果设置为 `True`，则请求的高度和宽度会先通过预定义的宽高比区间映射到最接近的分辨率。在生成的潜变量被解码为图像后，它们会被重新调整回请求的分辨率。适用于以最佳分辨率生成非正方形图像。

callback_on_step_end (`Callable`，*可选*)：一个在推理过程中每个去噪步骤结束时调用的函数。该函数以以下参数被调用：`callback_on_step_end(self, step, timestep, callback_kwargs)`。`callback_kwargs` 将包含由 `callback_on_step_end_tensor_inputs` 指定的所有张量列表。

callback_on_step_end_tensor_inputs (`list`，*可选*)：用于 `callback_on_step_end` 函数的张量输入列表。列表中指定的张量将作为 `callback_kwargs` 参数传入。您只能包含在 `._callback_tensor_inputs` 属性中列出的张量。

**返回：** [PRXPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/prx#diffusers.pipelines.prx.PRXPipelineOutput) 或 `tuple`

如果 `return_dict` 为 True，则返回 [PRXPipelineOutput](/docs/diffusers/v0.43.0/zh/api/pipelines/prx#diffusers.pipelines.prx.PRXPipelineOutput)，否则返回一个 `tuple。当返回元组时，第一个元素是一个包含生成图像的列表。

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

示例：
```py
>>> import torch
>>> from diffusers import PRXPixelPipeline

>>> pipe = PRXPixelPipeline.from_pretrained("Photoroom/prxpixel-t2i", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "A front-facing portrait of a lion in the golden savanna at sunset."
>>> image = pipe(prompt, num_inference_steps=28, guidance_scale=5.0).images[0]
>>> image.save("prxpixel_output.png")
```

#### check_inputs[[diffusers.PRXPixelPipeline.check_inputs]]

```python
check_inputs(prompt: str | list[str], height: int, width: int, guidance_scale: float, callback_on_step_end_tensor_inputs: list[str] | None = None, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/prx/pipeline_prx_pixel.py#L324)

检查所有输入是否处于正确的格式。

#### encode_prompt[[diffusers.PRXPixelPipeline.encode_prompt]]

```python
encode_prompt(prompt: str | list[str], device: typing.Optional[torch.device] = None, do_classifier_free_guidance: bool = True, negative_prompt: str = '', num_images_per_prompt: int = 1, prompt_embeds: typing.Optional[torch.FloatTensor] = None, negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None, prompt_attention_mask: typing.Optional[torch.BoolTensor] = None, negative_prompt_attention_mask: typing.Optional[torch.BoolTensor] = None, tokenizer_max_length: int | None = None, skip_text_cleaning: bool = False)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/prx/pipeline_prx_pixel.py#L263)

使用标准文本编码器和分词器对文本提示进行编码，或使用预计算的嵌入。

#### prepare_latents[[diffusers.PRXPixelPipeline.prepare_latents]]

```python
prepare_latents(batch_size: int, num_channels_latents: int, height: int, width: int, dtype: dtype, device: device, generator: typing.Optional[torch.Generator] = None, latents: typing.Optional[torch.Tensor] = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/prx/pipeline_prx_pixel.py#L378)

为扩散过程准备初始潜变量。

PRXPixel 使用非单位初始噪声尺度进行训练，因此采样的噪声会乘以 `self.config.noise_scale`。

## PRXPipelineOutput[[diffusers.pipelines.prx.PRXPipelineOutput]]

#### diffusers.pipelines.prx.PRXPipelineOutput[[diffusers.pipelines.prx.PRXPipelineOutput]]

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

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

**参数：**

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

PRX 流水线的输出类。

