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

相关文章

MySQL中的LENGTH()函数用法详解与实例分析

《MySQL中的LENGTH()函数用法详解与实例分析》MySQLLENGTH()函数用于计算字符串的字节长度,区别于CHAR_LENGTH()的字符长度,适用于多字节字符集(如UTF-8)的数据验证... 目录1. LENGTH()函数的基本语法2. LENGTH()函数的返回值2.1 示例1:计算字符串

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Python通用唯一标识符模块uuid使用案例详解

《Python通用唯一标识符模块uuid使用案例详解》Pythonuuid模块用于生成128位全局唯一标识符,支持UUID1-5版本,适用于分布式系统、数据库主键等场景,需注意隐私、碰撞概率及存储优... 目录简介核心功能1. UUID版本2. UUID属性3. 命名空间使用场景1. 生成唯一标识符2. 数

Linux系统性能检测命令详解

《Linux系统性能检测命令详解》本文介绍了Linux系统常用的监控命令(如top、vmstat、iostat、htop等)及其参数功能,涵盖进程状态、内存使用、磁盘I/O、系统负载等多维度资源监控,... 目录toppsuptimevmstatIOStatiotopslabtophtopdstatnmon

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

Java中的数组与集合基本用法详解

《Java中的数组与集合基本用法详解》本文介绍了Java数组和集合框架的基础知识,数组部分涵盖了一维、二维及多维数组的声明、初始化、访问与遍历方法,以及Arrays类的常用操作,对Java数组与集合相... 目录一、Java数组基础1.1 数组结构概述1.2 一维数组1.2.1 声明与初始化1.2.2 访问

SpringBoot线程池配置使用示例详解

《SpringBoot线程池配置使用示例详解》SpringBoot集成@Async注解,支持线程池参数配置(核心数、队列容量、拒绝策略等)及生命周期管理,结合监控与任务装饰器,提升异步处理效率与系统... 目录一、核心特性二、添加依赖三、参数详解四、配置线程池五、应用实践代码说明拒绝策略(Rejected

一文详解SpringBoot中控制器的动态注册与卸载

《一文详解SpringBoot中控制器的动态注册与卸载》在项目开发中,通过动态注册和卸载控制器功能,可以根据业务场景和项目需要实现功能的动态增加、删除,提高系统的灵活性和可扩展性,下面我们就来看看Sp... 目录项目结构1. 创建 Spring Boot 启动类2. 创建一个测试控制器3. 创建动态控制器注