在选择好需要微调的一个大语言模型之后。比如chatglm、llama、bloom等,要想使用它,得了解三个方面:输入数据的格式、tokenization、模型的使用方式,需要注意的是不同的 LLM 需要的输入数据格式可能不一样。
指令数据一般由三部分组成:instruction(instruct)、input(query)、output(answer),分别表示提示指令、文本、返回的结果。 构造的时候一般是 instruction 和 input 进行拼接,当然 input 可能是为空的,最终对 output 进行预测。需要注意的是,除了 instruction 之外,可能还有特殊的 prompt,不同模型的 prompt 是不一样的,比如:
PROMPT_DICT = {
"chatglm_input": ("{instruction}{input}"),
"alpaca_input": (
"Below is an instruction that describes a task. "
"Write a response that appropriately completes the request.\n\n"
"### Instruction:\n{instruction}{input}\n\n### Response: "
),
"bloom_input": ("Human: \n{instruction}{input}\n\nAssistant: \n"),
}
这里直接给出代码:
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("model_hub/chatglm-6b", trust_remote_code=True)
text = "世界,你好"
print(tokenizer(text))
print(tokenizer.convert_ids_to_tokens([18060, 12247, 14949]))
print(tokenizer.decode([18060, 12247, 14949]))
# 打印特殊 token
print("BOS token: ", tokenizer.bos_token)
print("EOS token: ", tokenizer.eos_token)
print("PAD token: ", tokenizer.pad_token)
print("UNK token: ", tokenizer.unk_token)
# 打印特殊 token_id
print("BOS token: ", tokenizer.bos_token_id)
print("EOS token: ", tokenizer.eos_token_id)
print("PAD token: ", tokenizer.pad_token_id)
print("UNK token: ", tokenizer.unk_token_id)
print(tokenizer.decode([130004,
67470, 24, 83049, 4, 76699, 24, 83049, 4, 67357,
65065, 24, 83049, 4, 64484, 68137, 63940, 24, 64539,
63972, 4, 69670, 72232, 69023, 24, 83049, 4, 64372,
64149, 24, 83049, 4, 63855, 24, 83049, 130005]))
# 这个是chatglm特有的。
input_ids = tokenizer.build_inputs_with_special_tokens([1], [2])
print(input_ids)
我们要注意看一下特殊标记是否为空,其它的话一些编码、解码、分词、tokenizer(文本)返回什么(input_ids、attention_mask)之类的。可以根据自己的需要进行尝试。
型加载方式的话,一般使用的是 AutoTenizer 和 AutoModelForCausalLM,但有的模型可能有特殊的加载方式,比如LLaMA的加载方式就是:LlamaForCausalLM 和 LlamaTokenizer,。针对于 chatglm 的话,加载方式为:AutoTenizer 和 AutoModel,但需要注意的是其加载的时候设置了 trust_remote_code=True,该参数会根据映射找到真正使用的模型文件。下载好模型权重后,我们可以根据情况先看看效果:
from transformers import AutoTokenizer, AutoModel
tokenizer = AutoTokenizer.from_pretrained("model_hub/chatglm-6b", trust_remote_code=True)
model = AutoModel.from_pretrained("model_hub/chatglm-6b", trust_remote_code=True).half().cuda()
model = model.eval()
response, history = model.chat(tokenizer, "你好", history=[])
print(response)
response, history = model.chat(tokenizer, "晚上睡不着应该怎么办", history=history)
print(response)
可以使用一些其他的库,比如:
需要注意的是, 我们可以把数据拆分为很多小文件放在一个文件夹下,然后遍历文件夹里面的数据,用datasets加载数据并进行并行处理后保存到磁盘上。如果中间发现处理数据有问题的话要先删除掉保存的处理后的数据,再重新进行处理,否则的话就是直接加载保存的处理好的数据。
阅读量:880
点赞量:0
收藏量:0