利用HAI的ChatGLM2 6B做一個(gè)即時(shí)對話小游戲
ChatGLM2-6B 是開源中英雙語對話模型 ChatGLM-6B 的第二代版本,在保留了初代模型對話流暢、部署門檻較低等眾多優(yōu)秀特性的基礎(chǔ)之上,ChatGLM2-6B 引入了更強(qiáng)大的性能、更長的上下文、更高效的推理,所以用來做個(gè)小游戲非常的合適了。
我基本沒有做什么語句優(yōu)化,直接給了,并且能看到回復(fù)的情況,相當(dāng)可以的呢。接下來我們使用ChatGLM2 6B返回的結(jié)果來做個(gè)適合大學(xué)生們學(xué)習(xí)的職場即時(shí)對話類游戲。?
游戲框架概述
在大學(xué)中,我們能學(xué)到有限的知識,但是我們要步入社會(huì),想要在短時(shí)間內(nèi)能站穩(wěn)跟腳絕對是一件很難的事情,那么,我們就可以通過我們這款小游戲來歷練我們的對話能力。
【騰訊云 HAI域探秘】——即時(shí)職場生存指南小游戲
游戲接口的用語,可以自己嘗試,挺好的。
目標(biāo):生成領(lǐng)導(dǎo)與員工的對話語句,來考驗(yàn)員工的職場適應(yīng)能力。
1、信息1領(lǐng)導(dǎo)提問員工一個(gè)問題;
2、信息2是普通員工的回答方式;
3、信息3是優(yōu)秀員工的回答方式;
4、信息4是領(lǐng)導(dǎo)對信息2普通員工的回復(fù)并告知回錯(cuò)誤,給予一定的錯(cuò)誤懲罰;
5、信息5是領(lǐng)導(dǎo)對信息3優(yōu)秀員工的回復(fù)并告知回正確,給予一定的獎(jiǎng)勵(lì)話語。
6、僅生成以上5條信息,每條信息長度不超過50個(gè)字。
7、對話中不能有不文明用語。
這里用到了Stable Diffusion來創(chuàng)建AI圖片使游戲變得更加有意思。
例如,下圖就是游戲頁面,老板生成的時(shí)候我寫的:
翻譯完成后到【Stable Diffusion】里面生成就行,注意反向用語我寫的:【(semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime:1.1)close up】,反向用詞很多我再下面的SD中有說明。
開啟ChatGLM2 6B的服務(wù),下面有對應(yīng)操作。這里建議選用高性能的服務(wù)。不然可能起不來。
成功示例:?
有了這個(gè)就代表我們有接口了。
先返回到騰訊云,搜索一下Cloud Studio創(chuàng)建一個(gè)空項(xiàng)目
創(chuàng)建空項(xiàng)目
編碼:
編碼完成后就能運(yùn)行了哦,網(wǎng)頁單獨(dú)的使用【python -m http.server】來啟動(dòng),不啟動(dòng)無法訪問的哦。
自帶的內(nèi)置瀏覽器訪問不效果不如單獨(dú)打開的,我們可以進(jìn)行測試以下。
目錄
利用HAI的ChatGLM2 6B做一個(gè)即時(shí)對話小游戲
游戲框架概述
自行搭建Stable Diffusion模型服務(wù)用于生成AI圖片
一、服務(wù)創(chuàng)建
1、服務(wù)地址:
2、等待審核(大概24小時(shí))
二、創(chuàng)建服務(wù)
1、新建服務(wù)
2、選擇AI模型:Stable Diffusion
3、等待創(chuàng)建(5~8分鐘)
三、操作面板介紹
1、webui操作
2、jupyter_lab操作
四、webui操作步驟
1、中文插件安裝
2、配置中文插件操作步驟
3、Reload UI后效果
五、stable Diffusion——AI繪圖技巧(特色功能)
六、jupyter_lab操作步驟
?1、進(jìn)入jupyter_lab操作頁面
2、面板功能介紹
3、啟動(dòng)服務(wù)
4、添加7862端口規(guī)則
3、訪問swagger接口
七、python接口解析生成AI圖片
1、打開python開發(fā)工具
2、創(chuàng)建py文件并輸入以下代碼
?3、運(yùn)行效果
Stable Diffusion模型總結(jié)
自行搭建ChatGL M26BAI模型服務(wù)用于AI對話
一、服務(wù)創(chuàng)建
新建服務(wù)
服務(wù)選擇:(這里可以下拉選擇大一些的硬盤)
二、操作面板介紹
1、chatglm_gradio:
2、jupyter_lab:
三、基礎(chǔ)服務(wù)示例(jupyter_lab操作)
1、進(jìn)入并啟動(dòng)服務(wù)
2、啟動(dòng)后開啟訪問端口(8000)
3、Python接口訪問效果
四、正式服務(wù)代碼
1、修改【openai-api.py】文件
?2、運(yùn)行【openai-api.py】文件,服務(wù)端開啟服務(wù)
五、可視化頁面搭建
1、在創(chuàng)建cloud Studio的時(shí)候選擇【應(yīng)用推薦】
2、Fork項(xiàng)目
3、修改【.env.template】文件
4、修改【.env.template】為【.env】文件
六、運(yùn)行可視化操作頁面
1、新建終端
?編輯
2、運(yùn)行服務(wù)
3、選擇打開方式
ChatGL M26BAI模型總結(jié)、
Pytorch2.0 AI框架視頻處理
一、框架選擇
二、使用 JupyterLab 體驗(yàn)完整的機(jī)器學(xué)習(xí)工作流程
1、Terminal操作
2、打開root/dataset-fashion-mnist/data/fashion文件夾
3、創(chuàng)建【Notebook】
4、運(yùn)行方法
5、修改pip環(huán)境配置
6、創(chuàng)建Terminal持續(xù)運(yùn)行以下代碼?
7、保存模型
8、加載模型并預(yù)測
9、預(yù)測模型
三、使用 JupyterLab 體驗(yàn)使用字符級循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN) 生成姓名
1、數(shù)據(jù)準(zhǔn)備
2、新建一個(gè)?Notebook?頁面,選擇?Python 3
3、第八步驟的代碼
4、繪制損失
5、網(wǎng)絡(luò)采樣
四、使用 JupyterLab 體驗(yàn)視頻摳像神器RobustVideoMatting
1、依賴安裝
2、下載實(shí)驗(yàn)資源
?3、運(yùn)行
4、摳圖效果
5、換背景效果
Pytorch2.0總結(jié)
?
自行搭建Stable Diffusion模型服務(wù)用于生成AI圖片
一、服務(wù)創(chuàng)建
1、服務(wù)地址:
高性能應(yīng)用服務(wù)HAI 新品內(nèi)測
2、等待審核(大概24小時(shí))
二、創(chuàng)建服務(wù)
1、新建服務(wù)
2、選擇AI模型:Stable Diffusion
高性能,效率更快。
3、等待創(chuàng)建(5~8分鐘)
這里可以看到溫馨提示,創(chuàng)建中不計(jì)費(fèi)的。
創(chuàng)建完成效果:
三、操作面板介紹
1、webui操作
都是鼠標(biāo)點(diǎn)擊操作,方便。
2、jupyter_lab操作
命令行操作,有一定難度,但是按照步驟可以一步步搞定哦。自己配置接口,多舒服。
四、webui操作步驟
1、中文插件安裝
步驟1、選擇Extensions、
步驟2、選擇Available、
步驟3、按照圖示選擇
步驟4、搜索zh_CH
步驟5、點(diǎn)擊【Load from】進(jìn)行搜索
搜索效果
搜索【zh_CN】找到后,點(diǎn)擊【install】進(jìn)行安裝。
安裝完畢效果
2、配置中文插件操作步驟
按照下圖操作,其中步驟3是在沒有看到zh_CN的情況下刷新一下。
3、Reload UI后效果
刷新后能看到中文的顯示狀態(tài)。剛才我們在擴(kuò)展中安裝了中文的插件,在設(shè)置中配置了中文插件。
頁面說明,這個(gè)圖給的描述很詳細(xì)。
數(shù)據(jù)示例:
參數(shù)名 | 描述 | 值 |
---|---|---|
提示詞 | 主要描述圖像,包括內(nèi)容風(fēng)格等信息,原始的webui會(huì)對這個(gè)地方有字?jǐn)?shù)的限制,可以安裝一些插件突破字?jǐn)?shù)的限制 | a pretty cat,cyberpunk art,kerem beyit,very cute robot zen,Playful,Independent,beeple |
反向提示詞 | 為了提供給模型,我們不需要的風(fēng)格 | (deformed,distorted,disfigured:1.0),poorly drawn,bad anatomy,wrong anatomy,extra limb,missing limb,floating limbs,(mutated hands and fingers:1.5),disconnected limbs,mutation,mutated,ugly,disgusting,blurry,amputation,flowers,human,man,woman |
提示詞相關(guān)性(CFG scale) | 分類器自由引導(dǎo)尺度——圖像與提示符的一致程度——越低的值產(chǎn)生的結(jié)果越有創(chuàng)意,數(shù)值越大成圖越貼近描述文本。一般設(shè)置為7 | 7 |
采樣方法(Sampling method) | 采樣模式,即擴(kuò)散算法的去噪聲采樣模式會(huì)影響其效果,不同的采樣模式的結(jié)果會(huì)有很大差異,一般是默認(rèn)選擇euler,具體效果我也在逐步嘗試中。 | Euler a |
采樣迭代步數(shù)(Sampling steps) | 在使用擴(kuò)散模型生成圖片時(shí)所進(jìn)行的迭代步驟。每經(jīng)過一次迭代,AI就有更多的機(jī)會(huì)去比對prompt和當(dāng)前結(jié)果,并作出相應(yīng)的調(diào)整。需要注意的是,更高的迭代步數(shù)會(huì)消耗更多的計(jì)算時(shí)間和成本,但并不意味著一定會(huì)得到更好的結(jié)果。然而,如果迭代步數(shù)過少,一般不少于50,則圖像質(zhì)量肯定會(huì)下降 | 80 |
隨機(jī)種子(Seed) | 隨機(jī)數(shù)種子,生成每張圖片時(shí)的隨機(jī)種子,這個(gè)種子是用來作為確定擴(kuò)散初始狀態(tài)的基礎(chǔ)。不懂的話,用隨機(jī)的即可 | 127361827368 |
隨機(jī)種子也可以自己添加,下面的實(shí)驗(yàn)我用-1和?
實(shí)驗(yàn)效果:
?隨機(jī)種子實(shí)驗(yàn)效果
五、stable Diffusion——AI繪圖技巧(特色功能)
在stable Diffusion中會(huì)有正向提示詞&反向提示詞,這個(gè)是很獨(dú)特的一個(gè)功能,這里深入的測試一下。
提示詞(prompt)由多個(gè)詞綴構(gòu)成,分為正向提示詞(positive prompt)和反向提示詞(negative prompt),用來告訴AI哪些需要,哪些不需要。
注:詞綴的權(quán)重默認(rèn)值都是1,從左到右依次減弱,權(quán)重會(huì)影響畫面生成結(jié)果。 比如景色Tag在前,人物就會(huì)小,相反的人物會(huì)變大或半身。 選擇正確的順序、語法來使用提示詞,將更好、更快、更有效率地展現(xiàn)所想所愿的畫面。
逗號(,):分割詞綴,有一定權(quán)重排序功能,逗號前權(quán)重高,逗號后權(quán)重低,因而建議排序:
綜述(圖像質(zhì)量+畫風(fēng)+鏡頭效果+光照效果+主題+構(gòu)圖)
主體(人物&對象+姿勢+服裝+道具)
細(xì)節(jié)(場景+環(huán)境+飾品+特征)
權(quán)重示例:
冒號(:):自定義權(quán)重?cái)?shù)值 格式:左圓括號 + 詞綴 + 冒號 + 數(shù)字 + 右圓括號
單人女孩詞綴,權(quán)重為0.75 (1girl:0.75)()僅圓括號:增加權(quán)重0.1 大部分情況用圓括號即可。
權(quán)重乘以1.1 (1girl){}花括號:增加權(quán)重0.05
權(quán)重乘以1.05 {1girl}[] 方括號:減少權(quán)重0.1,也有說是減弱0.05的 方括號中無法自定義權(quán)重?cái)?shù)值,自定義權(quán)重只能使用(x:0.5)形式。
權(quán)重除以1.1 [1girl](())、{{}}、[[]]復(fù)用括號:疊加權(quán)重
權(quán)重乘以1.1*1.1,即權(quán)重為1.21 ((1girl))
提示詞:
hanfu,tang style outfits,pink upper shan, blue chest po skirt, purple with white waistband, light green pibo, 1girl, blue eyes, gray hair, dusk, over the sea, HDR,UHD,8K, best quality, masterpiece, Highly detailed, Studio lighting, ultra-fine painting, sharp focus, physically-based rendering, extreme detail description, Professional, Vivid Colors, close-up view
反向(負(fù)面)提示詞:
nsfw,logo,text,badhandv4,EasyNegative,ng_deepnegative_v1_75t,rev2-badprompt,verybadimagenegative_v1.3,negative_hand-neg,mutated hands and fingers,poorly drawn face,extra limb,missing limb,disconnected limbs,malformed hands,ugly
可以直接生成,效果還是不錯(cuò)的,就是時(shí)間較長,這里建議使用高一些配置的服務(wù),能快一些。
提示詞我們還可以加以修飾一下效果會(huì)更好。
1girl, aqua eyes, lipstick, brown hair, asymmetrical bangs, light smile, in summer, bamboo forest, flower sea, HDR,UHD,8K, best quality, masterpiece, Highly detailed, ultra-fine painting, sharp focus, physically-based rendering, extreme detail description, Professional, Vivid Colors, close-up view, looking at viewer, hanfu, tang style outfits,<lora:hanfuTang_v32:0.5>, red upper shan, blue chest po skirt, orange waistband, light green pibo
我生成了幾張圖片,這是使用的詞語
a young female holding a sign that says “I Love CSDN”, highlights in hair, sitting outside restaurant, brown eyes, wearing a dress, side light,[the: (painting cartoon:1.9): 0.3]
反向詞語
painting, cartoon
我生成了6張,可以看看。
六、jupyter_lab操作步驟
?1、進(jìn)入jupyter_lab操作頁面
操作頁面效果
2、面板功能介紹
3、啟動(dòng)服務(wù)
命令如下,直接復(fù)制并【ctrl+v】即可
cd /root/stable-diffusion-webui
python launch.py --nowebui --xformers --opt-split-attention ?--listen --port 7862
命令參數(shù)描述:
命令 | 描述 |
---|---|
--nowebui | 以 API 模式啟動(dòng) |
--xformers | 使用xformers庫。極大地改善了內(nèi)存消耗和速度。 |
--opt-split-attention | Cross attention layer optimization 優(yōu)化顯著減少了內(nèi)存使用,幾乎沒有成本(一些報(bào)告改進(jìn)了性能)。黑魔法。默認(rèn)情況下torch.cuda,包括 NVidia 和 AMD 卡。 |
--listen | 默認(rèn)啟動(dòng)綁定的 ip 是 127.0.0.1,只能是你自己電腦可以訪問 webui,如果你想讓同個(gè)局域網(wǎng)的人都可以訪問的話,可以配置該參數(shù)(會(huì)自動(dòng)綁定 0.0.0.0 ip)。 |
--port | 默認(rèn)端口是 7860,如果想換個(gè)端口,可以配置該參數(shù),例如:--port 7862 |
--gradio-auth username:password | 如果你希望給 webui 設(shè)置登錄密碼,可以配置該參數(shù),例如:--gradio-auth GitLqr:123456。 |
本地啟動(dòng)效果(不支持公網(wǎng)訪問,可以看到是127.0.0.1:7862)
啟動(dòng)效果(支持公網(wǎng)訪問,可以看到是0.0.0.0:7862)
4、添加7862端口規(guī)則
操作1、進(jìn)入模型操作面板
添加7862端口號碼
添加端口操作
3、訪問swagger接口
訪問地址:ip:7862端口
七、python接口解析生成AI圖片
1、打開python開發(fā)工具
我們使用的是【PyCharm Community Edition 2023.1.4】版本。
2、創(chuàng)建py文件并輸入以下代碼
注:這里一定要修改服務(wù)的IP,也就是公網(wǎng)的那個(gè)IP
import json
import base64
import requests
your_ip = '0.0.0.0' # HAI服務(wù)器IP地址
your_port = 7862 # SD api 監(jiān)聽的端口
def submit_post(url: str,data: dict):
"""
Submit a POST request to the given URL with the given data.
"""
return requests.post(url,data=json.dumps(data))
def save_encoded_image(b64_image: str,output_path: str):
"""
Save the given image to the given output path.
"""
with open(output_path,"wb") as image_file:
image_file.write(base64.b64decode(b64_image))
if __name__ == '__main__':
# /sdapi/v1/txt2img
txt2img_url = f'http://{your_ip}:{your_port}/sdapi/v1/txt2img'
data = {
'prompt': 'a pretty cat,cyberpunk art,kerem beyit,very cute robot zen,Playful,Independent,beeple |',
'negative_prompt':'(deformed,distorted,disfigured:1.0),poorly drawn,bad anatomy,wrong anatomy,extra limb,missing limb,floating limbs,(mutated hands and fingers:1.5),disconnected limbs,mutation,mutated,ugly,disgusting,blurry,amputation,flowers,human,man,woman',
'Steps':50,
'Seed':127361827368
}
response = submit_post(txt2img_url,data)
save_encoded_image(response.json()['images'][0],'cat.png')
參數(shù)說明
名稱 | 說明 |
---|---|
prompt | 提示詞 |
negative_prompt | 反向提示詞 |
seed | 種子,隨機(jī)數(shù) |
batch_size | 每次張數(shù) |
n_iter | 生成批次 |
steps | 生成步數(shù) |
cfg_scale | 關(guān)鍵詞相關(guān)性 |
width | 寬度 |
height | 高度 |
restore_faces | 臉部修復(fù) |
tiling | 可平鋪 |
sampler_index | 采樣方法 |
?3、運(yùn)行效果
可以看到生成的圖片就在對應(yīng)的文件夾內(nèi),我們還可以改很多參數(shù)。
Stable Diffusion模型總結(jié)
圖片生成,還是用處非常多的,而且價(jià)格也比較劃算,使用和配置都很方便,效率也好高,可以自己搭建嘗試一下,很棒的。
自行搭建ChatGL M26BAI模型服務(wù)用于AI對話
單獨(dú)訪問效果:?
vscode內(nèi)運(yùn)行效果:
我們使用騰訊云來創(chuàng)建,有完整的操作流程,很方便我們搭建使用。
一、服務(wù)創(chuàng)建
創(chuàng)建效果:
新建服務(wù)
服務(wù)選擇:(這里可以下拉選擇大一些的硬盤)
剩余的時(shí)間需要等待。
創(chuàng)建完畢效果:
二、操作面板介紹
1、chatglm_gradio:
我們可以直接通過這個(gè)網(wǎng)址進(jìn)行對話操作。
2、jupyter_lab:
創(chuàng)建控制臺窗口,可以在這里進(jìn)行具體的代碼編輯與運(yùn)行。
三、基礎(chǔ)服務(wù)示例(jupyter_lab操作)
1、進(jìn)入并啟動(dòng)服務(wù)
cd /root/ChatGLM2-6B/
python api.py
運(yùn)行起來能看到有信息提示。?
2、啟動(dòng)后開啟訪問端口(8000)
進(jìn)入到服務(wù)詳情。
添加防火墻可通過的端口號。?
添加效果:
3、Python接口訪問效果
添加后即可訪問:http://你的公網(wǎng)IP:8000/?的這個(gè)接口,具體服務(wù)參數(shù)如下列代碼:
import requests
# 定義測試數(shù)據(jù),以及FastAPI服務(wù)器的地址和端口
server_url = "http://0.0.0.0:8000" # 請確保將地址和端口更改為您的API服務(wù)器的實(shí)際地址和端口
test_data = {
"prompt": "'電影雨人講的是什么?'",
"history": [],
"max_length": 50,
"top_p": 0.7,
"temperature": 0.95
}
# 發(fā)送HTTP POST請求
response = requests.post(server_url, json=test_data)
# 處理響應(yīng)
if response.status_code == 200:
result = response.json()
print("Response:", result["response"])
print("History:", result["history"])
print("Status:", result["status"])
print("Time:", result["time"])
else:
print("Failed to get a valid response. Status code:", response.status_code)
訪問效果:
四、正式服務(wù)代碼
1、修改【openai-api.py】文件
使用以下代碼覆蓋原有的代碼:
# coding=utf-8
# Implements API for ChatGLM2-6B in OpenAI's format. (https://platform.openai.com/docs/api-reference/chat)
# Usage: python openai_api.py
# Visit http://localhost:8000/docs for documents.
import time
import torch
import uvicorn
from pydantic import BaseModel, Field
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from typing import Any, Dict, List, Literal, Optional, Union
from transformers import AutoTokenizer, AutoModel
from sse_starlette.sse import ServerSentEvent, EventSourceResponse
@asynccontextmanager
async def lifespan(app: FastAPI): # collects GPU memory
yield
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
app = FastAPI(lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class ModelCard(BaseModel):
id: str
object: str = "model"
created: int = Field(default_factory=lambda: int(time.time()))
owned_by: str = "owner"
root: Optional[str] = None
parent: Optional[str] = None
permission: Optional[list] = None
class ModelList(BaseModel):
object: str = "list"
data: List[ModelCard] = []
class ChatMessage(BaseModel):
role: Literal["user", "assistant", "system"]
content: str
class DeltaMessage(BaseModel):
role: Optional[Literal["user", "assistant", "system"]] = None
content: Optional[str] = None
class ChatCompletionRequest(BaseModel):
model: str
messages: List[ChatMessage]
temperature: Optional[float] = None
top_p: Optional[float] = None
max_length: Optional[int] = None
stream: Optional[bool] = False
class ChatCompletionResponseChoice(BaseModel):
index: int
message: ChatMessage
finish_reason: Literal["stop", "length"]
class ChatCompletionResponseStreamChoice(BaseModel):
index: int
delta: DeltaMessage
finish_reason: Optional[Literal["stop", "length"]]
class ChatCompletionResponse(BaseModel):
model: str
object: Literal["chat.completion", "chat.completion.chunk"]
choices: List[Union[ChatCompletionResponseChoice, ChatCompletionResponseStreamChoice]]
created: Optional[int] = Field(default_factory=lambda: int(time.time()))
@app.get("/v1/models", response_model=ModelList)
async def list_models():
global model_args
model_card = ModelCard(id="gpt-3.5-turbo")
return ModelList(data=[model_card])
@app.post("/v1/chat/completions", response_model=ChatCompletionResponse)
async def create_chat_completion(request: ChatCompletionRequest):
global model, tokenizer
if request.messages[-1].role != "user":
raise HTTPException(status_code=400, detail="Invalid request")
query = request.messages[-1].content
prev_messages = request.messages[:-1]
if len(prev_messages) > 0 and prev_messages[0].role == "system":
query = prev_messages.pop(0).content + query
history = []
if len(prev_messages) % 2 == 0:
for i in range(0, len(prev_messages), 2):
if prev_messages[i].role == "user" and prev_messages[i+1].role == "assistant":
history.append([prev_messages[i].content, prev_messages[i+1].content])
if request.stream:
generate = predict(query, history, request.model)
return EventSourceResponse(generate, media_type="text/event-stream")
response, _ = model.chat(tokenizer, query, history=history)
choice_data = ChatCompletionResponseChoice(
index=0,
message=ChatMessage(role="assistant", content=response),
finish_reason="stop"
)
return ChatCompletionResponse(model=request.model, choices=[choice_data], object="chat.completion")
async def predict(query: str, history: List[List[str]], model_id: str):
global model, tokenizer
choice_data = ChatCompletionResponseStreamChoice(
index=0,
delta=DeltaMessage(role="assistant"),
finish_reason=None
)
chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object="chat.completion.chunk")
#yield "{}".format(chunk.json(exclude_unset=True, ensure_ascii=False))
yield "{}".format(chunk.model_dump_json(exclude_unset=True))
current_length = 0
for new_response, _ in model.stream_chat(tokenizer, query, history):
if len(new_response) == current_length:
continue
new_text = new_response[current_length:]
current_length = len(new_response)
choice_data = ChatCompletionResponseStreamChoice(
index=0,
delta=DeltaMessage(content=new_text),
finish_reason=None
)
chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object="chat.completion.chunk")
#yield "{}".format(chunk.json(exclude_unset=True, ensure_ascii=False))
yield "{}".format(chunk.model_dump_json(exclude_unset=True))
choice_data = ChatCompletionResponseStreamChoice(
index=0,
delta=DeltaMessage(),
finish_reason="stop"
)
chunk = ChatCompletionResponse(model=model_id, choices=[choice_data], object="chat.completion.chunk")
#yield "{}".format(chunk.json(exclude_unset=True, ensure_ascii=False))
yield "{}".format(chunk.model_dump_json(exclude_unset=True))
yield '[DONE]'
if __name__ == "__main__":
tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", revision="v1.0", trust_remote_code=True)
model = AutoModel.from_pretrained("THUDM/chatglm2-6b", revision="v1.0", trust_remote_code=True).cuda()
# 多顯卡支持,使用下面兩行代替上面一行,將num_gpus改為你實(shí)際的顯卡數(shù)量
# from utils import load_model_on_gpus
# model = load_model_on_gpus("THUDM/chatglm2-6b", num_gpus=2)
model.eval()
uvicorn.run(app, host='0.0.0.0', port=8000, workers=1)
?2、運(yùn)行【openai-api.py】文件,服務(wù)端開啟服務(wù)
在控制臺直接輸入python openai-api.py即可運(yùn)行
五、可視化頁面搭建
1、在創(chuàng)建cloud Studio的時(shí)候選擇【應(yīng)用推薦】
選擇【ChatGPT Next Web】
2、Fork項(xiàng)目
3、修改【.env.template】文件
直接替換我下面的就行,但是需要替換一下你服務(wù)的IP。
# Your openai api key. (required)
OPENAI_API_KEY="hongMuXiangXun"
# Access passsword, separated by comma. (optional)
CODE=
# You can start service behind a proxy
PROXY_URL=http://你的IP:8000
# Override openai api request base url. (optional)
# Default: https://api.openai.com
# Examples: http://your-openai-proxy.com
BASE_URL=http://你的IP:8000
# Specify OpenAI organization ID.(optional)
# Default: Empty
OPENAI_ORG_ID=
# (optional)
# Default: Empty
# If you do not want users to input their own API key, set this value to 1.
HIDE_USER_API_KEY=
# (optional)
# Default: Empty
# If you do not want users to use GPT-4, set this value to 1.
DISABLE_GPT4=
# (optional)
# Default: Empty
# If you do not want users to query balance, set this value to 1.
HIDE_BALANCE_QUERY=
4、修改【.env.template】為【.env】文件
鼠標(biāo)右鍵,重命名即可。
六、運(yùn)行可視化操作頁面
1、新建終端
2、運(yùn)行服務(wù)
?先運(yùn)行npm的安裝,在通過【yarn dev】啟動(dòng)。
npm install
yarn dev
安裝時(shí)間較長,別急,等一會(huì)。
運(yùn)行yarn dev效果:
3、選擇打開方式
這里需要選擇到端口處進(jìn)行具體的選擇,選擇方式如下圖。
我覺得這個(gè)頁面設(shè)計(jì)的還是不錯(cuò)的。
內(nèi)部訪問效果也OK:
到此,恭喜你,創(chuàng)建完畢了。
ChatGL M26BAI模型總結(jié)、
整體上六個(gè)大步驟,沒有消耗多長時(shí)間,我是搞了一遍之后開始寫的這篇文章,故而看著時(shí)間長一些,其實(shí)熟練操作也就分分鐘的事情,應(yīng)該是適合絕大多數(shù)的程序員來操作的。
操作不復(fù)雜,基本都有提示,希望對大家都能有所幫助,下面我單獨(dú)問了一個(gè)問題,就是我們程序員未來發(fā)展之路,未遂沒有一個(gè)具體解答,但是還是很中肯的,那就是學(xué)無止境。
Pytorch2.0 AI框架視頻處理
一、框架選擇
1、這里選擇【Pytorch2.0】框架辦版本。
創(chuàng)建完就是等待的時(shí)間,這個(gè)還是比較快的,我們主要使用【jupyter_lab】。
二、使用 JupyterLab 體驗(yàn)完整的機(jī)器學(xué)習(xí)工作流程
這里主要使用的是?FashionMNIST 數(shù)據(jù)集。
1、Terminal操作
使用的是清華大學(xué)的鏡像加載本地?cái)?shù)據(jù)集
mkdir dataset-fashion-mnist #創(chuàng)建文件夾 dataset-fashion-mnist
cd dataset-fashion-mnist
wget https://mirror.tuna.tsinghua.edu.cn/raspberry-pi-os/raspbian/pool/main/d/dataset-fashion-mnist/dataset-fashion-mnist_0.0~git20200523.55506a9.orig.tar.xz #下載數(shù)據(jù)集
tar -xf dataset-fashion-mnist_0.0~git20200523.55506a9.orig.tar.xz --strip-components=1
cd data && mkdir FashionMNIST && mkdir FashionMNIST/raw
2、打開root/dataset-fashion-mnist/data/fashion文件夾
復(fù)制文件至【root/dataset-fashion-mnist/data/FashionMNIST/raw/】文件夾
3、創(chuàng)建【Notebook】
運(yùn)行以下代碼:
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
# 加載本地訓(xùn)練數(shù)據(jù)
training_data = datasets.FashionMNIST(
root="/root/dataset-fashion-mnist/data",
train=True,
download=True,
transform=ToTensor(),
)
# 加載本地測試數(shù)據(jù)
test_data = datasets.FashionMNIST(
root="/root/dataset-fashion-mnist/data",
train=False,
download=True,
transform=ToTensor(),
)
4、運(yùn)行方法
注意看下圖:
運(yùn)行效果:?
5、修改pip環(huán)境配置
pip config set global.index-url http://mirrors.cloud.tencent.com/pypi/simple
pip config set global.trusted-host mirrors.cloud.tencent.com
6、創(chuàng)建Terminal持續(xù)運(yùn)行以下代碼?
import matplotlib.pyplot as plt
labels_map = {
0: "T-Shirt",
1: "Trouser",
2: "Pullover",
3: "Dress",
4: "Coat",
5: "Sandal",
6: "Shirt",
7: "Sneaker",
8: "Bag",
9: "Ankle Boot",
}
figure = plt.figure(figsize=(8, 8))
cols, rows = 3, 3
for i in range(1, cols * rows + 1):
sample_idx = torch.randint(len(training_data), size=(1,)).item()
img, label = training_data[sample_idx]
figure.add_subplot(rows, cols, i)
plt.title(labels_map[label])
plt.axis("off")
plt.imshow(img.squeeze(), cmap="gray")
plt.show()
?運(yùn)行效果:
batch_size = 64
# 創(chuàng)建 dataloader
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)
for X, y in test_dataloader:
print(f"Shape of X [N, C, H, W]: {X.shape}")
print(f"Shape of y: {y.shape} {y.dtype}")
break
# 獲取用于訓(xùn)練的 cpu 或 gpu 設(shè)備
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
print(f"Using {device} device")
# 定義模型
class NeuralNetwork(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10)
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
model = NeuralNetwork().to(device)
print(model)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
model.train()
for batch, (X, y) in enumerate(dataloader):
X, y = X.to(device), y.to(device)
# 計(jì)算預(yù)測誤差
pred = model(X)
loss = loss_fn(pred, y)
# 反向傳播
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch % 100 == 0:
loss, current = loss.item(), (batch + 1) * len(X)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
def test(dataloader, model, loss_fn):
size = len(dataloader.dataset)
num_batches = len(dataloader)
model.eval()
test_loss, correct = 0, 0
with torch.no_grad():
for X, y in dataloader:
X, y = X.to(device), y.to(device)
pred = model(X)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= num_batches
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
這里是第7步,這里需要等一會(huì),一直等到出現(xiàn)【Done!】才結(jié)束。這里等一會(huì)。?
epochs = 5
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train(train_dataloader, model, loss_fn, optimizer)
test(test_dataloader, model, loss_fn)
print("Done!")
7、保存模型
torch.save(model.state_dict(), "/root/model.pth")
print("Saved PyTorch Model State to model.pth")
8、加載模型并預(yù)測
model = NeuralNetwork()
model.load_state_dict(torch.load("/root/model.pth"))
9、預(yù)測模型
classes = [
"包",
"上衣",
"套頭衫",
"連衣裙",
"外套",
"涼鞋",
"襯衫",
"運(yùn)動(dòng)鞋",
"包",
"短靴",
] #定義了一個(gè)包含類別標(biāo)簽的 classes 列表
model.eval() #將 PyTorch 模型設(shè)置為評估模式
x, y = test_data[1][0], test_data[1][1]#測試數(shù)據(jù) test_data 中獲取樣本 分別為圖像數(shù)據(jù)和其真實(shí)標(biāo)簽
with torch.no_grad():
pred = model(x)
predicted, actual = classes[pred[0].argmax(0)], classes[y]#選擇具有最高概率的類別索引
print(f'Predicted: "{predicted}", Actual: "{actual}"') #模型的預(yù)測結(jié)果 predicted 與真實(shí)標(biāo)簽 actual 進(jìn)行比較,并使用 print 函數(shù)輸出這兩個(gè)值。
#輸出圖片信息
# 將 x 轉(zhuǎn)換回圖像格式
image = x.numpy().transpose(1, 2, 0)
# 顯示圖像
plt.figure(figsize=(4, 4))
plt.imshow(image)
# 設(shè)置中文標(biāo)題
print('預(yù)測結(jié)果: "{predicted}", 實(shí)際結(jié)果: "{actual}"'.format(predicted=predicted, actual=actual))
plt.axis('off')
plt.show()
預(yù)測結(jié)果:?
三、使用 JupyterLab 體驗(yàn)使用字符級循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN) 生成姓名
1、數(shù)據(jù)準(zhǔn)備
新建一個(gè)命令窗口,輸入以下命令,下載資源包并解壓
cd /root
wget https://gitee.com/mmliujc/tencent_gpu/raw/master/data.zip
unzip data
2、新建一個(gè)?Notebook?頁面,選擇?Python 3
持續(xù)運(yùn)行以下代碼到步驟8。
from __future__ import unicode_literals, print_function, division
from io import open
import glob
import os
import unicodedata
import string
all_letters = string.ascii_letters + " .,;'-"
n_letters = len(all_letters) + 1 # Plus EOS marker
def findFiles(path): return glob.glob(path)
# Turn a Unicode string to plain ASCII, thanks to https://stackoverflow.com/a/518232/2809427
def unicodeToAscii(s):
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn'
and c in all_letters
)
# Read a file and split into lines
def readLines(filename):
with open(filename, encoding='utf-8') as some_file:
return [unicodeToAscii(line.strip()) for line in some_file]
# Build the category_lines dictionary, a list of lines per category
category_lines = {}
all_categories = []
for filename in findFiles('/root/data/names/*.txt'):
category = os.path.splitext(os.path.basename(filename))[0]
all_categories.append(category)
lines = readLines(filename)
category_lines[category] = lines
n_categories = len(all_categories)
if n_categories == 0:
raise RuntimeError('Data not found. Make sure that you downloaded data '
'from https://download.pytorch.org/tutorial/data.zip and extract it to '
'the current directory.')
print('# categories:', n_categories, all_categories)
print(unicodeToAscii("O'Néàl"))
創(chuàng)建網(wǎng)絡(luò)
import torch
import torch.nn as nn
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(n_categories + input_size + hidden_size, hidden_size)
self.i2o = nn.Linear(n_categories + input_size + hidden_size, output_size)
self.o2o = nn.Linear(hidden_size + output_size, output_size)
self.dropout = nn.Dropout(0.1)
self.softmax = nn.LogSoftmax(dim=1)
def forward(self, category, input, hidden):
input_combined = torch.cat((category, input, hidden), 1)
hidden = self.i2h(input_combined)
output = self.i2o(input_combined)
output_combined = torch.cat((hidden, output), 1)
output = self.o2o(output_combined)
output = self.dropout(output)
output = self.softmax(output)
return output, hidden
def initHidden(self):
return torch.zeros(1, self.hidden_size)
訓(xùn)練網(wǎng)絡(luò)
import random
# Random item from a list
def randomChoice(l):
return l[random.randint(0, len(l) - 1)]
# Get a random category and random line from that category
def randomTrainingPair():
category = randomChoice(all_categories)
line = randomChoice(category_lines[category])
return category, line
# One-hot vector for category
def categoryTensor(category):
li = all_categories.index(category)
tensor = torch.zeros(1, n_categories)
tensor[0][li] = 1
return tensor
# One-hot matrix of first to last letters (not including EOS) for input
def inputTensor(line):
tensor = torch.zeros(len(line), 1, n_letters)
for li in range(len(line)):
letter = line[li]
tensor[li][0][all_letters.find(letter)] = 1
return tensor
# ``LongTensor`` of second letter to end (EOS) for target
def targetTensor(line):
letter_indexes = [all_letters.find(line[li]) for li in range(1, len(line))]
letter_indexes.append(n_letters - 1) # EOS
return torch.LongTensor(letter_indexes)
# Make category, input, and target tensors from a random category, line pair
def randomTrainingExample():
category, line = randomTrainingPair()
category_tensor = categoryTensor(category)
input_line_tensor = inputTensor(line)
target_line_tensor = targetTensor(line)
return category_tensor, input_line_tensor, target_line_tensor
criterion = nn.NLLLoss()
learning_rate = 0.0005
def train(category_tensor, input_line_tensor, target_line_tensor):
target_line_tensor.unsqueeze_(-1)
hidden = rnn.initHidden()
rnn.zero_grad()
loss = 0
for i in range(input_line_tensor.size(0)):
output, hidden = rnn(category_tensor, input_line_tensor[i], hidden)
l = criterion(output, target_line_tensor[i])
loss += l
loss.backward()
for p in rnn.parameters():
p.data.add_(p.grad.data, alpha=-learning_rate)
return output, loss.item() / input_line_tensor.size(0)
import time
import math
def timeSince(since):
now = time.time()
s = now - since
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
3、第八步驟的代碼
這里需要運(yùn)行的時(shí)間比較長,需要長時(shí)間等待。過程中可以看到顯示,官方提示大概21分鐘。
rnn = RNN(n_letters, 128, n_letters)
n_iters = 100000
print_every = 5000
plot_every = 500
all_losses = []
total_loss = 0 # Reset every ``plot_every`` ``iters``
start = time.time()
for iter in range(1, n_iters + 1):
output, loss = train(*randomTrainingExample())
total_loss += loss
if iter % print_every == 0:
print('%s (%d %d%%) %.4f' % (timeSince(start), iter, iter / n_iters * 100, loss))
if iter % plot_every == 0:
all_losses.append(total_loss / plot_every)
total_loss = 0
持續(xù)顯示過程,注意看顯示是否執(zhí)行。
4、繪制損失
在Notebook中執(zhí)行
import matplotlib.pyplot as plt
plt.figure()
plt.plot(all_losses)
5、網(wǎng)絡(luò)采樣
進(jìn)行采樣時(shí),向網(wǎng)絡(luò)中輸入一個(gè)字母,預(yù)測下一個(gè)字母是什么,并將其作為下一個(gè)輸入的字母,重復(fù)此過程直到遇到 EOS。
創(chuàng)建輸入類別、起始字母和空隱藏狀態(tài)的張量
使用起始字母創(chuàng)建一個(gè)字符串 output_name
在最大輸出長度范圍內(nèi),
將當(dāng)前字母輸入網(wǎng)絡(luò)
從最近輸出中獲取下一個(gè)字母和下一個(gè)隱藏狀態(tài)
如果字母是 EOS,則停止
如果是普通字母,則將其添加到 output_name 中并繼續(xù)
返回最終的姓名
注意: 比起要求輸入一個(gè)起始字母,另一種策略是在訓(xùn)練中加入一個(gè)“字符串起始”的標(biāo)記,并讓網(wǎng)絡(luò)自己選擇起始字母。
max_length = 20
# Sample from a category and starting letter
def sample(category, start_letter='A'):
with torch.no_grad(): # no need to track history in sampling
category_tensor = categoryTensor(category)
input = inputTensor(start_letter)
hidden = rnn.initHidden()
output_name = start_letter
for i in range(max_length):
output, hidden = rnn(category_tensor, input[0], hidden)
topv, topi = output.topk(1)
topi = topi[0][0]
if topi == n_letters - 1:
break
else:
letter = all_letters[topi]
output_name += letter
input = inputTensor(letter)
return output_name
# Get multiple samples from one category and multiple starting letters
def samples(category, start_letters='ABC'):
for start_letter in start_letters:
print(sample(category, start_letter))
samples('Russian', 'RUS')
samples('German', 'GER')
samples('Spanish', 'SPA')
samples('Chinese', 'CHI')
執(zhí)行效果:?
四、使用 JupyterLab 體驗(yàn)視頻摳像神器RobustVideoMatting
1、依賴安裝
克隆gitee
git clone https://gitee.com/ai-toys/RobustVideoMatting
# 輸入你的gitee賬號密碼
cd RobustVideoMatting
克隆后進(jìn)行環(huán)境安裝。
pip install -r requirements_inference.txt
?這里需要等一會(huì),安裝完成后顯示是:有一個(gè)Error沒關(guān)系哦。
2、下載實(shí)驗(yàn)資源
在【RobustVideoMatting】文件夾下上傳【rvm_res.zip】文件。
可以直接下載:【https://download.csdn.net/download/feng8403000/88519620】
單獨(dú)wget也可以
wget https://gitee.com/mmliujc/tencent_gpu/raw/master/rvm_res.zip
下載完成后再【RobustVideoMatting】文件夾下解壓即可。
unzip rvm_res.zip
解壓完畢后我們創(chuàng)建一個(gè)【output】文件夾
mkdir output
?3、運(yùn)行
創(chuàng)建一個(gè)文件,粘貼以下代碼,使用【ctrl+s】保存文件,文件名為【test.py】
import torch
import base64
from model import MattingNetwork
from inference import convert_video
model = MattingNetwork('mobilenetv3').eval().cuda() # 或 "resnet50"
model.load_state_dict(torch.load('rvm_mobilenetv3.pth'))
convert_video(
model, # 模型,可以加載到任何設(shè)備(cpu 或 cuda)
input_source='1917.mp4', # 視頻文件,或圖片序列文件夾
output_type='video', # 可選 "video"(視頻)或 "png_sequence"(PNG 序列)
output_composition='output/com.mp4', # 若導(dǎo)出視頻,提供文件路徑。若導(dǎo)出 PNG 序列,提供文件夾路徑
output_alpha="output/pha.mp4", # [可選項(xiàng)] 輸出透明度預(yù)測
output_foreground="output/fgr.mp4", # [可選項(xiàng)] 輸出前景預(yù)測
output_video_mbps=4, # 若導(dǎo)出視頻,提供視頻碼率
downsample_ratio=None, # 下采樣比,可根據(jù)具體視頻調(diào)節(jié),或 None 選擇自動(dòng)
seq_chunk=12, # 設(shè)置多幀并行計(jì)算
)
保存完畢后在【Terminal】下執(zhí)行【python test.py】
python test.py
別著急,等到完成。生成完成后可以在output中看到:
創(chuàng)建【Notebook】
4、摳圖效果
運(yùn)行以下代碼,如果路徑不對自己改一下。
import torch
import base64
from IPython.display import HTML
outpath = "/root/RobustVideoMatting/output/com.mp4"
mp4 = open(outpath,'rb').read()
data_url = "data:video/mp4;base64," + base64.b64encode(mp4).decode()
HTML("""
<video width=400 controls>
<source src="%s" type="video/mp4">
</video>
""" % data_url)
5、換背景效果
import torch
import base64
from IPython.display import HTML
outpath = "/root/RobustVideoMatting/output/fgr.mp4"
mp4 = open(outpath,'rb').read()
data_url = "data:video/mp4;base64," + base64.b64encode(mp4).decode()
HTML("""
<video width=400 controls>
<source src="%s" type="video/mp4">
</video>
""" % data_url)
Pytorch2.0總結(jié)
這里3個(gè)實(shí)驗(yàn)示例可以幫助大家在預(yù)測、生成姓名、視頻摳像上幫助到大家,上手也是非常的快的,自己搞定后希望能在工作中幫助到到家。
現(xiàn)在還有活動(dòng)呢,下面是活動(dòng)的連接:
騰訊云 HAI 新品公測產(chǎn)品體驗(yàn)地址 :https://cloud.tencent.com/act/pro/hai
騰訊云 HAI 新品公測專題頁地址:https://marketing.csdn.net/p/b18dedb1166a0d94583db1877e49b039
騰訊云 HAI 新品公測活動(dòng)報(bào)名地址:https://jinshuju.net/f/dHxwJ7文章來源:http://www.zghlxwxcb.cn/news/detail-713309.html
希望大家踴躍參加啊。文章來源地址http://www.zghlxwxcb.cn/news/detail-713309.html
到了這里,關(guān)于【騰訊云 HAI域探秘】——自行搭建Stable Diffusion模型服務(wù)用于生成AI圖片 | 自行搭建ChatGL M26BAI模型服務(wù)用于AI對話的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!