оригинал статьи здесь: https://zenn.dev/ktakayama/articles/6c627e0956f32c
Генератор AI изображений Stable Diffusion теперь с открытым исходным кодом. Я хочу запустить его на локальной машине, но у меня есть только MacBook Pro, что не так просто.
https://github.com/CompVis/stable-diffusion
Следующая тема очень полезна!
https://github.com/CompVis/stable-diffusion/issues/25
Скорость
Вот спецификация моего MacBook Pro 14.
- Чип Apple M1 Pro
- 8-ядерный процессор с 6 производительными ядрами и 2 эффективными ядрами
- 14-ядерный графический процессор
- 16-ядерный нейронный движок
- 32 ГБ памяти
Для генерации изображений требуется около 15-20 ГБ памяти. 6 изображений могут быть сгенерированы примерно за 5 минут.
Получить модель
Зарегистрируйтесь и клонируйте этот репозиторий.
https://huggingface.co/CompVis/stable-diffusion-v-1-4-original
Получить исходный код
Получить исходный код в ветке apple-silicon-mps-support этого репозитория.
https://github.com/magnusviri/stable-diffusion/tree/apple-silicon-mps-support
Установка
Установите conda и rust с помощью homebrew.
brew install miniconda rust
Настройте среду оболочки для conda. Я использую zsh.
conda init zsh
Когда я запускаю conda env create, я получаю ошибку.
$ conda env create -f environment-mac.yaml
Collecting package metadata (repodata.json): done
Solving environment: failed
ResolvePackageNotFound:
- python=3.8.5
Отредактируйте environment-mac.yaml, чтобы он соответствовал вашему окружению. В частности, измените номер версии в соответствии с вашим окружением. Например.
diff --git a/environment-mac.yaml b/environment-mac.yaml
index d923d56..c8a0a8e 100644
--- a/environment-mac.yaml
+++ b/environment-mac.yaml
@@ -3,14 +3,14 @@ channels:
- pytorch
- defaults
dependencies:
- - python=3.8.5
- - pip=20.3
+ - python=3.9.12
+ - pip=21.2.4
- pytorch=1.12.1
- torchvision=0.13.1
- numpy=1.19.2
- pip:
- albumentations==0.4.3
- - opencv-python==4.1.2.30
+ - opencv-python>=4.1.2.30
- pudb==2019.2
- imageio==2.9.0
- imageio-ffmpeg==0.4.2
активировать и связать с моделью.
conda activate ldm
mkdir -p models/ldm/stable-diffusion-v1
ln -s /path/to/stable-diffusion-v-1-4-original/sd-v1-4.ckpt models/ldm/stable-diffusion-v1/model.ckpt
Выполните генерацию изображения!
При выполнении txt2image я получаю ошибку, связанную с PyTorch.
$ python scripts/txt2img.py --prompt "a photograph of an astronaut riding a horse" --plms
〜 skip 〜
NotImplementedError: The operator 'aten::index.Tensor' is not current implemented for the MPS device. If you want this op to be added in priority during the prototype phase of this feature, please comment on https://github.com/pytorch/pytorch/issues/77764. As a temporary fix, you can set the environment variable `PYTORCH_ENABLE_MPS_FALLBACK=1` to use the CPU as a fallback for this op. WARNING: this will be slower than running natively on MPS.
Установите ночную версию.
conda install pytorch torchvision torchaudio -c pytorch-nightly
По-прежнему возникает ошибка.
$ python scripts/txt2img.py --prompt "a photograph of an astronaut riding a horse" --plms
return torch.layer_norm(input, normalized_shape, weight, bias, eps, torch.backends.cudnn.enabled)
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.
Исправьте эту ошибку.
https://github.com/CompVis/stable-diffusion/issues/25#issuecomment-1221667017
vi /opt/homebrew/Caskroom/miniconda/base/envs/ldm/lib/python3.9/site-packages/torch/nn/functional.py
--- functional.py_ 2022-08-23 17:07:29.000000000 +0900
+++ functional.py 2022-08-23 17:07:31.000000000 +0900
@@ -2506,9 +2506,9 @@ def layer_norm(
"""
if has_torch_function_variadic(input, weight, bias):
return handle_torch_function(
- layer_norm, (input, weight, bias), input, normalized_shape, weight=weight, bias=bias, eps=eps
+ layer_norm, (input.contiguous(), weight, bias), input, normalized_shape, weight=weight, bias=bias, eps=eps
)
- return torch.layer_norm(input, normalized_shape, weight, bias, eps, torch.backends.cudnn.enabled)
+ return torch.layer_norm(input.contiguous(), normalized_shape, weight, bias, eps, torch.backends.cudnn.enabled)
Все ОК! Отлично!!!
$ python scripts/txt2img.py --prompt "a photograph of an astronaut riding a horse" --plms
...
Your samples are ready and waiting for you here:
outputs/txt2img-samples
Enjoy.