本篇文章聊聊,如何快速上手 Stable Diffusion XL Turbo 模型的文生圖和圖生圖實戰(zhàn)。
寫在前面
分享一篇去年 11 月測試過模型,為月末分享的文章做一些技術(shù)鋪墊,以及使用新的環(huán)境進行完整復(fù)現(xiàn)。
本篇文章相關(guān)的代碼保存在 soulteary/docker-stable-diffusion-xl-turbo,有需要可以自取,歡迎“一鍵三連”。
23 年 11 月末,Stability 將 Stable Diffusion 在 2023 年的速度極限一錘定音,在 SDXL Turbo 上實現(xiàn)了實時生成。
“文生圖”戰(zhàn)場上,自去年下半年開始,“Stable Diffusion 模型” 開始狂飆,不斷產(chǎn)生效率的質(zhì)變:生成圖片的等待時間變的越來越少,生成圖片的尺寸和質(zhì)量越來越好,并且開始往移動端設(shè)備上擴展。
- 2023 年 5 月,Nvidia 發(fā)布了 “Key-Locked Lora” 方案,將 Lora 模型訓練縮減到 4 分鐘,每個模型只需要 100KB 大小,并在 SIGGRAPH 2023 發(fā)布,可惜代碼尚未發(fā)布。論文:《Key-Locked Rank One Editing for Text-to-Image Personalization》。
- 2023 年 6 月,Google 一篇 “Speed is all you need”,拉開了新的競爭序幕,在搭載 Android 操作系統(tǒng)的三星手機上,實現(xiàn)了 12 秒生成圖片。論文:《Speed Is All You Need: On-Device Acceleration of Large Diffusion Models via GPU-Aware Optimizations》。
- 2023 年 7 月,官方推出了 SDXL 1.0,將競爭維度提升了一檔,相比較 SD 模型,尤其是市面上流行的 SD 1.5 而言,質(zhì)量有大比例提升。論文:《SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis》
- 2023 年 10 月,清華學子推出了 LCM,將生成圖片推理計算降低到只需要幾步,Stable 來到了準實時生成階段。論文:《Latent Consistency Models: Synthesizing High-Resolution Images with Few-Step Inference》。
- 2023 年 11 月,官方推出了年度最強方案,并發(fā)布了 Stable Diffusion XL Turbo,性能比 LCM 進一步提升數(shù)倍,實現(xiàn)了實時出圖。論文:《Adversarial Diffusion Distillation》。
- 2023 年 11 月末,Google 推出了移動端性能更強的推理方案,在 iPhone 15 Pro 上完成了 0.2 秒出圖。論文:《MobileDiffusion: Subsecond Text-to-Image Generation on Mobile Devices》。
雖然,到現(xiàn)在為止,社區(qū)還有許多工具停留在 SD 1.5,但是在生成效率(成本)和生成質(zhì)量的優(yōu)勢下,未來可以預(yù)見的是,會有越來越多的模型創(chuàng)作者基于 SDXL Turbo 來創(chuàng)作風格模型。
一起撿起這張船票,揚帆起航。
準備環(huán)境
我個人比較傾向使用 Docker 作為運行環(huán)境,在投入很少額外資源的情況下,能夠快速獲得純凈、可復(fù)現(xiàn)的一致性非常棒的環(huán)境。
如果你選擇 Docker 路線,不論你的設(shè)備是否有顯卡,都可以根據(jù)自己的操作系統(tǒng)喜好,參考這兩篇來完成基礎(chǔ)環(huán)境的配置《基于 Docker 的深度學習環(huán)境:Windows 篇》、《基于 Docker 的深度學習環(huán)境:入門篇》。當然,使用 Docker 之后,你還可以做很多事情,比如:之前幾十篇有關(guān) Docker 的實踐,在此就不贅述啦。
除此之外,為了高效運行模型,我推薦使用 Nvidia 官方的容器鏡像(nvcr.io/nvidia/pytorch:23.12-py3),以及 HuggingFace 出品的 Diffusers 工具包。
我們可以基于上面的內(nèi)容,快速折騰一個干凈、高效的基礎(chǔ)運行環(huán)境:
FROM nvcr.io/nvidia/pytorch:23.12-py3
RUN pip install transformers==4.36.2 gradio==4.14.0 diffusers==0.25.0 accelerate==0.26.1
WORKDIR /app
你也可以選擇使用下面的配置,在安裝軟件包的時候效率更高:
FROM nvcr.io/nvidia/pytorch:23.12-py3
RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
RUN pip install transformers==4.36.2 gradio==4.14.0 diffusers==0.25.0 accelerate==0.26.1
WORKDIR /app
在本地創(chuàng)建一個名為 docker
的目錄,將上面的代碼保存到文件夾內(nèi),文件名稱為 Dockerfile
,然后使用下面的命令完成鏡像的構(gòu)建,基礎(chǔ)工作就準備好了一半:
docker build -t soulteary/sdxl-turbo-runtime -f docker/Dockerfile .
當然,如果你和我一樣,喜歡“偷懶”,可以用文章開頭提到的示例項目中的文件直接開搞:
# 下載項目代碼
git clone https://github.com/soulteary/docker-stable-diffusion-xl-turbo.git
# 切換工作目錄
cd docker-stable-diffusion-xl-turbo
# 構(gòu)建基礎(chǔ)環(huán)境鏡像
docker build -t soulteary/sdxl-turbo-runtime -f docker/Dockerfile .
# 如果你希望速度快一些,可以用這條命令替代上面的命令
docker build -t soulteary/sdxl-turbo-runtime -f docker/Dockerfile.cn .
等到鏡像構(gòu)建完畢后,我們開始準備模型文件。
下載模型
我們來完成鏡像準備之外的 50% 的準備工作,下載模型。不論你從哪里獲取模型,建議你在得到模型后進行文件 Hash 驗證:
# shasum stabilityai/sdxl-turbo/sd_xl_turbo_1.0.safetensors
b60babf652bedb03098c03b889293de84a8294f2 stabilityai/sdxl-turbo/sd_xl_turbo_1.0.safetensors
# shasum stabilityai/sdxl-turbo/sd_xl_turbo_1.0_fp16.safetensors
285e9cfa0c674009912559242027b3bc2dceb3f2 stabilityai/sdxl-turbo/sd_xl_turbo_1.0_fp16.safetensors
你可以根據(jù)你的實際網(wǎng)絡(luò)情況,來選擇到底是從 HuggingFace 下載模型還是從 ModelScope 來下載模型,如果你選擇的是 Model Scope,別忘記在你下載完模型之后,再從 HuggingFace 進行下倉庫內(nèi)容除兩個大尺寸模型文件之外的內(nèi)容更新。
如果你想更快的下載模型,我建議你閱讀這篇文章《節(jié)省時間:AI 模型靠譜下載方案匯總》,在此就不做展開了。
模型下載好之后,我們可以整理下目錄結(jié)構(gòu),保持 stabilityai/sdxl-turbo
目中有我們下載好的模型就好:
├── docker
│ ├── Dockerfile
│ └── Dockerfile.cn
├── LICENSE
├── README.md
└── stabilityai
└── sdxl-turbo
├── model_index.json
├── scheduler
├── sd_xl_turbo_1.0_fp16.safetensors
├── sd_xl_turbo_1.0.safetensors
├── text_encoder
├── text_encoder_2
├── tokenizer
├── tokenizer_2
├── unet
├── vae
├── vae_decoder
└── vae_encoder
編寫模型推理程序
完整的程序文件在這里,算上空格和美觀的換行,大概不到 160 多行,我這里再做一些簡化,主要講解下程序的運行流程:
from diffusers import AutoPipelineForImage2Image, AutoPipelineForText2Image
import gradio as gr
from PIL import Image
# ... 省略其他引用
# 加載指定目錄的模型
model_name_and_path = "/app/stabilityai/sdxl-turbo"
# 保證樂子,讓隨機數(shù)范圍大一些
max_64_bit_int = 2 ** 63 - 1
# ... 省略其他準備工作
# 初始化圖生圖和文生圖兩條 AI Pipeline
pipelines = {
"img2img": AutoPipelineForImage2Image.from_pretrained(
model_name_and_path, torch_dtype=torch_dtype, variant="fp16"
),
"txt2img": AutoPipelineForText2Image.from_pretrained(
model_name_and_path, torch_dtype=torch_dtype, variant="fp16"
),
}
...
# 調(diào)整上傳圖片內(nèi)容的尺寸,模型對處理的圖片尺寸有要求
def resize_crop(image: Image, size: int = 512):
# ...省略若干圖片調(diào)整邏輯,圖片模式、尺寸裁剪等等
return image
# 處理輸入,生成圖片
async def predict(
image: Image,
prompt: str,
strength: float = 0.7,
guidance: float = 0.0,
steps: int = 2,
seed: int = 42,
):
# 如果輸入包含圖片,那么使用圖生圖 Pipeline
if image is not None:
# ...
results = pipelines["img2img"](
prompt=prompt,
image=image,
generator=generator,
num_inference_steps=steps,
guidance_scale=guidance,
strength=strength,
width=512,
height=512,
output_type="pil",
)
else:
# 使用文生圖 Pipeline
# ...
results = pipelines["txt2img"](
prompt=prompt,
generator=generator,
num_inference_steps=steps,
guidance_scale=guidance,
width=512,
height=512,
output_type="pil",
)
return results.images[0]
with gr.Blocks() as app:
init_image_state = gr.State()
with gr.Column():
with gr.Row():
prompt = gr.Textbox(placeholder="Prompt", scale=5, container=False)
submit = gr.Button("Generate", scale=1)
with gr.Row():
with gr.Column():
image_input = gr.Image(
sources=["upload", "webcam", "clipboard"],
label="Webcam",
type="pil",
)
with gr.Column():
generated = gr.Image(type="filepath")
with gr.Accordion("Advanced options", open=False):
# 省略 Gradio 界面控件聲明
# ...
# 啟動服務(wù),允許我們來玩
app.queue()
app.launch(share=False, server_name="0.0.0.0", ssl_verify=False)
準備好程序后,我們將程序放置在目錄的根部,然后就可以準備運行開玩了。
├── app.py
├── docker
│ ├── Dockerfile
│ └── Dockerfile.cn
├── LICENSE
├── README.md
└── stabilityai
└── sdxl-turbo
├── model_index.json
├── scheduler
├── sd_xl_turbo_1.0_fp16.safetensors
├── sd_xl_turbo_1.0.safetensors
├── text_encoder
├── text_encoder_2
├── tokenizer
├── tokenizer_2
├── unet
├── vae
├── vae_decoder
└── vae_encoder
運行模型
因為使用 Docker ,所以運行模型非常簡單,只需要執(zhí)行下面的命令即可:
docker run --rm -it -p 7860:7860 -p 7680:7680 -p 8080:8080 --gpus all --ipc=host --ulimit memlock=-1 -v `pwd`:/app soulteary/sdxl-turbo-runtime python app.py
當命令執(zhí)行完畢,我們會看到類似下面的日志:
=============
== PyTorch ==
=============
NVIDIA Release 23.12 (build 76438008)
PyTorch Version 2.2.0a0+81ea7a4
Container image Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Copyright (c) 2014-2023 Facebook Inc.
Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
Copyright (c) 2011-2013 NYU (Clement Farabet)
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
Copyright (c) 2015 Google Inc.
Copyright (c) 2015 Yangqing Jia
Copyright (c) 2013-2016 The Caffe contributors
All rights reserved.
Various files include modifications (c) NVIDIA CORPORATION & AFFILIATES. All rights reserved.
This container image and its contents are governed by the NVIDIA Deep Learning Container License.
By pulling and using the container, you accept the terms and conditions of this license:
https://developer.nvidia.com/ngc/nvidia-deep-learning-container-license
WARNING: CUDA Minor Version Compatibility mode ENABLED.
Using driver version 525.147.05 which has support for CUDA 12.0. This container
was built with CUDA 12.3 and will be run in Minor Version Compatibility mode.
CUDA Forward Compatibility is preferred over Minor Version Compatibility for use
with this container but was unavailable:
[[Forward compatibility was attempted on non supported HW (CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE) cuInit()=804]]
See https://docs.nvidia.com/deploy/cuda-compatibility/ for details.
The cache for model files in Transformers v4.22.0 has been updated. Migrating your old cache. This is a one-time only operation. You can interrupt this and resume the migration later on by calling `transformers.utils.move_cache()`.
0it [00:00, ?it/s]
Loading pipeline components...: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 7/7 [00:00<00:00, 9.46it/s]
Loading pipeline components...: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 7/7 [00:00<00:00, 12.78it/s]
Running on local URL: http://0.0.0.0:7860
To create a public link, set `share=True` in `launch()`.
然后,我們在瀏覽器訪問容器運行主機的 IP:7860 就可以開始體驗和驗證 SD XL Turbo 啦。
接下來,我們可以輸入任意的內(nèi)容,來讓它進行圖片生成,比如我使用的是下面的 Prompt (提示詞):
# 叢林中的宇航員,冷色調(diào),柔和的色彩,詳細,8k
Astronaut in a jungle, cold color palette, muted colors, detailed, 8k
你會發(fā)現(xiàn),當我們在輸入的時候,圖片會非??焖俚谋簧沙鰜怼?/p>
不論我們是使用調(diào)整 Prompt 提示詞文本,還是拖拽界面下面的參數(shù),圖片都會被快速的重新生成。如果你對參數(shù)還不是很了解,可以閱讀文末的“AI Pipeline 參數(shù)概述”。
如果我們檢查服務(wù)日志,你會發(fā)現(xiàn)除了第一次生成較慢,在 0.75s
左右,剩下的渲染基本都在 0.13-0.14
秒。
Pipe took 0.752417802810669 seconds
Pipe took 0.13779544830322266 seconds
Pipe took 0.13955378532409668 seconds
Pipe took 0.1433868408203125 seconds
Pipe took 0.13985347747802734 seconds
Pipe took 0.13831496238708496 seconds
接下來,我們來嘗試“圖生圖”模式,這里我將網(wǎng)上搜索到的 Prompt 進行了簡單的修改,試著讓模型將圖片中的“宇航員”換成“蝙蝠俠”:
# 蝙蝠俠萬圣節(jié)服裝的肖像,面部彩繪,眩光姿勢,詳細,復(fù)雜,色彩豐富,電影燈光,藝術(shù)站趨勢,8k,超現(xiàn)實,聚焦,極端細節(jié),虛幻引擎 5 電影,杰作
Portrait of The batman halloween costume, face paintin, glare pose, detailed, intricate, full of colour, cinematic lighting, trending on artstation, 8k, hyperrealistic, focused, extreme details, unreal engine 5 cinematic, masterpiece
如果我們將上面生成的圖片上傳到界面,并且調(diào)整生成圖片的提示詞如上,接著點擊“生成按鈕”,或者稍微調(diào)整下參數(shù),觸發(fā)圖片重新生成:
你會發(fā)現(xiàn),依舊是非常迅速的即時生成體驗。同樣的,我們可以隨意調(diào)整提示詞或者參數(shù),或者換張圖片,程序都會比較迅速的完成我們的生成任務(wù):
Pipe took 0.23278570175170898 seconds
Pipe took 0.21840667724609375 seconds
Pipe took 0.21840357780456543 seconds
Pipe took 0.21806550025939941 seconds
Pipe took 0.2180163860321045 seconds
當我們查看顯卡使用情況,會發(fā)現(xiàn)差不多需要 16G+ 左右的顯存。
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 525.147.05 Driver Version: 525.147.05 CUDA Version: 12.0 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|===============================+======================+======================|
| 0 NVIDIA GeForce ... Off | 00000000:01:00.0 Off | Off |
| 31% 37C P2 63W / 450W | 16490MiB / 24564MiB | 0% Default |
| | | N/A |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=============================================================================|
| 0 N/A N/A 1504 G /usr/lib/xorg/Xorg 75MiB |
| 0 N/A N/A 1612 G /usr/bin/gnome-shell 16MiB |
| 0 N/A N/A 10984 C python 16394MiB |
+-----------------------------------------------------------------------------+
SDXL Turbo AI Pipeline 參數(shù)概述
Strength
生成過程中非常重要的參數(shù),它決定了我們使用的圖片和最終生成圖片有多相似。 如果我們希望生成圖片和原始圖片比較相似,我們需要盡可能調(diào)低 strength
的數(shù)值。如果你希望模型更有創(chuàng)造力,那么可以將 strength
數(shù)值往接近 1
的方向拉高。
Steps
是另外一個重要參數(shù),它決定了程序?qū)⒒ǘ嗌俟Ψ騺硗瓿蓤D片的生成。并且和 strength
息息相關(guān),如果我們將 strength
設(shè)置為 0.6
(和原圖 60% 相似),并設(shè)置 step
為 2 ,那么模型將對原始圖片進行兩次添加 0.6
步的噪聲,然后再進行兩次去噪,然后我們就得到了最終的圖片結(jié)果。
Guidance
是用于控制生成圖像和我們輸入的文本對齊的程度,我們可以拉高 guidance
的數(shù)值,讓圖像和我們輸入的提示詞更加一致,也可以將 guidance
數(shù)值保持在比較低的程度,讓模型更加有創(chuàng)意。比如,我們可以將 strength
和 guidance
都保持在比較低的數(shù)值,讓模型生成類似原始圖像,但是更有趣的結(jié)果。
最后
好了,這篇文章就先寫到這里啦。
有機會的時候,我們聊聊如何使用 SDXL Turbo 實現(xiàn) Midjourney 的“混圖”(圖生圖生圖),以及如何控制圖片盡量趨近于我們想要的結(jié)果,還有性能優(yōu)化。
–EOF
我們有一個小小的折騰群,里面聚集了一些喜歡折騰、彼此坦誠相待的小伙伴。
我們在里面會一起聊聊軟硬件、HomeLab、編程上、生活里以及職場中的一些問題,偶爾也在群里不定期的分享一些技術(shù)資料。
關(guān)于交友的標準,請參考下面的文章:
致新朋友:為生活投票,不斷尋找更好的朋友
當然,通過下面這篇文章添加好友時,請備注實名和公司或?qū)W校、注明來源和目的,珍惜彼此的時間 ??
關(guān)于折騰群入群的那些事
本文使用「署名 4.0 國際 (CC BY 4.0)」許可協(xié)議,歡迎轉(zhuǎn)載、或重新修改使用,但需要注明來源。 署名 4.0 國際 (CC BY 4.0)
本文作者: 蘇洋文章來源:http://www.zghlxwxcb.cn/news/detail-810324.html
創(chuàng)建時間: 2024年01月13日
統(tǒng)計字數(shù): 11843字
閱讀時間: 24分鐘閱讀
本文鏈接: https://soulteary.com/2024/01/13/stable-diffusion-xl-turbo-image-generation.html文章來源地址http://www.zghlxwxcb.cn/news/detail-810324.html
到了這里,關(guān)于Stable Diffusion XL Turbo 文生圖和圖生圖實踐的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!