# 명령줄 인터페이스

`diffusers-cli`는 Diffusers 파이프라인을 실행하고, 검사하고, 패키징하기 위한 명령줄 클라이언트입니다.

## 사용 가능한 명령

| 명령 | 목적 |
|---|---|
| [`env`](#env) | 버그 보고를 위한 환경 정보를 출력합니다. |
| [`schema`](#schema) | 가중치를 다운로드하지 않고 파이프라인의 `__call__` 시그니처를 검사합니다. |
| [`run`](#run) | 로컬 또는 Hugging Face Sandbox에서 파이프라인을 실행합니다. |
| [`custom_blocks`](#customblocks) | `ModularPipelineBlocks` 하위 클래스를 패키징하여 Hub에 업로드합니다. |
| [`fp16_safetensors`](#fp16safetensors) | 체크포인트를 `.safetensors` 형식의 fp16으로 변환합니다. |
| [`skills`](#skills) | AI 코딩 에이전트에 사전 작성된 스킬 번들을 설치합니다. |

> [!TIP]
> 이 페이지에서는 각 하위 명령의 모든 옵션에 대한 세부 정보를 제공하지 않습니다. 특정 하위 명령의 전체적이고 항상 최신인 옵션 목록을 확인하려면 `diffusers-cli <command> --help`(`diffusers-cli run --help`)를 실행하세요.

## env

Python, PyTorch, Diffusers 버전, CUDA 정보 및 설치된 선택적 의존성을 출력합니다. 유지보수자가 사용자의 환경을 재현할 수 있도록 이슈를 열 때 이 명령을 사용하세요.

```bash
diffusers-cli env
```

## schema

가중치를 다운로드하지 않고 파이프라인이 허용하는 입력을 반환합니다. [`run`](#run)에 사용할 `--pipeline-kwargs`를 구성할 때 사용하세요.

인덱스 파일만 가져옵니다. 표준 파이프라인은 `model_index.json`을, 모듈형 파이프라인은 `modular_model_index.json`을 읽습니다. 커스텀 블록 저장소는 `modular_config.json`을 읽고, Hub 코드를 실행하기 때문에 `--trust-remote-code`가 필요합니다.

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

## 실행

파이프라인을 끝에서 끝까지 실행합니다. CLI는 표준 저장소와 모듈형 저장소를 자동으로 감지합니다. URL 또는 로컬 경로에서 미디어 입력을 자동으로 로드하고, 파이프라인의 반환 유형에 따라 출력을 저장하며, `--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-kwargs`는 `pipeline(**kwargs)`로 전달되는 JSON 객체를 받습니다. 알려진 미디어 입력 키에 있는 문자열 값은 자동으로 로드됩니다:

- 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, 로컬 경로, 또는 버킷 마운트 경로), Diffusers는 GPU에서 하나의 forward pass로 전체 목록을 처리합니다:

```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}` — 가중치 dtype.
- `--device-map <value>` — 구성 요소 배치. torch 디바이스 문자열(`cuda`, `cuda:0`, `cpu`, `mps`), `balanced`(구성 요소를 가시적인 GPU에 자동으로 분배), 또는 구성 요소별 명시적 배치를 위한 JSON 딕셔너리를 허용합니다. 생략하면 자동으로 감지됩니다. 자세한 내용은 [device_map](../training/distributed_inference#devicemap)을 참조하세요.
- `--variant fp16` — 가중치 변형을 선택합니다.
- `--revision <sha>` — 특정 모델 리비전을 고정합니다.
- `--trust-remote-code` — Hub의 사용자 정의 코드 허용(사용자 정의 pipeline 클래스나 modular blocks를 포함하는 저장소에 필수). 표준 사용자 정의 pipeline은 [Community pipelines](../using-diffusers/custom_pipeline_overview), [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에는 일반 device 문자열이 필요합니다).
  - `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` 사용 시 activations를 위해 비워둘 device memory 용량으로, `enable_auto_cpu_offload`에 `memory_reserve_margin`으로 전달됩니다(기본값 `3GB`). 큰 canvas에서 forward 진행 중 메모리가 부족하면 이 값을 높여야 합니다. offloader는 구성 요소가 메모리에 들어가는 동안 해당 구성 요소를 resident 상태로 유지하므로, VRAM이 큰 카드에서는 기본 margin이 너무 작아 긴 video의 activations를 위한 공간이 부족할 수 있습니다.
- `--attention-backend` — Hub에 호스팅된 attention 커널로, 첫 사용 시 자동으로 다운로드됩니다. 선택지는 `default`와 Diffusers에 등록된 Hub 백엔드(예: `flash_hub`, `flash_varlen_hub`, `flash_4_hub`, `sage_hub`, `sage_blackwell_hub`)입니다. 현재 목록은 `diffusers-cli run --help`를 실행하여 확인하세요. Transformer 기반 파이프라인만 지원하며, 레거시 UNet 파이프라인에서는 경고와 함께 무시됩니다. [Attention backends](../optimization/attention_backends)를 참조하세요.
- `--vae-tiling` / `--vae-slicing` — VAE 디코딩 VRAM을 낮춥니다. [VAE tiling](../optimization/memory#vae-tiling) 및 [VAE slicing](../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`를 대신 래핑합니다. [컨텍스트 병렬성](../training/distributed_inference#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` (0으로 채운 인덱스, 예: `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`, … |

Directory 출력은 항상 패딩된 이름(`0000`, `0001`, …)을 사용합니다. 명시된 파일 경로는 사용자가 선택한 stem을 유지하고, 배치에서 여러 출력이 생성되면 패딩된 인덱스가 추가됩니다.

`--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` 설정됨? | 결과 |
|---|---|---|
| 아니요 | 아니요 | 기본 로컬 디렉토리로 다운로드 |
| 아니요 | 네 | `--output`에 다운로드 |
| 네 | 아니요 | 버킷만, 로컬 다운로드 없음 |
| 네 | 네 | bucket AND `--output` |

`--format`은 stdout 메타데이터(경로, 타이밍, 샌드박스 정보)의 형식을 결정합니다. 미디어 자체의 파일 형식은 변경하지 않습니다. 작성된 이미지는 항상 PNG, 비디오는 MP4, 오디오는 WAV 형식입니다.

### 원격 실행(`--remote`)

[Hugging Face Sandbox](https://huggingface.co/docs/huggingface_hub/en/guides/sandbox) 내부에서 동일한 호출을 실행합니다. 이는 CLI가 HTTP를 통해 제어하는 격리된 클라우드 VM으로, 입력을 업로드하고 파이프라인을 실행한 후 출력을 다운로드하고 샌드박스를 종료합니다. `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>` — 샌드박스 내부의 run 명령에 대한 최대 실행 시간(기본값 `10m`).
- `--dependencies <pkg>` — 추가 pip 의존성(반복 가능). 이미지 위에 설치됩니다. diffusers 브랜치 tarball을 고정하거나 파이프라인별 추가 항목을 추가하는 데 유용합니다.
- `--namespace <name>` — 다른 HF 조직/계정 아래에 샌드박스를 생성합니다.
- `--image <ref>` — 샌드박스 이미지를 재정의합니다. `--flavor`의 드라이버와 호환되는 torch + CUDA를 포함해야 합니다. CLI는 모든 콜드 샌드박스에서 자체 의존성을 추가로 설치하며, 기본 이미지는 이를 피합니다.
- `--volume <bucket-id>[:<mount-path>]` — [HF storage bucket](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 파일을 읽고, `ModularPipelineBlocks` 또는 그 복합 하위 클래스(`SequentialPipelineBlocks`, `AutoPipelineBlocks`, `ConditionalPipelineBlocks`, `LoopSequentialPipelineBlocks`)에서 파생된 클래스를 AST 스캔하여 선택된 클래스를 인스턴스화한 후, 현재 작업 디렉터리에서 `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
```

블록 클래스는 생성자 인자가 0개인 상태로 인스턴스화 가능해야 하며, `__init__`에서 기본값을 하드코딩하거나 호출 시점에 파이프라인 `state`에서 설정을 읽어야 합니다.

## `fp16_safetensors`

> [!CAUTION]
> 이 명령은 이제 비추천(deprecated)되며 향후 버전에서 제거될 예정입니다.

Hub의 체크포인트를 `.safetensors` 형식의 fp16으로 변환하고 결과를 push합니다. 저장소의 가중치 크기를 줄여 로딩 속도를 높이는 데 유용합니다. 정확한 인수는 `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
```

target 플래그가 없으면 CLI는 해당 CLI를 실행한 에이전트에 대해 설치하거나, 구별할 수 없는 경우 모든 에이전트에 대해 설치합니다. Claude Code는 `.claude/skills/diffusers/` 아래에 플러그인 번들을 설치하며(`/diffusers:<skill name>` 네임스페이스로 지정됨), Codex와 Cursor에는 `.agents/skills/<skill name>/`에 설치합니다.

