Skip to main content

HuggingFace Diffusers로 Apple M1 Mac에서 Stable Diffusion 실행하기

이 글에서는 Hugging Face Diffusers를 사용해 M1 Mac에서 Stable Diffusion을 실행하는 방법을 살펴보고, 장점과 주의할 점을 함께 정리합니다. 이 글은 AI 번역본입니다. 오역 가능성이 있는 부분은 댓글로 알려주세요.
Created on September 15|Last edited on September 15
Hugging Face Diffusers 손쉽게 이미지를 생성해 볼 수 있는 진입점을 제공하며, 이제 Mac M1은 물론 GPU에서도 작동합니다!
이 글에서는 실행의 이점을 살펴봅니다 Stable Diffusion Mac M1에서 허깅페이스 Diffusers를 충분히 활용하는 방법을 함께 살펴보겠습니다.
다음 내용을 다룹니다:

목차



시작해봅시다.

Mac M1에서 Stable Diffusion 텍스트 투 이미지

아래 단계는 2020년형 M1 Mac(메모리 16GB, 8코어)에서 정상 동작했습니다. 제 머신에서는 추론 한 단계가 약 ~4.2초 걸리며, 예를 들어 512×512 이미지 1장을 50단계로 생성하면 약 3.5분이 소요됩니다. 간단한 예시:

prompt
image_0
image_1
image_2
image_3
image_4
image_5
image_6
image_7
guidance_scale
num_inference_steps
2
Stable Diffusion 생성 예시 몇 가지 여기 Colab로 생성됨

내 시스템 및 Python 버전

여기에서 사용한 관련 버전과 시스템:
  • macOS 12.4
  • Python 3.8.8
  • torch 1.13.0.dev20220830
  • diffusers 0.2.4
  • transformers 4.21.2

설치 단계

1. macOS 버전

Mac이 macOS 12.3 이상에서 실행 중인지 확인하세요. 아니라면 시스템 업데이트를 실행하는 것을 권장합니다.

2. PyTorch 나이트리 빌드 설치

오늘 기준(2022년 8월 31일) 최신 PyTorch 나이트리 릴리지가 해결하는 문제 aten::index.Tensor Mac M1에서 실행할 때 오류:
NotImplementedError: The operator 'aten::index.Tensor' is not current implemented for the MPS device
conda를 사용하여 PyTorch 나이트리 설치하기:
conda install pytorch torchvision torchaudio -c pytorch-nightly
pip으로 PyTorch 나이트리 설치하기:
pip3 install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu

3. Fastcore를 사용해 Diffusers의 BasicTransformerBlock 패치하기

M1 Mac을 지원하려면 어텐션 계산에도 또 다른 수정이 필요합니다. 이를 위해 우리는 다음을 사용할 것입니다 patch 훌륭한 …의 함수 fastcore 라이브러리 (정말 놀라울 정도로 강력합니다—꼭 한 번 확인해 보시길 강력히 추천합니다.)
패치하기 BasicTransformerBlock 그렇지 않으면 발생하는 이 오류를 수정합니다:
RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead
아무도 그렇게 되길 원하지 않습니다.
from diffusers.models.attention import BasicTransformerBlock

from fastcore.basics import patch

@patch
def forward(self:BasicTransformerBlock, x, context=None):
# x = self.attn1(self.norm1(x)) + x
x = self.attn1(self.norm1(x.contiguous())) + x # <--- added x.contiguous()
x = self.attn2(self.norm2(x), context=context) + x
x = self.ff(self.norm3(x)) + x
return x
GitHub의 @fragmede님께 감사드립니다 여기에서 x.contiguous 수정 사항을 확인했습니다

4. StableDiffusionPipeline 설정

설정할 때 StableDiffusionPipeline 주의해야 할 몇 가지가 있습니다:
  • 사용하지 마십시오 revision="fp16"
  • 사용하지 마십시오 torch_dtype=torch.float16
  • 파이프라인 디바이스를 다음으로 설정 "mps"
from diffusers import StableDiffusionPipeline

DEVICE='mps'

pipe = StableDiffusionPipeline.from_pretrained(
"CompVis/stable-diffusion-v1-4",
use_auth_token=True
).to(DEVICE)

5. 추론 실행하기!

이제 M1 Mac에서 이미지를 생성할 준비가 모두 되었길 바랍니다!
image = pipe(prompt="a happy dog working on a macbook air, sythwave")["sample"][0]

기타 참고사항

저에게는 이 방법이 잘 작동합니다. 다만 코드베이스가 매우 빠르게 변하고 있어서, 새로운 버그가 생기거나 여기 소개한 일부 수정이 불필요해질 수도 있습니다!
또한 제 M1 Mac에서 이 작업을 실행하는 데 PYTORCH_ENABLE_MPS_FALLBACK 환경 변수를 설정할 필요가 없었습니다.

이 보고서도 마음에 드실 거예요



이 글은 AI로 번역되었습니다. 오역이 의심되면 댓글에 알려주세요. 원문 보고서는 여기에서 확인하실 수 있습니다: 원문 보고서 보기
Sebastian Topalian
Sebastian Topalian •  *
Hey Morgan, Thank you for the article - I had success after struggling for some time, but then I created a new environment with python 3.8.8, diffusers 0.2.4, transformers 4.21.2 and then I installed PyTorch nightly as described and followed the remaining steps. Before I was running: torch = 1.12.1, diffuser 0.4.2, transformers 4.23.1 and python 3.10.4 :) Thx!
1 reply
Dennis Faucher
Dennis Faucher •  
You should add one more line at the end: image.save("diffusion.png")
Reply
Dennis Faucher
Dennis Faucher •  *
Having an issue with device='mps'. Getting this error from the StableDiffusionPipeline command "RuntimeError: Expected one of cpu, cuda, xpu, mkldnn, opengl, opencl, ideep, hip, ve, ort, mlc, xla, lazy, vulkan, meta, hpu device type at start of device string: mps" I'll hack at it. Fixed it $ pip install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu (Install RUST) $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh $ pip install transformers $ pip install diffusers
Reply
List<Maybe<File<(table)>>>