开源模型应用落地-qwen模型小试-入门篇(三)

一、前言

    相信您已经学会了如何在Windows环境下以最低成本、无需GPU的情况下运行qwen大模型。现在,让我们进一步探索如何在Linux环境下,并且拥有GPU的情况下运行qwen大模型,以提升性能和效率。


二、术语

    2.1. CentOS

        CentOS是一种基于Linux的自由开源操作系统。它是从Red Hat Enterprise Linux(RHEL)衍生出来的,因此与RHEL具有高度的兼容性。CentOS的目标是提供一个稳定、可靠且免费的企业级操作系统,适用于服务器和桌面环境。

    2.2. GPU

        是Graphics Processing Unit(图形处理单元)的缩写。它是一种专门设计用于处理图形和图像计算的处理器。与传统的中央处理器(CPU)相比,GPU具有更高的并行计算能力,适用于处理大规模数据并进行复杂的计算任务。


三、技术实现

3.1. 创建虚拟环境

conda create --name ai python=3.10

3.2. 切换虚拟环境

conda activate ai

3.3. 安装第三方软件包

pip install -r requirements.txt

requirements.txt文件:https://github.com/QwenLM/Qwen/blob/main/requirements.txt

具体内容如下:

transformers==4.32.0
accelerate
tiktoken
einops
transformers_stream_generator==0.0.4
scipy

3.4. 代码实现

# -*-  coding = utf-8 -*-
import traceback

from transformers import AutoTokenizer, AutoModelForCausalLM
import time
modelPath = "/data/model/qwen-1-8b-chat"

def chat(model,tokenizer,message,history):
    position = 0
    result = []
    try:
        for response in model.chat_stream(tokenizer, message, history=history):
            result.append(response[position:])

            position = len(response)

            yield "".join(result)
    except Exception:
        traceback.print_exc()

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

def loadModel():
    model = AutoModelForCausalLM.from_pretrained(modelPath, device_map="auto", trust_remote_code=True, fp16=True).eval()
    return model

if __name__ == '__main__':
    model = loadModel()
    tokenizer = loadTokenizer()
    start_time = time.time()

    message = "我家有什么特产?"
    history = [('hi,你好', '你好!有什么我可以帮助你的吗?'), ('我家在广州,很好玩哦', '广州是一个美丽的城市,有很多有趣的地方可以去。'), ]

    response = chat(model,tokenizer,message,history)
    result = []
    for r in response:
        result.append(r)

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

3.4. 代码执行

python -u qwen1_8b_chat_test.py

3.5. 结果输出

PS:

上述代码实现了流式输出,但它在内容完全生成后才进行一次性打印。


四、附带说明

4.1. 在Python中,使用-u选项可以启用无缓冲的标准输出,这意味着输出将立即显示在终端上,而不会等待缓冲区填满或遇到换行符。

4.2.可以安装flash-attention包来提高运行效率以及降低显存占用,但会受到cuda版本等限制导致安装失败。

4.3.qwen大模型运行在CPU/GPU环境下的配置差异主要体现在:

device_map dtype
CPU cpu
GPU auto/cuda/cuda:0 fp16/bf16/fp32/bf32

你可能感兴趣的:(应用落地,深度学习)