SDXL-Turboやーる（Windows 11、CPU）

# はじめに
[がちもとさんアドベントカレンダー](https://qiita.com/advent-calendar/2023/gachimoto3)23日目の記事です。
今日は、SDXL-Turboを用いてテキストから画像生成します。

https://huggingface.co/stabilityai/sdxl-turbo

# 開発環境
- Windows 11 PC
- Python 3.11

# 導入

## GPUの場合

1．sdxl-turboをクローンします。

~~~
git lfs install
git clone https://huggingface.co/stabilityai/sdxl-turbo
~~~

2．ライブラリのインストール

~~~
pip install diffusers transformers accelerate --upgrade
~~~

<!--
Successfully installed MarkupSafe-2.1.3 accelerate-0.25.0 diffusers-0.24.0 filelock-3.13.1 fsspec-2023.12.1 huggingface-hub-0.19.4 importlib-metadata-7.0.0 jinja2-3.1.2 mpmath-1.3.0 psutil-5.9.6 safetensors-0.4.1 sympy-1.12 tokenizers-0.15.0 torch-2.1.1 transformers-4.35.2 zipp-3.17.0
-->

3．pytorchのインストール

https://pytorch.org/

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/ed2161b3-e201-0e3c-4a98-f8b5847b686f.png)

~~~
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
~~~

<!--
Successfully installed torch-2.1.1+cu118 torchaudio-2.1.1+cu118 torchvision-0.16.1+cu118
-->

4．プログラムの作成

~~~text2image.py
from diffusers import AutoPipelineForText2Image
import torch

pipe = AutoPipelineForText2Image.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16")
pipe.to("cuda")

prompt = "A cinematic shot of a baby racoon wearing an intricate italian priest robe."

image = pipe(prompt=prompt, num_inference_steps=1, guidance_scale=0.0).images[0]
print(image)
~~~

5．python text2image.pyで実行

torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 14.00 MiB. GPU 0 has a total capacty of 6.00 GiB of which 0 bytes is free. Of the allocated memory 5.18 GiB is allocated by PyTorch, and 175.59 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting max_split_size_mb to avoid fragmentation.  See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

GPUが足りませんでした！

## CPUの場合

https://huggingface.co/spaces/Manjushri/SDXL-Turbo-CPU

1．ライブラリをインストール

~~~
pip install gradio
pip install modin[all]
pip install pydantic --upgrade
~~~

<!--
Successfully installed aiofiles-23.2.1 altair-5.2.0 contourpy-1.2.0 cycler-0.12.1 fastapi-0.104.1 ffmpy-0.3.1 fonttools-4.46.0 gradio-4.8.0 gradio-client-0.7.1 importlib-resources-6.1.1 jsonschema-4.20.0 jsonschema-specifications-2023.11.2 kiwisolver-1.4.5 markdown-it-py-3.0.0 matplotlib-3.8.2 mdurl-0.1.2 orjson-3.9.10 pydub-0.25.1 pygments-2.17.2 pyparsing-3.1.1 python-multipart-0.0.6 referencing-0.31.1 rich-13.7.0 rpds-py-0.13.2 semantic-version-2.10.0 shellingham-1.5.4 starlette-0.27.0 tomlkit-0.12.0 toolz-0.12.0 typer-0.9.0 uvicorn-0.24.0.post1 websockets-11.0.3
-->

<!--
Successfully installed pydantic-2.5.2 pydantic-core-2.14.5
-->

2．プログラムを作成

~~~text2image.py
import gradio as gr
import torch
import modin.pandas as pd
import numpy as np
from diffusers import DiffusionPipeline 

device = "cuda" if torch.cuda.is_available() else "cpu"
device = "cpu"
# if torch.cuda.is_available():
#     torch.cuda.max_memory_allocated(device=device)
#     torch.cuda.empty_cache()
#     pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
#     pipe.enable_xformers_memory_efficient_attention()
#     pipe = pipe.to(device)
#     torch.cuda.empty_cache()
# else: 
pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
pipe = pipe.to(device)
    
def genie (prompt, steps, seed):
    generator = np.random.seed(0) if seed == 0 else torch.manual_seed(seed)
    int_image = pipe(prompt=prompt, generator=generator, num_inference_steps=steps, guidance_scale=0.0).images[0]
    return int_image
    
gr.Interface(fn=genie, inputs=[gr.Textbox(label='What you want the AI to generate. 77 Token Limit.'), 
    gr.Slider(1, maximum=5, value=2, step=1, label='Number of Iterations'), 
    gr.Slider(minimum=0, step=1, maximum=999999999999999999, randomize=True),
    ],
    outputs='image', 
    title="Stable Diffusion Turbo CPU or GPU", 
    description="SDXL Turbo CPU or GPU. Currently running on CPU. <br><br><b>WARNING: This model is capable of producing NSFW (Softcore) images.</b>", 
    article = "If You Enjoyed this Demo and would like to Donate, you can send to any of these Wallets. <br>BTC: bc1qzdm9j73mj8ucwwtsjx4x4ylyfvr6kp7svzjn84 <br>3LWRoKYx6bCLnUrKEdnPo3FCSPQUSFDjFP <br>DOGE: DK6LRc4gfefdCTRk9xPD239N31jh9GjKez <br>SHIB (BEP20): 0xbE8f2f3B71DFEB84E5F7E3aae1909d60658aB891 <br>PayPal: https://www.paypal.me/ManjushriBodhisattva <br>ETH: 0xbE8f2f3B71DFEB84E5F7E3aae1909d60658aB891 <br>Code Monkey: <a href=\"https://huggingface.co/Manjushri\">Manjushri</a>").launch(debug=True, max_threads=80)
~~~

3．python text2image.pyで実行

4．http://127.0.0.1:7860 を開く

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/b5cd35bd-a0ae-3dad-dbc6-15c2ee0414b3.png)

<!--
1分くらいでできました

 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/8e3a1e17-1c5c-3f06-8142-6e3e8dacef70.png)

32秒くらいでできました
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/eb2d42e1-ec48-6203-49bd-647f72268ef5.png)

1分くらいでできました
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/fb2e15b0-78b9-55e3-3d7c-75bb3397d380.png)
-->

5．プロンプトを入力しSubmit

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/7ef3e59e-531f-abd3-e43a-0f3c3dd22c01.png)

1分くらいで生成されました！
お疲れさまでした。