# 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 토큰이 제공되지 않으므로, `-s HF_TOKEN`을 사용하여 토큰을 전달해야 스크립트가 LoRA를 push할 수 있습니다. Job이 종료되면 Job의 디스크는 삭제되며, push하지 않은 모든 데이터는 손실됩니다. [DreamBooth](./dreambooth) 및 [LoRA](./lora) 가이드에서 학습 인자에 대해 설명합니다.

## Job 관리

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에 마운트하고, `--dataset_name` 대신 마운트 경로를 `--instance_data_dir`에 전달합니다. 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 스크립트는 [torchao](https://github.com/pytorch/ao)를 사용하여 FP8로 학습하기 위해 `--do_fp8_training`를 사용하며, 이를 통해 메모리 사용량을 줄일 수 있습니다. 스크립트 헤더에 torchao가 포함되어 있지 않으므로 `--` 앞에 `--with torchao`를 추가해야 합니다. FP8은 L4(`l4x1`) 또는 L40S(`l40sx1`)와 같이 컴퓨트 캐피빌리티 8.9 이상의 GPU가 필요합니다. A10G(8.6)와 A100(8.0)은 이를 지원하지 않습니다.

## 의존성 헤더 없이 스크립트 실행

`# /// script` 블록을 파일 상단에 선언하는 스크립트는 [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) 폴더에 있는 스크립트뿐입니다. 해당 폴더 안의 `train_dreambooth_lora_sdxl.py`와 같은 일부 스크립트에는 이 블록이 없습니다.

헤더가 없는 스크립트의 경우 각 종속성을 `--with`로 전달합니다. 학습 스크립트는 개발 버전을 필요로 하므로 Diffusers는 소스에서 설치합니다. 다른 종속성은 스크립트의 `requirements.txt` 파일과 그 import에서 가져옵니다.

```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)마다 `checkpoint-<step>` 폴더를 `--output_dir`에 저장하므로, 학습이 진행되는 동안 체크포인트가 버킷에 저장됩니다. `--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 문서의 [Train Models on Jobs](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)을 참고하세요.

