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

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 deepcopyfrom transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation import GenerationConfig
from transformers.trainer_utils import set_seedDEFAULT_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, configdef _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')continueexcept KeyboardInterrupt:exit(1)if message:return messageprint('[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.seedwhile 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']:breakelif command in ['clear', 'cl']:_clear_screen()print(_WELCOME_MSG)continueelif command in ['clear-history', 'clh']:print(f'[INFO] All {len(history)} history cleared')history.clear()continueelif command in ['help', 'h']:print(_HELP_MSG)continueelif command in ['history', 'his']:_print_history(history)continueelif command in ['seed']:if len(command_words) == 1:print(f'[INFO] Current random seed: {seed}')continueelse: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_seedcontinueelif 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>')continueconf_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)continueelse:print(f'[INFO] Change config: model.generation_config.{conf_key} = {conf_value}')setattr(model.generation_config, conf_key, conf_value)continueelif command in ['reset-conf']:print('[INFO] Reset generation config')model.generation_config = deepcopy(orig_gen_config)print(model.generation_config)continueelse:# 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')continuehistory.append((query, response))if __name__ == "__main__":main()

请注意print的位置。

python cli_demo.py

(全文完,谢谢阅读)

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

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

相关文章

【AI视野·今日Sound 声学论文速览 第十八期】Wed, 4 Oct 2023

AI视野今日CS.Sound 声学论文速览 Wed, 4 Oct 2023 Totally 4 papers &#x1f449;上期速览✈更多精彩请移步主页 Daily Sound Papers Mel-Band RoFormer for Music Source Separation Authors Ju Chiang Wang, Wei Tsung Lu, Minz Won最近&#xff0c;基于多频段频谱图的方法…

windows server 2012 服务器打开系统远程功能

服务器上开启远程功能 进入服务器&#xff0c;选择“添加角色和功能” 需要选择安装的服务器类型&#xff0c;如图所示 然后在服务器池中选择你需要使用的服务器。 选择完成后&#xff0c;在图示列表下勾选“远程桌面服务” 再选择需要安装的功能和角色服务。 选择完成确认内容…

大模型部署手记(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++_pen_友元

友元&#xff08;破坏封装&#xff09; 我故意让别人能使用我的私有成员 友元类 friend class B;友元函数 friend void func();友元成员函数 friend void A::func();例 #include <stdio.h>class A;class C{ public:void CprintA(A &c); };class B{ public:void Bpri…

qt 5.15.2 安卓 macos

macos环境安卓配置 我的系统是monterey12.5.1 打开qt的配置界面 这里版本是java1.8&#xff0c;注意修改这个json文件&#xff0c;显示包内容 {"common": {"sdk_tools_url": {"linux": "https://dl.google.com/android/repository/comm…

lv7 嵌入式开发-网络编程开发 07 TCP服务器实现

目录 1 函数介绍 1.1 socket函数 与 通信域 1.2 bind函数 与 通信结构体 1.3 listen函数 与 accept函数 2 TCP服务端代码实现 3 TCP客户端代码实现 4 代码优化 5 练习 1 函数介绍 其中read、write、close在IO中已经介绍过&#xff0c;只需了解socket、bind、listen、acc…

Python爬虫案例入门教程(纯小白向)——夜读书屋小说

Python爬虫案例——夜读书屋小说 前言 如果你是python小白并且对爬虫有着浓厚的兴趣&#xff0c;但是面对网上错综复杂的实战案例看也看不懂&#xff0c;那么你可以尝试阅读我的文章&#xff0c;我也是从零基础python开始学习爬虫&#xff0c;非常清楚在过程中所遇到的困难&am…

简单查找重复文本文件

声明这是最初 我的提问给个文本分类清单input查找文件夹下 .py .txt .excel .word 一模一样的文本不是找文件名 找相同格式下的文件文本是否一样 文件单独复制到文件夹下两个文件全部复制到文件夹下 print 打印相同文本文件的名字 比如查找到了3.py与4.5.是.py文件中的文本文件…

Scala第一章节

Scala第一章节 scala总目录 章节目标 理解Scala的相关概述掌握Scala的环境搭建掌握Scala小案例: 做最好的自己 1. Scala简介 1.1 概述 ​ Scala(斯嘎拉)这个名字来源于"Scalable Language(可伸缩的语言)", 它是一门基于JVM的多范式编程语言, 通俗的说: Scala是一…

JAVAWeb业务层开发->普通和基于MP

普通方式业务层开发 service定义接口&#xff08;主要实现逻辑层面的业务功能&#xff09; serviceImpl实现该接口 注意事项&#xff1a; 逻辑判断的代码可以使用&#xff1e;号&#xff0c;使得返回结果为布尔类型。 小结&#xff1a;每一个接口写完都要写测试类去检测&#…

JMeter的详细使用及相关问题

一、中文乱码问题 如果出现乱码&#xff0c;需要修改编码集&#xff0c;&#xff08;版本问题有的不需要修改&#xff0c;就不用管&#xff09; 修改后保存重启就好了。 JMeter5.5版本的按照如下修改&#xff1a; 二、JMeter的启动 ①建议直接用ApacheJMeter.jar双击启动…

<一>Qt斗地主游戏开发:开发环境搭建--VS2019+Qt5.15.2

1. 开发环境概述 对于Qt的开发环境来说&#xff0c;主流编码IDE界面一般有两种&#xff1a;Qt Creator或VSQt。为了简单起见&#xff0c;这里的操作系统限定为windows&#xff0c;编译器也通用VS了。Qt版本的话自己选择就可以了&#xff0c;当然VS的版本也是依据Qt版本来选定的…

QT4.8.7安装详细教程

QT4.8.7安装详细教程&#xff08;MinGW 4.8.2和QTCreator4.2.0&#xff09; 1.下载及安装2.配置环境 此文是在下方链接博文的基础上&#xff0c;按自己的理解整理的https://blog.csdn.net/xiaowanzi199009/article/details/104119265 1.下载及安装 这三个文件&#xff0c;顺序是…

Swift SwiftUI CoreData 过滤数据 1

Xcode: Version 14.3.1 (14E300c) iOS: 16 预览&#xff1a; Code: import SwiftUI import CoreDatastruct TodosSearch: View {State private var search_title "测试"FetchRequest var todos_search: FetchedResults<Todo>init() {let request: NSFetchReq…

Cortex-A9 架构

一、Cortex-A 处理器运行模式 Cortex-A9处理器有 9中处理模式&#xff0c;如下表所示&#xff1a; 九种运行模式 在上表中&#xff0c;除了User(USR)用户模式以外&#xff0c;其它8种运行模式都是特权模式&#xff0c;在特权模式下&#xff0c;程序可以访问所有的系统资源。这…

在openwrt dnsmasq DHCP中为客户端分配不同的网关和DNS | 旁路由 禁止上网

环境&#xff1a;openwrt dnsmasq PS4/Switch 问题&#xff1a;为路由器下的设备分配不同的网关和DNS&#xff0c;禁止局域网设备上网 解决办法&#xff1a;修改dnsmasq配置文件 背景&#xff1a;Openwrt 的DHCP服务是使用dnsmasq实现的&#xff0c;他可以给内网的客户端设备…

网络安全工程师考证指南,不看就亏了!!

目前网络安全行业&#xff0c;国内都有哪些证书可以考&#xff1f; 一、CISP-PTE &#xff08;国家注册渗透测试工程师&#xff09; CISP-PTE即注册信息安全渗透测试工程师&#xff0c;该证书由中国信息安全测评中心颁发&#xff0c;证书是国内唯一认可的渗透测试认证&#x…

el-menu 导航栏学习(1)

最简单的导航栏学习跳转实例效果&#xff1a; &#xff08;1&#xff09;index.js路由配置&#xff1a; import Vue from vue import Router from vue-router import NavMenuDemo from /components/NavMenuDemo import test1 from /components/test1 import test2 from /c…

Redis中Hash类的操作

Redis中Hash类型是键值对的形式保存数据&#xff0c;其中键被称为字段&#xff08;field&#xff09;&#xff0c;值称为字段值&#xff08;value&#xff09;。在一个key中&#xff0c;字段不能重复&#xff0c;而值可以重复。无论是字段还是值都是无序的&#xff08;保存的次…

mysql双主+双从集群连接模式

架构图&#xff1a; 详细内容参考&#xff1a; 结果展示&#xff1a; 178.119.30.14(主) 178.119.30.15(主) 178.119.30.16(从) 178.119.30.17(从)