大模型部署手记(3)通义千问+Windows GPU

news2024/9/21 0:48:55

1.简介

组织机构:阿里

代码仓:GitHub - QwenLM/Qwen: The official repo of Qwen (通义千问) chat & pretrained large language model proposed by Alibaba Cloud.

模型:Qwen/Qwen-7B-Chat-Int4

下载:http://huggingface.co/Qwen/Qwen-7B-Chat-Int4

modelscope下载:https://modelscope.cn/models/qwen/Qwen-7B-Chat-Int4/summary

硬件环境:暗影精灵7Plus

Windows版本:Windows 11家庭中文版 Insider Preview 22H2

内存 32G

GPU显卡:Nvidia GTX 3080 Laptop (16G)

安装阿里的 通义千问大模型有两种方式,modelscope方式和transformers(huggingface)方式。

参考资料:

1.玩一玩140亿参数的阿里千问!Qwen+Win11+3060 https://zhuanlan.zhihu.com/p/659000534

2.玩一玩通义千问Qwen开源版,Win11 RTX3060本地安装记录! https://zhuanlan.zhihu.com/p/648368704

2.代码和模型下载

下载代码仓:

d:

git clone https://github.com/QwenLM/Qwen.git

模型下载参见 第四部分执行 python Qwen-7B-Chat-Int4.py的过程。

3.安装依赖

打开Anaconda Powershell Prompt,创建conda环境:

conda create -n model310 python=3.10

conda activate model310

安装modelscope基础库

pip install modelscope

在安装modelscope的时候,系统会自动安装pytorch 2.0.1(后面会发现装的torch这个完全不对)

打开 魔搭社区 http://modelscope.cn

注册一下:

打开 Qwen-7B inr4量化的主页:https://modelscope.cn/models/qwen/Qwen-7B-Chat-Int4/summary

安装量化依赖:

pip install auto-gptq optimum

安装量化包:

pip install bitsandbytes --prefer-binary --extra-index-url=https://jllllll.github.io/bitsandbytes-windows-webui

安装其他依赖:

pip install transformers_stream_generator

pip install tiktoken

pip install deepspeed

目前deepspeed在windows上的安装还存在问题。我们先忽略掉吧!

安装flash-attention库

git clone -b v1.0.8 https://github.com/Dao-AILab/flash-attention

cd flash-attention

pip install .

# 下方安装可选,安装可能比较缓慢。

# Below are optional. Installing them might be slow.

# pip install csrc/layer_norm

# pip install csrc/rotary

看日志应该是torch可能不是CUDA的版本。

验证下:

果然如此。

还是使用conda安装pytorch 2.0的CUDA版本吧!

conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia

为了保险,还是要验证一下:

python

import torch

#pytorch的版本

torch.__version__

#是否支持CUDA

torch.cuda.is_available()

#CUDA的版本

print(torch.version.cuda)

#cuDNN的版本

print(torch.backends.cudnn.version())

#GPU内存

torch.cuda.get_device_capability(device=0)

再来:

pip install .

4.部署验证

编辑d:\Qwen\Qwen-7B-Chat-Int4.py 文件,内容如下:

from modelscope import AutoTokenizer, AutoModelForCausalLM, snapshot_download
model_dir = snapshot_download("qwen/Qwen-7B-Chat-Int4", revision = 'v1.1.3' )

# Note: The default behavior now has injection attack prevention off.
tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)

model = AutoModelForCausalLM.from_pretrained(
    model_dir,
    device_map="auto",
    trust_remote_code=True
).eval()
response, history = model.chat(tokenizer, "你好", history=None)
print(response)
# 你好!很高兴为你提供帮助。

执行这个文件:

cd d:\Qwen

python Qwen-7B-Chat-Int4.py

pip install chardet

再来:

python Qwen-7B-Chat-Int4.py

耐心等待模型下载完毕。。。

看来模型是下载到了这个目录:C:\Users\用户名\.cache\modelscope\hub\qwen\Qwen-7B-Chat-Int4

这个下载的时候不显示速度,下载完毕之后才显示速度。。。

仔细看看还少装了什么包:

pip install cchardet

再来:

python Qwen-7B-Chat-Int4.py

看来已经能成功运行了。

将 前面下载目录 C:\Users\用户名\.cache\modelscope\hub\qwen\Qwen-7B-Chat-Int4 下的所有文件复制到 当前目录的 Qwen\Qwen-7B-Chat-Int4 目录:

修改cli_demo.py

修改如下代码:

DEFAULT_CKPT_PATH = './Qwen/Qwen-7B-Chat-Int4'

运行 python cli_demo.py

系统很快会弹出:

做一些交互:

不过每次都要清屏,有点不舒服。

把代码中的clear_screen都去掉:(除了收到明确的clear命令)

CTRL-C退出去重新运行:python cli_demo.py

貌似有点问题,代码好像每次都在做刷屏,然后输入一行新的话处理。

经过多次尝试,代码这样修改就可以了:

# Copyright (c) Alibaba Cloud.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.

"""A simple command-line interactive chat demo."""

import argparse
import os
import platform
import shutil
from copy import deepcopy

from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation import GenerationConfig
from transformers.trainer_utils import set_seed

DEFAULT_CKPT_PATH = './Qwen/Qwen-7B-Chat-Int4'

_WELCOME_MSG = '''\
Welcome to use Qwen-Chat model, type text to start chat, type :h to show command help.
(欢迎使用 Qwen-Chat 模型,输入内容即可进行对话,:h 显示命令帮助。)

Note: This demo is governed by the original license of Qwen.
We strongly advise users not to knowingly generate or allow others to knowingly generate harmful content, including hate speech, violence, pornography, deception, etc.
(注:本演示受Qwen的许可协议限制。我们强烈建议,用户不应传播及不应允许他人传播以下内容,包括但不限于仇恨言论、暴力、色情、欺诈相关的有害信息。)
'''
_HELP_MSG = '''\
Commands:
    :help / :h          Show this help message              显示帮助信息
    :exit / :quit / :q  Exit the demo                       退出Demo
    :clear / :cl        Clear screen                        清屏
    :clear-his / :clh   Clear history                       清除对话历史
    :history / :his     Show history                        显示对话历史
    :seed               Show current random seed            显示当前随机种子
    :seed <N>           Set random seed to <N>              设置随机种子
    :conf               Show current generation config      显示生成配置
    :conf <key>=<value> Change generation config            修改生成配置
    :reset-conf         Reset generation config             重置生成配置
'''


def _load_model_tokenizer(args):
    tokenizer = AutoTokenizer.from_pretrained(
        args.checkpoint_path, trust_remote_code=True, resume_download=True,
    )

    if args.cpu_only:
        device_map = "cpu"
    else:
        device_map = "auto"

    model = AutoModelForCausalLM.from_pretrained(
        args.checkpoint_path,
        device_map=device_map,
        trust_remote_code=True,
        resume_download=True,
    ).eval()

    config = GenerationConfig.from_pretrained(
        args.checkpoint_path, trust_remote_code=True, resume_download=True,
    )

    return model, tokenizer, config


def _clear_screen():
    if platform.system() == "Windows":
        os.system("cls")
    else:
        os.system("clear")


def _print_history(history):
    terminal_width = shutil.get_terminal_size()[0]
    print(f'History ({len(history)})'.center(terminal_width, '='))
    for index, (query, response) in enumerate(history):
        print(f'User[{index}]: {query}')
        print(f'QWen[{index}]: {response}')
    print('=' * terminal_width)


def _get_input() -> str:
    while True:
        try:
            message = input('User> ').strip()
        except UnicodeDecodeError:
            print('[ERROR] Encoding error in input')
            continue
        except KeyboardInterrupt:
            exit(1)
        if message:
            return message
        print('[ERROR] Query is empty')


def main():
    parser = argparse.ArgumentParser(
        description='QWen-Chat command-line interactive chat demo.')
    parser.add_argument("-c", "--checkpoint-path", type=str, default=DEFAULT_CKPT_PATH,
                        help="Checkpoint name or path, default to %(default)r")
    parser.add_argument("-s", "--seed", type=int, default=1234, help="Random seed")
    parser.add_argument("--cpu-only", action="store_true", help="Run demo with CPU only")
    args = parser.parse_args()

    history, response = [], ''

    model, tokenizer, config = _load_model_tokenizer(args)
    orig_gen_config = deepcopy(model.generation_config)

    #_clear_screen()
    print(_WELCOME_MSG)

    seed = args.seed

    while True:
        query = _get_input()

        # Process commands.
        if query.startswith(':'):
            command_words = query[1:].strip().split()
            if not command_words:
                command = ''
            else:
                command = command_words[0]

            if command in ['exit', 'quit', 'q']:
                break
            elif command in ['clear', 'cl']:
                _clear_screen()
                print(_WELCOME_MSG)
                continue
            elif command in ['clear-history', 'clh']:
                print(f'[INFO] All {len(history)} history cleared')
                history.clear()
                continue
            elif command in ['help', 'h']:
                print(_HELP_MSG)
                continue
            elif command in ['history', 'his']:
                _print_history(history)
                continue
            elif command in ['seed']:
                if len(command_words) == 1:
                    print(f'[INFO] Current random seed: {seed}')
                    continue
                else:
                    new_seed_s = command_words[1]
                    try:
                        new_seed = int(new_seed_s)
                    except ValueError:
                        print(f'[WARNING] Fail to change random seed: {new_seed_s!r} is not a valid number')
                    else:
                        print(f'[INFO] Random seed changed to {new_seed}')
                        seed = new_seed
                    continue
            elif command in ['conf']:
                if len(command_words) == 1:
                    print(model.generation_config)
                else:
                    for key_value_pairs_str in command_words[1:]:
                        eq_idx = key_value_pairs_str.find('=')
                        if eq_idx == -1:
                            print('[WARNING] format: <key>=<value>')
                            continue
                        conf_key, conf_value_str = key_value_pairs_str[:eq_idx], key_value_pairs_str[eq_idx + 1:]
                        try:
                            conf_value = eval(conf_value_str)
                        except Exception as e:
                            print(e)
                            continue
                        else:
                            print(f'[INFO] Change config: model.generation_config.{conf_key} = {conf_value}')
                            setattr(model.generation_config, conf_key, conf_value)
                continue
            elif command in ['reset-conf']:
                print('[INFO] Reset generation config')
                model.generation_config = deepcopy(orig_gen_config)
                print(model.generation_config)
                continue
            else:
                # As normal query.
                pass

        # Run chat.
        set_seed(seed)
        try:
             for response in model.chat_stream(tokenizer, query, history=history, generation_config=config):
               pass
#                _clear_screen()
#             print(f"\nUser: {query}")
             print(f"\nQwen-Chat: {response}")
        except KeyboardInterrupt:
            print('[WARNING] Generation interrupted')
            continue

        history.append((query, response))


if __name__ == "__main__":
    main()

请注意print的位置。

python cli_demo.py

(全文完,谢谢阅读)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1061358.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Modelsim测试覆盖率操作说明

1、打开Project窗口界面 2、在project界面下&#xff0c;选中所有需要测试覆盖率的.v文件&#xff08;不包括tb文件&#xff09;&#xff0c;鼠标点击右键&#xff0c;在Properties选项中选择Coverage选项&#xff0c;选择需要测试的覆盖率类型 3、重新编译所有的源文件&#x…

【gitlab】从其他仓库创建项目

需求描述 解决方法 以renren-fast脚手架为例 第一步 第二步 第三步 第四步 参考文章

Echarts 教程二

Echarts 教程二 Echarts 常用配置篇柱状图常用配置折线图常用配置散点图常用配置饼图常用配置地图常用配置 Echarts 常用配置篇 柱状图常用配置 配置柱状图的最大最小值 平均值 显示柱状图文字 柱状图宽度 折线图常用配置 配置最大最小值 平均值 标记区域 线的平滑 线的样式 等…

苹果签名有多少种类之TF签名(TestFlight签名)是什么?优势是什么?什么场合需要应用到?

&#xff08;一&#xff09;TestFlight 能够让您&#xff1a;邀请内部和外部的测试人员为应用程序提供反馈。 跟踪应用程序在测试过程中发现的 bug 和用户体验问题。 收集 Crash 报告&#xff0c;了解应用程序在真实设备上的运行状况。 要使用 TestFlight&#xff0c;您可以按照…

用Python操作Word文档,看这一篇就对了!

本文主要讲解Python中操作word的思路。 一、Hello&#xff0c;world&#xff01; 使用win32com需要安装pypiwin32 pip install pypiwin32 推荐使用python的IDLE&#xff0c;交互方便 1、如何新建文档 from win32com.client import Dispatchapp Dispatch(Word.Application…

大模型部署手记(4)MOSS+Jetson AGX Orin

1.简介 组织机构&#xff1a;复旦大学 代码仓&#xff1a;GitHub - OpenLMLab/MOSS: An open-source tool-augmented conversational language model from Fudan University 模型&#xff1a;fnlp/moss-moon-003-sft-int4 下载&#xff1a;https://huggingface.co/fnlp/mos…

【C语言】八大排序算法

文章目录 一、冒泡排序1、定义2、思想及图解3、代码 二、快速排序1、hoare版本2、挖坑法3、前后指针法4、非递归快排5、快速排序优化1&#xff09;三数取中选key值2&#xff09;小区间优化 三、直接插入排序1、定义2、代码 四、希尔排序1、定义2、图解3、代码 五、选择排序1、排…

Solidity 合约漏洞,价值 38BNB 漏洞分析

Solidity 合约漏洞&#xff0c;价值 38BNB 漏洞分析 1. 漏洞简介 https://twitter.com/NumenAlert/status/1626447469361102850 https://twitter.com/bbbb/status/1626392605264351235 2. 相关地址或交易 攻击交易&#xff1a; https://bscscan.com/tx/0x146586f05a451313…

(c语言进阶)数据存储——整形存储

1.Release程序运行时会对Debug程序进行优化 例如将变量创建在数组之后&#xff0c;避免了数组越界引用时导致死循环的可能。 2.整形变量所占空间的大小 3.构造类型 数组的类型为去掉数组名之后的剩余部分 4.指针类型 5.空类型 6.数值的不同表现形式 7.数据在内存中的两种存…

03.requests入门

1、requests概述 ​ 前面的课程中我们了解了requests模块是一个网络请求模块,可以帮助我们模拟成客户端去请求服 务器的数据。我们今天就是主要针对这个模块进行学习。 ​ 我们可以在浏览器中抓取到这些请求与响应的内容,那么我们可以“伪造”请求吗?也就是不再通过 浏览器…

python+pygame+opencv+gpt实现虚拟数字人直播(一)

AI技术突飞猛进&#xff0c;不断的改变着人们的工作和生活。数字人直播作为新兴形式&#xff0c;必将成为未来趋势&#xff0c;具有巨大的、广阔的、惊人的市场前景。它将不断融合创新技术和跨界合作&#xff0c;提供更具个性化和多样化的互动体验&#xff0c;成为未来的一种趋…

大模型部署手记(2)baichuan2+Windows GPU

1.简介 组织机构&#xff1a;百川智能&#xff08;前搜狗CEO王小川创立&#xff09; 代码仓&#xff1a;GitHub - baichuan-inc/Baichuan2: A series of large language models developed by Baichuan Intelligent Technology 模型&#xff1a;baichuan-inc/Baichuan2-7B-Ch…

二十九、高级IO与多路转接之epollreactor(收官!)

文章目录 一、Poll&#xff08;一&#xff09;定义&#xff08;二&#xff09;实现原理&#xff08;三&#xff09;优点&#xff08;四&#xff09;缺点 二、I/O多路转接之epoll&#xff08;一&#xff09;从网卡接收数据说起&#xff08;二&#xff09;如何知道接收了数据&…

【C++】vector相关OJ

文章目录 1. 只出现一次的数字2. 杨辉三角3. 电话号码字母组合 ヾ(๑╹◡╹)&#xff89;" 人总要为过去的懒惰而付出代价ヾ(๑╹◡╹)&#xff89;" 1. 只出现一次的数字 力扣链接 代码展示&#xff1a; class Solution { public:int singleNumber(vector<i…

留学生用ChatGPT改论文被教授痛骂

最近&#xff0c;随着AI的突然出世&#xff01;瞬间在澳洲及各国留学圈掀起大浪潮&#xff01;然而一则帖子也在网上火了&#xff0c;值得留学生们看看。 “用ChatGPT改论文被教授痛骂...” 这个帖子表示&#xff0c;Chat GPT真是堪称Essay的第一生产力&#xff0c;但是Chat …

Septentrio接收机二进制的BDS b2b改正数解码

Galileo的HAS和BDS B2b改正数为实时PPP提供了可能&#xff0c;要实现实时PPP解算&#xff0c;必须对对应的数据进行解码。由于没有做过解码的工作&#xff0c;现结合qzsl6tool代码对Septentrio的解码代码进行学习。 1. 二进制枕头的识别和解码 定义一个读取数据的类&#xff…

ASUS华硕天选4笔记本FA507NU7735H_4050原装出厂Win11系统

下载链接&#xff1a;https://pan.baidu.com/s/1puxQOxk4Rbno1DqxhkvzXQ?pwdhkzz 系统自带网卡、显卡、声卡等所有驱动、出厂主题壁纸、Office办公软件、MyASUS华硕电脑管家、奥创控制中心等预装程序

Java类型转换和类型提升

目录 一、类型转换 1.1 自动类型转换&#xff08;隐式&#xff09; 1.1.1 int 与 long 之间 1.1.2 float 与 double 之间 1.1.3 int 与 byte 之间 1.2 强制类型转换&#xff08;显示&#xff09; 1.2.1 int 与 long 之间 1.2.2 float 与 double 之间 1.2.3 int 与 d…

Android12之H264、H265、H266视频编码标准总结(四十八)

简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长! 优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀 人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药. 更多原创,欢迎关注:Android…

Redis高可用之哨兵模式、集群

文章目录 一、Redis哨兵模式1.1 简介1.2 哨兵模式的作用1.3 哨兵结构1.4 故障转移机制&#xff08;重要&#xff09;1.5 主节点选举机制 二、部署Redis哨兵模式Step1 修改 Redis 哨兵模式的配置文件&#xff08;所有节点操作&#xff09;Step2 实现基于VIP&#xff08;虚拟IP&a…