Diffusers documentation

Metal Performance Shaders (MPS)

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Metal Performance Shaders (MPS)

MPS 배지가 있는 Pipelines는 Apple silicon 기기에서 MPS 백엔드를 활용하여 추론 속도를 높일 수 있는 모델임을 나타냅니다. 배지가 누락된 pipelines에 이 배지를 추가하기 위해 Pull Request를 열어 주세요.

🤗 Diffusers는 MacOS 기기의 GPU를 활용하기 위해 Metal 프레임워크를 사용하는 PyTorch mps 디바이스를 통해 Apple silicon(M1/M2 칩)과 호환됩니다. 다음이 필요합니다:

  • Apple silicon (M1/M2) 하드웨어가 탑재된 macOS 컴퓨터
  • macOS 12.6 이상 (13.0 이상 권장)
  • arm64 버전의 Python
  • PyTorch 2.0 (권장) 또는 1.13(mps의 최소 지원 버전)

mps 백엔드는 PyTorch의 .to() 인터페이스를 사용하여 Stable Diffusion 파이프라인을 M1 또는 M2 장치로 이동합니다:

from diffusers import DiffusionPipeline

pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
pipe = pipe.to("mps")

# Recommended if your computer has < 64 GB of RAM
pipe.enable_attention_slicing()

prompt = "a photo of an astronaut riding a horse on mars"
image = pipe(prompt).images[0]
image

PyTorch mps 백엔드는 2**32를 초과하는 NDArray 크기를 지원하지 않습니다. 이 문제를 만나셨다면 조사할 수 있도록 Issue를 열어 주세요.

PyTorch 1.13를 사용하는 경우, 파이프라인을 한 번 더 통과시켜 “prime”해야 합니다. 이는 첫 번째 추론 패스가 이후 패스와 약간 다른 결과를 생성하는 문제를 해결하기 위한 임시 조치입니다. 이 패스는 한 번만 수행하면 되며, 추론 단계 한 번만 거치면 결과를 폐기할 수 있습니다.

  from diffusers import DiffusionPipeline

  pipe = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5").to("mps")
  pipe.enable_attention_slicing()

  prompt = "a photo of an astronaut riding a horse on mars"
  # First-time "warmup" pass if PyTorch version is 1.13
+ _ = pipe(prompt, num_inference_steps=1)

  # Results match those from the CPU device after the warmup pass.
  image = pipe(prompt).images[0]

문제 해결

이 섹션에서는 mps 백엔드를 사용할 때 발생하는 일반적인 문제와 해결 방법을 나열합니다.

Attention 슬라이싱

M1/M2의 성능은 메모리 압력에 매우 민감합니다. 이러한 상황이 발생하면 시스템은 필요할 때 자동으로 스왑을 수행하며, 이로 인해 성능이 크게 저하됩니다.

이러한 문제를 방지하기 위해 추론 중 메모리 부담을 줄이고 스왑을 막기 위해 attention slicing을 사용하는 것을 권장합니다. 컴퓨터의 시스템 RAM이 64GB 미만이거나 512×512 픽셀보다 큰 비표준 해상도로 이미지를 생성하는 경우 특히 중요합니다. 파이프라인에서 enable_attention_slicing() 함수를 호출하세요:

from diffusers import DiffusionPipeline
import torch

pipeline = DiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", dtype=torch.float16, variant="fp16", use_safetensors=True).to("mps")
pipeline.enable_attention_slicing()

Attention slicing은 비용이 높은 attention 연산을 한 번에 수행하는 대신 여러 단계로 나누어 수행합니다. 범용 메모리가 없는 컴퓨터에서는 일반적으로 성능이 약 20% 향상되지만, 64GB 이상의 RAM이 없는 대부분의 Apple silicon 컴퓨터에서는 더 나은 성능을 관찰했습니다.

배치 추론

Generating multiple prompts in a batch를 사용하면 충돌이 발생하거나 안정적으로 작동하지 않을 수 있습니다. 이 경우, 배치 처리 대신 반복(iteration)을 시도해 보세요.

Update on GitHub