Diffusers 文件

模型檔案和佈局

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

模型檔案和佈局

擴散模型以各種檔案型別儲存並以不同的佈局組織。Diffusers 將模型權重儲存為 Diffusers-多資料夾 佈局中的 safetensors 檔案,它還支援從擴散生態系統中常用的 單檔案 佈局載入檔案(如 safetensors 和 ckpt 檔案)。

每種佈局都有其自身的優點和用例,本指南將向您展示如何載入不同的檔案和佈局,以及如何轉換它們。

檔案

PyTorch 模型權重通常使用 Python 的 pickle 實用程式儲存為 ckpt 或 bin 檔案。然而,pickle 不安全, pickled 檔案可能包含可執行的惡意程式碼。考慮到模型共享的流行性,這種漏洞是一個嚴重的問題。為了解決這個安全問題,Safetensors 庫被開發為 pickle 的安全替代品,它將模型儲存為 safetensors 檔案。

safetensors

Safetensors 經審計確認為真正安全併成為預設部落格文章中,瞭解有關設計決策以及為何優先使用 safetensor 檔案來儲存和載入模型權重的更多資訊。

Safetensors 是一種安全快速的檔案格式,用於安全地儲存和載入張量。Safetensors 限制了頭部大小以限制某些型別的攻擊,支援延遲載入(對於分散式設定很有用),並且通常具有更快的載入速度。

請確保您已安裝 Safetensors 庫。

!pip install safetensors

Safetensors 將權重儲存在 safetensors 檔案中。如果 safetensors 檔案可用且 Safetensors 庫已安裝,Diffusers 預設載入 safetensors 檔案。safetensors 檔案有兩種組織方式:

  1. Diffusers-多資料夾佈局:可能有多個獨立的 safetensors 檔案,每個檔案用於一個流水線元件(文字編碼器、UNet、VAE),組織在子資料夾中(請參閱 stable-diffusion-v1-5/stable-diffusion-v1-5 倉庫作為示例)
  2. 單檔案佈局:所有模型權重都可以儲存在一個檔案中(請參閱 WarriorMama777/OrangeMixs 倉庫作為示例)
多資料夾
單檔案

使用 from_pretrained() 方法載入儲存在多個資料夾中的 safetensors 檔案的模型。

from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "stable-diffusion-v1-5/stable-diffusion-v1-5",
    use_safetensors=True
)

LoRA 檔案

LoRA 是一種輕量級介面卡,訓練快速簡便,因此在以特定方式或風格生成影像方面特別受歡迎。這些介面卡通常儲存在 safetensors 檔案中,並在 civitai 等模型共享平臺上廣泛流行。

LoRA 透過 load_lora_weights() 方法載入到基礎模型中。

from diffusers import StableDiffusionXLPipeline
import torch

# base model
pipeline = StableDiffusionXLPipeline.from_pretrained(
    "Lykon/dreamshaper-xl-1-0", torch_dtype=torch.float16, variant="fp16"
).to("cuda")

# download LoRA weights
!wget https://civitai.com/api/download/models/168776 -O blueprintify.safetensors

# load LoRA weights
pipeline.load_lora_weights(".", weight_name="blueprintify.safetensors")
prompt = "bl3uprint, a highly detailed blueprint of the empire state building, explaining how to build all parts, many txt, blueprint grid backdrop"
negative_prompt = "lowres, cropped, worst quality, low quality, normal quality, artifacts, signature, watermark, username, blurry, more than one bridge, bad architecture"

image = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    generator=torch.manual_seed(0),
).images[0]
image

ckpt

Pickled 檔案可能不安全,因為它們可能被利用來執行惡意程式碼。建議儘可能使用 safetensors 檔案,或將權重轉換為 safetensors 檔案。

PyTorch 的 torch.save 函式使用 Python 的 pickle 實用程式來序列化和儲存模型。這些檔案儲存為 ckpt 檔案,其中包含整個模型的權重。

使用 from_single_file() 方法直接載入 ckpt 檔案。

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"
)

儲存佈局

模型檔案有兩種組織方式,要麼是 Diffusers-多資料夾佈局,要麼是單檔案佈局。Diffusers-多資料夾佈局是預設的,每個元件檔案(文字編碼器、UNet、VAE)都儲存在單獨的子資料夾中。Diffusers 還支援從將所有元件捆綁在一起的單檔案佈局載入模型。

Diffusers-多資料夾

Diffusers-多資料夾佈局是 Diffusers 的預設儲存佈局。每個元件(文字編碼器、UNet、VAE)的權重都儲存在單獨的子資料夾中。權重可以儲存為 safetensors 或 ckpt 檔案。

多資料夾佈局
UNet 子資料夾

要從 Diffusers-多資料夾佈局載入,請使用 from_pretrained() 方法。

from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0",
    torch_dtype=torch.float16,
    variant="fp16",
    use_safetensors=True,
).to("cuda")

使用 Diffusers-多資料夾佈局的優點包括:

  1. 更快地單獨或並行載入每個元件檔案。

  2. 減少記憶體使用,因為您只加載所需的元件。例如,像 SDXL TurboSDXL LightningHyper-SD 這樣的模型除了 UNet 之外,具有相同的元件。您可以使用 from_pipe() 方法重用它們的共享元件,而無需消耗任何額外的記憶體(請參閱 重用流水線 指南),並且只加載 UNet。這樣,您無需下載冗餘元件並避免不必要的記憶體使用。

    import torch
    from diffusers import StableDiffusionXLPipeline, UNet2DConditionModel, EulerDiscreteScheduler
    
    # download one model
    sdxl_pipeline = StableDiffusionXLPipeline.from_pretrained(
        "stabilityai/stable-diffusion-xl-base-1.0",
        torch_dtype=torch.float16,
        variant="fp16",
        use_safetensors=True,
    ).to("cuda")
    
    # switch UNet for another model
    unet = UNet2DConditionModel.from_pretrained(
        "stabilityai/sdxl-turbo",
        subfolder="unet",
        torch_dtype=torch.float16,
        variant="fp16",
        use_safetensors=True
    )
    # reuse all the same components in new model except for the UNet
    turbo_pipeline = StableDiffusionXLPipeline.from_pipe(
        sdxl_pipeline, unet=unet,
    ).to("cuda")
    turbo_pipeline.scheduler = EulerDiscreteScheduler.from_config(
        turbo_pipeline.scheduler.config,
        timestep+spacing="trailing"
    )
    image = turbo_pipeline(
        "an astronaut riding a unicorn on mars",
        num_inference_steps=1,
        guidance_scale=0.0,
    ).images[0]
    image
  3. 減少儲存需求,因為如果一個元件(例如 SDXL VAE)在多個模型之間共享,您只需下載和儲存它的一個副本,而不是多次下載和儲存它。對於 10 個 SDXL 模型,這可以節省約 3.5GB 的儲存空間。對於 PixArt Sigma 等新模型,儲存節省量甚至更大,其中 文字編碼器 單獨就有約 19GB!

  4. 靈活地用更新或更好的版本替換模型中的元件。

    from diffusers import DiffusionPipeline, AutoencoderKL
    
    vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16, use_safetensors=True)
    pipeline = DiffusionPipeline.from_pretrained(
        "stabilityai/stable-diffusion-xl-base-1.0",
        vae=vae,
        torch_dtype=torch.float16,
        variant="fp16",
        use_safetensors=True,
    ).to("cuda")
  5. 有關模型元件的更多可見性和資訊,這些元件儲存在每個元件子資料夾中的 config.json 檔案中。

單檔案

單檔案佈局將所有模型權重儲存在一個檔案中。所有模型元件(文字編碼器、UNet、VAE)的權重都打包在一起,而不是分別儲存在子資料夾中。這可以是 safetensors 或 ckpt 檔案。

要從單檔案佈局載入,請使用 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",
    torch_dtype=torch.float16,
    variant="fp16",
    use_safetensors=True,
).to("cuda")

使用單檔案佈局的優點包括:

  1. 與通常使用單檔案佈局的擴散介面(如 ComfyUIAutomatic1111)輕鬆相容。
  2. 更易於管理(下載和共享)單個檔案。

DDUF

DDUF 是一種實驗性檔案格式,其相關 API 將來可能會發生變化。

DDUF (DDUF Diffusion Unified Format) 是一種檔案格式,旨在使擴散模型的儲存、分發和使用更加便捷。DDUF 基於 ZIP 檔案格式構建,提供了一種標準化、高效且靈活的方式,可將擴散模型的所有部分打包成一個易於管理的單個檔案。它在 Diffusers 多資料夾格式和廣泛流行的單檔案格式之間取得了平衡。

在 Hugging Face Hub 文件上了解更多關於 DDUF 的詳細資訊。

將檢查點傳遞給 dduf_file 引數以將其載入到 DiffusionPipeline 中。

from diffusers import DiffusionPipeline
import torch

pipe = DiffusionPipeline.from_pretrained(
    "DDUF/FLUX.1-dev-DDUF", dduf_file="FLUX.1-dev.dduf", torch_dtype=torch.bfloat16
).to("cuda")
image = pipe(
    "photo a cat holding a sign that says Diffusers", num_inference_steps=50, guidance_scale=3.5
).images[0]
image.save("cat.png")

要將流水線儲存為 .dduf 檢查點,請使用 export_folder_as_dduf 實用程式,該實用程式負責所有必要的檔案級驗證。

from huggingface_hub import export_folder_as_dduf
from diffusers import DiffusionPipeline
import torch 

pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)

save_folder = "flux-dev"
pipe.save_pretrained("flux-dev")
export_folder_as_dduf("flux-dev.dduf", folder_path=save_folder)

> [!TIP]
> Packaging and loading quantized checkpoints in the DDUF format is supported as long as they respect the multi-folder structure.

## Convert layout and files

Diffusers provides many scripts and methods to convert storage layouts and file formats to enable broader support across the diffusion ecosystem.

Take a look at the [diffusers/scripts](https://github.com/huggingface/diffusers/tree/main/scripts) collection to find a script that fits your conversion needs.

> [!TIP]
> Scripts that have "`to_diffusers`" appended at the end mean they convert a model to the Diffusers-multifolder layout. Each script has their own specific set of arguments for configuring the conversion, so make sure you check what arguments are available!

For example, to convert a Stable Diffusion XL model stored in Diffusers-multifolder layout to a single-file layout, run the [convert_diffusers_to_original_sdxl.py](https://github.com/huggingface/diffusers/blob/main/scripts/convert_diffusers_to_original_sdxl.py) script. Provide the path to the model to convert, and the path to save the converted model to. You can optionally specify whether you want to save the model as a safetensors file and whether to save the model in half-precision.

```bash
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-多資料夾佈局。如果目錄不存在,此方法會為您建立目錄,並且預設將檔案儲存為 safetensors 檔案。

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()

最後,還有一些 Space,例如 SD To DiffusersSD-XL To Diffusers,它們提供了更使用者友好的介面,用於將模型轉換為 Diffusers-多資料夾佈局。這是轉換佈局最簡單、最方便的選項,它會在您的模型倉庫中開啟一個包含轉換檔案的 PR。然而,此選項不如執行指令碼可靠,並且 Space 可能會在更復雜的模型上失敗。

單檔案佈局使用

既然您熟悉了 Diffusers-多資料夾和單檔案佈局之間的區別,本節將向您展示如何使用 from_single_file() 方法載入模型和流水線元件,自定義載入的配置選項,以及載入本地檔案。

載入流水線或模型

將流水線或模型的檔案路徑傳遞給 from_single_file() 方法以載入它。

流水線
模型
from diffusers import StableDiffusionXLPipeline

ckpt_path = "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0_0.9vae.safetensors"
pipeline = StableDiffusionXLPipeline.from_single_file(ckpt_path)

透過將元件直接傳遞給 from_single_file() 方法來定製流水線中的元件。例如,您可以在流水線中使用不同的排程器。

from diffusers import StableDiffusionXLPipeline, DDIMScheduler

ckpt_path = "https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/blob/main/sd_xl_base_1.0_0.9vae.safetensors"
scheduler = DDIMScheduler()
pipeline = StableDiffusionXLPipeline.from_single_file(ckpt_path, scheduler=scheduler)

或者您可以在流水線中使用 ControlNet 模型。

from diffusers import StableDiffusionControlNetPipeline, ControlNetModel

ckpt_path = "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.safetensors"
controlnet = ControlNetModel.from_pretrained("lllyasviel/control_v11p_sd15_canny")
pipeline = StableDiffusionControlNetPipeline.from_single_file(ckpt_path, controlnet=controlnet)

自定義配置選項

模型有一個配置檔案,用於定義其屬性,例如 UNet 中的輸入數量。流水線的配置選項可在流水線的類中找到。例如,如果您檢視 StableDiffusionXLInstructPix2PixPipeline 類,會有一個選項可以使用 is_cosxl_edit 引數縮放影像潛在空間。

這些配置檔案可以在模型的 Hub 倉庫或其他配置檔案的來源位置(例如,GitHub 倉庫或本地裝置)中找到。

Hub 配置檔案
原始配置檔案

from_single_file() 方法會自動將檢查點對映到適當的模型倉庫,但在某些情況下,使用 config 引數會很有用。例如,如果檢查點中的模型元件與原始檢查點不同,或者檢查點沒有必要的元資料來正確確定流水線要使用的配置。

from_single_file() 方法會自動從模型倉庫中的配置檔案確定要使用的配置。您還可以透過向 config 引數提供倉庫 ID 來顯式指定要使用的配置。

from diffusers import StableDiffusionXLPipeline

ckpt_path = "https://huggingface.co/segmind/SSD-1B/blob/main/SSD-1B.safetensors"
repo_id = "segmind/SSD-1B"

pipeline = StableDiffusionXLPipeline.from_single_file(ckpt_path, config=repo_id)

模型從倉庫中各自的子資料夾載入 UNetVAE文字編碼器 的配置檔案。

雖然配置檔案指定了流水線或模型的預設引數,但您可以透過直接向 from_single_file() 方法提供引數來覆蓋它們。模型或流水線類支援的任何引數都可以透過這種方式配置。

流水線
模型

例如,要在 StableDiffusionXLInstructPix2PixPipeline 中縮放影像潛在空間,請傳遞 is_cosxl_edit 引數。

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)

本地檔案

在 Diffusers>=v0.28.0 中,from_single_file() 方法嘗試透過檢查點檔案中的鍵推斷模型型別來配置流水線或模型。推斷出的模型型別用於確定 Hugging Face Hub 上適當的模型倉庫,以配置模型或流水線。

例如,任何基於 Stable Diffusion XL 基礎模型的單檔案檢查點都將使用 stabilityai/stable-diffusion-xl-base-1.0 模型倉庫來配置流水線。

但是,如果您在網路受限的環境中工作,則應使用 snapshot_download 函式下載配置檔案,並使用 hf_hub_download 函式下載模型檢查點。預設情況下,這些檔案會下載到 Hugging Face Hub 快取目錄,但您可以使用 local_dir 引數指定首選的下載目錄。

將配置和檢查點路徑傳遞給 from_single_file() 方法以在本地載入。

Hub 快取目錄
特定本地目錄
from huggingface_hub import hf_hub_download, snapshot_download

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)

不使用符號連結的本地檔案

在 huggingface_hub>=v0.23.0 中,hf_hub_downloadsnapshot_download 函式不再需要 local_dir_use_symlinks 引數。

from_single_file() 方法依賴於 huggingface_hub 快取機制來獲取和儲存模型和流水線的檢查點和配置檔案。如果您在不支援符號連結的檔案系統上工作,應首先將檢查點檔案下載到本地目錄,並在 hf_hub_download 函式和 snapshot_download 函式中將 local_dir_use_symlink=False 引數設定為停用符號連結。

from huggingface_hub import hf_hub_download, snapshot_download

my_local_checkpoint_path = hf_hub_download(
    repo_id="segmind/SSD-1B",
    filename="SSD-1B.safetensors"
    local_dir="my_local_checkpoints",
    local_dir_use_symlinks=False
)
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"]
    local_dir_use_symlinks=False,
)
print("My local config: ", my_local_config_path)

然後可以將本地路徑傳遞給 pretrained_model_link_or_pathconfig 引數。

pipeline = StableDiffusionXLPipeline.from_single_file(my_local_checkpoint_path, config=my_local_config_path, local_files_only=True)
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.