HuggingFace镜像/Qwen2.5-0.5B-Instruct
模型介绍文件和版本分析
下载使用量0

Qwen2.5-0.5B-Instruct

简介

Qwen2.5 是最新系列的 Qwen 大语言模型。针对 Qwen2.5,我们发布了一系列基础语言模型和指令微调语言模型,参数规模从 0.5B 到 72B 不等。相比 Qwen2,Qwen2.5 带来了以下改进:

  • 知识量显著增加,并且在代码和数学能力上有大幅提升,这得益于我们在这些领域专门训练的专家模型。
  • 在指令遵循、长文本生成(超过 8K tokens)、结构化数据理解(如表格)以及结构化输出生成(尤其是 JSON)方面有显著改进。对系统提示的多样性更具鲁棒性,增强了角色扮演的实现和聊天机器人的条件设置能力。
  • 长上下文支持,最长可达 128K tokens,生成文本长度可达 8K tokens。
  • 多语言支持,覆盖超过 29 种语言,包括中文、英文、法语、西班牙语、葡萄牙语、德语、意大利语、俄语、日语、韩语、越南语、泰语、阿拉伯语等。

本仓库包含经过指令微调的 0.5B Qwen2.5 模型,其具有以下特点:

  • 类型:因果语言模型
  • 训练阶段:预训练与后训练
  • 架构:采用 RoPE、SwiGLU、RMSNorm、Attention QKV 偏置和绑定词嵌入的 transformers
  • 参数数量:0.49B
  • 非嵌入参数数量:0.36B
  • 层数:24
  • 注意力头数量(GQA):Q 为 14 个,KV 为 2 个
  • 上下文长度:完整上下文 32,768 tokens,生成文本 8192 tokens

更多详情,请参考我们的 博客、GitHub 和 文档。

要求

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}
}