添加chat_template到gguf模型文件
目前使用的很多gguf模型文件缺少chat_template, 为了更好的使用,需要添加chat_template到gguf模型文件中
查询了gguf-py代码,hack如下
- 需要知道该model的
chat_template
, 以openhermes-2.5-mistral-7b.Q5_K_M.gguf
为例,chat_template
如下
“{% for message in messages %}{ {‘<|im_start|>’ + message[‘role’] + ‘\n’ + message[‘content’] + ‘<|im_end|>’ + ‘\n’}}{% endfor %}{% if add_generation_prompt %}{ { ‘<|im_start|>assistant\n’ }}{% endif %}”
-
查看gguf模型中kv的结构,找到需要插入的位置,确认
chat_template
的bytes的长度,根据model对齐长度,添加空格到chat_template
的bytes的长度 -
构件
chat_template
的bytes,添加到模型文件中 -
重新写入新的gguf文件
代码如下
import struct
import numpy as np
from gguf import GGUFReader, GGUFValueType, GGUF_DEFAULT_ALIGNMENT
# 原始gguf文件路径和新的gguf文件路径
file_path = "../openhermes.gguf"
new_file_path = "../add_chat_model.gguf"
#
reader = GGUFReader(file_path, "r+"<