
使用简易的Python代码让开源模型ChatGLM与自己聊天
如何让ChatGLM稍微跑起来。
·
一、检查运行环境
1.确认是否安装pytorch GPU版
2.确认自己的显卡是(NVIDIA显卡)N卡,且有12GB或者以上的显存
3.确认下载好ChatGLM运行环境
这是清华大学的开源文字生成对话模型下载地址,Hugging Face社区
https://huggingface.co/THUDM/chatglm2-6b
这是该模型的Demo脚本下载地址, GitHub社区
https://github.com/THUDM/ChatGLM2-6B
二、开跑
1.极简版(测试版)
import torch
from transformers import AutoTokenizer, AutoModel
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f'torch.cuda.is_available(): {torch.cuda.is_available()}')
print(f'Using device: {device}')
tokenizer = AutoTokenizer.from_pretrained("E:\Python\ChatGLM\chatglm2-6b", trust_remote_code=True)
model = AutoModel.from_pretrained("E:\Python\ChatGLM\chatglm2-6b", trust_remote_code=True, device='cuda')
model = model.eval()
response, history = model.chat(tokenizer, "你好", history=[])
print(response)
# 你好👋!我是人工智能助手 ChatGLM2-6B,很高兴见到你,欢迎问我任何问题。
print(f'model.device {model.device}')
response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
print(response)
# 晚上睡不着可能会让你感到焦虑或不舒服,但以下是一些可以帮助你入睡的方法:
#
# 1. 制定规律的睡眠时间表:保持规律的睡眠时间表可以帮助你建立健康的睡眠习惯,使你更容易入睡。尽量在每天的相同时间上床,并在同一时间起床。
# 2. 创造一个舒适的睡眠环境:确保睡眠环境舒适,安静,黑暗且温度适宜。可以使用舒适的床上用品,并保持房间通风。
# 3. 放松身心:在睡前做些放松的活动,例如泡个热水澡,听些轻柔的音乐,阅读一些有趣的书籍等,有助于缓解紧张和焦虑,使你更容易入睡。
# 4. 避免饮用含有咖啡因的饮料:咖啡因是一种刺激性物质,会影响你的睡眠质量。尽量避免在睡前饮用含有咖啡因的饮料,例如咖啡,茶和可乐。
# 5. 避免在床上做与睡眠无关的事情:在床上做些与睡眠无关的事情,例如看电影,玩游戏或工作等,可能会干扰你的睡眠。
# 6. 尝试呼吸技巧:深呼吸是一种放松技巧,可以帮助你缓解紧张和焦虑,使你更容易入睡。试着慢慢吸气,保持几秒钟,然后缓慢呼气。
#
# 如果这些方法无法帮助你入睡,你可以考虑咨询医生或睡眠专家,寻求进一步的建议。
2.个人修改版
import torch
from transformers import AutoTokenizer, AutoModel
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f'torch.cuda.is_available(): {torch.cuda.is_available()}')
print(f'Using device: {device}')
tokenizer = AutoTokenizer.from_pretrained("E:\\Python\\ChatGLM\\chatglm2-6b", trust_remote_code=True)
model = AutoModel.from_pretrained("E:\\Python\\ChatGLM\\chatglm2-6b", trust_remote_code=True)
model = model.to(device).eval()
history = []
while True:
user_input = input("你: ")
if user_input == "退出":
print("ChatGLM2-6B: 再见!")
break
response, history = model.chat(tokenizer, user_input, history=history)
print("ChatGLM2-6B:", response)

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐


所有评论(0)