# 命令行界面

`diffusers-cli` 是一个命令行客户端，用于运行、检查和打包 Diffusers 流水线。

## 可用命令

| 命令 | 目的 |
|---|---|
| [`env`](#env) | 打印环境信息以用于提交错误报告。 |
| [`schema`](#schema) | 在不下载权重的情况下，检查 pipeline 的 `__call__` 签名。 |
| [`run`](#run) | 在本地或 Hugging Face Sandbox 中运行 pipeline。 |
| [`custom_blocks`](#customblocks) | 为 Hub 打包一个本地的 `ModularPipelineBlocks` 子类。 |
| [`fp16_safetensors`](#fp16safetensors) | 将检查点转换为 fp16 `.safetensors`。 |
| [`skills`](#skills) | 将预制的技能包安装到您的 AI 编码代理中。 |

> [!TIP]
> 此页面未列出每个子命令下的所有选项。要查看任意子命令的完整且始终最新的选项列表，请运行 `diffusers-cli <command> --help`（`diffusers-cli run --help`）。

## env

打印 Python、PyTorch、Diffusers 的版本、CUDA 信息以及已安装的可选依赖。在提交 issue 时使用它，以便维护者能够复现你的环境配置。

```bash
diffusers-cli env
```

## 模式

返回流水线接受的输入，而无需下载权重。在构建 [`run`](#run) 的 `--pipeline-kwargs` 时使用它。

仅会获取索引文件。标准流水线读取 `model_index.json`。模块化流水线读取 `modular_model_index.json`。自定义块仓库读取 `modular_config.json`，并且需要 `--trust-remote-code`，因为加载它们会执行 Hub 代码。

```bash
diffusers-cli --format json schema --model black-forest-labs/FLUX.1-dev
diffusers-cli schema --model my-org/my-custom-blocks --trust-remote-code
```

## 运行

端到端运行 pipeline。CLI 会自动检测标准仓库与模块化仓库。它会自动从 URL 或本地路径加载媒体输入，根据 pipeline 的返回类型保存输出，并可通过 `--remote` 在 Hugging Face Sandbox 上远程运行。

最小示例：

```bash
diffusers-cli run \
    --model black-forest-labs/FLUX.1-dev \
    --dtype bf16 \
    --pipeline-kwargs '{"prompt": "an astronaut riding a horse"}'
```

### 传递 pipeline 参数

`--pipeline-kwargs` 接受一个 JSON 对象，并将其转发给 `pipeline(**kwargs)`。位于已知媒体输入键处的字符串值会被自动加载：

- Images (`image`、`last_image`、`mask_image`、`control_image`、`ip_adapter_image`、`image_2`) → 通过 `load_image` 转换为 `PIL.Image`。
- Videos (`video`, `control_video`) → 通过 `load_video` 得到 `list[PIL.Image]`。
- Audio (`initial_audio_waveforms`、`reference_audio`、`src_audio`) → `torch.Tensor`，通过 `torchaudio.load` 加载。

```bash
diffusers-cli run \
    --model black-forest-labs/FLUX.2-klein-9B --dtype bf16 \
    --pipeline-kwargs '{"prompt": "make the fur grey", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cat.png", "strength": 0.6}'
```

媒体键和文本键均接受 JSON 数组，以便通过单次 pipeline 调用执行批量处理。媒体列表中的每个条目都会单独加载（URL、本地路径或 bucket 挂载路径），而 Diffusers 会在 GPU 上通过一次前向传播处理整个列表：

```bash
diffusers-cli run \
    --model black-forest-labs/FLUX.1-Kontext-dev --dtype bf16 \
    --pipeline-kwargs '{
        "prompt": ["make it grey", "make it pink", "make it blue"],
        "image": [
            "https://.../cat1.png",
            "https://.../cat2.png",
            "https://.../cat3.png"
        ]
    }'
```

### 加载

配置 CLI 如何加载模型权重和自定义流水线代码。

- `--dtype {auto, bfloat16, bf16, float16, fp16, float32, fp32}` — 权重数据类型。
- `--device-map <value>` — 组件放置。接受 torch 设备字符串（`cuda`、`cuda:0`、`cpu`、`mps`）、`balanced`（自动将组件拆分到可见的 GPU 上），或用于显式指定每个组件放置位置的 JSON 字典。如果省略，则自动检测。有关更多详细信息，请参阅 [device_map](../optimization/device_map)。
- `--variant fp16` — 选择权重变体。
- `--revision <sha>` — 固定特定的模型版本。
- `--trust-remote-code` — 允许使用来自 Hub 的自定义代码（对于包含自定义 pipeline 类或模块化模块的仓库是必需的）。有关标准自定义 pipeline，请参阅 [社区 pipeline](../using-diffusers/custom_pipeline_overview)；有关模块化 Diffusers，请参阅 [Modular Diffusers](../modular_diffusers/overview)。
- `--lora <spec>` — 在加载后附加一个 LoRA 适配器。每个值都是一个 JSON 字典。重复该标志以堆叠多个适配器。每个条目中 `lora_id` 为必填项，`lora_scale` 的默认值为 `1.0`，`adapter_name` 为可选项（在堆叠时会自动生成为 `lora_<i>`）。
  - 单个：`--lora '{"lora_id": "alvdansen/flux-koda", "lora_scale": 0.8}'`
  - 多个：`--lora '{"lora_id": "alvdansen/flux-koda", "lora_scale": 0.6, "adapter_name": "koda"}' --lora '{"lora_id": "Shakker-Labs/FLUX.1-dev-LoRA-AntiBlur", "lora_scale": 0.4}'`

  所有规格均由 `pipeline.load_lora_weights(...)` 加载，然后通过一次 `pipeline.set_adapters(names, adapter_weights=scales)` 调用同时激活。有关适配器堆叠、缩放调度以及热切换的详细说明，请参阅 [LoRA](../tutorials/using_peft_for_inference)。

### 优化

- `--cpu-offload {model, group, auto}` — onload 目标来自 `--device-map`（offload 需要纯设备字符串）。
  - `model` — 用于标准流水线，`enable_model_cpu_offload`。参见 [模型卸载](../optimization/memory#model-offloading)。
  - `group` — 用于标准流水线，调用 `enable_group_offload(offload_type="leaf_level", use_stream=True)`。请参阅 [组卸载](../optimization/memory#group-offloading)。
  - `auto` — 仅在 [`ComponentsManager`](../modular_diffusers/components_manager) 中支持模块化。标准模式在模块化管道中会抛出异常。`auto` 在标准管道中会抛出异常。
- `--offload-margin <size>` — 在 `--cpu-offload auto` 下，为激活值保留的设备内存大小，作为 `memory_reserve_margin` 参数传递给 `enable_auto_cpu_offload`（默认值为 `3GB`）。当大画布在前向传播过程中出现内存不足时，请调高此值。由于 offloader 会在组件能够容纳时保持其驻留，因此在高显存显卡上，默认的 margin 可能无法为长视频的激活值留出足够的空间。
- `--attention-backend` — 托管在 Hub 上的注意力内核，首次使用时会自动下载。可选值为 `default` 以及 Diffusers 中注册的 Hub 后端（例如 `flash_hub`、`flash_varlen_hub`、`flash_4_hub`、`sage_hub`、`sage_blackwell_hub`）。运行 `diffusers-cli run --help` 可查看当前列表。它仅支持基于 Transformer 的流水线，在旧版 UNet 流水线中会被忽略并给出警告。参见 [注意力后端](../optimization/attention_backends)。
- `--vae-tiling` / `--vae-slicing` — 降低 VAE 解码的显存占用。参见 [VAE 分块](../optimization/memory#vae-tiling) 和 [VAE 切片](../optimization/memory#vae-slicing)。
- `--compile [JSON]` — 使用 [torch.compile](../optimization/fp16#torchcompile) 编译 denoiser 模块。对于包含重复块的模块，CLI 优先采用 [regional compilation](../optimization/fp16#regional-compilation)。仅使用 `--compile` 时，会采用 `fullgraph=true`。JSON 对象会直接传递给 `torch.compile`。不支持与 `--context-parallel` 一起使用。
- `--context-parallel` — 基于 DiT 的流水线上的 Ulysses 风格上下文并行。本地需要 torchrun，但在 `--remote` 下，CLI 会为您封装 `torchrun --nproc-per-node=gpu`。参见 [上下文并行](../optimization/context_parallelism)。

### 模块化流水线

`run` 会自动检测 [模块化仓库](../modular_diffusers/overview)——无论是因为它附带了 `modular_model_index.json`，还是因为其 `model_index.json` 中指定了 `ModularPipeline` 的子类——因此无需使用任何标志即可启用。

一些模块化仓库定义了多个 *工作流*，它们类似于命名任务，共享相同的组件，但运行的模块和接受的输入有所不同。例如，[MiniMax-H3](../api/pipelines/minimax_h3) 提供了 `t2va`（文本转视频和音频）、`fl2va`（首帧和/或尾帧）以及 `ref2va`（图像、视频和音频参考的有序组合）。传入 `--workflow` 以选择其中一个：

```bash
diffusers-cli run \
    --model MiniMaxAI/MiniMax-H3 --workflow fl2va \
    --pipeline-kwargs '{
        "prompt": "the camera pushes in slowly as rain falls",
        "image": "opening-frame.png",
        "last_image": "closing-frame.png",
        "num_frames": 124
    }' \
    --output-key videos --output-key audio \
    --fps 24 --sampling-rate 32000 \
    --cpu-offload auto --dtype bf16
```

选择某个工作流后，仅保留该任务对应的模块，因此流水线只声明其所需的组件，`load_components` 也只获取相应的子文件夹。省略 `--workflow` 参数可保留所有可用工作流，让流水线根据每次调用时提供的输入自行选择。

```bash
diffusers-cli --format json schema --model MiniMaxAI/MiniMax-H3 --trust-remote-code
```

`--workflow` 仅适用于模块化流水线。在标准流水线中，该参数会被忽略并触发警告。

模块化流水线返回的是 [`PipelineState`](../modular_diffusers/modular_pipeline)，而非单个输出对象，因此 `--output-key` 用于指定要保存的中间结果。

### 输出

`run` 会检测流水线输出类型：

- `PIL.Image`/list → `<NNNN>.png`（零填充索引，例如 `0000.png`）
- 图像序列 → `0000.mp4`（`--fps` 控制帧率，默认值为 8）
- 音频数组 → `0000.wav`（`--sampling-rate` 控制采样率）
- 其他任何内容 → JSON 转储

默认输出目录格式为 `~/.diffusers/cli/run/outputs/diffusers-run-<YYYYMMDDTHHMMSS>-<uuid>/`。每次运行都会生成一个独立的子目录，因此连续调用不会相互覆盖。

使用 `--output <path>` 进行覆盖。路径的展开方式取决于其形式和批处理大小：

| `--output` | 1 个输出 | N 个输出 |
|---|---|---|
| _已省略_ | 默认目录 → `0000.png` | 默认目录 → `0000.png`、`0001.png`、`0002.png`、…… |
| `./results/`（末尾的 `/` 或一个已存在的目录） | `./results/0000.png` | `./results/0000.png`, `./results/0001.png`, … |
| `my-cat.png`（文件路径） | `my-cat.png`（原样使用） | `my-cat-0000.png`, `my-cat-0001.png`, … |

目录输出始终使用纯填充名称（`0000`、`0001`……）。显式文件路径会保留你选择的词干，并在批次产生多个输出时追加填充索引。

使用 `--push-to` 将输出上传到 [Hugging Face 存储桶](https://huggingface.co/docs/hub/en/storage-buckets)。它接受一个：

- HF 存储桶 ID（`<namespace>/<name>`）
- `hf://buckets/<namespace>/<name>[/<subpath>]`
[HF URI](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/hf_uris)
- 浏览器 URL

子路径用作文件夹前缀。如果存储桶不存在，则会自动创建，对象将放置在 `[<subpath>/]<run_id>/<filename>` 下。

```bash
# HF bucket id — files at hf://buckets/alice/edit-outputs/<run_id>/<file>
--push-to alice/edit-outputs

# URI with subpath — files at hf://buckets/alice/edit-outputs/greyscale/2026-07/<run_id>/<file>
--push-to hf://buckets/alice/edit-outputs/greyscale/2026-07

# Browser URL copy-paste from the Hub also works.
--push-to https://huggingface.co/buckets/alice/edit-outputs/tree/greyscale/2026-07
```

下表描述了远程运行。对于本地运行，`--push-to` 会上传本地保存的输出。它不会抑制本地文件的创建。

| `--push-to` 是否已设置？ | `--output` 是否已设置？ | 结果 |
|---|---|---|
| no | no | 下载至默认本地目录 |
| no | 是的 | 下载至 `--output` |
| 是的 | no | 仅 bucket，不进行本地下载 |
| 是的 | 是的 | bucket 和 `--output` |

`--format` 用于控制标准输出中的元数据（路径、耗时、沙箱信息）。它不会改变媒体文件本身的格式。生成的图像始终为 PNG，视频为 MP4，音频为 WAV。

### 远程执行（`--remote`）

在 [Hugging Face Sandbox](https://huggingface.co/docs/huggingface_hub/en/guides/sandbox) 中运行相同的调用——这是一个由 CLI 通过 HTTP 驱动的隔离云虚拟机：它会上传输入、运行流水线、下载输出，然后终止沙箱。需要 `huggingface_hub>=1.23`。

沙箱从 [`diffusers/diffusers-cli-cuda`](https://hub.docker.com/r/diffusers/diffusers-cli-cuda) 启动，这是一个预构建的镜像，已内置 torch、CUDA 以及 CLI 的依赖项，因此冷启动时可直接开始生成，而无需先进行安装。

```bash
diffusers-cli run \
    --model black-forest-labs/FLUX.1-dev --dtype bf16 \
    --pipeline-kwargs '{"prompt": "an astronaut riding a horse"}' \
    --remote --flavor a100-large
```

远程标志：

- `--flavor <name>` — 沙箱硬件（例如，`a10g-small`、`h200`、`rtx-pro-6000`）。
- `--timeout <duration>` — 沙箱内运行命令的最大实际耗时（默认值为 `10m`）。
- `--dependencies <pkg>` — 额外的 pip 依赖项（可重复使用），安装在镜像之上。适用于固定 diffusers 分支的 tarball 或添加特定于 pipeline 的额外依赖项。
- `--namespace <name>` — 在不同的 HF 组织/账户下创建沙箱。
- `--image <ref>` — 覆盖沙箱镜像。该镜像必须包含与 `--flavor` 的驱动程序兼容的 torch + CUDA。CLI 随后会在每个冷启动沙箱上安装其自身的依赖项，而默认镜像可以避免这一点。
- `--volume <bucket-id>[:<mount-path>]` — 将一个 [HF 存储桶](https://huggingface.co/docs/hub/en/storage-buckets) 以读写目录的形式挂载到沙箱中（可重复使用）。默认挂载路径为 `/mnt/buckets/<bucket-id>`。在 `--pipeline-kwargs` 中引用已挂载的文件时，可将其视为任意其他本地路径。此选项仅在新建沙箱时生效，通过 `--sandbox-id` 重新连接时会被忽略。

默认情况下，每次 `--remote` 运行都是临时的（创建 → 运行 → 下载 → 终止）。若要在多次运行之间复用已就绪的沙箱——在其磁盘上保留依赖项、模型权重缓存以及 `torch.compile` 缓存——请保持其存活并重新连接：

- `--keep-alive` — 运行结束后不终止沙箱。其 id 会被打印出来。
- `--sandbox-id <id>` — 重新连接到保持活动的沙箱，而不是创建一个新的沙箱。
- `--idle-timeout <duration>` — 在此时长无活动后自动关闭（默认 `10m`）。仅在创建新沙箱时生效，通过 `--sandbox-id` 重新连接时会被忽略。

```bash
# First run keeps the sandbox alive and prints sandbox_id=<id>.
diffusers-cli run -m black-forest-labs/FLUX.1-dev --dtype bf16 \
    --pipeline-kwargs '{"prompt": "a cat"}' --remote --flavor a100-large --keep-alive

# Reconnect for the next run — the model is already cached, so only inference runs.
diffusers-cli run -m black-forest-labs/FLUX.1-dev --dtype bf16 \
    --pipeline-kwargs '{"prompt": "a dog"}' --remote --flavor a100-large --sandbox-id <id>

# Stop it when done (or let it timeout).
hf sandbox kill <id>
```

## `custom_blocks`

将本地 `ModularPipelineBlocks` 子类打包以便上传至 Hub。读取一个 Python 文件，通过 AST 扫描其中继承自 `ModularPipelineBlocks` 或其某个复合子类（`SequentialPipelineBlocks`、`AutoPipelineBlocks`、`ConditionalPipelineBlocks`、`LoopSequentialPipelineBlocks`）的类，实例化所选的类，并在当前工作目录中调用 `save_pretrained`。

```bash
# Package the first block found in ./block.py
diffusers-cli custom_blocks

# Point at a different file / pick a specific class
diffusers-cli custom_blocks --block_module_name my_block.py --block_class_name MyDenoiseBlock
```

Block 类必须能够以零个构造参数实例化，并在 `__init__` 中硬编码默认值，或在调用时从 pipeline 的 `state` 中读取配置。

## `fp16_safetensors`

> [!CAUTION]
> 此命令现已弃用，并将在未来版本中移除。

将 Hub 上的检查点转换为 fp16 `.safetensors` 并推送结果。此操作有助于缩小仓库的权重体积，从而加快加载速度。有关确切参数，请参阅 `diffusers-cli fp16_safetensors --help`。

## `skills`

从 diffusers 仓库安装技能（[`.ai/skills/`](https://github.com/huggingface/diffusers/tree/main/.ai/skills)）。

```bash
# Install a single skill
diffusers-cli skills add "<skill name>"

# Install every skill in the registry
diffusers-cli skills add --all

# List available skills with a one-line summary of each
diffusers-cli skills list

# Preview a skill's SKILL.md without installing
diffusers-cli skills preview diffusers-cli

# Refetch and reinstall every managed skill
diffusers-cli skills update

# Install to the user-level directory instead of the current project
diffusers-cli skills add diffusers-cli --global

# Install for one agent instead of detecting it from the environment
diffusers-cli skills add --all --claude   # or --codex / --cursor
```

若未指定目标标志，CLI 将为启动它的 agent 进行安装；若无法确定，则将为所有 agent 安装。Claude Code 会在 `.claude/skills/diffusers/` 下安装一个插件包（命名空间为 `/diffusers:<skill name>`）。Codex 和 Cursor 则会安装到 `.agents/skills/<skill name>/`。

