Ubuntu服务器端部署大模型

调用Ollama

下载

1
curl -fsSL https://ollama.com/install.sh | sh

docker方式

1
docker run -d --gpus=all -v ~/ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama
1
docker run -d -v ~/ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama

开启ollama服务端

好像也不需要?可能是用于在后台运行的

1
ollama serve

下载模型

1
ollama run llama2-chinese:latest

docker方式

1
docker exec -it ollama ollama run llama2-chinese

运行大模型WebUI

文档:🚀 Getting Started | Open WebUI

此处使用开源项目openwebui

1
docker run -d --gpus=all -d -p 3000:8080 -e HF_ENDPOINT=https://hf-mirror.com/ -e OLLAMA_BASE_URL=http://10.248.68.50:11434 -v ~/open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
1
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main

BUG

  1. huggingface.co 的连接问题

docker logs -f open-webui获取到错误日志,虽然日志超级无敌长,但是关键词是hugging face

截取部分日志

1
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='huggingface.co', port=443): Max retries exceeded with url: /sentence-transformers/all-MiniLM-L6-v2/resolve/main/config.json (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x7fd5bc4d0510>, 'Connection to huggingface.co timed out. (connect timeout=10)'))
  1. docker内部的网络隔离问题
    ollama也是通过docker进行部署的,如果这样的情况下,两个不同的Container中是无法通过--add-host=host.docker.internal:host-gateway命令进行连接的,需要通过IP+地址的方式进行访问或者将其放置到Compose中形成一个内部网络

    Linux - Ollama 和 Open WebUI 在容器中,在不同的网络中

    截屏2024-07-06 20.17.33

    Linux - 主机本地上的Ollama,在容器中打开WebUI
    截屏2024-07-06 20.16.26
    Linux - Ollama 和 Open WebUI 在同一个 Compose 堆栈中

    截屏2024-07-06 20.17.23

通过服务器返回数据

返回格式参考:API 参考 - Ollama中文网

默认启动后就会启动API的服务

http://127.0.0.1:11434/api/generate

微调模型

使用LLaMA-Factory进行微调

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
```



## 导出模型

原文:[Ollama 运行 GGUF 模型_51CTO博客_olap模型](https://blog.51cto.com/u_15588078/10133275#:~:text=Ollama 加载GGUF模型文件 1 1、创建模型配置文件 创建一个包含以下内容的模型配置文件,比如%3A causallm7bq5.mf 这个文件名,文件内容如下: FROM,ollama run c7b "请写一个情色幽默笑话" 1. 您得到的结果将与我得到的结果不同,因为这些模型是随机的,下面是我在其中一次尝试中得到的输出: 不同的尝试,会有不同的惊喜, )



要求进行INT量化,导出为后缀为`.gguf`的模型

然后新建一个`.mf`,里面是导出后的模型的位置

```bash
FROM /Users/tec/Downloads/model-unsloth.Q4_K_M.gguf

然后运行下面的命令

1
ollama create nftchat -f ./causallm7bq5.mf

API调用

ChatGLM3/openai_api_demo/api_server.py

1
python api_server.py

LLaMA-Factory/src/api.py

1
2
3
4
5
CUDA_VISIBLE_DEVICES=0 API_PORT=8000 python src/api.py \
--model_name_or_path /home/ypy/langchan/LLaMA-Factory/saves/AIChat \
--template chatglm2
--infer_backend vllm
--vllm_enforce_eager

vLLM

1
2
3
4
5
python -m vllm.entrypoints.openai.api_server \
--model /home/ypy/langchan/LLaMA-Factory/saves/AIChat \
--trust-remote-code \
--served-model-name AIChat \
--port 8000

Ubuntu服务器端部署Stable Diffusion

安装

1
git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git

docker安装

注意需要最新版本的compose

以Ubuntu 22.04为例,采用AbdBarho维护的docker-compose,仅支持Nvidia显卡。

  1. 拷贝AbdBarho的保存库
1
2
git clone https://github.com/AbdBarho/stable-diffusion-webui-docker.git
cd stable-diffusion-webui-docker
  1. 安装依赖套件,过程中会自动下载一个Stable Diffusion的模型。
1
docker compose --profile download up --build
  1. 启动容器,选取auto代表启动AUTOMATIC1111开发的WebUI
1
docker compose --profile auto up --build

启动

这里注意webui.py的位置,下面的命令,会根据系统配置,默认配置好项目环境,并安装好项目依赖包

1
./webui.sh

注意需要先使用命令

1
2
export http_proxy="http://127.0.0.1:7890"
export https_proxy="http://127.0.0.1:7890"

下面同时配置了外网通过IP访问,以及API访问

1
./webui.sh --listen --api

上面的这些命令可以直接在webui-user.sh中进行集成

COMMANDLINE_ARGS中指定需要的命令,之后直接执行./webui.sh就可以携带上这些命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
#########################################################
# Uncomment and change the variables below to your need:#
#########################################################

# Install directory without trailing slash
#install_dir="/home/$(whoami)"

# Name of the subdirectory
#clone_dir="stable-diffusion-webui"

# Commandline arguments for webui.py, for example: export COMMANDLINE_ARGS="--medvram --opt-split-attention"
export COMMANDLINE_ARGS="--listen --api --enable-insecure-extension-access"

# python3 executable
#python_cmd="python3"

启动报错

1
Cannot locate TCMalloc (improves CPU memory usage)

解决:安装 libgoogle-perftools4libtcmalloc-minimal4 库。这两个库是 Google 开源的性能分析工具库,可以帮助开发者优化程序性能。

1
sudo apt-get install libgoogle-perftools4 libtcmalloc-minimal4 -y

访问

进入下面的地址

1
http://localhost:7860

API访问则使用下面的地址

1
2
3
4
curl -X POST http://localhost:7860/sdapi/v1/txt2img -H "Content-Type: application/json" -d '{
"prompt": "a futuristic cityscape",
"steps": 20
}'

添加扩展

安装中文和双语界面

Stable Diffusion WebUI可以通过扩充功能将界面变成中文。如果您想协助翻译,请点击以上的Github保存库链接,帮帮他们。

  1. 进入Extensions页面,取消勾选localization,再点击Load from:,找到zh_TW Localizationzh_CN Localization,点击Install。

img

  1. 到Settings页面,找到左边的Localization,点击zh-twzh-cn,再点击Apply Settings

img

  1. 之后重启WebUI,界面就会变成中文了。

sd-webui-bilingual-localization/README_ZH.md at main · journey-ad/sd-webui-bilingual-localization (github.com)

由于SD WebUI的扩充功能发展太快,翻译可能跟不上,建议另外安装双语对照sd-webui-bilingual-localization,同时显示中文和英文的文本,这样看教学时就不会找无按钮了。

双语扩充功能安装方法:在Extensions页面按Install from URL,填入https://github.com/journey-ad/sd-webui-bilingual-localization,再按Install

在激活双语扩充功能前,要到Settings → User interface → Localization设为None

接着到Bilingual Localization中去把这里面的Localization修改为zh_CN,再重启WebUI才会生效。

img

BUG

报错如下:

1
AssertionError: extension access disabled because of command line flags

原因是开启了--listen的命令,官方出于安全考虑,在外网访问时是不能安装任何扩展的,所以需要加上--enable-insecure-extension-access的命令,用于绕开这个安全选项

大模型(基座模型,底模)添加

可以进入https://civitai.com/的Models部分进行下载,后缀为ckpt,为Checkpoint的缩写

模型权重下载好后,需要将模型放到对应的文件夹中,这里最常用的是:大模型 和 微调的LoRA 模型,分别放在 models/stable-diffusionmodels/Lora下,启动后,WebUI 会自动从这几个文件夹中找到对应的模型

类梵高:

1、Van Gogh Diffusion:Van Gogh Diffusion - V1 | Stable Diffusion Checkpoint | Civitai

2、Van Gogh Style(Lora):奇维泰 |共享您的模型 (civitai.com)

水墨风:

1、国画山水和水墨山水Chinese Landscape Art:国画山水和水墨山水Chinese Landscape Art - v1.0 | Stable Diffusion Checkpoint | Civitai

像素风:

1、PixelStyleCKPT/像素画:PixelStyleCKPT/像素画 - Strength:0.7 | Stable Diffusion Checkpoint | Civitai

2、像素人:Application error: a client-side exception has occurred (civitai.com)

3、Pixel Art XL:Pixel Art XL - v1.1 | Stable Diffusion LoRA | Civitai

莫奈风:

下面为lora模型,lora还不知道怎么使用

1、Claude Monet/Oscar-Claude Monet style:Claude Monet/Oscar-Claude Monet style - v2.0 | Stable Diffusion LoRA | Civitai

赛伯朋克风:

1、赛博世界/Cyberworld/赛博朋克场景 Lora:赛博世界/Cyberworld/赛博朋克场景 Lora - v1.0 | Stable Diffusion LoRA | Civitai

科幻风:

1、XSArchi_127新科幻Neo Sci-Fi:XSArchi_127新科幻Neo Sci-Fi - v1.0 | Stable Diffusion LoRA | Civitai

文生图API参数调整

参数含义:

在Stable Diffusion Web UI中,使用API时可以传递各种参数来控制图像生成的过程。以下是一些常见的API参数及其说明:

参考:全网最全stable diffusion webui API调用示例,包含controlneth和segment anything的API(附json示例)-CSDN博客

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

data = {
"prompt": "提示词",
"negative_prompt": "反向提示词",
"seed": -1, # 随机种子
"sampler_name": "取样器(之间复制webui的名字就行)",
"cfg_scale": 7.5, # 提示词相关性 越大越接近提示词
"width": 640, # 宽 (注意要被16整除)
"height": 360, # 高 (注意要被16整除)
"batch_size": 4, # 批量数量 并行 显存不够会爆显存
"n_iter": 4, # 批量数量 队列 显存不够排队一个一个来 和 batch_size 二选一
"steps": 30, # 迭代步数
"return_grid": True, # 返回网格预览 xl-base 好像没用
"restore_faces": True, # 脸部修复
"send_images": True, # 是否在响应中返回生成的图像
"save_images": False, # 是否保存生成的图像 一般api设置成False
"do_not_save_samples": False, # 是否保存samples 一般api设置成False
"do_not_save_grid": False, # 是否保存网格的图像 一般api设置成False
# 下面的很少用
"enable_hr": True, # 是否开启高清修复
"denoising_strength": 0.5, # 去噪强度 要求enable_hr = True
"firstphase_width": 0,
# firstphase_width 和firstphase_height 定义了图像的初始分辨率。在图像生成的第一阶段,这些值决定了图像的大小。如果这些值设置为0,系统可能会使用默认或预设的分辨率。
"firstphase_height": 0,
"hr_scale": 2, # 放大倍数 对应webui Upscale by
"hr_upscaler": "string", # 对应webui 的 Upscaler
"hr_second_pass_steps": 0, # 迭代步数 对应webui 的 Hires steps。
"hr_resize_x": 0, # 不放大,指定宽高 对应webui Resize width to 和Resize height to
"hr_resize_y": 0, # 不放大,指定宽高 对应webui Resize width to 和Resize height to
"hr_checkpoint_name": "string", # 高分辨率模式下使用的大模型昵称。
"hr_sampler_name": "string", # 高分辨率模式下使用的采样器名称。
"hr_prompt": "", # 高分辨率模式下使用的提示词名称。
"hr_negative_prompt": "", # 高分辨率模式下使用的反向提示词名称。
"override_settings": {
"sd_model_checkpoint": "sd_xl_base_1.0.safetensors [31e35c80fc]", # 指定大模型
"sd_vae": "Automatic", # 指定vae 默认自动
},
"override_settings_restore_afterwards": True # override_settings 是否在之后恢复覆盖的设置 默认是True


}

通用参数

这些参数适用于大多数API端点,例如/sdapi/v1/txt2img/sdapi/v1/img2img

  • prompt (str): 文本提示,用于描述要生成的图像内容。例如:”a futuristic cityscape”。
  • steps (int): 采样步骤数。值越高,图像质量越好,但生成时间也越长。常用值在20-50之间。
  • sampler_index (int): 采样方法索引,默认为0。可以使用不同的采样方法(例如DDIM、PLMS)。
  • cfg_scale (float): Classifier-Free Guidance (CFG) 比例,控制生成图像与提示的相关性。值越高,图像越接近提示内容。常用值在7-15之间。
  • seed (int): 随机种子,用于控制生成图像的随机性。相同的种子和参数会生成相同的图像。
  • height (int): 生成图像的高度,默认值通常是512。
  • width (int): 生成图像的宽度,默认值通常是512。
  • batch_size (int): 一次生成的图像数量。
  • n_iter (int): 生成图像的迭代次数。一次请求中生成的图像总数等于batch_size * n_iter
  • negative_prompt (str): 负面提示,用于描述不希望在图像中出现的内容。
  • eta (float): DDIM采样中的eta参数,控制随机性。
  • ckpt:在API请求中,通过指定ckpt或model参数来选择要使用的模型

特定参数

这些参数适用于特定的API端点,例如/sdapi/v1/img2img

  • init_images (list of str): 输入图像的Base64编码列表,用于img2img任务。
  • denoising_strength (float): 降噪强度,用于img2img任务。值越高,生成图像与输入图像的差异越大。常用值在0.2-0.8之间。
  • mask (str): 掩码图像的Base64编码,用于指定图像的哪些部分需要重绘。
  • inpainting_fill (int): 修补时使用的填充方式。

完整示例

以下是一个使用/sdapi/v1/txt2img端点的完整示例,展示了常用参数的用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import requests
import json

# 设置API端点
url = "http://localhost:7860/sdapi/v1/txt2img"

# 设置请求数据
data = {
"prompt": "a futuristic cityscape",
"steps": 30,
"sampler_index": 0,
"cfg_scale": 10.0,
"seed": 42,
"height": 512,
"width": 512,
"batch_size": 1,
"n_iter": 1,
"negative_prompt": "no people, no animals",
"eta": 0.0,
"ckpt": "models/Stable-diffusion/model1.ckpt" # 指定模型路径
}

# 发送POST请求
response = requests.post(url, headers={"Content-Type": "application/json"}, data=json.dumps(data))

# 打印响应
print(response.json())

API端点

  1. /sdapi/v1/txt2img: 基于文本提示生成图像。
  2. /sdapi/v1/img2img: 基于输入图像和文本提示生成新图像。
  3. /sdapi/v1/extra: 执行额外的图像处理任务。

参数说明总结

  • prompt: 输入的文本描述。
  • steps: 采样步骤数。
  • sampler_index: 采样方法索引。
  • cfg_scale: Classifier-Free Guidance比例。
  • seed: 随机种子。
  • height: 图像高度。
  • width: 图像宽度。
  • batch_size: 批量生成数量。
  • n_iter: 生成迭代次数。
  • negative_prompt: 负面提示。
  • eta: DDIM采样中的eta参数。
  • init_images: 输入图像列表(用于img2img)。
  • denoising_strength: 降噪强度(用于img2img)。
  • mask: 掩码图像。
  • inpainting_fill: 修补填充方式。

通过这些参数,你可以高度自定义图像生成过程,满足各种应用需求。如果你有任何其他问题或需要更详细的说明,请随时告诉我。

例子

仿梵高的向日葵

1
2
3
4
5
6
7
8
9
{
"prompt": "vg,<lora:vgv1-000009:0.9>,vibrant sunflowers chasing the sun,details,",
"negative_prompt": "easynegative bad-hands-5,",
"steps": 20,
"cfg_scale": 7.0,
"height": 1024,
"width": 512,
"sampler_name": "DPM++ 2M SDE",
}

仿莫奈的睡莲

1
2
3
4
5
6
7
8
9
{
"prompt": "<lora:monet_v2-000004:1>,painting (medium), lake, water lilies",
"negative_prompt": "sketches, out of frame, lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature",
"steps": 50,
"cfg_scale": 7.0,
"height": 1024,
"width": 512,
"sampler_name": "DPM++ 2M SDE"
}

BUG

访问后出现下面的返回

1
2
3
{
"detail": "Not Found"
}

参考解决:[错误]:我没有 /sdapi/v1/txt2img 在稳定扩散中填充 ·问题 #13279 ·AUTOMATIC1111/stable-diffusion-webui (github.com)

这是端口问题导致的BUG,glm把7860端口占了,所以只能使用7861端口,以后要是无法启动,注意观察终端端口输出

获取图片进度API

目前猜测实现方式是,在进行文生图API后,马上调用http://127.0.0.1:7860/sdapi/v1/progress?skip_current_image=false

这个API,每秒访问一次,不过这个参数skip_current_image含义,还得到时候再试试

Ubuntu服务器端配置外网访问

使用clash进行配置,由于官方的项目已经跑路,这里选择的项目为:

Elegycloud/clash-for-linux-backup: 基于Clash Core 制作的Clash For Linux备份仓库 A Clash For Linux Backup Warehouse Based on Clash Core (github.com)

详细可见和xyc的聊天记录,哪天自己也再去配置一下