Diffusers documentation

모델

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

모델

🤗 Diffusers는 인기 있는 알고리즘에 대한 사전 학습된 모델과 커스텀 diffusion 시스템을 생성하기 위한 모듈을 제공합니다. 모델의 주요 기능은 분포 pθ(xt−1∣xt)p_{\theta}(x_{t-1}|x_{t}).

모든 모델은 로컬 및 Hugging Face Hub에서 모델을 저장하고 로드하는 기본 기능을 제공하는 torch.nn.Module인 기본 ModelMixin 클래스로 구성됩니다.

ModelMixin

클래스 diffusers.ModelMixin

< >

( )

모든 모델의 베이스 클래스입니다.

ModelMixin은 모델 구성을 저장하는 역할을 하며, 모델을 로드, 다운로드 및 저장하는 메서드를 제공합니다.

  • config_name (str) — save_pretrained()를 호출할 때 모델을 저장할 파일 이름.

compile_repeated_blocks

< >

( *args**kwargs )

모델 전체를 컴파일하는 대신, 모델의 자주 반복되는 서브모듈(예: Transformer 레이어)만 컴파일합니다. 이 기법은 리전널 컴파일이라고도 불리며(관련 PyTorch 레시피: https://docs.pytorch.org/tutorials/recipes/regional_compilation.html), 전체 torch.compile에서 기대할 수 있는 런타임 속도 향상을 유지하면서 엔드투엔드 컴파일 시간을 크게 줄일 수 있습니다.

컴파일할 서브모듈 집합은 모델 정의에 _repeated_blocks 속성이 존재하는지 여부로 결정됩니다. 이 속성을 모델 서브클래스에 클래스 이름(문자열)의 리스트/튜플로 정의하십시오. 클래스 이름이 일치하는 모든 모듈이 컴파일됩니다.

발견된 각 매칭 서브모듈은 submodule.compile(*args, **kwargs)를 호출하여 컴파일됩니다. compile_repeated_blocks에 전달하는 모든 위치 인자 또는 키워드 인자는 torch.compile에 그대로 전달됩니다.

cuda

( *args**kwargs )

점으로 구분된 경로(예: torch.float32)에 대한 mock 값: 속성 접근 체인, 호출은 pass-through 데코레이터처럼 동작하며, repr은 해당 점으로 구분된 경로입니다. 이를 베이스 클래스로 사용하면 plain-type 베이스로 대체됩니다(PEP 560 __mro_entries__). 따라서 실제 서브클래스는 일반적인 메타클래스를 유지하고, inspect.signature는 mock의 __init__가 아닌 실제 __init__를 읽습니다.

dequantize

< >

( )

양자화 방법 중 역양자화를 지원하는 것으로 양자화된 경우, 모델을 역양자화할 수 있습니다.

disable_gradient_checkpointing

< >

( )

현재 모델에 대한 gradient checkpointing을 비활성화합니다(다른 프레임워크에서는 activation checkpointing 또는 checkpoint activations라고도 불립니다).

disable_npu_flash_attention

< >

( )

torch_npu에서 npu flash attention 비활성화

disable_xformers_memory_efficient_attention

< >

( )

xFormers에서 메모리 효율적 어텐션을 비활성화합니다.

disable_xla_flash_attention

< >

( )

torch_xla의 flash attention pallals 커널을 비활성화합니다.

enable_gradient_checkpointing

< >

( gradient_checkpointing_func: typing.Optional[typing.Callable] = None )

매개변수

  • gradient_checkpointing_func (Callable, 선택 사항) — Gradient checkpointing에 사용할 함수입니다. None인 경우, 기본 PyTorch checkpointing 함수(torch.utils.checkpoint.checkpoint)가 사용됩니다.

현재 모델에 대해 gradient checkpointing을 활성화합니다(다른 프레임워크에서는 activation checkpointing 또는 checkpoint activations라고도 불립니다).

enable_group_offload

< >

( onload_device: deviceoffload_device: device = torch.device()offload_type: str = 'block_level'num_blocks_per_group: int | None = Nonenon_blocking: bool = Falseuse_stream: bool = Falserecord_stream: bool = Falselow_cpu_mem_usage = Falseoffload_to_disk_path: str | None = Noneblock_modules: str | None = Noneexclude_kwargs: str | None = None )

현재 모델에 대한 그룹 오프로딩을 활성화합니다.

자세한 내용은 apply_group_offloading()을 참조하세요.

예:

>>> from diffusers import CogVideoXTransformer3DModel

>>> transformer = CogVideoXTransformer3DModel.from_pretrained(
...     "THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=torch.bfloat16
... )

>>> transformer.enable_group_offload(
...     onload_device=torch.device("cuda"),
...     offload_device=torch.device("cpu"),
...     offload_type="leaf_level",
...     use_stream=True,
... )

enable_layerwise_casting

< >

( storage_dtype: dtype = torch.float8_e4m3fncompute_dtype: typing.Optional[torch.dtype] = Noneskip_modules_pattern: tuple[str, ...] | None = Noneskip_modules_classes: tuple[typing.Type[torch.nn.Module], ...] | None = Nonenon_blocking: bool = False )

매개변수

  • storage_dtype (torch.dtype) — 모델을 저장하기 위해 캐스팅할 dtype입니다.
  • compute_dtype (torch.dtype) — forward pass 동안 모델 가중치가 캐스팅되어야 할 dtype입니다.
  • skip_modules_pattern (tuple[str, ...], 선택 사항) — 레이어별 캐스팅 과정에서 건너뛸 모듈의 이름을 일치시키기 위한 패턴 목록입니다. None으로 설정하면, 모듈의 특정 내부 레이어와 PEFT 레이어를 무시하기 위한 기본 건너뛰기 패턴이 사용됩니다.
  • skip_modules_classes (tuple[Type[torch.nn.Module], ...], 선택 사항) — 레이어별 캐스팅 과정에서 건너뛸 모듈 클래스 목록입니다.
  • non_blocking (bool, 선택 사항, 기본값 False) — True인 경우, 가중치 캐스팅 작업이 비차단 방식으로 수행됩니다.

현재 모델에 대해 레이어별 캐스팅을 활성화합니다.

Layerwise casting은 모델 가중치를 저장을 위해 더 낮은 정밀도의 dtype으로 캐스팅하고, 계산 시에는 더 높은 정밀도의 dtype으로 즉시 업캐스팅하는 기법입니다. 이 과정은 모델 가중치로 인한 메모리 사용량을 크게 줄일 수 있지만, 출력의 품질이 일부 저하될 수 있습니다. 대부분의 품질 저하는 무시할 수 있는 수준이며, 주로 정규화 및 변조 레이어의 가중치 캐스팅에서 비롯됩니다.

기본적으로 diffusers의 대부분의 모델은 패치 임베딩, 위치 임베딩 및 정규화 레이어를 무시하도록 _skip_layerwise_casting_patterns 속성을 설정합니다. 이는 이러한 레이어가 품질에 있어 정밀도가 가장 중요할 가능성이 높기 때문입니다. 이 동작을 변경하려면 _skip_layerwise_casting_patterns 속성을 None으로 설정하거나, 사용자 정의 인수를 사용하여 apply_layerwise_casting()을 호출할 수 있습니다.

예:

enable_layerwise_casting() 사용:

>>> from diffusers import CogVideoXTransformer3DModel

>>> transformer = CogVideoXTransformer3DModel.from_pretrained(
...     "THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=torch.bfloat16
... )

>>> # Enable layerwise casting via the model, which ignores certain modules by default
>>> transformer.enable_layerwise_casting(storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)

enable_npu_flash_attention

< >

( )

torch_npu에서 npu flash attention 활성화

enable_xformers_memory_efficient_attention

< >

( attention_op: typing.Optional[typing.Callable] = None )

매개변수

  • attention_op (Callable, 선택 사항) — xFormers의 memory_efficient_attention() 함수의 op 인수로 사용될 None 기본 연산자를 재정의합니다.

xFormers에서 메모리 효율적인 어텐션을 활성화합니다.

이 옵션이 활성화되면 추론 중에 GPU 메모리 사용량이 감소하고 속도가 향상되는 것을 관찰할 수 있습니다. 학습 중 속도 향상은 보장되지 않습니다.

> ⚠️ memory efficient attention과 sliced attention이 모두 활성화된 경우, memory efficient attention이 > 우선합니다.

예:

>>> import torch
>>> from diffusers import UNet2DConditionModel
>>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

>>> model = UNet2DConditionModel.from_pretrained(
...     "stabilityai/stable-diffusion-2-1", subfolder="unet", torch_dtype=torch.float16
... )
>>> model = model.to("cuda")
>>> model.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)

enable_xla_flash_attention

< >

( partition_spec: typing.Optional[typing.Callable] = None**kwargs )

torch_xla에 대한 flash attention pallals 커널을 활성화합니다.

from_pretrained

< >

( pretrained_model_name_or_path: str | os.PathLike | None**kwargs )

매개변수

  • pretrained_model_name_or_path (str 또는 os.PathLike, 선택 사항) — 다음 중 하나일 수 있습니다:
    • Hub에 호스팅된 사전 학습 모델의 model id 문자열(예: google/ddpm-celebahq-256).
    • A path to a directory (for example ./my_model_directory) containing the model weights saved with save_pretrained().
  • cache_dir (str | os.PathLike, 선택 사항) — 표준 캐시를 사용하지 않을 경우, 다운로드된 사전 학습 모델 구성이 캐시되는 디렉터리의 경로입니다.
  • dtype (torch.dtype, 선택 사항) — 기본 torch.dtype를 무시하고 다른 dtype로 모델을 로드합니다.
  • force_download (bool, 선택 사항, 기본값 False) — 모델 가중치 및 구성 파일의 (재)다운로드를 강제할지 여부입니다. 캐시된 버전이 존재하는 경우 이를 무시합니다.
  • proxies (dict[str, str], 선택) — 프로토콜 또는 엔드포인트별로 사용할 프록시 서버의 사전입니다. 예를 들어, {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}와 같습니다. 각 요청에 프록시가 사용됩니다.
  • output_loading_info (bool, 선택 사항, 기본값 False) — 누락된 키, 예상치 못한 키 및 오류 메시지를 포함하는 사전도 함께 반환할지 여부.
  • local_files_only(bool, 선택 사항, 기본값 False) — 로컬 모델 가중치 및 구성 파일만 로드할지 여부를 지정합니다. True로 설정하면 Hub에서 모델을 다운로드하지 않습니다.
  • token (str 또는 bool, 선택 사항) — 원격 파일에 대한 HTTP bearer 인증으로 사용할 토큰입니다. True인 경우, diffusers-cli login에서 생성된 토큰(~/.huggingface에 저장됨)이 사용됩니다.
  • revision (str, 선택 사항, 기본값 "main") — 사용할 특정 모델 버전입니다. Git에서 허용하는 브랜치 이름, 태그 이름, 커밋 ID 또는 기타 식별자일 수 있습니다.
  • subfolder (str, 선택 사항, 기본값 "") — Hub 또는 로컬의 더 큰 모델 저장소 내에서 모델 파일의 서브폴더 위치입니다.
  • mirror (str, 선택 사항) — 중국에서 모델을 다운로드할 때 접근성 문제를 해결하기 위한 미러 소스입니다. 소스의 적시성이나 안전성을 보장하지 않으며, 자세한 정보는 해당 미러 사이트를 참고하세요.
  • device_map (int | str | torch.device 또는 dict[str, int | str | torch.device], 선택 사항) — 각 서브모듈이 어디에 배치되어야 하는지 지정하는 맵입니다. 각 파라미터/버퍼 이름마다 정의할 필요는 없으며, 특정 모듈 이름이 포함되면 해당 모듈의 모든 서브모듈이 동일한 장치로 전송됩니다. 기본값은 None, 이며, 이는 모델이 CPU에 로드됨을 의미합니다.

    예:

pretrained model configuration에서 사전 학습된 PyTorch 모델을 초기화합니다.

모델은 기본적으로 평가 모드(model.eval())로 설정되며, dropout 모듈은 비활성화됩니다. 모델을 학습하려면 model.train()을 사용하여 다시 학습 모드로 설정해야 합니다.

> 비공개 또는 게이트된 모델을 사용하려면 hf > auth login으로 로그인하세요. 또한 방화벽이 있는 환경에서 이 방법을 사용하려면 특수 > “오프라인 모드”를 활성화할 수도 있습니다.

예:

from diffusers import UNet2DConditionModel

unet = UNet2DConditionModel.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", subfolder="unet")

아래와 같은 오류 메시지가 표시되면 다운스트림 작업을 위해 가중치를 미세 조정해야 합니다:

Some weights of UNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
- conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.

get_memory_footprint

< >

( return_buffers = True )

매개변수

  • return_buffers (bool, 선택 사항, 기본값 True) — 메모리 사용량 계산 시 버퍼 텐서의 크기를 반환할지 여부입니다. 버퍼는 그래디언트가 필요하지 않고 파라미터로 등록되지 않은 텐서를 의미합니다. 예를 들어, 배치 정규화 레이어의 mean과 std가 해당됩니다. 자세한 내용은 https://discuss.pytorch.org/t/what-pytorch-means-by-buffers/120266/2를 참고하세요.

모델의 메모리 사용량을 가져옵니다. 현재 모델의 메모리 사용량을 바이트 단위로 반환합니다. 현재 모델의 메모리 사용량을 벤치마크하고 테스트를 설계하는 데 유용합니다. PyTorch 토론에서 영감을 받은 솔루션: https://discuss.pytorch.org/t/gpu-memory-that-model-uses/56822/2

num_parameters

< >

( only_trainable: bool = Falseexclude_embeddings: bool = False ) → int

매개변수

  • only_trainable (bool, 선택 사항, 기본값 False) — 학습 가능한 매개변수의 수만 반환할지 여부입니다.
  • exclude_embeddings (bool, 선택 사항, 기본값 False) — 임베딩이 아닌 매개변수의 개수만 반환할지 여부를 지정합니다.

반환값

int

파라미터의 수.

모듈의 (학습 가능 또는 임베딩이 아닌) 매개변수 수를 가져옵니다.

예:

from diffusers import UNet2DConditionModel

model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
unet = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet")
unet.num_parameters(only_trainable=True)
859520964

reset_attention_backend

< >

( )

모델의 attention backends를 초기화합니다. 이후 forward 호출 시 환경 변수가 설정되어 있으면 해당 기본값을, 그렇지 않으면 torch 네이티브 scaled dot product attention을 사용합니다.

save_pretrained

< >

( save_directory: str | os.PathLikeis_main_process: bool = Truesave_function: typing.Optional[typing.Callable] = Nonesafe_serialization: bool = Truevariant: str | None = Nonemax_shard_size: int | str = '10GB'push_to_hub: bool = Falseuse_flashpack: bool = False**kwargs )

매개변수

  • save_directory (str 또는 os.PathLike) — 모델과 해당 구성 파일을 저장할 디렉터리입니다. 존재하지 않으면 생성됩니다.
  • is_main_process (bool, 선택 사항, 기본값 True) — 이 함수를 호출하는 프로세스가 메인 프로세스인지 여부입니다. 분산 학습 중에 모든 프로세스에서 이 함수를 호출해야 하는 경우 유용합니다. 이 경우 레이스 조건을 피하기 위해 메인 프로세스에서만 is_main_process=True로 설정하세요.
  • save_function (Callable) — 상태 사전(state dictionary)을 저장하는 데 사용할 함수입니다. 분산 학습(distributed training) 중에 torch.save를 다른 방법으로 대체해야 할 때 유용합니다. 환경 변수 DIFFUSERS_SAVE_MODE로 설정할 수 있습니다.
  • safe_serialization (bool, 선택 사항, 기본값 True) — safetensors를 사용하여 모델을 저장할지, 아니면 pickle을 사용한 전통적인 PyTorch 방식으로 저장할지를 결정합니다.
  • variant (str, 선택 사항) — 지정된 경우, 가중치는 pytorch_model.<variant>.bin 형식으로 저장됩니다.
  • max_shard_size (int 또는 str, 기본값 "10GB") — 샤딩되기 전 체크포인트의 최대 크기입니다. 샤딩된 각 체크포인트의 크기는 이 크기보다 작아집니다. 문자열로 표현할 경우, 숫자 뒤에 단위(예: "5GB")가 따라와야 합니다. 정수로 표현할 경우, 단위는 바이트입니다. 2024년 10월부터 특정 기간이 지난 후 이 한도가 낮아질 수 있으며, 이는 사용자가 diffusers의 최신 버전으로 업그레이드할 수 있도록 하기 위한 것입니다. 이는 Hugging Face 생태계의 다른 라이브러리(예: transformers, accelerate)에서 이 인수의 공통 기본 크기를 설정하기 위한 것입니다.
  • push_to_hub (bool, 선택 사항, 기본값 False) — 모델을 저장한 후 Hugging Face Hub에 푸시할지 여부입니다. repo_id를 사용하여 푸시할 저장소를 지정할 수 있으며, 지정하지 않으면 네임스페이스 내 save_directory의 이름이 기본값으로 사용됩니다.
  • kwargs (dict[str, Any], 선택) — push_to_hub() 메서드에 함께 전달되는 추가 키워드 인자입니다.

모델과 해당 구성 파일을 디렉토리에 저장하여 from_pretrained() 클래스 메서드를 사용해 다시 로드할 수 있도록 합니다.

set_attention_backend

< >

( backend: str )

매개변수

  • backend (str) — 설정할 백엔드의 이름입니다. AttentionBackendName에 정의된 사용 가능한 백엔드 중 하나여야 합니다. 사용 가능한 백엔드는 diffusers.attention_dispatch.AttentionBackendName에서 확인할 수 있습니다. 기본값은 torch 네이티브 scaled dot product attention을 백엔드로 사용합니다.

모델의 attention 백엔드를 설정합니다.

set_use_npu_flash_attention

< >

( valid: bool )

npu flash attention 스위치를 설정합니다.

(으)로

( *args**kwargs )

점으로 구분된 경로(예: torch.float32)에 대한 mock 값: 속성 접근 체인, 호출은 pass-through 데코레이터처럼 동작하며, repr은 해당 점으로 구분된 경로입니다. 이를 베이스 클래스로 사용하면 plain-type 베이스로 대체됩니다(PEP 560 __mro_entries__). 따라서 실제 서브클래스는 일반적인 메타클래스를 유지하고, inspect.signature는 mock의 __init__가 아닌 실제 __init__를 읽습니다.

PushToHubMixin

class diffusers.utils.PushToHubMixin

< >

( )

Hugging Face Hub에 모델, 스케줄러 또는 파이프라인을 푸시하기 위한 Mixin입니다.

push_to_hub

< >

( repo_id: strcommit_message: str | None = Noneprivate: bool | None = Nonetoken: str | None = Nonecreate_pr: bool = Falsesafe_serialization: bool = Truevariant: str | None = Nonesubfolder: str | None = None )

매개변수

  • repo_id (str) — 모델, 스케줄러 또는 파이프라인 파일을 푸시할 저장소의 이름입니다. 조직에 푸시할 경우 조직 이름을 포함해야 합니다. repo_id는 로컬 디렉토리의 경로일 수도 있습니다.
  • commit_message (str, 선택 사항) — 푸시할 때 커밋할 메시지. 기본값은 "Upload {object}"입니다.
  • private (bool, 선택 사항) — 리포지토리를 비공개로 만들지 여부를 지정합니다. None(기본값)인 경우, 조직의 기본 설정이 비공개가 아닌 한 리포지토리는 공개됩니다. 이미 리포지토리가 존재하면 이 값은 무시됩니다.
  • token (str, 선택 사항) — 원격 파일에 대한 HTTP bearer 인증으로 사용할 토큰입니다. hf auth login 실행 시 생성된 토큰(~/.huggingface에 저장됨)입니다.
  • create_pr (bool, 선택 사항, 기본값 False) — 업로드된 파일로 PR을 생성할지 아니면 직접 커밋할지 여부.
  • safe_serialization (bool, 선택 사항, 기본값 True) — 모델 가중치를 safetensors 형식으로 변환할지 여부입니다.
  • variant (str, 선택 사항) — 지정된 경우, 가중치는 pytorch_model.<variant>.bin 형식으로 저장됩니다.

모델, 스케줄러 또는 파이프라인 파일을 🤗 Hugging Face Hub에 업로드합니다.

예:

from diffusers import UNet2DConditionModel

unet = UNet2DConditionModel.from_pretrained("stabilityai/stable-diffusion-2", subfolder="unet")

# Push the `unet` to your namespace with the name "my-finetuned-unet".
unet.push_to_hub("my-finetuned-unet")

# Push the `unet` to an organization with the name "my-finetuned-unet".
unet.push_to_hub("your-org/my-finetuned-unet")
Update on GitHub