当前位置: 首页 > news >正文

实战 - 使用 AutoAWQ 进行量化

文章目录

    • 一、准备
      • 1、安装 autoawq
      • 2、模型准备
    • 二、量化
        • `config.json` 文件变化
    • 三、加载量化后模型
        • 量化后的输出
        • 原始输出
        • 对比
    • 四、查看模型的精度
      • 1、查看模型卡
      • 2、查看 config.json 中的 `torch_dtype`
      • 3、打印模型信息
      • 4、model.dtype 未必是模型精度


一、准备

1、安装 autoawq

pip install autoawq 
pip install transformers==4.47.1 

使用的较低版本的 transformers,如果执行下面代码有问题,可以检查 transformers 版本。

目前我的测试 Python 环境为 3.9


2、模型准备

这里以 mistralai/Mistral-7B-Instruct-v0.2 为例

如果下载有问题,可以前往模型界面查看是否需要申请权限:https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2


后面代码会自动下载模型,你也可以提前下载模型:

huggingface-cli download mistralai/Mistral-7B-Instruct-v0.2

如果网络受限,可以设置镜像地址到环境变量:

export HF_ENDPOINT='https://hf-mirror.com'

二、量化

from awq import AutoAWQForCausalLM
from transformers import AutoTokenizermodel_path = 'mistralai/Mistral-7B-Instruct-v0.2'
quant_path = 'mistral-instruct-v0.2-awq'
quant_config = { "zero_point": True, "q_group_size": 128, "w_bit": 4, "version": "GEMM" }# Load model
model = AutoAWQForCausalLM.from_pretrained(model_path)
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)# 查看模型类型
model.dtype
# torch.float32 - 32-bit(FP32) # Quantize
model.quantize(tokenizer, quant_config=quant_config)# Save quantized model
model.save_quantized(quant_path)
tokenizer.save_pretrained(quant_path)print(f'Model is quantized and saved at "{quant_path}"')


quant_config 也可以写成:

from transformers import AwqConfig, AutoConfig
quantization_config = AwqConfig(bits=quant_config["w_bit"],group_size=quant_config["q_group_size"],zero_point=quant_config["zero_point"],version=quant_config["version"].lower(),
).to_dict()model.model.config.quantization_config = quantization_config

config.json 文件变化

config.json 文件会变成下方的样子:

相比原来的文件,多出 quantization_config 内容,其中 "quant_method": "awq"

{"_name_or_path": "/home/wx/.cache/huggingface/hub/models--mistralai--Mistral-7B-Instruct-v0.2/snapshots/3ad372fc79158a2148299e3318516c786aeded6c","architectures": ["MistralForCausalLM"],"attention_dropout": 0.0,"bos_token_id": 1,"eos_token_id": 2,"head_dim": 128,"hidden_act": "silu","hidden_size": 4096,"initializer_range": 0.02,"intermediate_size": 14336,"max_position_embeddings": 32768,"model_type": "mistral","num_attention_heads": 32,"num_hidden_layers": 32,"num_key_value_heads": 8,"quantization_config": {"bits": 4,"group_size": 128,"modules_to_not_convert": null,"quant_method": "awq","version": "gemm","zero_point": true},"rms_norm_eps": 1e-05,"rope_theta": 1000000.0,"sliding_window": null,"tie_word_embeddings": false,"torch_dtype": "bfloat16","transformers_version": "4.47.1","use_cache": false,"vocab_size": 32000
}

原始 config.json

{"architectures": ["MistralForCausalLM"],"attention_dropout": 0.0,"bos_token_id": 1,"eos_token_id": 2,"hidden_act": "silu","hidden_size": 4096,"initializer_range": 0.02,"intermediate_size": 14336,"max_position_embeddings": 32768,"model_type": "mistral","num_attention_heads": 32,"num_hidden_layers": 32,"num_key_value_heads": 8,"rms_norm_eps": 1e-05,"rope_theta": 1000000.0,"sliding_window": null,"tie_word_embeddings": false,"torch_dtype": "bfloat16","transformers_version": "4.36.0","use_cache": true,"vocab_size": 32000
}

三、加载量化后模型


from transformers import AutoModelForCausalLM, AutoTokenizer
quant_dir = '/home/wx/mistral-instruct-v0.2-awq'  
model = AutoModelForCausalLM.from_pretrained(quant_dir, device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(quant_dir, trust_remote_code=True)prompt = "Tell me about blackhole."
prompt_template=f'''{prompt}'''tokens = tokenizer(prompt_template, return_tensors="pt").input_ids.cuda()generated_ids = model.generate(tokens, do_sample=True,temperature=0.7,top_p=0.95,top_k=40,max_new_tokens=512)
decoded = tokenizer.decode(generated_ids[0])
print(decoded)

量化后的输出

GPU 占用:4550MiB

<s> Tell me about blackhole.A black hole is a region in space where the gravitational pull is so strong that nothing, not even light, can escape. It's called a "black" hole because it appears black due to the absence of light emanating from it.Black holes are formed when a massive star collapses in on itself after it has exhausted its nuclear fuel. The collapse causes the star to shrink down to an incredibly small size, creating an incredibly dense object. This object is so dense that its gravity warps space and time around it, forming an event horizon, which is the point of no return. Once anything crosses this event horizon, it's pulled into the black hole and cannot escape.Black holes come in different sizes, with the smallest being about the size of a star and the largest being billions of times larger than the sun. The largest black hole that has been discovered is located at the center of the galaxy, and it's estimated to be about 40 billion times the mass of the sun.Despite their intimidating name, black holes are not necessarily a threat to us. The closest known black hole to Earth is about 1,600 light-years away, which is far enough that we don't need to worry about being sucked in. However, they are fascinating objects that continue to captivate scientists and the general public alike.</s>

原始输出

mistralai/Mistral-7B-Instruct-v0.2 , GPU 占用:21988MiB

<s> Tell me about blackhole. I've heard that it is some sort of astronomical thing, but I don't really understand what it is or how it works.A black hole is an extremely dense object in space that has such strong gravitational pull that nothing, not even light, can escape from it once it gets too close. Black holes are formed when a massive star collapses in on itself after it has exhausted its nuclear fuel and can no longer produce the pressure needed to counteract the force of gravity.The boundary around a black hole from which nothing can escape is called the event horizon. This is not a physical boundary that you can see, but rather a theoretical construct based on the laws of physics. Once an object crosses the event horizon, it is considered to be inside the black hole itself.Black holes are not completely black, as they do emit some form of radiation, but they appear black because they absorb all the light that falls on them. This is due to the fact that the intense gravitational pull causes the surface of the black hole to be at a temperature so hot that it emits very little visible light.Black holes can vary in size, from small ones that are only a few times the mass of the sun, to supermassive black holes that can be millions or even billions of times the mass of the sun. The supermassive black holes are thought to be at the center of most, if not all, galaxies, including our own Milky Way.Despite their fearsome reputation, black holes are not a threat to us here on Earth, as they are typically located billions of light-years away. However, they are fascinating objects of study for astronomers and physicists, who continue to learn new things about them and their role in the universe.</s>

对比
原始4bit 量化后
占用磁盘大小14G3.9G
GPU 占用21988MiB4550MiB (4.8倍)

四、查看模型的精度

对于一个模型,我们想知道原始的精度是多少,可以用下面几种方式:

1、查看模型卡

如:https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2
右边的 Safetensors 信息
在这里插入图片描述


2、查看 config.json 中的 torch_dtype

"torch_dtype": "bfloat16",


3、打印模型信息

from transformers import AutoTokenizermodel_path = 'mistralai/Mistral-7B-Instruct-v0.2'# Load model
model = AutoAWQForCausalLM.from_pretrained(model_path)for name, param in model.named_parameters():print(f"{name}: {param.dtype}")break  # 只打印第一个权重的数据类型

4、model.dtype 未必是模型精度

上述模型,model.dtype 打印的结果为 torch.float32,表示模型当前是以 32-bit 浮点数(FP32)精度加载的。
config.json 中的 "torch_dtype": "bfloat16"表示模型设计时支持或推荐使用 bfloat16 精度,但实际加载时可能由于环境 或 代码设置 未启用 bfloat16。


2025-03-08(六)

相关文章:

实战 - 使用 AutoAWQ 进行量化

文章目录 一、准备1、安装 autoawq2、模型准备 二、量化config.json 文件变化 三、加载量化后模型量化后的输出原始输出对比 四、查看模型的精度1、查看模型卡2、查看 config.json 中的 torch_dtype3、打印模型信息4、model.dtype 未必是模型精度 一、准备 1、安装 autoawq p…...

C++20 格式化库:强大的字符串格式化工具

文章目录 格式化语法常见用法1. 填充和对齐2. 数值格式化3. 进制格式化4. 自定义类型 示例代码注意事项 C20 的格式化库是一个强大的工具&#xff0c;用于处理字符串的格式化操作。它提供了类似于 Python 中 str.format() 的功能&#xff0c;但语法和用法更符合 C 的风格。以下…...

【一文学会 HTML5】

目录 HTML概述基本概念HTML 发展历程HTML 基本结构 网页基本标签标题标签&#xff08;<h1> - <h6>&#xff09;段落标签&#xff08;<p>&#xff09;换行标签&#xff08;<br>&#xff09;水平线标签&#xff08;<hr>&#xff09;注释&#xff0…...

如何在WPS中接入DeepSeek并使用OfficeAI助手(超细!成功版本)

目录 第一步&#xff1a;下载并安装OfficeAI助手 第二步&#xff1a;申请API Key 第三步:两种方式导入WPS 第一种:本地大模型Ollama 第二种APIKey接入 第四步&#xff1a;探索OfficeAI的创作功能 工作进展汇报 PPT大纲设计 第五步&#xff1a;我的使用体验(体验建议) …...

蓝耘智算 + 通义万相 2.1:为 AIGC 装上 “智能翅膀”,翱翔创作新天空

1. 引言&#xff1a;AIGC 的崛起与挑战 在过去几年中&#xff0c;人工智能生成内容&#xff08;AIGC&#xff09;技术突飞猛进。AIGC 涉及了文本生成、图像创作、音乐创作、视频制作等多个领域&#xff0c;并逐渐渗透到日常生活的方方面面。传统的内容创作方式已经被许多人类创…...

电脑如何在系统默认的壁纸中切换自己喜欢的

1、声明&#xff1a;该切换壁纸仅支持win10。 当你想去切换系统默认的壁纸&#xff0c;但是不知道该怎么切换&#xff0c;别慌&#xff0c;小亦教你几招帮你快速切换自定义壁纸。 我们平常使用的win10桌面壁纸大部分都是 简单、朴素的壁纸&#xff0c;但如果你想要切换自己喜…...

【大模型安全】安全解决方案

【大模型安全】安全解决方案 1.技术层面2.数据层面数据收集阶段训练阶段模型推理阶段 1.技术层面 在使用大语言模型时&#xff0c;通常有几种选择&#xff1a;一种是采用封装好的大语言模型SaaS云服务&#xff1b;另一种是在公有云上部署自有的大语言模型&#xff0c;并通过权…...

Windows编译环境搭建(MSYS2\MinGW\cmake)

我的音视频/流媒体开源项目(github) 一、基础环境搭建 1.1 MSYS2\MinGW 参考&#xff1a;1. 基于MSYS2的Mingw-w64 GCC搭建Windows下C开发环境_msys2使用mingw64编译 在Widndows系统上&#xff0c;使用gcc工具链&#xff08;g&#xff09;进行C程序开发&#xff1f;可以的&a…...

云曦春季开学考复现(2025)

Crypto 划水的dp和dq 下载附件后是简单的RSA算法题&#xff0c;之所以说简单是因为给了公钥e 趁热打铁&#xff0c;昨天刚学的RSA&#xff0c;既然有p有q&#xff0c;也有e&#xff0c;而np*q&#xff0c;可以算出欧拉函数值phi&#xff08;p-1&#xff09;*&#xff08;q-1&…...

股票交易所官方api接口有哪些?获取和使用需要满足什么条件

炒股自动化&#xff1a;申请官方API接口&#xff0c;散户也可以 python炒股自动化&#xff08;0&#xff09;&#xff0c;申请券商API接口 python炒股自动化&#xff08;1&#xff09;&#xff0c;量化交易接口区别 Python炒股自动化&#xff08;2&#xff09;&#xff1a;获取…...

《WebForms 实例》

《WebForms 实例》 引言 WebForms 是微软推出的一种用于构建动态Web应用程序的技术。它基于ASP.NET框架&#xff0c;允许开发者使用服务器端控件来构建用户界面&#xff0c;并通过事件驱动模型来响应用户交互。本文将通过一些实例&#xff0c;详细介绍WebForms的使用方法&…...

【每日学点HarmonyOS Next知识】 状态变量、公共Page、可见区域变化回调、接收参数、拖拽排序控件

1、HarmonyOS 在定时器里面改变state修饰的变量&#xff0c;无法更新UI吗&#xff1f; 将函数function写成了封装函数的形式就可以了 Entry Component struct Index {State acSetValve: number 0;aboutToAppear(): void {setInterval(() > {this.acSetValve 200;console…...

Intent3D

1. 研究背景 在现实世界中&#xff0c;人们寻找 3D 物体的行为往往基于特定意图&#xff0c;例如“我想要一个可以支撑我背部的东西”&#xff08;即寻找枕头&#xff09;。传统 3D 视觉定位&#xff08;3D-VG&#xff09;主要依赖人工提供的参照信息&#xff08;如“沙发上的…...

【Python 数据结构 10.二叉树】

目录 一、二叉树的基本概念 1.二叉树的定义 2.二叉树的特点 3.特殊的二叉树 Ⅰ、斜树 Ⅱ、满二叉树 Ⅲ、完全二叉树 Ⅳ、完全二叉树和满二叉树的区别 4.二叉树的性质 5.二叉树的顺序存储 Ⅰ、完全二叉树 Ⅱ、非完全二叉树 Ⅲ、稀疏二叉树 6.二叉树的链式存储 7.二叉树的遍历概念…...

从0开始的操作系统手搓教程27:下一步,实现我们的用户进程

目录 第一步&#xff1a;添加用户进程虚拟空间 准备冲向我们的特权级3&#xff08;用户特权级&#xff09; 讨论下我们创建用户线程的基本步骤 更加详细的分析代码 用户进程的视图 说一说BSS段 继续看process.c中的函数 添加用户线程激活 现在&#xff0c;我们做好了TSS…...

set、LinkedHashSet和TreeSet的区别、Map接口常见方法、Collections 工具类使用

DAY7.2 Java核心基础 想学习Collection、list、ArrayList、Set、HashSet部分的小伙伴可以转到 7.1集合框架、Collection、list、ArrayList、Set、HashSet和LinkedHashSet、判断两个对象是否相等文章查看 set集合 在set集合中&#xff0c;处理LinkedHashSet是有序的&#xf…...

Qt开发:nativeEvent事件的使用

文章目录 一、概述二、nativeEvent 的定义三、Windows 平台示例三、使用nativeEvent监测设备变化 一、概述 Qt 的 nativeEvent 是一个特殊的事件处理机制&#xff0c;允许开发者处理操作系统级别的原生事件。通常&#xff0c;Qt 通过 QEvent 机制来管理事件&#xff0c;但有时…...

鸿蒙Next-应用检测、安装以及企业内部商店的实现

一、企业内部应用检测和更新升级 A应用检测是否安装B应用 canOpenApp():boolean{ try { let link schB://com.example.test/open; // 替换成你目标应用的link串儿 let canOpen bundleManager.canOpenLink(link); console.log("canOpen:"canOpen…...

存量思维和增量思维

在网上看一篇文章&#xff0c;有两种典型的阅读方式。 一种&#xff0c;是挑刺式&#xff0c;眼里只有缺点。 比如&#xff0c;有人不厌其烦地告诉作者&#xff0c;哪段有错别字&#xff0c;哪段不够严谨。 闲得蛋疼。 有这工夫&#xff0c;多看会书&#xff0c;不香么&…...

golang将大接口传递给小接口以及场景

文章目录 golang将大接口传递给小接口背景什么是大接口传递给小接口使用场景 golang将大接口传递给小接口 背景 在 Go 语言中&#xff0c;接口是一种强大的工具&#xff0c;它允许我们定义对象的行为而不关心其具体实现。特别是在复杂的应用程序中&#xff0c;将一个实现了较…...

DockerHub与私有镜像仓库在容器化中的应用与管理

哈喽&#xff0c;大家好&#xff0c;我是左手python&#xff01; Docker Hub的应用与管理 Docker Hub的基本概念与使用方法 Docker Hub是Docker官方提供的一个公共镜像仓库&#xff0c;用户可以在其中找到各种操作系统、软件和应用的镜像。开发者可以通过Docker Hub轻松获取所…...

【入坑系列】TiDB 强制索引在不同库下不生效问题

文章目录 背景SQL 优化情况线上SQL运行情况分析怀疑1:执行计划绑定问题?尝试:SHOW WARNINGS 查看警告探索 TiDB 的 USE_INDEX 写法Hint 不生效问题排查解决参考背景 项目中使用 TiDB 数据库,并对 SQL 进行优化了,添加了强制索引。 UAT 环境已经生效,但 PROD 环境强制索…...

python如何将word的doc另存为docx

将 DOCX 文件另存为 DOCX 格式&#xff08;Python 实现&#xff09; 在 Python 中&#xff0c;你可以使用 python-docx 库来操作 Word 文档。不过需要注意的是&#xff0c;.doc 是旧的 Word 格式&#xff0c;而 .docx 是新的基于 XML 的格式。python-docx 只能处理 .docx 格式…...

linux 下常用变更-8

1、删除普通用户 查询用户初始UID和GIDls -l /home/ ###家目录中查看UID cat /etc/group ###此文件查看GID删除用户1.编辑文件 /etc/passwd 找到对应的行&#xff0c;YW343:x:0:0::/home/YW343:/bin/bash 2.将标红的位置修改为用户对应初始UID和GID&#xff1a; YW3…...

BCS 2025|百度副总裁陈洋:智能体在安全领域的应用实践

6月5日&#xff0c;2025全球数字经济大会数字安全主论坛暨北京网络安全大会在国家会议中心隆重开幕。百度副总裁陈洋受邀出席&#xff0c;并作《智能体在安全领域的应用实践》主题演讲&#xff0c;分享了在智能体在安全领域的突破性实践。他指出&#xff0c;百度通过将安全能力…...

UR 协作机器人「三剑客」:精密轻量担当(UR7e)、全能协作主力(UR12e)、重型任务专家(UR15)

UR协作机器人正以其卓越性能在现代制造业自动化中扮演重要角色。UR7e、UR12e和UR15通过创新技术和精准设计满足了不同行业的多样化需求。其中&#xff0c;UR15以其速度、精度及人工智能准备能力成为自动化领域的重要突破。UR7e和UR12e则在负载规格和市场定位上不断优化&#xf…...

vue3+vite项目中使用.env文件环境变量方法

vue3vite项目中使用.env文件环境变量方法 .env文件作用命名规则常用的配置项示例使用方法注意事项在vite.config.js文件中读取环境变量方法 .env文件作用 .env 文件用于定义环境变量&#xff0c;这些变量可以在项目中通过 import.meta.env 进行访问。Vite 会自动加载这些环境变…...

Swagger和OpenApi的前世今生

Swagger与OpenAPI的关系演进是API标准化进程中的重要篇章&#xff0c;二者共同塑造了现代RESTful API的开发范式。 本期就扒一扒其技术演进的关键节点与核心逻辑&#xff1a; &#x1f504; 一、起源与初创期&#xff1a;Swagger的诞生&#xff08;2010-2014&#xff09; 核心…...

在web-view 加载的本地及远程HTML中调用uniapp的API及网页和vue页面是如何通讯的?

uni-app 中 Web-view 与 Vue 页面的通讯机制详解 一、Web-view 简介 Web-view 是 uni-app 提供的一个重要组件&#xff0c;用于在原生应用中加载 HTML 页面&#xff1a; 支持加载本地 HTML 文件支持加载远程 HTML 页面实现 Web 与原生的双向通讯可用于嵌入第三方网页或 H5 应…...

《C++ 模板》

目录 函数模板 类模板 非类型模板参数 模板特化 函数模板特化 类模板的特化 模板&#xff0c;就像一个模具&#xff0c;里面可以将不同类型的材料做成一个形状&#xff0c;其分为函数模板和类模板。 函数模板 函数模板可以简化函数重载的代码。格式&#xff1a;templa…...