# Hugging Face 职位

[Hugging Face Jobs](https://huggingface.co/docs/hub/jobs) 运行在 Hugging Face 的 GPU 上，因此您无需自行配置机器，即使关闭终端，任务也会继续运行。Diffusers 的训练脚本可以直接通过其 GitHub URL 在 Jobs 上运行，无需克隆仓库或在本地安装任何依赖。

在开始之前，请按照 [Jobs 快速入门](https://huggingface.co/docs/hub/jobs-quickstart) 安装 `hf` CLI，登录并往您的账户中充值。

## 在 Jobs 上训练 LoRA

以下命令使用 [diffusers/dog-example](https://huggingface.co/datasets/diffusers/dog-example) 中的五张狗的照片，为 [FLUX.2-klein-4B](https://huggingface.co/black-forest-labs/FLUX.2-klein-4B) 训练一个 LoRA。该命令在单张 A10G 上运行，并将 LoRA 推送到 Hub 上的您的命名空间。

```bash
# 20 steps is a test run. For a real run, raise --max_train_steps
# (the FLUX.2 README uses 500) and --timeout to match.
hf jobs uv run --flavor a10g-small --timeout 30m -s HF_TOKEN -- \
  https://raw.githubusercontent.com/huggingface/diffusers/main/examples/dreambooth/train_dreambooth_lora_flux2_klein.py \
  --pretrained_model_name_or_path black-forest-labs/FLUX.2-klein-4B \
  --dataset_name diffusers/dog-example \
  --instance_prompt "a photo of sks dog" \
  --resolution 512 --mixed_precision bf16 --guidance_scale 1 \
  --gradient_checkpointing --cache_latents \
  --optimizer adamW --use_8bit_adam --learning_rate 1e-4 \
  --max_train_steps 20 --seed 0 \
  --output_dir /tmp/out \
  --push_to_hub --hub_model_id your-username/klein-dog-lora
```

`uv` 会安装脚本 `# /// script` 头部中列出的依赖项，包括来自 `main` 的 Diffusers。Job 默认不会获取 Hugging Face token，因此 `-s HF_TOKEN` 会将你的 token 转发给脚本，以便其推送 LoRA。Job 结束时会丢弃其磁盘，任何未推送的内容都会丢失。[DreamBooth](./dreambooth) 和 [LoRA](./lora) 指南中介绍了训练参数。

## 管理任务

训练日志会在 Job 运行期间打印到您的终端。关闭终端或按 `Ctrl+C` 不会停止训练，因为 Job 是在 Hugging Face 的机器上运行的。若要启动长时间运行而不占用终端，请在 `--` 之前添加 `-d`。该命令会打印 Job ID 并返回。

使用 Job ID 重新连接到日志，在模型训练期间检查 GPU 内存和使用率，或停止运行。

```bash
hf jobs logs -f <job_id>
hf jobs stats <job_id>
hf jobs cancel <job_id>
```

如果运行失败，`hf jobs inspect <job_id>` 会显示错误信息。有关其他命令，请参阅 [管理任务](https://huggingface.co/docs/hub/jobs-manage)。

## 使用您自己的图像进行训练

要在您的图像上进行训练，请使用 `-v` 将图像文件夹挂载到 Job 中，并将挂载路径传递给 `--instance_data_dir`，而不是 `--dataset_name`。Job 会在启动前将该文件夹上传到私有存储桶，并以只读方式挂载。再次上传相同文件夹时，只会发送新增或已修改的文件。

```bash
hf jobs uv run --flavor a10g-small --timeout 30m -s HF_TOKEN \
  -v ./my-dog:/data -- \
  https://raw.githubusercontent.com/huggingface/diffusers/main/examples/dreambooth/train_dreambooth_lora_flux2_klein.py \
  --pretrained_model_name_or_path black-forest-labs/FLUX.2-klein-4B \
  --instance_data_dir /data \
  --instance_prompt "a photo of sks dog" \
  --resolution 512 --mixed_precision bf16 --guidance_scale 1 \
  --gradient_checkpointing --cache_latents \
  --optimizer adamW --use_8bit_adam --learning_rate 1e-4 \
  --max_train_steps 20 --seed 0 \
  --output_dir /tmp/out \
  --push_to_hub --hub_model_id your-username/klein-dog-lora
```

该脚本会将 `--instance_data_dir` 中的每个文件都作为图像打开，因此请确保该文件夹中只包含图像。像 `.DS_Store` 这样的隐藏文件会导致运行失败。有关挂载文件夹的更多信息，请参阅 [本地目录](https://huggingface.co/docs/hub/jobs-configuration#local-directories)。

使用 `--with_prior_preservation` 时，脚本会在训练开始前将类别图像生成到 `--class_data_dir` 中。请将其指向 Job 可写入的路径。若要在后续运行中复用这些类别图像，请将其放置在可读写存储桶挂载点中，例如 [为长时间运行保存检查点](#save-checkpoints-for-long-runs) 中所示的挂载点。

## 以 FP8 进行训练

FLUX.2、Z-Image、Ideogram 4 和 Krea 2 的 DreamBooth LoRA 脚本支持 `--do_fp8_training` 参数，用于通过 [torchao](https://github.com/pytorch/ao) 以 FP8 精度进行训练，从而降低内存占用。由于脚本头部未包含 torchao，请在 `--` 之前添加 `--with torchao`。FP8 还需要计算能力为 8.9 或更高的 GPU，例如 L4（`l4x1`）或 L40S（`l40sx1`）。A10G（8.6）和 A100（8.0）不支持该功能。

## 在没有依赖项头部的情况下运行脚本

只有 [examples/dreambooth](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth) 和 [examples/advanced_diffusion_training](https://github.com/huggingface/diffusers/tree/main/examples/advanced_diffusion_training) 中的脚本会在文件顶部的 `# /// script` 块中声明其依赖项。这些文件夹中的某些脚本（例如 `train_dreambooth_lora_sdxl.py`）并没有该块。

对于没有头部信息的脚本，请使用 `--with` 逐个传入每个依赖项。请从源代码安装 Diffusers，因为训练脚本需要开发版本。其他依赖项来自脚本的 `requirements.txt` 文件及其导入语句。

```bash
hf jobs uv run --flavor a10g-small --timeout 30m -s HF_TOKEN \
  --with "diffusers @ git+https://github.com/huggingface/diffusers.git" \
  --with torch --with torchvision --with accelerate --with transformers \
  --with peft --with datasets --with bitsandbytes \
  --with ftfy --with tensorboard --with Jinja2 -- \
  https://raw.githubusercontent.com/huggingface/diffusers/main/examples/dreambooth/train_dreambooth_lora_sdxl.py \
  --pretrained_model_name_or_path stabilityai/stable-diffusion-xl-base-1.0 \
  --pretrained_vae_model_name_or_path madebyollin/sdxl-vae-fp16-fix \
  --dataset_name diffusers/dog-example \
  --instance_prompt "a photo of sks dog" \
  --resolution 1024 --mixed_precision fp16 \
  --gradient_checkpointing --use_8bit_adam --learning_rate 1e-4 \
  --max_train_steps 20 --seed 0 \
  --output_dir /tmp/out \
  --push_to_hub --hub_model_id your-username/sdxl-dog-lora
```

## 为长时间运行的任务保存检查点

耗时数小时的运行任务可能会在结束前超时或崩溃。为了保留其进度，请使用 `-v` 将 [Storage Bucket](https://huggingface.co/docs/hub/storage-buckets) 挂载到 Job 中，并将 `--output_dir` 指向该存储桶。请先使用 `hf buckets create` 创建存储桶。

该脚本每 `--checkpointing_steps` 步（默认为 500 步）就会在 `--output_dir` 中保存一个 `checkpoint-<step>` 文件夹，因此检查点会随着训练的进行而存入存储桶。`--checkpoints_total_limit` 用于限制保留的检查点数量。`--resume_from_checkpoint latest` 会从 `--output_dir` 中最新的检查点继续训练；如果不存在检查点，则从头开始训练。因此，同一条命令既适用于首次运行，也适用于每次重启。

```bash
hf jobs uv run --flavor a10g-small --timeout 8h -s HF_TOKEN \
  -v hf://buckets/your-username/checkpoints:/ckpt -- \
  https://raw.githubusercontent.com/huggingface/diffusers/main/examples/dreambooth/train_dreambooth_lora_flux2_klein.py \
  --pretrained_model_name_or_path black-forest-labs/FLUX.2-klein-4B \
  --dataset_name diffusers/dog-example \
  --instance_prompt "a photo of sks dog" \
  --resolution 1024 --mixed_precision bf16 --guidance_scale 1 \
  --gradient_checkpointing --cache_latents \
  --optimizer adamW --use_8bit_adam --learning_rate 1e-4 \
  --max_train_steps 5000 --seed 0 \
  --checkpointing_steps 500 --checkpoints_total_limit 3 \
  --resume_from_checkpoint latest \
  --output_dir /ckpt/klein-dog
```

训练结束后，LoRA 会以 `pytorch_lora_weights.safetensors` 的形式保存到存储桶中。有关挂载选项，请参阅 [Volumes](https://huggingface.co/docs/hub/jobs-configuration#volumes)。

> [!NOTE]
> 当 `--output_dir` 中包含检查点时，请勿添加 `--push_to_hub`。上传操作仅跳过 `step_*` 和 `epoch_*` 文件夹，因此 `checkpoint-<step>` 文件夹会与 LoRA 一起被推送到模型仓库。请改为自行将 `pytorch_lora_weights.safetensors` 上传到模型仓库。

## 后续步骤

- 请参阅 Hub 文档中的 [在任务上训练模型](https://huggingface.co/docs/hub/jobs-training)，了解在长时间运行的任务开始前需要执行的检查，以及如何查看失败的任务。
- 使用 [LoRA](../tutorials/using_peft_for_inference) 指南加载你训练好的 LoRA 以进行推理。
- 请浏览 [DreamBooth README 文件](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth)，以获取特定于模型的命令和内存选项。

