Qwen2.5 是最新系列的 Qwen 大语言模型。针对 Qwen2.5,我们发布了一系列基础语言模型和指令微调语言模型,参数规模从 0.5B 到 72B 不等。相比 Qwen2,Qwen2.5 带来了以下改进:
本仓库包含经过指令微调的 0.5B Qwen2.5 模型,其具有以下特点:
Qwen2.5 的代码已集成到最新版的 Hugging face transformers 中,建议您使用最新版本的 transformers。
若使用 transformers<4.37.0,您将遇到以下错误:
KeyError: 'qwen2'import argparse
import torch
from openmind import is_torch_npu_available, AutoTokenizer, AutoModelForCausalLM,AutoModel
import time
def mean_pooling(model_output, attention_mask):
token_embeddings = model_output[0] # model_output的第一个元素包含所有token嵌入
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--model_name_or_path",
type=str,
help="Path to model",
default='Qwen/Qwen2.5-0.5B-Instruct',
)
args = parser.parse_args()
return args
def main():
start_time = time.time() # 记录开始时间
args = parse_args()
if args.model_name_or_path:
model_path = args.model_name_or_path
else:
model_path = ""
if is_torch_npu_available():
device = "npu:0"
else:
device='cpu'
# device='cpu'
sentences = ['This is an example sentence', 'Each sentence is converted']
# 从openmind_hub加载模型
tokenizer = AutoTokenizer.from_pretrained(model_path)
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
# tokenizer.pad_token = tokenizer.eos_token
model = AutoModel.from_pretrained(model_path).to(device)
# 对句子进行分词
encoded_input = tokenizer(sentences,return_tensors='pt',padding=True).to(device)
# 计算token嵌入
with torch.no_grad():
model_output = model(**encoded_input)
# 执行池化
sentence_embeddings = mean_pooling(model_output, encoded_input['attention_mask']).to(device)
# 归一化嵌入
# sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
print("Sentence embeddings:")
print(sentence_embeddings)
end_time = time.time() # 记录结束时间
elapsed_time = end_time - start_time # 计算差值
print(f"{device}:Program finished in {elapsed_time:.2f} seconds.") # 打印运行时间
if __name__ == "__main__":
main()这里提供一个使用apply_chat_template的代码片段,向您展示如何加载分词器和模型以及如何生成内容。
from transformers import AutoModelForCausalLM, AutoTokenizer
model_name = "Qwen/Qwen2.5-0.5B-Instruct"
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype="auto",
device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
prompt = "Give me a short introduction to large language model."
messages = [
{"role": "system", "content": "You are Qwen, created by Alibaba Cloud. 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(model.device)
generated_ids = model.generate(
**model_inputs,
max_new_tokens=512
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]详细的评估结果已在本📑 博客中报告。
有关 GPU 内存需求和相应吞吐量,请参见此处的结果。
如果您觉得我们的工作对您有帮助,欢迎引用我们。
@misc{qwen2.5,
title = {Qwen2.5: A Party of Foundation Models},
url = {https://qwenlm.github.io/blog/qwen2.5/},
author = {Qwen Team},
month = {September},
year = {2024}
}
@article{qwen2,
title={Qwen2 Technical Report},
author={An Yang and Baosong Yang and Binyuan Hui and Bo Zheng and Bowen Yu and Chang Zhou and Chengpeng Li and Chengyuan Li and Dayiheng Liu and Fei Huang and Guanting Dong and Haoran Wei and Huan Lin and Jialong Tang and Jialin Wang and Jian Yang and Jianhong Tu and Jianwei Zhang and Jianxin Ma and Jin Xu and Jingren Zhou and Jinze Bai and Jinzheng He and Junyang Lin and Kai Dang and Keming Lu and Keqin Chen and Kexin Yang and Mei Li and Mingfeng Xue and Na Ni and Pei Zhang and Peng Wang and Ru Peng and Rui Men and Ruize Gao and Runji Lin and Shijie Wang and Shuai Bai and Sinan Tan and Tianhang Zhu and Tianhao Li and Tianyu Liu and Wenbin Ge and Xiaodong Deng and Xiaohuan Zhou and Xingzhang Ren and Xinyu Zhang and Xipin Wei and Xuancheng Ren and Yang Fan and Yang Yao and Yichang Zhang and Yu Wan and Yunfei Chu and Yuqiong Liu and Zeyu Cui and Zhenru Zhang and Zhihao Fan},
journal={arXiv preprint arXiv:2407.10671},
year={2024}
}