# Metal Performance Shaders (MPS)

> [!TIP]
> Pipelines with a  badge indicate a model can take advantage of the MPS backend on Apple silicon devices for faster inference. Feel free to open a [Pull Request](https://github.com/huggingface/diffusers/compare) to add this badge to pipelines that are missing it.

🤗 Diffusers는 MacOS 기기의 GPU를 활용하기 위해 Metal 프레임워크를 사용하는 PyTorch [`mps`](https://pytorch.org/docs/stable/notes/mps.html) 장치를 통해 Apple silicon(M1/M2 칩)과 호환됩니다. 다음이 필요합니다:

- Apple silicon (M1/M2) 하드웨어가 탑재된 macOS 컴퓨터
- macOS 12.6 이상 (13.0 이상 권장)
- arm64 버전의 Python
- [PyTorch 2.0](https://pytorch.org/get-started/locally/) (권장) 또는 1.13(`mps`의 최소 지원 버전)

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

```python
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
```

> [!WARNING]
> PyTorch [mps](https://pytorch.org/docs/stable/notes/mps.html) 백엔드는 `2**32`를 초과하는 NDArray 크기를 지원하지 않습니다. 이 문제를 만나셨다면 조사할 수 있도록 [Issue](https://github.com/huggingface/diffusers/issues/new/choose)를 열어 주세요.

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

```diff
  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()](/docs/diffusers/v0.43.0/ko/api/pipelines/overview#diffusers.DiffusionPipeline.enable_attention_slicing) 함수를 호출하세요:

```py
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)을 시도해 보세요.

