大模型配置文件,生成文本长短与停用词介绍

1.一般base模型,普遍都是生成到最大字符max_new_tokens才截止

如上,是base模型的generation_config.json,这些参数用于generate()函数

base模型生成终止符151643,但是没有经过微调,它通常是无法生成151643这个token_id也意味着通常会生成到最大token数max_new_tokens才会强制截断

模型截断判断顺序:

模型推理生成id ---->长度是否等于max_new_tokens ----> 是,则截止;否,继续判断 ----> id是否等于eos_toekn ----> 是,则截止;否,即生成下一个token_id

2.chat模型,生成的最大长度max_new_tokens,但是它会设定终止符提前结束

这里以qwen/Qwen1.5-1.8B-Chat-AWQ量化版本为例

生成配置文件中,可以看到模型在generate()使用的一些配置参数,停用词的变量名为eos_token,在qwen中,停用词的设置为151645和151643。我们看看这两个token_id分别表示什么

tokenizer.convert_ids_to_tokens(151645)    # <|im_end|>
tokenizer.convert_ids_to_tokens(151643)    # <|endoftext|>
len(tokenizer)                             # 151646
# 注意:在默认配置中,还将pad_token这个变量也对应到151643这个token_id上
# tokenizer中所有词汇【词汇表+特殊词汇】共151646个,因此<|im_end|>对应的是最后一个特殊词汇

----------------------------------------- 验证模型生成结尾的停用词 --------------------------------------

from transformers import AutoModelForCausalLM, AutoTokenizer
device = "cuda" # the device to load the model onto


model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen1.5-1.8B-Chat-AWQ",
    device_map="auto",
    cache_dir='./cache' # cache_dir参数只有transformers库才有效,modelscope无法缓存!
)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen1.5-1.8B-Chat-AWQ",cache_dir='./cache')

prompt = "你是谁,请用十个词介绍?"
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": prompt}
]
text = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(device)

generated_ids = model.generate(
    model_inputs.input_ids,
    max_new_tokens=512,
)
generated_ids = [
    output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
# --------------- decode,省略特殊字符,id转token
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
print('res:',response)
print(generated_ids[0])
print(len(generated_ids[0]))    # token torch.Size([248])
#  [tensor([104198,  67071, 102661,  99718, 100048,   9370,  71304, 105483, 102064,...,   1773, 151645],device='cuda:0')]

文本token长度为248,没有到max_new_tokens就提前终止,因为产生了停用词。跳到最后一个token,可以看到停用词对应151645,即<|im_end|>。前一个1773对应的token是句号。【chat模型中一般不会出现除了<|im_end|>外其他的停用词】

 ----------------------------------------- 替换生成停用词 --------------------------------------

在配置文件中,修改停用词,我们添加上句号的token_id 1773作为停用词。

再次执行运行代码

可以看到,当生成第一个1773作为结尾时,就会停止模型的推理!

# (我记得模型推理时有个参数可以添加停用词的,但是忘了)

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值