AutoGPTQ 大语言模型量化工具包开源项目

我要开发同款
匿名用户2023年06月08日
359阅读

技术信息

开源地址
https://github.com/PanQiWei/AutoGPTQ/blob/main/README_zh.md
授权协议
MIT

作品详情

AutoGPTQ是一个基于GPTQ算法,简单易用且拥有用户友好型接口的大语言模型量化工具包。

性能对比推理速度

以下结果通过这个脚本生成,文本输入的batchsize为1,解码策略为beamsearch并且强制模型生成512个toke,速度的计量单位为tokes/s(越大越好)。

量化模型通过能够最大化推理速度的方式加载。

modelGPUum_beamsfp16gptq-it4llama-7b1xA100-40G118.8725.53llama-7b1xA100-40G468.7991.30moss-moo16b1xA100-40G112.4815.25moss-moo16b1xA100-40G4OOM42.67moss-moo16b2xA100-40G106.8306.78moss-moo16b2xA100-40G413.1010.80gpt-j6b1xRTX3060-12G1OOM29.55gpt-j6b1xRTX3060-12G4OOM47.36困惑度(PPL)对于困惑度的对比,你可以参考 这里 和 这里

快速开始量化和推理

警告:这里仅是对AutoGPTQ中基本接口的用法展示,只使用了一条文本来量化一个特别小的模型,因此其结果的表现可能不如在大模型上执行量化后预期的那样好。

以下展示了使用 auto_gptq 进行量化和推理的最简单用法:

fromtrasformersimportAutoTokeizer,TextGeeratioPipeliefromauto_gptqimportAutoGPTQForCausalLM,BaseQuatizeCofigpretraied_model_dir="facebook/opt-125m"quatized_model_dir="opt-125m-4bit"tokeizer=AutoTokeizer.from_pretraied(pretraied_model_dir,use_fast=True)examples=[tokeizer("auto-gptqisaeasy-to-usemodelquatizatiolibrarywithuser-friedlyapis,basedoGPTQalgorithm.")]quatize_cofig=BaseQuatizeCofig(bits=4,#将模型量化为4-bit数值类型group_size=128,#一般推荐将此参数的值设置为128desc_act=False,#设为False可以显著提升推理速度,但是ppl可能会轻微地变差)#加载未量化的模型,默认情况下,模型总是会被加载到CPU内存中model=AutoGPTQForCausalLM.from_pretraied(pretraied_model_dir,quatize_cofig)#量化模型,样本的数据类型应该为List[Dict],其中字典的键有且仅有iput_ids和attetio_maskmodel.quatize(examples)#保存量化好的模型model.save_quatized(quatized_model_dir)#使用safetesors保存量化好的模型model.save_quatized(quatized_model_dir,use_safetesors=True)#将量化好的模型直接上传至HuggigFaceHub#当使用use_auth_toke=True时,确保你已经首先使用huggigface-clilogi进行了登录#或者可以使用use_auth_toke="hf_xxxxxxx"来显式地添加账户认证toke#(取消下面三行代码的注释来使用该功能)#repo_id=f"YourUserName/{quatized_model_dir}"#commit_message=f"AutoGPTQmodelfor{pretraied_model_dir}:{quatize_cofig.bits}bits,gr{quatize_cofig.group_size},desc_act={quatize_cofig.desc_act}"#model.push_to_hub(repo_id,commit_message=commit_message,use_auth_toke=True)#或者你也可以同时将量化好的模型保存到本地并上传至HuggigFaceHub#(取消下面三行代码的注释来使用该功能)#repo_id=f"YourUserName/{quatized_model_dir}"#commit_message=f"AutoGPTQmodelfor{pretraied_model_dir}:{quatize_cofig.bits}bits,gr{quatize_cofig.group_size},desc_act={quatize_cofig.desc_act}"#model.push_to_hub(repo_id,save_dir=quatized_model_dir,use_safetesors=True,commit_message=commit_message,use_auth_toke=True)#加载量化好的模型到能被识别到的第一块显卡中model=AutoGPTQForCausalLM.from_quatized(quatized_model_dir,device="cuda:0")#从HuggigFaceHub下载量化好的模型并加载到能被识别到的第一块显卡中#model=AutoGPTQForCausalLM.from_quatized(repo_id,device="cuda:0",use_safetesors=True,use_trito=False)#使用model.geerate执行推理prit(tokeizer.decode(model.geerate(**tokeizer("auto_gptqis",retur_tesors="pt").to(model.device))[0]))#或者使用TextGeeratioPipeliepipelie=TextGeeratioPipelie(model=model,tokeizer=tokeizer)prit(pipelie("auto-gptqis")[0]["geerated_text"])参考 此样例脚本 以了解进阶的用法。

自定义模型

以下展示了如何拓展`auto_gptq`以支持`OPT`模型,如你所见,这非常简单:

fromauto_gptq.modeligimportBaseGPTQForCausalLMclassOPTGPTQForCausalLM(BaseGPTQForCausalLM):#chaiedattributeameoftrasformerlayerblocklayers_block_ame="model.decoder.layers"#chaiedattributeamesofothermodulesthatithesamelevelasthetrasformerlayerblockoutside_layer_modules=["model.decoder.embed_tokes","model.decoder.embed_positios","model.decoder.project_out","model.decoder.project_i","model.decoder.fial_layer_orm"]#chaiedattributeamesofliearlayersitrasformerlayermodule#ormally,therearefoursublists,foreachoethemodulesiitcabeseeasoeoperatio,#adtheordershouldbetheorderwhetheyaretrulyexecuted,ithiscase(adusuallyimostcases),#theyare:attetioq_k_vprojectio,attetiooutputprojectio,MLPprojectiput,MLPprojectoutputiside_layer_modules=[["self_att.k_proj","self_att.v_proj","self_att.q_proj"],["self_att.out_proj"],["fc1"],["fc2"]]

然后,你就可以像在基本用法一节中展示的那样使用 OPTGPTQForCausalLM.from_pretraied 和其他方法。

在下游任务上执行评估

你可以使用在 auto_gptq.eval_tasks 中定义的任务来评估量化前后的模型在某个特定下游任务上的表现。

这些预定义的模型支持所有在 trasformers 和本项目中被实现了的causal-laguage-models。

以下是使用`cardifflp/tweet_setimet_multiligual`数据集在序列分类(文本分类)任务上评估`EleutherAI/gpt-j-6b`模型的示例:fromfuctoolsimportpartialimportdatasetsfromtrasformersimportAutoTokeizer,AutoModelForCausalLM,GeeratioCofigfromauto_gptqimportAutoGPTQForCausalLM,BaseQuatizeCofigfromauto_gptq.eval_tasksimportSequeceClassificatioTaskMODEL="EleutherAI/gpt-j-6b"DATASET="cardifflp/tweet_setimet_multiligual"TEMPLATE="Questio:What'sthesetimetofthegivetext?Choicesare{labels}.\Text:{text}\Aswer:"ID2LABEL={0:"egative",1:"eutral",2:"positive"}LABELS=list(ID2LABEL.values())defds_refactor_f(samples):text_data=samples["text"]label_data=samples["label"]ew_samples={"prompt":[],"label":[]}fortext,labelizip(text_data,label_data):prompt=TEMPLATE.format(labels=LABELS,text=text)ew_samples["prompt"].apped(prompt)ew_samples["label"].apped(ID2LABEL[label])returew_samples#model=AutoModelForCausalLM.from_pretraied(MODEL).eval().half().to("cuda:0")model=AutoGPTQForCausalLM.from_pretraied(MODEL,BaseQuatizeCofig())tokeizer=AutoTokeizer.from_pretraied(MODEL)task=SequeceClassificatioTask(model=model,tokeizer=tokeizer,classes=LABELS,data_ame_or_path=DATASET,prompt_col_ame="prompt",label_col_ame="label",**{"um_samples":1000,#howmaysampleswillbesampledtoevaluatio"sample_max_le":1024,#maxtokesforeachsample"block_max_le":2048,#maxtokesforeachdatablock#fuctiotoloaddataset,oemustolyacceptdata_ame_or_pathasiput#adreturdatasets.Dataset"load_f":partial(datasets.load_dataset,ame="eglish"),#fuctiotopreprocessdataset,whichisusedfordatasets.Dataset.map,#mustreturDict[str,list]witholytwokeys:[prompt_col_ame,label_col_ame]"preprocess_f":ds_refactor_f,#trucatelabelwhesample'slegthexceedsample_max_le"trucate_prompt":False})#otethatmax_ew_tokeswillbeautomaticallyspecifiediterallybasedogiveclassesprit(task.ru())#self-cosistecyprit(task.ru(geeratio_cofig=GeeratioCofig(um_beams=3,um_retur_sequeces=3,do_sample=True)))了解更多

教程 提供了将 auto_gptq 集成到你的项目中的手把手指导和最佳实践准则。

示例 提供了大量示例脚本以将 auto_gptq 用于不同领域。

功能介绍

AutoGPTQ 是一个基于 GPTQ 算法,简单易用且拥有用户友好型接口的大语言模型量化工具包。 性能对比 推理速度 以下结果通过这个脚本生成,文本输入的 batch size 为1,解码策略...

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论