BaiChuan13B-GPTQ量化详解

2024-04-19 05:44
文章标签 详解 量化 gptq baichuan13b

本文主要是介绍BaiChuan13B-GPTQ量化详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

知识要点:
1、按照网上搜索的一些代码,如使用auto_gptq原生库进行训练后量化,可能会正常量化,但是在线推理时会出现如找不到bin文件或者tf文件,即模型权重文件,所以和网上大部分代码不同的地方在于,需要提前保存对应模型的权重文件,如果是BaiChuan13B,那么在进行模型量化前,对其进行保存
代码如下:

def save_bin(pretrained_model_dir, quantized_model_dir):from transformers import AutoModelForCausalLMimport torchimport osoriginal_model = AutoModelForCausalLM.from_pretrained(pretrained_model_dir, trust_remote_code=True,torch_dtype=torch.float16,      # 不执行这个保存的bin文件会非常的大,大概50多Gsafetensors=True)print("保存bin文件...")model_path = os.path.join(quantized_model_dir, "pytorch_model"+".bin")torch.save(original_model.state_dict(), model_path)print("保存bin文件完成...")

量化代码,使用原生库auto_gptq进行量化:

def from_authority_autogptq(pretrained_model_dir, quantized_model_dir):from transformers import AutoTokenizer, AutoModelForCausalLMfrom auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfigimport loggingimport torchimport oslogging.basicConfig(format="%(asctime)s %(levelname)s [%(name)s] %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S")# 量化分词器加载tokenizer = AutoTokenizer.from_pretrained(pretrained_model_dir, use_fast=False, trust_remote_code=True)examples = [tokenizer("auto-gptq is an easy-to-use model quantization library with user-friendly apis, based on GPTQ algorithm.")]# 量化参数配置quantize_config = BaseQuantizeConfig(bits=4,             # quantize model to 4-bitgroup_size=128,     # it is recommended to set the value to 128desc_act=False,     # set to False can significantly speed up inference but the perplexity may slightly bad)# load un-quantized model, by default, the model will always be loaded into CPU memoryquantize_model = AutoGPTQForCausalLM.from_pretrained(pretrained_model_dir, quantize_config=quantize_config, trust_remote_code=True,device_map="auto",)print("开始量化模型.......")quantize_model.quantize(examples)# save model weightsprint("保存量化文件...")quantize_model.save_quantized(quantized_model_dir)print("保存量化文件完成...")print("保存tokenizer...")tokenizer.save_pretrained(quantized_model_dir)print("保存tokenizer完成...")

按照上述步骤,此时模型量化文件保存成功,接下来就是模型在线推理

def get_baichuan2_autogptq(quantized_model_dir):from transformers import AutoModelForCausalLM, AutoTokenizerfrom transformers.generation.utils import GenerationConfigimport torch# 模型地址model_id = quantized_model_dirprint("加载分词器tokenizer...")tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True,use_fast=False)'''warnings.warn(f'Input type into Linear4bit is torch.float16, but bnb_4bit_compute_type=torch.float32 (default).This will lead to slow inference or training speed'''print("加载量化model...")quantized_model_4bit = AutoModelForCausalLM.from_pretrained(# 要载入的模型名称model_id, load_in_4bit=True,# 仅使用本地模型,不通过网络下载模型local_files_only=True,# 指定模型精度torch_dtype=torch.float16,trust_remote_code=True,safetensors=True)print("加载config...")quantized_model_4bit.generation_config = GenerationConfig.from_pretrained(model_id)# 实例测试print("生成...")messages = []messages.append({"role": "user", "content":"亚历山大为何如此厉害"})response = quantized_model_4bit.chat(tokenizer, messages)print(response)return response 

最后整合代码:

'''bin 文件是保存的是原始的加载模型文件,不涉及量化操作的模型过程,不然会报错或者加载不出来!!!'''
def save_bin(pretrained_model_dir, quantized_model_dir):from transformers import AutoModelForCausalLMimport torchimport osoriginal_model = AutoModelForCausalLM.from_pretrained(pretrained_model_dir, trust_remote_code=True,torch_dtype=torch.float16,      # 不执行这个保存的bin文件会非常的大,大概50多Gsafetensors=True)print("保存bin文件...")model_path = os.path.join(quantized_model_dir, "pytorch_model"+".bin")torch.save(original_model.state_dict(), model_path)print("保存bin文件完成...")# auto_gptq原生库, 量化占用显存7-10G不等,用时23分钟,推理18G
def from_authority_autogptq(pretrained_model_dir, quantized_model_dir):from transformers import AutoTokenizer, AutoModelForCausalLMfrom auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfigimport loggingimport torchimport oslogging.basicConfig(format="%(asctime)s %(levelname)s [%(name)s] %(message)s", level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S")# 量化分词器加载tokenizer = AutoTokenizer.from_pretrained(pretrained_model_dir, use_fast=False, trust_remote_code=True)examples = [tokenizer("auto-gptq is an easy-to-use model quantization library with user-friendly apis, based on GPTQ algorithm.")]# 量化参数配置quantize_config = BaseQuantizeConfig(bits=4,             # quantize model to 4-bitgroup_size=128,     # it is recommended to set the value to 128desc_act=False,     # set to False can significantly speed up inference but the perplexity may slightly bad)# load un-quantized model, by default, the model will always be loaded into CPU memoryquantize_model = AutoGPTQForCausalLM.from_pretrained(pretrained_model_dir, quantize_config=quantize_config, trust_remote_code=True,device_map="auto",)print("开始量化模型.......")quantize_model.quantize(examples)# save model weightsprint("保存量化文件...")quantize_model.save_quantized(quantized_model_dir)print("保存量化文件完成...")print("保存tokenizer...")tokenizer.save_pretrained(quantized_model_dir)print("保存tokenizer完成...")# 加载量化后的模型方法
def get_baichuan2_autogptq(quantized_model_dir):from transformers import AutoModelForCausalLM, AutoTokenizerfrom transformers.generation.utils import GenerationConfigimport torch# 模型地址model_id = quantized_model_dirprint("加载分词器tokenizer...")tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True,use_fast=False)'''warnings.warn(f'Input type into Linear4bit is torch.float16, but bnb_4bit_compute_type=torch.float32 (default).This will lead to slow inference or training speed'''print("加载量化model...")quantized_model_4bit = AutoModelForCausalLM.from_pretrained(# 要载入的模型名称model_id, load_in_4bit=True,# 仅使用本地模型,不通过网络下载模型local_files_only=True,# 指定模型精度torch_dtype=torch.float16,trust_remote_code=True,safetensors=True)print("加载config...")quantized_model_4bit.generation_config = GenerationConfig.from_pretrained(model_id)# 实例测试print("生成...")messages = []messages.append({"role": "user", "content":"```桥架\n1、名称:机房走线架(铝合金) 2、规格:300mm*100mm 3、含支吊架制作安装 4、其它:具体详见图纸、技术规范书、图集、招标文件、招标答疑、政府相关文件、规范等其它资料,满足验收要求```\n请仔细阅读上文,并从中分析出实体列表中的各实体。请使用json字典格式回答,其中,键为各实体名称,值为从文本中提取出的内容(若没有相应实体则值为'无')。\n实体列表如下(目标实体之间通过“;”隔开): ```名称;型号;材质;类型;规格;接地方式```"})response = quantized_model_4bit.chat(tokenizer, messages)print(response)return response if __name__ == "__main__":# from_transformers_autogptq 方法量化模型# pretrained_model_dir = "/root/lk/big_model/Baichuan2-13B-Chat"# quantized_model_dir = "/root/lk/big_model/baichuan2_autogptq"# from_transformers_autogptq(pretrained_model_dir, quantized_model_dir)import datetimeprint("程序开始时间------->>>>>>", datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))# 地址pretrained_model_dir = "/root/lk/big_model/Baichuan2-13B-Chat"quantized_model_dir = "/root/lk/big_model/baichuan2_autogptq"# 第一步:保存原始模型的Bin文件,然后再量化(很关键)# save_bin(pretrained_model_dir, quantized_model_dir)# 第二部:执行来自autogptq原始包量化模型# from_authority_autogptq(pretrained_model_dir, quantized_model_dir)# 第三部:使用量化模型进行推理(需要添加对应文件)get_baichuan2_autogptq(quantized_model_dir)print("程序结束时间------->>>>>>", datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

对应包版本:

auto-gptq==0.6.0
transformers==4.39.2
torch==2.0.1

这篇关于BaiChuan13B-GPTQ量化详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/916752

相关文章

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

MySQL 删除数据详解(最新整理)

《MySQL删除数据详解(最新整理)》:本文主要介绍MySQL删除数据的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、前言二、mysql 中的三种删除方式1.DELETE语句✅ 基本语法: 示例:2.TRUNCATE语句✅ 基本语

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

Java内存分配与JVM参数详解(推荐)

《Java内存分配与JVM参数详解(推荐)》本文详解JVM内存结构与参数调整,涵盖堆分代、元空间、GC选择及优化策略,帮助开发者提升性能、避免内存泄漏,本文给大家介绍Java内存分配与JVM参数详解,... 目录引言JVM内存结构JVM参数概述堆内存分配年轻代与老年代调整堆内存大小调整年轻代与老年代比例元空

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

mysql表操作与查询功能详解

《mysql表操作与查询功能详解》本文系统讲解MySQL表操作与查询,涵盖创建、修改、复制表语法,基本查询结构及WHERE、GROUPBY等子句,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随... 目录01.表的操作1.1表操作概览1.2创建表1.3修改表1.4复制表02.基本查询操作2.1 SE

MySQL中的锁机制详解之全局锁,表级锁,行级锁

《MySQL中的锁机制详解之全局锁,表级锁,行级锁》MySQL锁机制通过全局、表级、行级锁控制并发,保障数据一致性与隔离性,全局锁适用于全库备份,表级锁适合读多写少场景,行级锁(InnoDB)实现高并... 目录一、锁机制基础:从并发问题到锁分类1.1 并发访问的三大问题1.2 锁的核心作用1.3 锁粒度分

MySQL数据库中ENUM的用法是什么详解

《MySQL数据库中ENUM的用法是什么详解》ENUM是一个字符串对象,用于指定一组预定义的值,并可在创建表时使用,下面:本文主要介绍MySQL数据库中ENUM的用法是什么的相关资料,文中通过代码... 目录mysql 中 ENUM 的用法一、ENUM 的定义与语法二、ENUM 的特点三、ENUM 的用法1