作者简介:赵辉,区块链技术专家,精通各种联盟链、公链的底层原理,拥有丰富的区块链应用开发经验。
在之前对 ChatGLM 的搭建部署和测试使用过程中,我对 ChatGLM 和 Langchain 的能力有了初步了解。尽管这些工具已经具备了一定的通用性,但由于本地知识库的效果不理想,我仍然觉得需要为自己定制属于自己的模型和应用。因此,我决定学会基于 Langchain 和模型进行编程,从现在开始着重学习 Langchain 的基础知识和编码,为后续打造自己的贾维斯做知识储备。
目前,基于langchain的中文教程还是比较零散的,这里找到了两个网站教程https://www.langchain.com,https://python.langchain.com.cn/docs/。
学习langchain的第一步,是加载模型,官网给出的示例,都是基于openai,但由于openai属于海外服务,在境内使用有一定的限制,最终还是选择 ChatGLM.
Langchain官网没有关于ChatGLM的教程,那么就从百度或者Github找到相似示例,这里我们可以参考上次搭建的langchain-ChatGLM的源码去着手,分析是怎么加载自己的原型的。
用pycharm打开langchain-ChatGLM的工程,回忆之前配置模型的文件是configs/model_config.py
文件,根据变量llm_model_dict
进行搜索,在models/loader/loader.py
中找到比较接近的代码,代码片段如下:
tokenizer = AutoTokenizer.from_pretrained(self.model_name)
而AutoTokenizer是在transformers中的,参见代码头部引用的依赖:
from transformers import (AutoConfig, AutoModel, AutoModelForCausalLM, AutoTokenizer, LlamaTokenizer)
找到接近的代码,那么就得想下如何编写自己的模型加载代码。直接拷贝工程中的代码不现实,代码量多,其他模块引用复杂,不适合初学者理解学习,那么就得从其他地方下手。这里想到transformers出自huggingface,而且之前chatglm-6b-32k也下载自huggingface。那么应该能从huggingface找到线索,打开huggingface网页,搜索chatglm-6b-32k,得到如下页面:
果然找到了对应的模型加载和使用的代码,对源码进行稍微修改保存到chatglm.py,引用本地下载好的模型,得到代码如下:
from transformers import AutoTokenizer, AutoModel
model_path = "/root/prj/ChatGLM-6B/THUDM/chatglm2-6b-32k"
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModel.from_pretrained(model_path, trust_remote_code=True).half().cuda()
model = model.eval()
response, history = model.chat(tokenizer, "你好", history=[])
print(response)
while True:
test_text = input("Kun Peng:")
if test_text == "exit":
break;
response, history = model.chat(tokenizer, test_text, history=history)
print("AI: " + response)
运行效果如下:
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
上述代码是根据模型创建分词器,
model = AutoModel.from_pretrained(model_path, trust_remote_code=True).half().cuda()
上述代码是初始化模型,AutoModel这是一个通用的模型类,当使用 from_pretrained() 类方法或 from_config() 类方法创建时,它将作为库中基础模型类之一进行实例化。
模型默认使用 model.eval() 进入评估模式(因此,例如,dropout 模块会被停用)。要训练模型,应该首先使用 model.train() 将其设置回训练模式。
response, history = model.chat(tokenizer, "你好", history=[])
上述代码即为第一次发起对话的语句,因此history中没有数据, response则为模型的回复。history为历史对话信息,如果要实现上下文关联,则需要在下次对话时用history的返回结果填充,代码如下:
response, history = model.chat(tokenizer, test_text, history=history)
除了模型通用对话模型,还有一些分类模型,可以用transformers来实现,比如情感分析模型。在huggingface中,找到情感分析模型,用transformers的pipeline加载后,即可使用,代码如下:
from transformers import pipeline
import sys
classifier = pipeline('sentiment-analysis')
while True:
test_text = input("Please input:")
if test_text == "exit":
break;
res = classifier(test_text)
print(res)
运行结果如下图,可以看出分析结果还是比较准确的。情感分类任务,通常为输入一段句子或一段话,返回该段话正向/负向的情感属性,在用户评价,观点抽取,意图识别中往往起到重要作用。
后续将继续输出ChatGLM 开发学习相关的内容,请继续关注。
—扩 展 阅 读—