Diffusers documentation
모델 형식
모델 형식
Diffusion 모델은 일반적으로 Diffusers 형식 또는 단일 파일 형식으로 저장됩니다. 모델 파일은 safetensors나 ckpt와 같은 다양한 파일 형식으로 저장될 수 있습니다.
Format은 가중치가 디렉터리 구조로 저장되는지를 나타냅니다. File type은 safetensors나 ckpt와 같이 해당 가중치가 직렬화되는 방식을 나타냅니다.
Diffusers format Single-file format model/ model.safetensors (or .ckpt) ├─ model_index.json └─ all components in one file ├─ unet/ (or transformer/) ├─ text_encoder/ ├─ vae/ └─ scheduler/
이 가이드에서는 이러한 형식과 파일에서 파이프라인과 모델을 로드하는 방법을 보여줍니다.
Diffusers 형식
Diffusers 형식은 각 모델(UNet, transformer, text encoder)을 별도의 하위 폴더에 저장합니다. 모델을 별도로 저장하면 여러 가지 이점이 있습니다.
- 필요한 개별 모델을 로드하거나 모든 모델을 병렬로 로드할 수 있으므로 전체 파이프라인 초기화가 더 빠릅니다.
- 필요한 모델이 하나뿐이라면 모든 파이프라인 구성 요소를 로드할 필요가 없으므로 메모리 사용량이 줄어듭니다. 여러 파이프라인에서 공유되는 모델을 재사용할 수 있습니다.
- 여러 파이프라인에서 공유되는 공통 모델은 한 번만 다운로드되므로 저장 요구 사항이 낮아집니다.
- 파이프라인에서 새 모델 또는 개선된 모델을 사용할 수 있는 유연성.
단일 파일 형식
단일 파일 형식은 모든 모델 가중치(UNet, transformer, text encoder)를 하나의 파일에 저장합니다. 단일 파일 형식의 장점은 다음과 같습니다:
- ComfyUI 또는 Automatic1111와의 호환성 향상.
- 단일 파일을 다운로드하고 공유하는 것이 더 쉽습니다.
from_single_file()를 사용하여 단일 파일을 로드합니다.
import torch
from diffusers import StableDiffusionXLPipeline
pipeline = StableDiffusionXLPipeline.from_single_file(
"https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors",
dtype=torch.float16,
device_map="cuda" # or "mps", "xpu", "cpu"
)from_single_file() 메서드는 새로운 모델 또는 스케줄러를 전달하는 것도 지원합니다.
import torch
from diffusers import FluxPipeline, FluxTransformer2DModel
transformer = FluxTransformer2DModel.from_single_file(
"https://huggingface.co/Kijai/flux-fp8/blob/main/flux1-dev-fp8.safetensors", dtype=torch.bfloat16
)
pipeline = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev",
transformer=transformer,
dtype=torch.bfloat16,
device_map="cuda" # or "mps", "xpu", "cpu"
)구성 옵션
Diffusers 형식의 모델은 레포지토리에 레이어 수와 어텐션 헤드 수와 같은 중요한 속성이 포함된 config.json 파일을 가지고 있습니다. from_single_file() 메서드는 config.json에서 사용할 적절한 config를 자동으로 결정합니다. 그러나 몇 가지 드문 경우에서 실패할 수 있으며, 이 경우 config 인수를 사용해야 합니다.
파이프라인의 모델이 원래 구현과 다르거나 올바른 설정을 결정하는 데 필요한 메타데이터가 없는 경우에도 config 인수를 사용해야 합니다.
from diffusers import StableDiffusionXLPipeline
ckpt_path = "https://huggingface.co/segmind/SSD-1B/blob/main/SSD-1B.safetensors"
pipeline = StableDiffusionXLPipeline.from_single_file(ckpt_path, config="segmind/SSD-1B")original_config를 local_files_only=True와 함께 전달하면 Diffusers는 파이프라인 클래스 시그니처에서 파이프라인 구성 요소를 추론합니다. Hub에서 설정 파일을 다운로드하지 않으므로 오프라인 상태일 때 발생하는 깨짐 변경을 방지합니다. 이 경로는 config에 로컬 모델 경로를 제공하는 것보다 신뢰성이 낮으며 오류가 발생할 수 있습니다. 나중에 오프라인에서 설정 파일이 필요할 경우를 대비하여 local_files_only=False로 한 번 실행하여 설정 파일이 로컬 캐시에 저장되도록 하십시오.
인수를 from_single_file()에 직접 전달하여 기본 설정을 재정의합니다. 아래 예제는 파이프라인 또는 모델에서 설정을 재정의하는 방법을 보여줍니다.
from diffusers import StableDiffusionXLInstructPix2PixPipeline
ckpt_path = "https://huggingface.co/stabilityai/cosxl/blob/main/cosxl_edit.safetensors"
pipeline = StableDiffusionXLInstructPix2PixPipeline.from_single_file(
ckpt_path, config="diffusers/sdxl-instructpix2pix-768", is_cosxl_edit=True
)from diffusers import UNet2DConditionModel
ckpt_path = "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0_0.9vae.safetensors"
model = UNet2DConditionModel.from_single_file(ckpt_path, upcast_attention=True)로컬 파일
from_single_file() 메서드는 체크포인트 파일의 키를 기반으로 모델 유형을 추론하여 파이프라인 또는 모델을 구성하려고 합니다. 예를 들어, Stable Diffusion XL 기반 모델에 기반한 단일 파일 체크포인트는 stabilityai/stable-diffusion-xl-base-1.0에서 구성됩니다.
로컬 파일로 작업하는 경우, snapshot_download 메서드로 설정 파일을, hf_hub_download로 모델 체크포인트를 다운로드합니다. 이 파일들은 캐시 디렉터리에 다운로드되지만, local_dir 인수를 사용하여 특정 디렉터리로 다운로드할 수 있습니다.
from huggingface_hub import hf_hub_download, snapshot_download
from diffusers import StableDiffusionXLPipeline
my_local_checkpoint_path = hf_hub_download(
repo_id="segmind/SSD-1B",
filename="SSD-1B.safetensors"
)
my_local_config_path = snapshot_download(
repo_id="segmind/SSD-1B",
allow_patterns=["*.json", "**/*.json", "*.txt", "**/*.txt"]
)
pipeline = StableDiffusionXLPipeline.from_single_file(
my_local_checkpoint_path, config=my_local_config_path, local_files_only=True
)심볼릭 링크
심볼릭 링크를 지원하지 않는 파일 시스템에서 작업하는 경우, local_dir 매개변수를 사용하여 먼저 체크포인트 파일을 로컬 디렉토리로 다운로드하세요. local_dir 매개변수를 사용하면 심볼릭 링크가 자동으로 비활성화됩니다.
from huggingface_hub import hf_hub_download, snapshot_download
from diffusers import StableDiffusionXLPipeline
my_local_checkpoint_path = hf_hub_download(
repo_id="segmind/SSD-1B",
filename="SSD-1B.safetensors",
local_dir="my_local_checkpoints",
)
print("My local checkpoint: ", my_local_checkpoint_path)
my_local_config_path = snapshot_download(
repo_id="segmind/SSD-1B",
allow_patterns=["*.json", "**/*.json", "*.txt", "**/*.txt"]
)
print("My local config: ", my_local_config_path)이 경로들을 from_single_file()에 전달하세요.
pipeline = StableDiffusionXLPipeline.from_single_file(
my_local_checkpoint_path, config=my_local_config_path, local_files_only=True
)파일 유형
모델은 여러 파일 형식으로 저장될 수 있습니다. Safetensors가 가장 일반적인 파일 형식이지만, Hub나 diffusion 커뮤니티에서 다른 파일 형식을 만나볼 수 있습니다.
safetensors
Safetensors는 텐서를 안전하게 저장하고 로드하기 위한 안전하고 빠른 파일 형식입니다. 헤더 크기를 제한하여 특정 유형의 공격을 방지하고, 지연 로딩을 지원하며(분산 환경에서 유용), 일반적으로 로딩 속도가 더 빠릅니다.
Safetensors 라이브러리가 설치되어 있고 safetensors 파일이 사용 가능한 경우, Diffusers는 기본적으로 safetensors 파일(필수 의존성)을 로드합니다.
Use from_pretrained() or from_single_file() to load safetensor files.
import torch
from diffusers import DiffusionPipeline, StableDiffusionXLPipeline
pipeline = DiffusionPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0",
dtype=torch.float16,
device_map="cuda", # or "mps", "xpu", "cpu"
)
pipeline = StableDiffusionXLPipeline.from_single_file(
"https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors",
dtype=torch.float16,
)Diffusers 학습 스크립트로 학습된 체크포인트를 사용하는 경우, LoRA 구성과 같은 메타데이터가 자동으로 저장됩니다. 파일이 로드되면 해당 메타데이터가 파싱되어 LoRA가 올바르게 구성됩니다. Hub에서 파일 옆의
아이콘을 클릭하여 safetensors 파일의 메타데이터를 확인하세요.
Diffusers로 학습되지 않은 체크포인트의 LoRA 어댑터 메타데이터를 저장하려면 save_lora_weights()에 전달하세요. 트랜스포머에는 transformer_lora_adapter_metadata를, 텍스트 인코더에는 text_encoder_lora_adapter_metadata를 사용하세요. 또한 save_directory와 transformer_lora_layers 또는 text_encoder_lora_layers 중 적어도 하나를 전달해야 합니다. 이 경로는 safetensors 파일에서만 지원됩니다.
import torch
from peft.utils import get_peft_model_state_dict
from diffusers import FluxPipeline
pipeline = FluxPipeline.from_pretrained(
"black-forest-labs/FLUX.1-dev", dtype=torch.bfloat16, device_map="cuda" # or "mps", "xpu", "cpu"
)
pipeline.load_lora_weights("linoyts/yarn_art_Flux_LoRA")
transformer_lora_layers = get_peft_model_state_dict(pipeline.transformer)
pipeline.save_lora_weights(
save_directory="path/to/lora",
transformer_lora_layers=transformer_lora_layers,
transformer_lora_adapter_metadata={"r": 8, "lora_alpha": 8},
)ckpt
이전 모델 가중치는 일반적으로 Python의 pickle 유틸리티를 사용하여 ckpt 파일로 저장됩니다.
Pickled 파일은 악성 코드 실행에 악용될 수 있어 안전하지 않을 수 있습니다. safetensors 파일을 사용하거나 가중치를 safetensors 파일로 변환하는 것이 권장됩니다.
ckpt 파일을 로드하려면 from_single_file()를 사용하세요.
from diffusers import StableDiffusionPipeline
pipeline = StableDiffusionPipeline.from_single_file(
"https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/v1-5-pruned.ckpt"
)GGUF
GGUF은 사전 양자화된 가중치를 단일 파일에 저장합니다. Diffusers는 GGUFQuantizationConfig를 사용하여 모델의 from_single_file()를 통해 GGUF를 로드합니다. 파이프라인 수준의 GGUF 로드는 지원되지 않습니다.
설치 단계와 전체 예제는 GGUF를 참조하세요.
import torch
from diffusers import FluxTransformer2DModel, GGUFQuantizationConfig
transformer = FluxTransformer2DModel.from_single_file(
"https://huggingface.co/city96/FLUX.1-dev-gguf/blob/main/flux1-dev-Q2_K.gguf",
quantization_config=GGUFQuantizationConfig(compute_dtype=torch.bfloat16),
)Converting formats and files
Diffusers는 확산 생태계의 더 많은 도구가 이를 사용할 수 있도록 형식과 파일을 변환하는 스크립트와 방법을 제공합니다.
변환 스크립트를 찾으려면 diffusers/scripts 폴더를 확인하세요. 끝에 "to_diffusers"가 붙은 스크립트는 모델을 Diffusers 형식으로 변환합니다. 각 스크립트에는 변환을 구성하기 위한 특정 인자 세트가 있습니다. 사용 가능한 인자가 무엇인지 확인하세요.
아래 예시는 Diffusers 형식으로 저장된 모델을 단일 파일 형식으로 변환합니다. 변환할 모델의 경로와 변환된 모델을 저장할 위치를 지정합니다. 선택적으로 모델을 저장할 파일 형식과 데이터 유형을 지정할 수 있습니다.
python convert_diffusers_to_original_sdxl.py --model_path path/to/model/to/convert --checkpoint_path path/to/save/model/to --use_safetensors
save_pretrained() 메서드도 Diffusers 형식으로 모델을 저장하며, 각 모델에 대한 하위 폴더를 생성하는 작업을 처리합니다. 기본적으로 파일을 safetensor 파일로 저장합니다.
from diffusers import StableDiffusionXLPipeline
pipeline = StableDiffusionXLPipeline.from_single_file(
"https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0.safetensors",
)
pipeline.save_pretrained("path/to/save/model")다음 단계
- 디자인 결정과 모델 가중치를 저장 및 로드할 때 safetensor 파일이 선호되는 이유에 대해 정말 안전하다고 감사된 Safetensors가 기본으로 채택됨 블로그 게시물에서 자세히 알아보세요.