开源模型应用落地-qwen模型小试-Qwen1.5-MoE-A2.7B-Chat-快速体验

一、前言

在追求大模型性能"天花板"的今天,算力成本与落地效率的矛盾始终如影随形。如何让大模型既"聪明"又"轻快"?Qwen1.5-MoE-A2.7B-Chat为这个问题提供了一个优秀的解决方案。基于混合专家(MoE)架构,这款仅激活27亿参数的模型,在对话、推理等任务中展现出媲美传统7B模型的性能,堪称大模型领域的"轻量化冠军"。

相关文章:

开源模型应用落地-DeepSeek-R1-Distill-Qwen-7B与vllm实现推理加速的正确姿势(一)

开源模型应用落地-DeepSeek-R1-Distill-Qwen-7B与vllm实现推理加速的正确姿势(二)


二、术语

2.1. MoE**(Mixture of Experts,混合专家模型)**

是一种神经网络架构设计,核心思想是将一个复杂的任务分解为多个子任务,由不同的"专家"(即小型神经网络模块)分别处理,再通过一个"门控网络"(Gating Network)动态选择最相关的专家组合并整合结果。

  • 特点

    • 高效性:仅激活部分专家(如每次推理仅调用2-4个专家),大幅减少计算量。

    • 可扩展性:通过增加专家数量(而非单个模型的深度)提升模型容量,适合构建大模型。

    • 灵活路由:门控网络根据输入内容动态分配任务,提升对多样化数据的适应性。

2.2. Qwen1.5-MoE-A2.7B

Qwen1.5-MoE-A2.7B 是阿里通义千问团队推出的首个开源 MoE(混合专家)模型。总参数量为 143 亿,但每次推理只激活 27 亿参数,在与顶尖 70 亿参数模型如 Mistral 7B、Qwen1.5-7B 等的对比中,能取得相当的性能,同时训练成本降低了 75%,推理速度相比 Qwen1.5-7B 提高了约 1.74 倍。

**2.3.**GPTQ 量化技术

是一种用于对已经训练好的模型进行量化的方法。它可以在几乎不损失模型性能的前提下,将模型的参数数据类型从较高精度(如 FP32、FP16)转换为较低精度(如 Int8、Int4 等),从而大大减少模型所占用的存储空间和计算资源,同时也能提高模型的推理速度。

**2.4.**Qwen1.5-MoE-A2.7B-GPTQ-Int4

是基于 Qwen1.5-MoE-A2.7B 模型经过 GPTQ 量化技术处理并将数据类型转换为 Int4 的版本。


三、前置条件

3.1. 基础环境

1. 操作系统:centos7

2. NVIDIA Tesla V100 32GB CUDA Version: 12.2

3.2. 下载模型

huggingface:

https://huggingface.co/Qwen/Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4/tree/main

ModelScope:

魔搭社区汇聚各领域最先进的机器学习模型,提供模型探索体验、推理、训练、部署和应用的一站式服务。https://www.modelscope.cn/models/Qwen/Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4/files

按需选择SDK或者Git方式下载

使用git方式下载示例:

 git-lfs clone https://www.modelscope.cn/Qwen/Qwen1.5-MoE-A2.7B-Chat-GPTQ-Int4.git

3.3. 创建虚拟环境

bash 复制代码
conda create --name qwen2.5 python=3.10
conda activate qwen2.5

3.4. 安装依赖库

bash 复制代码
pip install transformers torch accelerate
pip install optimum auto-gptq

依赖库列表:

python 复制代码
(base) [root@gpu ~]# conda activate moe
(moe) [root@gpu ~]# pip list
Package                  Version
------------------------ -----------
accelerate               1.3.0
aiohappyeyeballs         2.4.6
aiohttp                  3.11.12
aiosignal                1.3.2
async-timeout            5.0.1
attrs                    25.1.0
auto_gptq                0.7.1
certifi                  2025.1.31
charset-normalizer       3.4.1
datasets                 3.2.0
dill                     0.3.8
filelock                 3.17.0
frozenlist               1.5.0
fsspec                   2024.9.0
gekko                    1.2.1
huggingface-hub          0.28.1
idna                     3.10
Jinja2                   3.1.5
MarkupSafe               3.0.2
mpmath                   1.3.0
multidict                6.1.0
multiprocess             0.70.16
networkx                 3.4.2
numpy                    2.2.2
nvidia-cublas-cu12       12.4.5.8
nvidia-cuda-cupti-cu12   12.4.127
nvidia-cuda-nvrtc-cu12   12.4.127
nvidia-cuda-runtime-cu12 12.4.127
nvidia-cudnn-cu12        9.1.0.70
nvidia-cufft-cu12        11.2.1.3
nvidia-curand-cu12       10.3.5.147
nvidia-cusolver-cu12     11.6.1.9
nvidia-cusparse-cu12     12.3.1.170
nvidia-cusparselt-cu12   0.6.2
nvidia-nccl-cu12         2.21.5
nvidia-nvjitlink-cu12    12.4.127
nvidia-nvtx-cu12         12.4.127
optimum                  1.24.0
packaging                24.2
pandas                   2.2.3
peft                     0.14.0
pip                      25.0
propcache                0.2.1
psutil                   6.1.1
pyarrow                  19.0.0
python-dateutil          2.9.0.post0
pytz                     2025.1
PyYAML                   6.0.2
regex                    2024.11.6
requests                 2.32.3
rouge                    1.0.1
safetensors              0.5.2
sentencepiece            0.2.0
setuptools               75.8.0
six                      1.17.0
sympy                    1.13.1
tokenizers               0.21.0
torch                    2.6.0
tqdm                     4.67.1
transformers             4.48.3
triton                   3.2.0
typing_extensions        4.12.2
tzdata                   2025.1
urllib3                  2.3.0
wheel                    0.45.1
xxhash                   3.5.0
yarl                     1.18.3

四、技术实现

4.1. 非流式输出

python 复制代码
import traceback

from threading import Thread
from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
from transformers import GenerationConfig
from transformers import TextIteratorStreamer
import time
import torch

modelPath = "/data/model/qwen1.5-moe-a2.7b-chat-gptq-int4"


def generate(model,tokenizer,system,message,history):
    try:
        # assistant
        messages = [
            {"role": "system", "content": system},
        ]
        if len(history) > 0 :
            for his in history:
                user = his[0]
                assistant = his[1]

                user_obj = {"role": "user", "content": user}
                assistant_obj = {"role": "assistant", "content": assistant}

                messages.append(user_obj)
                messages.append(assistant_obj)

        messages.append({"role": "user", "content": message})

        print(messages)

        text = tokenizer.apply_chat_template(
            messages,
            tokenize=False,
            add_generation_prompt=True
        )
        model_inputs = tokenizer([text], return_tensors="pt").to('cuda')

        generated_ids = model.generate(
            model_inputs.input_ids
        )

        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]
        return response
    except Exception:
        traceback.print_exc()

def loadTokenizer():
    tokenizer = AutoTokenizer.from_pretrained(modelPath)
    return tokenizer


def loadModel(config):
    model = AutoModelForCausalLM.from_pretrained(modelPath, torch_dtype="auto",device_map="auto")
    model.generation_config = config
    return model

if __name__ == '__main__':
    config = GenerationConfig.from_pretrained(modelPath, top_p=0.9, temperature=0.45, repetition_penalty=1.1, do_sample=True, max_new_tokens=8192)
    tokenizer = loadTokenizer()
    model = loadModel(config)
    streamer = getStreamer(tokenizer)
    start_time = time.time()

    system = "You are a helpful assistant."
    message = "如果所有的猫都是动物,并且某些动物是狗,那么可以推导出哪些结论?"
    history = []

    response = generate(model, tokenizer, system, message,history)
    print(f"response: {response}")
    end_time = time.time()
    print("执行耗时: {:.2f}秒".format(end_time - start_time))

调用结果:

**1) 逻辑推理:**如果所有的猫都是动物,并且某些动物是狗,那么可以推导出哪些结论?

2) 数学应用: 如果一个三角形的两边长度分别为6和8,夹角为60度,请计算这个三角形的面积。

**3) 语言理解:**请将以下句子转换为被动语态: "The chef cooked a delicious meal."

**4) 数列推理:**给定数列:2, 4, 8, 16, ...,请找出数列的通项公式,并计算第10项的值。

**5) 推理与假设:**如果一个人每周慢跑三次,每次30分钟,他们每周能够燃烧多少卡路里?假设每分钟燃烧10卡路里,回答时请附上推理过程。

4.2. 流式输出

python 复制代码
import traceback

from threading import Thread
from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
from transformers import GenerationConfig
from transformers import TextIteratorStreamer
import time
import torch

modelPath = "/data/model/qwen1.5-moe-a2.7b-chat-gptq-int4"

def chat(model,tokenizer,streamer,system,message,history):
    try:
        # assistant
        messages = [
            {"role": "system", "content": system},
        ]
        if len(history) > 0:
            for his in history:
                user = his[0]
                assistant = his[1]

                user_obj = {"role": "user", "content": user}
                assistant_obj = {"role": "assistant", "content": assistant}

                messages.append(user_obj)
                messages.append(assistant_obj)

        messages.append( {"role": "user", "content": message})

        print(messages)

        text = tokenizer.apply_chat_template(
            messages,
            tokenize=False,
            add_generation_prompt=True,
            return_tensors="pt"
        )


        model_inputs = tokenizer([text], return_tensors="pt").to('cuda')

        generation_kwargs = dict(inputs=model_inputs.input_ids, streamer=streamer)

        thread = Thread(target=model.generate, kwargs=generation_kwargs)

        thread.start()

        for new_text in streamer:
            yield new_text


    except Exception:
        traceback.print_exc()


def loadTokenizer():
    tokenizer = AutoTokenizer.from_pretrained(modelPath)
    return tokenizer

def getStreamer(tokenizer):
    streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
    return streamer

def loadModel(config):
    model = AutoModelForCausalLM.from_pretrained(modelPath, torch_dtype="auto",device_map="auto")
    model.generation_config = config
    return model

if __name__ == '__main__':
    config = GenerationConfig.from_pretrained(modelPath, top_p=0.9, temperature=0.45, repetition_penalty=1.1, do_sample=True, max_new_tokens=8192)
    tokenizer = loadTokenizer()
    model = loadModel(config)
    streamer = getStreamer(tokenizer)
    start_time = time.time()

    system = "You are a helpful assistant."
    message = "如果所有的猫都是动物,并且某些动物是狗,那么可以推导出哪些结论?"
    history = []

    response = chat(model,tokenizer,streamer,system,message,history)

    for r in response:
        print(r, end='', flush=True)

    end_time = time.time()
    print("执行耗时: {:.2f}秒".format(end_time-start_time))

调用结果:

相关推荐
是小果果蛋儿啊4 小时前
2024 CyberHost 语音+图像-视频
人工智能·深度学习·音视频
TangGeeA4 小时前
对gru的理解
rnn·深度学习·gru
云边有个稻草人6 小时前
AI语言模型的技术之争:DeepSeek与ChatGPT的架构与训练揭秘
人工智能·算法·语言模型·chatgpt·deepseek
Jurio.7 小时前
【论文笔记】Are Self-Attentions Effective for Time Series Forecasting? (NeurIPS 2024)
论文阅读·人工智能·python·深度学习·自然语言处理·transformer
赵钰老师7 小时前
【大语言模型】最新ChatGPT、DeepSeek等大语言模型助力高效办公、论文与项目撰写、数据分析、机器学习与深度学习建模等科研应用
人工智能·python·深度学习·机器学习·语言模型·chatgpt·数据分析
adaierya8 小时前
简化的动态稀疏视觉Transformer的PyTorch代码
人工智能·深度学习
冰淇淋百宝箱8 小时前
解码DeepSeek家族系列:大语言模型赛道上的黑马传奇
人工智能·语言模型·自然语言处理
湫ccc9 小时前
从0搭建卷积神经网络(CNN)--详细教学
深度学习·神经网络·cnn