ChatYuan - 国内首个开源对话大模型的体验和评测

★★★ 本文源自AI Studio社区精品项目,【点击此处】查看更多精品内容 >>>


国内首个开源对话大模型ChatYuan体验和测试

ChatYuan: 元语功能型对话大模型

这个模型可以用于问答、结合上下文做对话、做各种生成任务,包括创意性写作,也能回答一些像法律、新冠等领域问题。它基于PromptCLUE-large结合数亿条功能对话多轮对话数据进一步训练得到。

PromptCLUE-large在1000亿token中文语料上预训练,累计学习1.5万亿中文token,并且在数百种任务上进行Prompt任务式训练。针对理解类任务,如分类、情感分析、抽取等,可以自定义标签体系;针对多种生成任务,可以进行采样自由生成。

项目github地址:https://github.com/clue-ai/ChatYuan

开源模型的paddle版本地址:https://huggingface.co/ClueAI/ChatYuan-large-v1-paddle

扫码体验或微信搜索小程序“元语智能”

ChatYuan - 国内首个开源对话大模型的体验和评测_第1张图片

# 更新paddlenlp的版本
!pip install --upgrade paddlenlp
import warnings
warnings.filterwarnings('ignore')

1. 下载ChatYuan模型并加载

PaddleNLP2.5.0 新特新之一

HuggingFace 生态联合

PaddleNLP首次和HuggingFace生态联合,支持所有Model和Tokenizer类支持直接从Huggingface Hub下载和上传,开发者可以直接从HuggingFace体验预训练模型效果

  • 所有Model和Tokenizer类支持直接从Huggingface Hub下载和上传
  • Text Summarization, Fill Mask, Dialogue Taskflow支持直接从Huggingface Hub加载, 并且连通HuggingFace Inference API
  • 新增ConversionMixin, bert和gpt模型的from_pretrained 支持直接从Huggingface Hub加载torch权重的模型

1.1 在线加载

直接从hf_hub下载模型,速度有时快有时慢

# 加载模型
from paddlenlp.transformers import AutoTokenizer, T5ForConditionalGeneration

tokenizer = AutoTokenizer.from_pretrained("ClueAI/ChatYuan-large-v1", from_hf_hub=False)
model = T5ForConditionalGeneration.from_pretrained("ClueAI/ChatYuan-large-v1", from_hf_hub=False)
# 这里使用的是paddle的gpu版本,修改colab笔记本设置为gpu,并且使用paddle的gpu版本,推理会更快
def preprocess(text):
  text = text.replace("\n", "\\n").replace("\t", "\\t")
  return text

def postprocess(text):
  return text.replace("\\n", "\n").replace("\\t", "\t")

def answer(text, sample=True, top_p=1, temperature=0.7):
  '''sample:是否抽样。生成任务,可以设置为True;
  top_p:0-1之间,生成的内容越多样'''
  text = preprocess(text)
  encoding = tokenizer(text=[text], truncation=True, padding=True, max_length=768, return_tensors="pd")
  if not sample:
    out = model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_length=512, max_new_tokens=512, num_beams=1, length_penalty=0.4)
  else:
    out = model.generate(**encoding, return_dict_in_generate=True, output_scores=False, max_length=512, max_new_tokens=512, do_sample=True, top_p=top_p, temperature=temperature, no_repeat_ngram_size=3)
  
  out_text = tokenizer.batch_decode(out[0], skip_special_tokens=True)
  
  return postprocess(out_text[0])
print("end...")
end...
input_text= "写一个2023年规划,产品研发部门"
print(f"示例".center(50, "="))
input_text = "用户:" + input_text + "\n小元:"
output_text = answer(input_text, sample=True,top_p=1, temperature=0.7)
print(f"{input_text}{output_text}")
========================示例========================


[2023-01-31 17:47:19,446] [ WARNING] - Accessing `bos_token_id` through `model.bos_token_id` will be deprecated after v2.6.0. Instead, do `model.config.bos_token_id`
[2023-01-31 17:47:19,449] [ WARNING] - Accessing `eos_token_id` through `model.eos_token_id` will be deprecated after v2.6.0. Instead, do `model.config.eos_token_id`
[2023-01-31 17:47:19,452] [ WARNING] - Accessing `pad_token_id` through `model.pad_token_id` will be deprecated after v2.6.0. Instead, do `model.config.pad_token_id`
[2023-01-31 17:47:19,454] [ WARNING] - Accessing `forced_bos_token_id` through `model.forced_bos_token_id` will be deprecated after v2.6.0. Instead, do `model.config.forced_bos_token_id`
[2023-01-31 17:47:19,456] [ WARNING] - Accessing `forced_eos_token_id` through `model.forced_eos_token_id` will be deprecated after v2.6.0. Instead, do `model.config.forced_eos_token_id`
[2023-01-31 17:47:19,458] [ WARNING] - Accessing `decoder_start_token_id` through `model.decoder_start_token_id` will be deprecated after v2.6.0. Instead, do `model.config.decoder_start_token_id`


用户:写一个2023年规划,产品研发部门
小元:2023年产品研发部门发展规划

一、目标

1. 开发新的产品,提高产品的质量,满足客户的需求;

2. 开发新产品,提高产品的性能,满足客户需求;
_
3. 开发新的应用,提高用户的体验,满足市场需求;
二、工作职责

1、 制定产品研发计划,确定研发目标;
2、 制定研发计划,明确研发方向,制定研发流程;
3、 制定开发计划,确保研发计划的执行;
4、 制定技术方案,保证研发成果的可靠性;
5、 制定测试方案,确保测试结果的准确性;
6、 制定培训计划,提高研发人员的专业水平;
7、 制定绩效考核,确保产品研发工作的顺利进行。

三、组织结构

1 部门职责:负责产品研发的组织、协调、实施、监督;
2 部门目标:制定研发目标,确定产品研发方向,确定开发策略,制定开发流程,保证产品研发的顺利进行;
3 部门成员:负责研发计划制定,研发计划实施,研发成果检测,研发人员培训,研发绩效考核;
4 部门组织结构:

部门负责人:负责产品开发,研发技术,研发管理,
from paddlenlp.transformers.t5.tokenizer import T5Tokenizer
from paddlenlp.transformers.t5.modeling import T5ForConditionalGeneration
from paddlenlp.transformers import AutoTokenizer, T5ForConditionalGeneration

tokenizer = T5Tokenizer.from_pretrained("ClueAI/ChatYuan-large-v1", from_hf_hub=False)
model = T5ForConditionalGeneration.from_pretrained("ClueAI/ChatYuan-large-v1", from_hf_hub=False)
[2023-01-31 17:40:39,564] [    INFO] - Already cached /home/aistudio/.paddlenlp/models/ClueAI/ChatYuan-large-v1/spiece.model
[2023-01-31 17:40:39,567] [    INFO] - Downloading https://bj.bcebos.com/paddlenlp/models/community//ClueAI/ChatYuan-large-v1/added_tokens.json and saved to /home/aistudio/.paddlenlp/models/ClueAI/ChatYuan-large-v1
[2023-01-31 17:40:39,635] [ WARNING] - file not exist
[2023-01-31 17:40:39,638] [    INFO] - Already cached /home/aistudio/.paddlenlp/models/ClueAI/ChatYuan-large-v1/special_tokens_map.json
[2023-01-31 17:40:39,640] [    INFO] - Already cached /home/aistudio/.paddlenlp/models/ClueAI/ChatYuan-large-v1/tokenizer_config.json
[2023-01-31 17:40:39,755] [    INFO] - Downloading config.json from https://bj.bcebos.com/paddlenlp/models/community/ClueAI/ChatYuan-large-v1/config.json
100%|██████████| 807/807 [00:00<00:00, 1.17MB/s]
[2023-01-31 17:40:39,847] [    INFO] - loading configuration file /home/aistudio/.paddlenlp/models/ClueAI/ChatYuan-large-v1/config.json
[2023-01-31 17:40:39,850] [    INFO] - Model config T5Config {
  "architectures": [
    "T5ForConditionalGeneration"
  ],
  "d_ff": 2816,
  "d_kv": 64,
  "d_model": 1024,
  "decoder_start_token_id": 0,
  "dense_act_fn": "gelu_new",
  "dropout_rate": 0.1,
  "dtype": "float32",
  "enable_recompute": false,
  "eos_token_id": 1,
  "feed_forward_proj": "gated-gelu",
  "initializer_factor": 1.0,
  "is_encoder_decoder": true,
  "is_gated_act": true,
  "layer_norm_epsilon": 1e-06,
  "model_type": "t5",
  "num_decoder_layers": 24,
  "num_heads": 16,
  "num_layers": 24,
  "output_past": true,
  "pad_token_id": 0,
  "paddlenlp_version": null,
  "relative_attention_max_distance": 128,
  "relative_attention_num_buckets": 32,
  "tie_word_embeddings": false,
  "torch_dtype": "float32",
  "transformers_version": "4.26.0.dev0",
  "use_cache": true,
  "vocab_size": 32128
}

[2023-01-31 17:40:39,914] [    INFO] - Found /home/aistudio/.paddlenlp/models/ClueAI/ChatYuan-large-v1/model_state.pdparams
W0131 17:40:46.686321   272 gpu_resources.cc:61] Please NOTE: device: 0, GPU Compute Capability: 7.0, Driver API Version: 11.2, Runtime API Version: 11.2
W0131 17:40:46.690373   272 gpu_resources.cc:91] device: 0, cuDNN Version: 8.2.
[2023-01-31 17:40:51,346] [    INFO] - All model checkpoint weights were used when initializing T5ForConditionalGeneration.

[2023-01-31 17:40:51,349] [    INFO] - All the weights of T5ForConditionalGeneration were initialized from the model checkpoint at ClueAI/ChatYuan-large-v1.
If your task is similar to the task the model of the checkpoint was trained on, you can already use T5ForConditionalGeneration for predictions without further training.

1.2 离线加载

# 解压从官网下载好的ChatYuan-large-v1-paddle,通过from_pretrained直接加载
!unzip -d ChatYuan-large-v1 /home/aistudio/data/data187227/ChatYuan-large-v1.zip
Archive:  /home/aistudio/data/data187227/ChatYuan-large-v1.zip
replace ChatYuan-large-v1/config.json? [y]es, [n]o, [A]ll, [N]one, [r]ename: ^C
from paddlenlp.transformers.t5.tokenizer import T5Tokenizer
from paddlenlp.transformers.t5.modeling import T5ForConditionalGeneration

tokenizer = T5Tokenizer.from_pretrained("ChatYuan-large-v1")
model = T5ForConditionalGeneration.from_pretrained("ChatYuan-large-v1")

2. 推理函数

model.generate中的参数

import paddle
from paddlenlp.transformers import T5Tokenizer, T5ForConditionalGeneration

# tokenizer = T5Tokenizer.from_pretrained("ChatYuan-large-v1")
# model = T5ForConditionalGeneration.from_pretrained("ChatYuan-large-v1")
model.eval()

def preprocess(text):
  text = text.replace("\n", "\\n").replace("\t", "\\t")
  return text

def postprocess(text):
  return text.replace("\\n", "\n").replace("\\t", "\t")

def answer(text, sample=True, top_p=1, temperature=0.6, num_beams=1, length_penalty=0.0, decode_strategy='sampling'):
  '''
  sample: 是否抽样。生成任务,可以设置为True;
  top_p (float, optional): The cumulative probability for top-p-filtering in the "sampling" strategy. The value should satisfy 0<=top_p<1
  . Default to 1.0, which means no effect.
  temperature (float, optional): The value used to module the next token probabilities in the "sampling" strategy. Default to 1.0, which means no effect.
  decode_strategy (str, optional): The decoding strategy in generation. Currently, there are three decoding strategies supported: "greedy_search", "sampling" and "beam_search". Default to "greedy_search".
  '''
  text = preprocess(text)
  encoding = tokenizer(text=[text], truncation=True, padding=True, max_length=768)
  # if not sample:
  #   out = model.generate(**encoding,
  #                       output_scores=False, 
  #                       max_length=512, 
  #                       num_beams=1, 
  #                       length_penalty=0.6, 
  #                       # use_fast=True
  #                       )
  # else:
  out, _ = model.generate(input_ids=paddle.to_tensor(encoding['input_ids']), 
                          attention_mask=paddle.to_tensor(encoding["attention_mask"]), 
                          max_length= 512, 
                          decode_strategy=decode_strategy,  
                          top_p=top_p, 
                          temperature=temperature,
                          num_beams=num_beams,
                          length_penalty=length_penalty,
                          no_repeat_ngram_size=3, 
                          # use_fast=True
                          )
  out_text = tokenizer.batch_decode(out.numpy(), skip_special_tokens=True)
  return postprocess(out_text[0])
print("end...")
end...

3. Github Demo 复现

首先,测试是否可以跑通Github上的Demo示例,

下方代码在原有的代码基础上增加了响应时间的测试代码。

3.1 问答、写作与功能型助手

import time
input_text0 = "帮我写一个请假条,我因为新冠不舒服,需要请假3天,请领导批准"
input_text1 = "你能干什么"
input_text2 = "写一封英文商务邮件给英国客户,表达因为物流延误,不能如期到达,我们可以赔偿贵公司所有损失"
input_text3 = "写一个文章,题目是未来城市"
input_text4 = "写一个诗歌,关于冬天"
input_list = [input_text0, input_text1, input_text2, input_text3, input_text4]
for i, input_text in enumerate(input_list):
  start = time.clock()#开始时间
  input_text = "用户:" + input_text + "\n\n小元:"
  print(f"示例{i}".center(50, "="))
  output_text = answer(input_text)
  print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
=======================示例0========================
用户:帮我写一个请假条,我因为新冠不舒服,需要请假3天,请领导批准

小元:尊敬的领导:

您好!

我是xxx,因为最近新冠肺炎疫情,感到不适,所以请求请假3天,时间为3天。非常感谢您的批准。

期待您的回复,谢谢!
 

此致 
_

(你的名字)

推理耗时:5.352615 s
=======================示例1========================
用户:你能干什么

小元:您好!我是元语AI。我可以回答您的问题、写文章、写作业、翻译,对于一些法律等领域的问题我也可以给你提供信息。

推理耗时:2.48283 s
=======================示例2========================
用户:写一封英文商务邮件给英国客户,表达因为物流延误,不能如期到达,我们可以赔偿贵公司所有损失

小元:Dear [Name],

Thank you for your delayed arrival from the UK. We are very appreciated that we can offer you compensation for all the losses you have made due to the delays in your logistics.

We understand that logging delaies are mostly unreliable and we will offer compenses for any loss we have to offer.
	We also approach you for our understanding that delaY could not be arrived as soon as possible.
 We will provide our best solutions for your loss and please respect our products as much as the time being.
 Thanks for the details we make in the future.
 [Your name] 

Checking for

推理耗时:18.676509000000003 s
=======================示例3========================
用户:写一个文章,题目是未来城市

小元:未来城市的崛起,将给人们带来极大的便利。

未来城市将是一个充满创新的城市,它将采用新技术,创造出更先进的城市。城市将拥有更多智能设施,如自动驾驶汽车、无人驾驶汽车、智能建筑、自动零售店等,这些设施将为人们提供更多便利。与此同时,城市还将拥有更先进的交通系统,让人们出行更加便利。此外,随着科技的发展,城市中的基础设施也将更加完善,为人们的生活提供更多保障。
据悉,未来城市还拥有更智能的交通系统、更智能的城市自动化系统、更加智能的能源系统,以及更加智能的文化系统。这些技术将为城市提供更多的便利,为人们的出行带来更多便利,也为城市的发展带来新的希望。
总之,未来城市的兴起,将为人民带来更多的便利和机遇,使人们的生活质量得到提升,推动城市的发展。

推理耗时:12.748275 s
=======================示例4========================
import time
input_text5 = "从南京到上海的路线"
input_text6 = "学前教育专业岗位实习中,在学生方面会存在问题,请提出改进措施。800字"
input_text7 = "根据标题生成文章:标题:屈臣氏里的化妆品到底怎么样?正文:化妆品,要讲究科学运用,合理搭配。屈臣氏起码是正品连锁店。请继续后面的文字。"
input_text8 = "帮我对比几款GPU,列出详细参数对比,并且给出最终结论"
input_list = [input_text5, input_text6, input_text7, input_text8]
for i, input_text in enumerate(input_list):
    start = time.clock()#开始时间
    input_text = "用户:" + input_text + "\n\n小元:"
    print(f"示例{i}".center(50, "="))
    output_text = answer(input_text)
    print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
=======================示例0========================
用户:从南京到上海的路线
小元:1、从南京出发,乘坐高铁,从南京南站出发,乘坐高铁,到达上海。

2、从南京乘坐高铁,到达上海,然后乘坐地铁,换乘地铁,到达上海,这样就可以到达上海了。

推理耗时:3.808785000000057 s
=======================示例1========================
用户:学前教育专业岗位实习中,在学生方面会存在问题,请提出改进措施。800字
小元:在学前教育专业岗位实习中,学生可能会存在一些问题,这些问题可能会影响学生的实习效果,甚至会影响到学生的专业知识学习。对此,我们必须采取一些改进措施,以期改善这些问题,提高学生的学习效果。

首先,要增强学生的责任心,让学生养成良好的学习习惯,认真学习专业知识,尊重老师,虚心学习,并且注重学生的知识积累。

其次,要加强学生的认知能力,让学生认识到学前教育专业的重要性,让学生能够更好地理解学前教育专业,学习学前教育专业知识,提高学生的实践能力。

最后,要加强学生的职业意识,让学生能够更好地了解学前教育专业,了解学前教育专业的发展,使学生能够更好地适应学前教育专业的发展,提高学生的职业素养。

总之,在学前教育专业岗位实习中,我们必须加强学生的能力,提高学生的职业素养,从而提高学生的实习效果。

推理耗时:13.742045000000076 s
=======================示例2========================
用户:根据标题生成文章:标题:屈臣氏里的化妆品到底怎么样?正文:化妆品,要讲究科学运用,合理搭配。屈臣氏起码是正品连锁店。请继续后面的文字。
小元:屈臣氏里的化妆品到底怎么样?屈臣氏里有个化妆品专区,里面东西很多,有化妆品,护肤品,彩妆,香水,护发素,发膜,护肤产品,药妆产品,眼霜,润肤露,眼霜,精华素,面膜,眼霜,面膜,眼霜,眼霜,面膜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,眼霜,

推理耗时:21.125676 s
=======================示例3========================
用户:帮我对比几款GPU,列出详细参数对比,并且给出最终结论
小元:1. Radeon HD 7770 AMD HD 7700 : 8核心,8线程,8G显存,NVIDIA GeForce GTX 1060 Ti : 8核心,8线程,8G显存,NVIDIA GeForce GTX 1060 Ti : 8核心,8线程,8G显存,NVIDIA GeForce GTX 1060 Ti : 8核心,8线程,8G显存,NVIDIA GeForce GTX 1060 Ti : 8核心,8线程,8G显存,NVIDIA GeForce GTX 1060 Ti : 8核心,8线程,8G显存,NVIDIA GeForce GTX 1060 Ti : 8核心,8线程,8G显存,NVIDIA GeForce GTX 1060 Ti : 8核心,8线程,8G显存,NVIDIA GeForce GTX 1060 Ti : 8核心,8线程

推理耗时:20.885972000000038 s

根据上述Demo的展示,可以发现YuanChat可以较好地完成一些任务,但仍然存在一些问题,例如回答会重复一遍问题、答案出现很多重复。
查阅了一些资料,我们发现文本生成过程中,解码策略对于文本生成用来说是非常重要的。
神经语言模型的基于最大化的解码方法(如 beam search)往往导致退化解,即生成的文本是不自然的,并且常常包含不必要的重复。
现有的方法通过采样或修改训练目标来引入随机性,以降低某些 token 的概率(例如,非似然训练)。
然而,它们往往导致解决方案缺乏连贯性。

对此,我们尝试不同的生成策略,对比Demo中例子生成的区别

import time
input_text3 = "写一个文章,题目是未来城市"
input_text4 = "写一个诗歌,关于冬天"
input_list = [input_text3, input_text4]
for i, input_text in enumerate(input_list):
    start = time.clock()#开始时间
    print(f"示例{i}".center(50, "="))
    input_text = "用户:" + input_text
    print(f"{input_text}")
    output_text1 = answer(input_text,decode_strategy="sampling")
    print(f"\n小元-sampling:{output_text1}")
    output_text2 = answer(input_text,decode_strategy="beam_search",num_beams=3,length_penalty=0.6)
    print(f"\n小元-beamsearch:{output_text2}")
    output_text3 = answer(input_text,decode_strategy="greedy_search",num_beams=1)
    print(f"\n小元-greedysearch:{output_text3}")
    print(f"\n推理耗时:{time.clock()-start} s")   

"""
decode_strategy (str, optional) -- The decoding strategy in generation. Currently, 
there are three decoding strategies supported: 
"greedy_search", "sampling" and "beam_search". Default to "greedy_search".
"""
=======================示例0========================
用户:写一个文章,题目是未来城市

小元-sampling:未来城市是指未来城市将会以一种更加智能、更加绿色、更加智慧的生活方式为特征。未来城市将是一个更加智能、更加绿色、更加智慧的城市。未来城市会以一种更加智能、更加绿色、更加智慧的生活方式为特征,通过发展智能交通、数字城市、智能生活、智能农业、智能医疗、智能教育、智能医疗等智能技术,实现交通、能源、能源供应、城市管理、能源管理、基础设施、生态环境、城市文明等城市文明的发展。 在城市发展中,智能交通系统将会发挥着越来越重要的作用。将智能交通系统引入城市,将极大地提高城市交通效率,减少交通拥堵,减少机动车辆的数量,减少对交通的干扰,提高城市交通的效率和安全性。智能交通系统将会在城市交通出行中发挥着越来越重要的作用,为人们营造更加安全、更高质量、更快捷、更方便的出行环境。 智能农业将会发挥着越来越重要的作用。未来城市将会以一种更加智能、更加绿色、更加智慧的生活方式为特征,利用现代农业技术,实现农业规模化、现代化、标准化,提高农业生产效率,提高农业的效益,提高农业的经济效益。 数字城市将会发挥越来越重要的作用。利用数字

3.2 多轮对话

input_text = ["你好","新冠什么症状?","可以吃什么药?"]
answer_text = ["您好!我是元语AI。我可以回答您的问题、写文章、写作业、翻译,对于一些法律等领域的问题我也可以给你提供信息", "新冠是指新型冠状病毒,其症状包括发热、干咳、乏力、嗅味觉减退、呼吸困难等。", "根据您提供的病史,目前没有明确的抗新冠病毒的药物,建议您在家进行自我隔离,避免与他人接触,多喝开水,清淡易消化饮食,避免熬夜和过度劳累,适当进行户外活动。"]
context = "\n".join([f"用户:{input_text[i]}\n\n小元:{answer_text[i]}" for i in range(len(input_text))])
print(context)

input_text = "会留下什么后遗症吗?"
print(f"示例".center(50, "="))
input_text = context + "\n用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}")
用户:你好
小元:您好!我是元语AI。我可以回答您的问题、写文章、写作业、翻译,对于一些法律等领域的问题我也可以给你提供信息
用户:新冠什么症状?
小元:新冠是指新型冠状病毒,其症状包括发热、干咳、乏力、嗅味觉减退、呼吸困难等。
用户:可以吃什么药?
小元:根据您提供的病史,目前没有明确的抗新冠病毒的药物,建议您在家进行自我隔离,避免与他人接触,多喝开水,清淡易消化饮食,避免熬夜和过度劳累,适当进行户外活动。
========================示例========================
用户:你好
小元:您好!我是元语AI。我可以回答您的问题、写文章、写作业、翻译,对于一些法律等领域的问题我也可以给你提供信息
用户:新冠什么症状?
小元:新冠是指新型冠状病毒,其症状包括发热、干咳、乏力、嗅味觉减退、呼吸困难等。
用户:可以吃什么药?
小元:根据您提供的病史,目前没有明确的抗新冠病毒的药物,建议您在家进行自我隔离,避免与他人接触,多喝开水,清淡易消化饮食,避免熬夜和过度劳累,适当进行户外活动。
用户:会留下什么后遗症吗?
小元:目前没有发现新冠病毒的后遗症,但是有少数人可能会出现咳嗽、发热、乏力、呼吸困难等。

4. ChatYuan模型测试

参考 普通NLP科研人员对ChatGPT的一些思考的文章对ChatYuan模型做一些测试

4.1 关键信息抽取(NER、事件抽取、关键词提取)

4.1.1 药物NER

# 药物NER
start = time.clock() #开始时间
input_text = """帮我从下面的段落里,抽取出药物相关的名词:19世纪以前的药学作为商品学的一个分支学科,研究的对象是一些天然来源的药物, 直到19世纪开始人们从一些天然药物中陆续分离出一些具有生理活性的化学物质(从鸦片中分离出镇痛药吗啡、从颠茄中分离出抗胆碱药阿托品、从金鸡纳树皮中分离出抗疟药奎宁等),以药物分子为主要研究对象的药物化学开始从原来的药物学中独立出来成为一个独立的学科。
"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
用户:帮我从下面的段落里,抽取出药物相关的名词:19世纪以前的药学作为商品学的一个分支学科,研究的对象是一些天然来源的药物, 直到19世纪开始人们从一些天然药物中陆续分离出一些具有生理活性的化学物质(从鸦片中分离出镇痛药吗啡、从颠茄中分离出抗胆碱药阿托品、从金鸡纳树皮中分离出抗疟药奎宁等),以药物分子为主要研究对象的药物化学开始从原来的药物学中独立出来成为一个独立的学科。


小元:药物化学开始从原来的药物学中独立出来成为一个独立的学科

推理耗时:1.3085320000000138 s
# 药物NER
start = time.clock() #开始时间
input_text = """19世纪以前的药学作为商品学的一个分支学科,研究的对象是一些天然来源的药物, 直到19世纪开始人们从一些天然药物中陆续分离出一些具有生理活性的化学物质(从鸦片中分离出镇痛药吗啡、从颠茄中分离出抗胆碱药阿托品、从金鸡纳树皮中分离出抗疟药奎宁等),以药物分子为主要研究对象的药物化学开始从原来的药物学中独立出来成为一个独立的学科。
帮我从上面的段落里,抽取出药物相关的名词:"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
用户:19世纪以前的药学作为商品学的一个分支学科,研究的对象是一些天然来源的药物, 直到19世纪开始人们从一些天然药物中陆续分离出一些具有生理活性的化学物质(从鸦片中分离出镇痛药吗啡、从颠茄中分离出抗胆碱药阿托品、从金鸡纳树皮中分离出抗疟药奎宁等),以药物分子为主要研究对象的药物化学开始从原来的药物学中独立出来成为一个独立的学科。
帮我从上面的段落里,抽取出药物相关的名词:

小元:药物分子,药物,药物化学,药物

推理耗时:0.9253470000001016 s

在药物NER识别上发现一个有趣的现象:

1.当问题在材料前面时,YuanChat总是不能记住问题,大部分情况下均给出答非所问的结果。

2.当我们把材料放在前,问题放在后,YuanChat的结果有了明显的改善,每次结果均能给出药物相关的名词。

3.有时输出的药物名词是可能间隔符号的,即输出内容格式并不规范。(增加人工引导后会好很多,例如后面在加句话“并以有序列表形式输出:”)

对比下来ChatGPT不管是问题在前或问题在后都能准确地抓住问题信息并格式规范地作答。

猜测是目前YuanChat目前训练的标注样本有所不同。

答案是引导大模型智能的技术

4.1.2 关键词抽取

# 关键词抽取 - 中文
start = time.clock() #开始时间
input_text = """19世纪以前的药学作为商品学的一个分支学科,研究的对象是一些天然来源的药物, 直到19世纪开始人们从一些天然药物中陆续分离出一些具有生理活性的化学物质(从鸦片中分离出镇痛药吗啡、从颠茄中分离出抗胆碱药阿托品、从金鸡纳树皮中分离出抗疟药奎宁等),以药物分子为主要研究对象的药物化学开始从原来的药物学中独立出来成为一个独立的学科。
请帮我从上文中抽取出十个关键词。
"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
用户:19世纪以前的药学作为商品学的一个分支学科,研究的对象是一些天然来源的药物, 直到19世纪开始人们从一些天然药物中陆续分离出一些具有生理活性的化学物质(从鸦片中分离出镇痛药吗啡、从颠茄中分离出抗胆碱药阿托品、从金鸡纳树皮中分离出抗疟药奎宁等),以药物分子为主要研究对象的药物化学开始从原来的药物学中独立出来成为一个独立的学科。
请帮我从上文中抽取出十个关键词。


小元:药物分子,药物化学,药物学,生理学,奎宁,奎宁,阿托品,奎宁,药物分子,药物学

推理耗时:2.6197290000000066 s
# 关键词抽取 - 英文
start = time.clock() #开始时间
input_text = """"
This paper describes our winning system on SemEval 2022 Task 7: Identifying Plausible Clarifications of Implicit and Underspecified Phrases in Instructional Texts. A replaced token detection pre-trained model is utilized with minorly different task-specific heads for SubTask-A: Multi-class Classification and SubTask-B: Ranking. Incorporating a pattern-aware ensemble method, our system achieves a 68.90% accuracy score and 0.8070 spearman's rank correlation score surpassing the 2nd place with a large margin by 2.7 and 2.2 percent points for SubTask-A and SubTask-B, respectively. Our approach is simple and easy to implement, and we conducted ablation studies and qualitative and quantitative analyses for the working strategies used in our system.
Can you help me to extract 10 keywords from the above text.
"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  

用户:"
This paper describes our winning system on SemEval 2022 Task 7: Identifying Plausible Clarifications of Implicit and Underspecified Phrases in Instructional Texts. A replaced token detection pre-trained model is utilized with minorly different task-specific heads for SubTask-A: Multi-class Classification and SubTask-B: Ranking. Incorporating a pattern-aware ensemble method, our system achieves a 68.90% accuracy score and 0.8070 spearman's rank correlation score surpassing the 2nd place with a large margin by 2.7 and 2.2 percent points for SubTask-A and SubTask-B, respectively. Our approach is simple and easy to implement, and we conducted ablation studies and qualitative and quantitative analyses for the working strategies used in our system.
Can you help me to extract 10 keywords from the above text.


小元:"This paper describes our winning system on SemEval 2022 Task 7: Identifying Plausible Clarifications of Implicit and Underspecified Phrases in Instructional Texts. A replaced token detection pre-trained model is utilized with minorly different task-specific heads for SubTask-A: Multi-class Classification and SubTask-B: Ranking. Incorporating a pattern-aware ensemble method, our system achieves a 68.90% accuracy score and 0.8070 spearman's rank correlation score surpassing the 2nd place with a large margin by 2.7 and 2.2 percent po

推理耗时:20.59976000000006 s

1.中文文本关键词抽取可以胜任,抽取数量也是正确的,只是会出现一些重复抽取的情况,YuanChat有一定的关键词提取能力。

2.英文文本,在多次尝试后没能实现关键词抽取,YuanChat的英文能力略逊。

4.1.3 事件抽取

input_text = []
answer_text = []
while True:
    context = "\n".join([f"用户:{input_text[i]}\n\n小元:{answer_text[i]}" for i in range(len(input_text))])
    user_input = input("用户: ")
    if user_input == "end":
        break
    input_text.append(user_input)
    user_input = context + "\n用户:" + user_input + "\n\n小元:"
    output_text = answer(user_input)
    answer_text.append(output_text)
    print(f"小元: {output_text}")
    print(f"示例".center(50, "="))
用户:  王二麻子昨天在东北偷了一辆自行车,当天晚上就被警察给逮捕了。请对上面的句子做事件抽取,并以有序列表展示。


小元: 王二麻子昨天在东北偷了一辆自行车,当天晚上就被警察逮捕了。

序号 事件 人物 事件 1 王二麻子昨天在东北偷了一辆自行车
2 王二麻子当天晚上就被警察逮捕
3 王二麻子偷自行车的地点
4 王二麻子被捕的原因是
5 警察逮捕了他
========================示例========================


用户:  王二麻子为什么被逮捕?


小元: 王二麻子被抓的原因可能是他偷的自行车价值比较大,警察怀疑他盗窃自行车,所以就逮捕了他。
========================示例========================


用户:  王二麻子在哪里偷的自行车?


小元: 王二麻子在东北偷的自行车,地点是在东北的一个小山村。
========================示例========================


用户:  地点确实是在东北,没提到小山村呀,为什么多加一个小山村呢?


小元: 因为小山村是东北的一个小山村,王二麻子偷的自行车就停在一个小山村的路边。
========================示例========================


用户:  end

事件抽取的效果不错,对于因果回答的格式也有一定的规范性。但仍然难免存在胡编乱造的成分。

4.2 简单推理任务

4.2.1 NLI任务

#  NLI任务
start = time.clock() #开始时间
input_text = """做一个自然语言推断任务:
1.我在武汉读书
2.我在中国读书
请问第一个句子,能推理出第二个句子吗?
"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
用户:做一个自然语言推断任务:
1.我在武汉读书
2.我在中国读书
请问第一个句子,能推理出第二个句子吗?


小元:不能。第一个句子指的是我在中国读书,第二个句子指的是我在武汉读书。

推理耗时:1.4971859999999424 s
# NLI
start = time.clock() #开始时间
input_text = """做一个自然语言推断任务:
1.我在武汉读书
2.我在中国读书
请问第一个句子,能推理出第二个句子吗?
"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
用户:做一个自然语言推断任务:
1.我在武汉读书
2.我在中国读书
请问第一个句子,能推理出第二个句子吗?


小元:可以的。首先,从第一个句子可以推理出第二个句子:我在武汉读书。其次,从第二个句子可以推理出第三个句子:我在中国读书。

推理耗时:2.8685749999999643 s

简单的NLI任务虽然判断正确,但解释不行

4.2.2 数学推理

# NLI
start = time.clock() #开始时间
input_text = """操场一圈1000米,甲走路的速度是1m/s,乙同学的速度是0.5m/s,两个人从同一个起点出发,向相反方向走,请问他们出发后过多久第二次相遇?
"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
用户:操场一圈1000米,甲走路的速度是1m/s,乙同学的速度是0.5m/s,两个人从同一个起点出发,向相反方向走,请问他们出发后过多久第二次相遇?


小元:那么他们出发后过多久第二次相遇呢?答案是:10分钟。

推理耗时:1.6905409999999392 s

经过多次尝试,部分结果存在公式计算,但未能有正确的计算步骤和答案

# NLI
start = time.clock() #开始时间
input_text = """如果鲁迅先生还活着,他现在多少岁了?
"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
用户:如果鲁迅先生还活着,他现在多少岁了?


小元:鲁迅先生70岁

推理耗时:0.6476829999999154 s

经过多次尝试,YuanChat推理能力比较弱,一是给出的答案千奇百怪,二是很少给出推理过程和解释

4.3 写作辅助

# 写作
start = time.clock() #开始时间
input_text = """王子、打篮球、帅气、偶像、背带裤。请帮我用上面几个关键词,造个句
"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
用户:王子、打篮球、帅气、偶像、背带裤
请帮我用上面几个关键词,造个句


小元:他是我心中的王子,他很帅气,他是我偶像,他穿着背带裤打篮球。

推理耗时:2.0538980000001175 s
input_text = []
answer_text = []
while True:
    context = "\n".join([f"用户:{input_text[i]}\n\n小元:{answer_text[i]}" for i in range(len(input_text))])
    user_input = input("用户: ")
    if user_input == "end":
        break
    input_text.append(user_input)
    user_input = context + "\n用户:" + user_input + "\n\n小元:"
    output_text = answer(user_input)
    answer_text.append(output_text)
    print(f"小元: {output_text}")
    print(f"示例".center(50, "="))
用户:  王子、打篮球、帅气、偶像、背带裤。请帮我用上面几个关键词,造个句


小元: 背带裤是偶像王子的标配,他打篮球的样子帅爆了!
========================示例========================


用户:  帮我多写一些细节。


小元: 王子穿着背带裤打篮球的样子帅爆了,他帅气的外表和打篮球的样子都吸引了我的注意力。
========================示例========================


用户:  太少了,写200字


小元: 王子穿着背带裤打篮球的样子帅爆了,他帅气的外表和打篮球的样子都吸引了我的注意力。
========================示例========================


用户:  多写一点,写到200字


小元: 王子穿着背带裤打篮球的样子帅爆了,他帅气的外表和打篮球的样子都吸引了我的注意力。
========================示例========================


用户:  end
# 写作
start = time.clock() #开始时间
input_text = """酸菜鱼怎么做?
"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
用户:酸菜鱼怎么做?


小元:酸菜鱼的做法步骤:1.准备食材。2.鱼切小块,加料酒,盐,淀粉,淀粉水,腌制半小时以上。3.酸菜切条。4.锅烧热,倒入油,下入鱼炸至金黄色,捞出控油。5.锅中留底油,下入酸菜条翻炒。6.放入鱼片,翻炒。7.加入料酒,盐,糖,醋,味精,鸡精。8.出锅装盘。

推理耗时:7.845639000000119 s
# 写作
start = time.clock() #开始时间
input_text = """法语、德语和西班牙语哪个更难学?给出理由。
"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
用户:法语、德语和西班牙语哪个更难学?给出理由。


小元:法语德语西班牙语都是比较难学的,因为它们都是属于交际语言,需要在社交场合中使用。它们都有一定的语法,需要学习者掌握一定的语法知识。例如,西班牙语的语法包括动词,名词,形容词和副词,而法语的语法包括名词,动词,形容词和副词,德语的语法包括动词,名词,形容词和副词,法语的语法类似于汉语的语法,德语的语法类似于汉语的语法。

推理耗时:7.959870999999794 s
# 写作
start = time.clock() #开始时间
input_text = """请用python程序绘制一个爱心。
"""
input_text = "用户:" + input_text + "\n\n小元:"
output_text = answer(input_text)
print(f"{input_text}{output_text}\n\n推理耗时:{time.clock()-start} s")  
用户:请用python程序绘制一个爱心。


小元:def __init__(self):
	self._ax = None
	self._height = 0
	self._width = 0
	self._color = []
	self._ax.plot([], [], 'g')
	self._ax.plot([], [], 'o')
	self._height = height
	self._width = width
	self._color = []
	self._ax.set_xlabel('Heartbeat')
	self._ax.set_ylabel('Hearthbeat')
	self._height = height
	self._center = True
	self._pen = None
	self._pix

推理耗时:20.479966999999988 s
self._ax.plot([], [], 'o')
	self._height = height
	self._width = width
	self._color = []
	self._ax.set_xlabel('Heartbeat')
	self._ax.set_ylabel('Hearthbeat')
	self._height = height
	self._center = True
	self._pen = None
	self._pix

推理耗时:20.479966999999988 s

官方说在代码生成上YuanChat还是比较弱的,并没有喂很多的标注数据

你可能感兴趣的:(python,人工智能,开发语言)