前言
同早段时间对接chatgpt一样,我们使用的是phpbb_ailabs项目。这个项目支持openai的DALL-E,官方的服务我们肯定是用不起的,而且还可能有隐私问题。
这里的作图后端我们是通过部署Localai实现的,其有着和openai相似的api,因此可以方便的集成到这个phpbb插件中。
模型我们使用的是 SDXL Turbo: https://huggingface.co/stabilityai/sdxl-turbo
只需要一个步长(step)即可出图,效果还不错,跑在我们24小时运行的迷你nuc上,intel N100 CPU大概20多秒可以出一张图。
LocalAI的部署细节
我们是通过docker compose
来部署的,避免处理各种依赖的编译问题compose.yaml
代码: 全选
services:
api:
image: local-ai-sd
tty: true
ports:
- 127.0.0.1:12345:8080
env_file:
- .env
volumes:
- ./models:/models:cached
- ./images/:/tmp/generated/images/
command: ["/usr/bin/local-ai" ]
THREADS
设置为你CPU的核数,COMPEL=0
这里的注释要去掉,设置为0
代码: 全选
## Set number of threads.
## Note: prefer the number of physical cores. Overbooking the CPU degrades performance notably.
THREADS=4
## Specify a different bind address (defaults to ":8080")
# ADDRESS=127.0.0.1:8080
## Default models context size
# CONTEXT_SIZE=512
#
## Define galleries.
## models will to install will be visible in `/models/available`
GALLERIES=[{"name":"model-gallery", "url":"github:go-skynet/model-gallery/index.yaml"}]
## CORS settings
# CORS=true
# CORS_ALLOW_ORIGINS=*
## Default path for models
MODELS_PATH=/models
## Enable debug mode
DEBUG=true
## Disables COMPEL (Diffusers)
COMPEL=0
## Enable/Disable single backend (useful if only one GPU is available)
# SINGLE_ACTIVE_BACKEND=true
## Specify a build type. Available: cublas, openblas, clblas.
## cuBLAS: This is a GPU-accelerated version of the complete standard BLAS (Basic Linear Algebra Subprograms) library. It's provided by Nvidia and is part of their CUDA toolkit.
## OpenBLAS: This is an open-source implementation of the BLAS library that aims to provide highly optimized code for various platforms. It includes support for multi-threading and can be compiled to use hardware-specific features for additional performance. OpenBLAS can run on many kinds of hardware, including CPUs from Intel, AMD, and ARM.
## clBLAS: This is an open-source implementation of the BLAS library that uses OpenCL, a framework for writing programs that execute across heterogeneous platforms consisting of CPUs, GPUs, and other processors. clBLAS is designed to take advantage of the parallel computing power of GPUs but can also run on any hardware that supports OpenCL. This includes hardware from different vendors like Nvidia, AMD, and Intel.
BUILD_TYPE=openblas
## Uncomment and set to true to enable rebuilding from source
# REBUILD=true
## Enable go tags, available: stablediffusion, tts
## stablediffusion: image generation with stablediffusion
## tts: enables text-to-speech with go-piper
## (requires REBUILD=true)
#
# GO_TAGS=stablediffusion
## Path where to store generated images
# IMAGE_PATH=/tmp
## Specify a default upload limit in MB (whisper)
# UPLOAD_LIMIT
## List of external GRPC backends (note on the container image this variable is already set to use extra backends available in extra/)
# EXTERNAL_GRPC_BACKENDS=my-backend:127.0.0.1:9000,my-backend2:/usr/bin/backend.py
### Advanced settings ###
### Those are not really used by LocalAI, but from components in the stack ###
##
### Preload libraries
# LD_PRELOAD=
### Huggingface cache for models
# HUGGINGFACE_HUB_CACHE=/usr/local/huggingface
### Python backends GRPC max workers
### Default number of workers for GRPC Python backends.
### This actually controls wether a backend can process multiple requests or not.
# PYTHON_GRPC_MAX_WORKERS=1
### Define the number of parallel LLAMA.cpp workers (Defaults to 1)
# LLAMACPP_PARALLEL=1
### Enable to run parallel requests
# PARALLEL_REQUESTS=true
### Watchdog settings
###
# Enables watchdog to kill backends that are inactive for too much time
# WATCHDOG_IDLE=true
#
# Enables watchdog to kill backends that are busy for too much time
# WATCHDOG_BUSY=true
#
# Time in duration format (e.g. 1h30m) after which a backend is considered idle
# WATCHDOG_IDLE_TIMEOUT=5m
#
# Time in duration format (e.g. 1h30m) after which a backend is considered busy
# WATCHDOG_BUSY_TIMEOUT=5m
local-ai-sd
而不是官方文档中的quay.io/go-skynet/local-ai:latest
,因为这是我们特殊处理过的,请接着往下面看。在最开始运行官方镜像后,我们在models目录下创建一个名为
stablediffusion.yaml
的配置文件,内容如下
代码: 全选
name: stablediffusion
parameters:
model: stabilityai/sdxl-turbo
backend: diffusers
step: 1
cuda: false
# Force CPU usage - set to true for GPU
f16: false
diffusers:
scheduler_type: euler_a
cfg_scale: 1
代码: 全选
curl http://127.0.0.1:12345/v1/images/generations -H "Content-Type: application/json" -d '{
"prompt": "face focus, cute, masterpiece, best quality, 1girl, green hair, sweater, looking at viewer, upper body, beanie, outdoors, night, turtleneck",
"size": "512x512"
}'
docker compose down && docker compose up -d
)不再浪费时间下载模型,我们需要commit一个下载了作图模型的新image,fd3782b2c44d
换成你的容器id,可以通过docker ps
找到
代码: 全选
docker commit fd3782b2c44d local-ai-sd
local-ai-sd
镜像就是这么来的。
2024-1-4 补充说明: 找到huggingface的缓存在 /root/.cache/huggingface,可以把这个路径挂载一下,就不需要上面的操作了。
这里我为LocalAI项目提交了一个PR,没有这个更改,截至发文时,在LocalAI中使用sdxl turbo模型生成的图片会出现大量的噪点,完全没法看,具体细节你可以点击下面的箭头展开来看。
查看细节
为什么会这样呢?看容器里的日志会发现有类似这样的提醒
stderr Keyword arguments {'guidance_scale': 1.0} are not expected by StableDiffusionXLPipeline and will be ignored.
根据SDXL Turbo官方的文档: https://huggingface.co/docs/diffusers/a ... sdxl_turbo
需要禁用掉
guidance_scale
,将其设置为0.0
,在LocalAI和Stable Diffusion webui中是通过配置cfg_scale=1
实现的。上面的日志说明我们的配置没有起到应有的作用,于是我就开始翻LocalAI的源码,再对比diffusers项目中的例子找到了问题的真正所在,详细更改见PR。修改前
修改后
目前这个PR已被合并,使用最新版即可
到这里LocalAI这个作图后端的部署细节算是介绍完了,下面讲解phpbb_ailabs这个插件的配置。phpbb_ailabs插件配置
虽然前面我们部署好了LocalAI的作图后端,看它的文档,表面上与openai兼容,但实际从v2.0+版本开始,已经不再完全兼容了。有人在matrix_chatgpt_bot项目里开issue我才发现这个问题,这个问题的解决为此插件的正确配置打下了基础。总结一下不兼容的地方就是,不再支持n
,response_format
等参数,请求的json body只能包含prompt
和size
。所以为了成功的在phpbb_allabs插件中对接我们的后端,必须对其代码进行一定的更改。
这里先放上我修改好的插件的repo地址: https://github.com/hibobmaster/phpbb_ailabs
主要修改的内容是去掉那些不兼容的参数以及
variations
功能
代码: 全选
diff --git a/privet/ailabs/controller/dalle.php b/privet/ailabs/controller/dalle.php
index ffc1d81..73e7c86 100644
--- a/privet/ailabs/controller/dalle.php
+++ b/privet/ailabs/controller/dalle.php
@@ -66,22 +66,10 @@ class dalle extends GenericController
protected function prepare($opts)
{
- if (filter_var($this->job['request'], FILTER_VALIDATE_URL)) {
- // https://platform.openai.com/docs/api-reference/images/create-variation
- // The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.
- $image = curl_file_create($this->job['request'], 'image/png');
- $opts += [
- 'image' => $image,
- 'n' => $this->cfg->n,
- 'response_format' => $this->cfg->response_format,
- ];
- } else {
- $opts += [
- 'prompt' => trim($this->job['request']),
- 'n' => $this->cfg->n,
- 'response_format' => $this->cfg->response_format,
- ];
- }
+
+ $opts += [
+ 'prompt' => trim($this->job['request']),
+ ];
return $opts;
}
@@ -93,13 +81,7 @@ class dalle extends GenericController
$result = new resultSubmit();
- if (empty($opts['image'])) {
- // https://api.openai.com/v1/images/generations
- $result->response = $api->sendRequest($this->cfg->url_generations, 'POST', $opts);
- } else {
- // https://api.openai.com/v1/images/variations
- $result->response = $api->sendRequest($this->cfg->url_variations, 'POST', $opts);
- }
+ $result->response = $api->sendRequest($this->cfg->url_generations, 'POST', $opts);
$result->responseCodes = $api->responseCodes;
@@ -173,4 +155,4 @@ class dalle extends GenericController
return $result;
}
-}
+}
512x512
,此外这里的api_key可以乱填,哪怕你没有在LocalAI中启用访问校验
代码: 全选
{
"api_key": "xxxxxxxxx",
"url_generations": "https://xxxxxxxx.xxxxxxx/v1/images/generations",
"size": "512x512",
"response_format": "url"
}
![图片](https://api.quanquan.space/imageproxy/https://i.imgur.com/dV1XkKL.jpg)
你可能会好奇不是说不兼容
response_format
吗,为啥这里还有?如果你看了代码的话,这个参数现在不会添加到json的请求体了,只是用来对响应做相应的判断。配置好后,就可以测试插件了。
Bonus time之如何修改图片附件的前缀名称
你可能会注意到,图片附件的名称大致是这样的ailabs_xxx_xx_x.png
下面介绍修改前缀的方法,找到
includes/AIController.php
下的image_filename
函数将ailabs改成你想要的名称即可
代码: 全选
protected function image_filename($ind)
{
return 'ailabs_' . $this->job['ailabs_user_id'] . '_' . $this->job_id . '_' . $ind;
}
修改后停止并重新启用插件即可,新生成图片的前缀名称将会是你设置的名称,效果如下
修改前:
![图片](https://api.quanquan.space/imageproxy/https://i.imgur.com/kLmJeFm.jpg)
修改后:
![图片](https://api.quanquan.space/imageproxy/https://i.imgur.com/MBxhlvO.jpg)
总结
希望上面的教程能够给那些想为phpbb论坛对接stable diffusion作图功能的朋友提供一些帮助。由于我不是特别熟悉php开发,上面的魔改可能会导致原版Dall-E的功能没法正常使用了。
此外这套作图方案的缺点就是比较占用空间,docker容器的镜像大小,大概有70多G
![图片](https://api.quanquan.space/imageproxy/https://i.imgur.com/io4K7aX.jpg)
最后非常感谢下面的开发者,没有他们的开源项目,我们也没法为大家提供这么好玩的东东。
- huggingface的SDXL Turbo模型,没有该模型,我们也没法让作图功能“流畅”的在CPU上跑起来
- LocalAI项目,该项目让我们能够方便的部署自己的大语言模型、AI作图后端等
- phpbb_ailabs插件的作者privet.fun,让我们能够通过原生的方式将AI集成进phpbb论坛中