首先我们还是要让我们的ChatGLM3模型先进行下载
import os
import moxing as mox
#拷贝chatglm3模型到chatglm3-6b目录下
work_dir = '/home/ma-user/work'
obs_path = 'obs://dtse-models/tar-models/chatglm3-6b.tar'
ma_path = os.path.join(work_dir, 'chatglm3-6b.tar')
mox.file.copy(obs_path, ma_path)
mox.file.copy_parallel('obs://modelarts-labs-bj4-v2/course/ModelBox/frpc_linux_amd64', '/home/ma-user/work/frpc_linux_amd64')
对应的我们进行解压
os.chdir(work_dir)
!pwd
!tar -xvf chatglm3-6b.tar
然后我们进行环境配置
我们配置环境为python3.10.10
!/home/ma-user/anaconda3/bin/conda create -n python-3.10.10 python=3.10.10 -y --override-channels --channel https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
!/home/ma-user/anaconda3/envs/python-3.10.10/bin/pip install ipykernel
然后通过Python进行配置
import json
import os
data = {
"display_name": "python-3.10.10",
"env": {
"PATH": "/home/ma-user/anaconda3/envs/python-3.10.10/bin:/home/ma-user/anaconda3/envs/python-3.7.10/bin:/modelarts/authoring/notebook-conda/bin:/opt/conda/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/ma-user/modelarts/ma-cli/bin:/home/ma-user/modelarts/ma-cli/bin:/home/ma-user/anaconda3/envs/PyTorch-1.8/bin"
},
"language": "python",
"argv": [
"/home/ma-user/anaconda3/envs/python-3.10.10/bin/python",
"-m",
"ipykernel",
"-f",
"{connection_file}"
]
}
if not os.path.exists("/home/ma-user/anaconda3/share/jupyter/kernels/python-3.10.10/"):
os.mkdir("/home/ma-user/anaconda3/share/jupyter/kernels/python-3.10.10/")
with open('/home/ma-user/anaconda3/share/jupyter/kernels/python-3.10.10/kernel.json', 'w') as f:
json.dump(data, f, indent=4)
然后我们刷新即可
我们看到我们这个环境变成了python3.10.10就证明我们这个成功了
然后我们进行依赖库安装
!pip install transformers==4.30.2
!pip install sentencepiece==0.1.99
!pip install torch==2.0.1
!pip install gradio==3.39 mdtex2html -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn
!cp /home/ma-user/work/frpc_linux_amd64 /home/ma-user/anaconda3/envs/python-3.10.10/lib/python3.10/site-packages/gradio/frpc_linux_amd64_v0.2
!chmod +x /home/ma-user/anaconda3/envs/python-3.10.10/lib/python3.10/site-packages/gradio/frpc_linux_amd64_v0.2
安装成功以后我们就可以进行模型测试了
然后我们就用最开始的方法进行测试
然后这个结果就是我们想要的
但是有人就会问了这里也没有用到我们要求的这个gradio,首先我们要知道这个是什么,简单的来说这个是个
python库,主要的作用是在我们测试人工智能的时候我们可以不用自己搭建前端,我们可以通过这个库当中的函数进行测试
现在我们就开始使用吧
# 编写Gradio调用函数
import mdtex2html
#将文本中的字符转为网页上可以支持的字符,避免被误认为是HTML标签
def parse_text(text):
lines = text.split("\n")
lines = [line for line in lines if line != ""]
count = 0
for i, line in enumerate(lines):
if "```" in line:
count += 1
items = line.split('`')
if count % 2 == 1:
lines[i] = f'<pre><code class="language-{items[-1]}">'
else:
lines[i] = f'<br></code></pre>'
else:
if i > 0:
if count % 2 == 1:
line = line.replace("`", "\`")
line = line.replace("<", "<")
line = line.replace(">", ">")
line = line.replace(" ", " ")
line = line.replace("*", "*")
line = line.replace("_", "_")
line = line.replace("-", "-")
line = line.replace(".", ".")
line = line.replace("!", "!")
line = line.replace("(", "(")
line = line.replace(")", ")")
line = line.replace("$", "$")
lines[i] = "<br>"+line
text = "".join(lines)
return text
#采用流聊天方式(stream_chat)调用模型,使得生成答案有逐字生成的效果
def predict(input, chatbot, max_length, top_p, temperature, history, past_key_values):
chatbot.append((parse_text(input), parse_text(input)))
for response, history, past_key_values in model.stream_chat(tokenizer, input, history, past_key_values=past_key_values,
return_past_key_values=True,
max_length=max_length, top_p=top_p,
temperature=temperature):
chatbot[-1] = (parse_text(input), parse_text(response))
yield chatbot, history, past_key_values
#去除输入框的内容
def reset_user_input():
return gr.update(value='')
#清除状态
def reset_state():
return [], [], None
#运行Gradio界面,运行成功后点击“Running on public URL”后的网页链接即可体验
import gradio as gr
with gr.Blocks() as demo:
gr.HTML("""<h1 align="center">ChatGLM3-6B</h1>""")
chatbot = gr.Chatbot()
with gr.Row():
with gr.Column(scale=4):
with gr.Column(scale=12):
user_input = gr.Textbox(show_label=False, placeholder="Input...", lines=10,container=False)
with gr.Column(min_width=32, scale=1):
submitBtn = gr.Button("Submit", variant="primary")
with gr.Column(scale=1):
emptyBtn = gr.Button("Clear History")
max_length = gr.Slider(0, 32768, value=8192, step=1.0, label="Maximum length", interactive=True)
top_p = gr.Slider(0, 1, value=0.8, step=0.01, label="Top P", interactive=True)
temperature = gr.Slider(0, 1, value=0.95, step=0.01, label="Temperature", interactive=True)
history = gr.State([])
past_key_values = gr.State(None)
submitBtn.click(predict, [user_input, chatbot, max_length, top_p, temperature, history, past_key_values],
[chatbot, history, past_key_values], show_progress=True)
submitBtn.click(reset_user_input, [], [user_input])
emptyBtn.click(reset_state, outputs=[chatbot, history, past_key_values], show_progress=True)
demo.queue().launch(share=True, inbrowser=True)
这两个代码需要同时进行运行,我的意思是指运行一个以后再运行一个,只有两个都运行成功这个才能显示出gradio界面
然后我们会看到几个链接,如果你的电脑上面运行了gradio第一个链接可以进行点击,否则对应的界面确实加载不出来
于是我们就会点击另一个链接,这个链接你只需要点击即可,不需要运行什么环境
然后我们来看看吧
只需要 我们在input里面输入对应文字就行啦
是不是很牛
希望这篇文章可以对您有所帮助