EC2 に stable-diffusion-auto1111 を立ち上げる

September 2, 2024

Intro

EC2 で Stable diffusion を実現するためのメモです。 EC2 自体の構築やセキュリティグループ、VPC などの設定は割愛しています。

  • GPU インスタンスを使用
  • stable-diffusion-webui を使用
  • python 3.10.6 を使用
  • nginx でリバースプロキシ

環境

イメージ:amazon linux 2023

インスタンスタイプ:g4dn.xlarge

GPU 環境構築

dnf install kernel-devel-$(uname -r) kernel-headers-$(uname -r) kernel-modules-extra-$(uname -r)
dnf config-manager --add-repo https://developer.download.nvidia.com/compute/cuda/repos/amzn2023/x86_64/cuda-amzn2023.repo
dnf module install nvidia-driver:latest-dkms
dnf install cuda-toolkit
dnf install nvidia-gds

stable-diffusion-webui の構築

インストール

git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui
cd stable-diffusion-webui
ln -s . stable-diffusion-webui
# 起動スクリプト修正(shareオプションは使わない)
vim webui-user.sh
export COMMANDLINE_ARGS="--xformers --enable-insecure-extension-access"

python 環境構築

python 3.10.6 のインストール

dnf install wget git python3 gperftools-libs libglvnd-glx
# pyenvインストール
curl https://pyenv.run | bash
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
source ~/.bashrc
# pythonのビルドに必要なライブラリをインストールする
yum groupinstall "Development Tools" -y
yum install zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel openssl-devel xz xz-devel libffi-devel -y
# 3.10.6のバージョンをインストールする
pyenv install 3.10.6
pyenv local 3.10.6

リバプロ

  • nginx の設定

sudo dnf install nginx

sudo vi /etc/nginx/conf.d/stable-diffusion.conf

server {
    listen 80;
    server_name your-domain.com;
    location / {
        proxy_pass http://localhost:7860;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        # WebSocket設定
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 86400;
    }
}
sudo nginx -t
sudo systemctl restart nginx

service の起動

sudo vim /etc/systemd/system/stable-diffusion-webui.service
[Unit]
Description=Stable Diffusion WebUI
After=network.target
[Service]
Type=simple
User=ec2-user
WorkingDirectory=/home/ec2-user/stable-diffusion-webui/v1.9.4
ExecStart=/bin/bash /home/ec2-user/stable-diffusion-webui/v1.9.4/webui.sh
Restart=always
RestartSec=15
[Install]
WantedBy=multi-user.target
Nifty tech tag lists from Wouter Beeftink