日B视频 亚洲,啪啪啪网站一区二区,91色情精品久久,日日噜狠狠色综合久,超碰人妻少妇97在线,999青青视频,亚洲一区二卡,让本一区二区视频,日韩网站推荐

0
  • 聊天消息
  • 系統(tǒng)消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會員中心
創(chuàng)作中心

完善資料讓更多小伙伴認識你,還能領取20積分哦,立即完善>

3天內(nèi)不再提示

使用LoRA和Hugging Face高效訓練大語言模型

深度學習自然語言處理 ? 來源:Hugging Face ? 2023-04-14 17:37 ? 次閱讀
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

在本文中,我們將展示如何使用 大語言模型低秩適配 (Low-Rank Adaptation of Large Language Models,LoRA) 技術在單 GPU 上微調(diào) 110 億參數(shù)的 FLAN-T5 XXL 模型。在此過程中,我們會使用到 Hugging Face 的 Transformers、Accelerate 和 PEFT 庫。

快速入門: 輕量化微調(diào) (Parameter Efficient Fine-Tuning,PEFT)

PEFT 是 Hugging Face 的一個新的開源庫。使用 PEFT 庫,無需微調(diào)模型的全部參數(shù),即可高效地將預訓練語言模型 (Pre-trained Language Model,PLM) 適配到各種下游應用。

注意: 本教程是在 g5.2xlarge AWS EC2 實例上創(chuàng)建和運行的,該實例包含 1 個 NVIDIA A10G。

1. 搭建開發(fā)環(huán)境

在本例中,我們使用 AWS 預置的 PyTorch 深度學習 AMI,其已安裝了正確的 CUDA 驅(qū)動程序和 PyTorch。在此基礎上,我們還需要安裝一些 Hugging Face 庫,包括 transformers 和 datasets。運行下面的代碼就可安裝所有需要的包。

#installHuggingFaceLibraries
!pipinstallgit+https://github.com/huggingface/peft.git
!pipinstall"transformers==4.27.1""datasets==2.9.0""accelerate==0.17.1""evaluate==0.4.0""bitsandbytes==0.37.1"loralib--upgrade--quiet
#installadditionaldependenciesneededfortraining
!pipinstallrouge-scoretensorboardpy7zr

2. 加載并準備數(shù)據(jù)集

這里,我們使用 samsum 數(shù)據(jù)集,該數(shù)據(jù)集包含大約 16k 個含摘要的聊天類對話數(shù)據(jù)。這些對話由精通英語的語言學家制作。

{
"id":"13818513",
"summary":"AmandabakedcookiesandwillbringJerrysometomorrow.",
"dialogue":"Amanda:Ibakedcookies.Doyouwantsome?
Jerry:Sure!
Amanda:I'llbringyoutomorrow:-)"
}

我們使用 Datasets 庫中的 load_dataset() 方法來加載 samsum 數(shù)據(jù)集。

fromdatasetsimportload_dataset

#Loaddatasetfromthehub
dataset=load_dataset("samsum")

print(f"Traindatasetsize:{len(dataset['train'])}")
print(f"Testdatasetsize:{len(dataset['test'])}")

#Traindatasetsize:14732
#Testdatasetsize:819

為了訓練模型,我們要用 Transformers Tokenizer 將輸入文本轉(zhuǎn)換為詞元 ID。

fromtransformersimportAutoTokenizer,AutoModelForSeq2SeqLM

model_id="google/flan-t5-xxl"

#LoadtokenizerofFLAN-t5-XL
tokenizer=AutoTokenizer.from_pretrained(model_id)

在開始訓練之前,我們還需要對數(shù)據(jù)進行預處理。生成式文本摘要屬于文本生成任務。我們將文本輸入給模型,模型會輸出摘要。我們需要了解輸入和輸出文本的長度信息,以利于我們高效地批量處理這些數(shù)據(jù)。

fromdatasetsimportconcatenate_datasets
importnumpyasnp
#Themaximumtotalinputsequencelengthaftertokenization.
#Sequenceslongerthanthiswillbetruncated,sequencesshorterwillbepadded.
tokenized_inputs=concatenate_datasets([dataset["train"],dataset["test"]]).map(lambdax:tokenizer(x["dialogue"],truncation=True),batched=True,remove_columns=["dialogue","summary"])
input_lenghts=[len(x)forxintokenized_inputs["input_ids"]]
#take85percentileofmaxlengthforbetterutilization
max_source_length=int(np.percentile(input_lenghts,85))
print(f"Maxsourcelength:{max_source_length}")

#Themaximumtotalsequencelengthfortargettextaftertokenization.
#Sequenceslongerthanthiswillbetruncated,sequencesshorterwillbepadded."
tokenized_targets=concatenate_datasets([dataset["train"],dataset["test"]]).map(lambdax:tokenizer(x["summary"],truncation=True),batched=True,remove_columns=["dialogue","summary"])
target_lenghts=[len(x)forxintokenized_targets["input_ids"]]
#take90percentileofmaxlengthforbetterutilization
max_target_length=int(np.percentile(target_lenghts,90))
print(f"Maxtargetlength:{max_target_length}")

我們將在訓練前統(tǒng)一對數(shù)據(jù)集進行預處理并將預處理后的數(shù)據(jù)集保存到磁盤。你可以在本地機器或 CPU 上運行此步驟并將其上傳到 Hugging Face Hub。

defpreprocess_function(sample,padding="max_length"):
#addprefixtotheinputfort5
inputs=["summarize:"+itemforiteminsample["dialogue"]]

#tokenizeinputs
model_inputs=tokenizer(inputs,max_length=max_source_length,padding=padding,truncation=True)

#Tokenizetargetswiththe`text_target`keywordargument
labels=tokenizer(text_target=sample["summary"],max_length=max_target_length,padding=padding,truncation=True)

#Ifwearepaddinghere,replacealltokenizer.pad_token_idinthelabelsby-100whenwewanttoignore
#paddingintheloss.
ifpadding=="max_length":
labels["input_ids"]=[
[(lifl!=tokenizer.pad_token_idelse-100)forlinlabel]forlabelinlabels["input_ids"]
]

model_inputs["labels"]=labels["input_ids"]
returnmodel_inputs

tokenized_dataset=dataset.map(preprocess_function,batched=True,remove_columns=["dialogue","summary","id"])
print(f"Keysoftokenizeddataset:{list(tokenized_dataset['train'].features)}")

#savedatasetstodiskforlatereasyloading
tokenized_dataset["train"].save_to_disk("data/train")
tokenized_dataset["test"].save_to_disk("data/eval")

3. 使用 LoRA 和 bnb int-8 微調(diào) T5

除了 LoRA 技術,我們還使用 bitsanbytes LLM.int8() 把凍結的 LLM 量化為 int8。這使我們能夠?qū)?FLAN-T5 XXL 所需的內(nèi)存降低到約四分之一。

訓練的第一步是加載模型。我們使用 philschmid/flan-t5-xxl-sharded-fp16 模型,它是 google/flan-t5-xxl 的分片版。分片可以讓我們在加載模型時不耗盡內(nèi)存。

fromtransformersimportAutoModelForSeq2SeqLM

#huggingfacehubmodelid
model_id="philschmid/flan-t5-xxl-sharded-fp16"

#loadmodelfromthehub
model=AutoModelForSeq2SeqLM.from_pretrained(model_id,load_in_8bit=True,device_map="auto")

現(xiàn)在,我們可以使用 peft 為 LoRA int-8 訓練作準備了。

frompeftimportLoraConfig,get_peft_model,prepare_model_for_int8_training,TaskType

#DefineLoRAConfig
lora_config=LoraConfig(
r=16,
lora_alpha=32,
target_modules=["q","v"],
lora_dropout=0.05,
bias="none",
task_type=TaskType.SEQ_2_SEQ_LM
)
#prepareint-8modelfortraining
model=prepare_model_for_int8_training(model)

#addLoRAadaptor
model=get_peft_model(model,lora_config)
model.print_trainable_parameters()

#trainableparams:18874368||allparams:11154206720||trainable%:0.16921300163961817

如你所見,這里我們只訓練了模型參數(shù)的 0.16%!這個巨大的內(nèi)存增益讓我們安心地微調(diào)模型,而不用擔心內(nèi)存問題。

接下來需要創(chuàng)建一個 DataCollator,負責對輸入和標簽進行填充,我們使用 Transformers 庫中的 DataCollatorForSeq2Seq 來完成這一環(huán)節(jié)。

fromtransformersimportDataCollatorForSeq2Seq

#wewanttoignoretokenizerpadtokenintheloss
label_pad_token_id=-100
#Datacollator
data_collator=DataCollatorForSeq2Seq(
tokenizer,
model=model,
label_pad_token_id=label_pad_token_id,
pad_to_multiple_of=8
)

最后一步是定義訓練超參 ( TrainingArguments)。

fromtransformersimportSeq2SeqTrainer,Seq2SeqTrainingArguments

output_dir="lora-flan-t5-xxl"

#Definetrainingargs
training_args=Seq2SeqTrainingArguments(
output_dir=output_dir,
auto_find_batch_size=True,
learning_rate=1e-3,#higherlearningrate
num_train_epochs=5,
logging_dir=f"{output_dir}/logs",
logging_strategy="steps",
logging_steps=500,
save_strategy="no",
report_to="tensorboard",
)

#CreateTrainerinstance
trainer=Seq2SeqTrainer(
model=model,
args=training_args,
data_collator=data_collator,
train_dataset=tokenized_dataset["train"],
)
model.config.use_cache=False#silencethewarnings.Pleasere-enableforinference!

運行下面的代碼,開始訓練模型。請注意,對于 T5,出于收斂穩(wěn)定性考量,某些層我們?nèi)员3?float32 精度。

#trainmodel
trainer.train()

訓練耗時約 10 小時 36 分鐘,訓練 10 小時的成本約為 13.22 美元。相比之下,如果 在 FLAN-T5-XXL 上進行全模型微調(diào) 10 個小時,我們需要 8 個 A100 40GB,成本約為 322 美元。

我們可以將模型保存下來以用于后面的推理和評估。我們暫時將其保存到磁盤,但你也可以使用 model.push_to_hub 方法將其上傳到 Hugging Face Hub。

#SaveourLoRAmodel&tokenizerresults
peft_model_id="results"
trainer.model.save_pretrained(peft_model_id)
tokenizer.save_pretrained(peft_model_id)
#ifyouwanttosavethebasemodeltocall
#trainer.model.base_model.save_pretrained(peft_model_id)

最后生成的 LoRA checkpoint 文件很小,僅需 84MB 就包含了從 samsum 數(shù)據(jù)集上學到的所有知識。

4. 使用 LoRA FLAN-T5 進行評估和推理

我們將使用 evaluate 庫來評估 rogue 分數(shù)。我們可以使用 PEFT 和 transformers 來對 FLAN-T5 XXL 模型進行推理。對 FLAN-T5 XXL 模型,我們至少需要 18GB 的 GPU 顯存。

importtorch
frompeftimportPeftModel,PeftConfig
fromtransformersimportAutoModelForSeq2SeqLM,AutoTokenizer

#Loadpeftconfigforpre-trainedcheckpointetc.
peft_model_id="results"
config=PeftConfig.from_pretrained(peft_model_id)

#loadbaseLLMmodelandtokenizer
model=AutoModelForSeq2SeqLM.from_pretrained(config.base_model_name_or_path,load_in_8bit=True,device_map={"":0})
tokenizer=AutoTokenizer.from_pretrained(config.base_model_name_or_path)

#LoadtheLoramodel
model=PeftModel.from_pretrained(model,peft_model_id,device_map={"":0})
model.eval()

print("Peftmodelloaded")

我們用測試數(shù)據(jù)集中的一個隨機樣本來試試摘要效果。

fromdatasetsimportload_dataset
fromrandomimportrandrange

#Loaddatasetfromthehubandgetasample
dataset=load_dataset("samsum")
sample=dataset['test'][randrange(len(dataset["test"]))]

input_ids=tokenizer(sample["dialogue"],return_tensors="pt",truncation=True).input_ids.cuda()
#withtorch.inference_mode():
outputs=model.generate(input_ids=input_ids,max_new_tokens=10,do_sample=True,top_p=0.9)
print(f"inputsentence:{sample['dialogue']}
{'---'*20}")

print(f"summary:
{tokenizer.batch_decode(outputs.detach().cpu().numpy(),skip_special_tokens=True)[0]}")

不錯!我們的模型有效!現(xiàn)在,讓我們仔細看看,并使用 test 集中的全部數(shù)據(jù)對其進行評估。為此,我們需要實現(xiàn)一些工具函數(shù)來幫助生成摘要并將其與相應的參考摘要組合到一起。評估摘要任務最常用的指標是 rogue_score,它的全稱是 Recall-Oriented Understudy for Gisting Evaluation。與常用的準確率指標不同,它將生成的摘要與一組參考摘要進行比較。

importevaluate
importnumpyasnp
fromdatasetsimportload_from_disk
fromtqdmimporttqdm

#Metric
metric=evaluate.load("rouge")

defevaluate_peft_model(sample,max_target_length=50):
#generatesummary
outputs=model.generate(input_ids=sample["input_ids"].unsqueeze(0).cuda(),do_sample=True,top_p=0.9,max_new_tokens=max_target_length)
prediction=tokenizer.decode(outputs[0].detach().cpu().numpy(),skip_special_tokens=True)
#decodeevalsample
#Replace-100inthelabelsaswecan'tdecodethem.
labels=np.where(sample['labels']!=-100,sample['labels'],tokenizer.pad_token_id)
labels=tokenizer.decode(labels,skip_special_tokens=True)

#Somesimplepost-processing
returnprediction,labels

#loadtestdatasetfromdistk
test_dataset=load_from_disk("data/eval/").with_format("torch")

#runpredictions
#thiscantake~45minutes
predictions,references=[],[]
forsampleintqdm(test_dataset):
p,l=evaluate_peft_model(sample)
predictions.append(p)
references.append(l)

#computemetric
rogue=metric.compute(predictions=predictions,references=references,use_stemmer=True)

#printresults
print(f"Rogue1:{rogue['rouge1']*100:2f}%")
print(f"rouge2:{rogue['rouge2']*100:2f}%")
print(f"rougeL:{rogue['rougeL']*100:2f}%")
print(f"rougeLsum:{rogue['rougeLsum']*100:2f}%")

#Rogue1:50.386161%
#rouge2:24.842412%
#rougeL:41.370130%
#rougeLsum:41.394230%

我們 PEFT 微調(diào)后的 FLAN-T5-XXL 在測試集上取得了 50.38% 的 rogue1 分數(shù)。相比之下,flan-t5-base 的全模型微調(diào)獲得了 47.23 的 rouge1 分數(shù)。rouge1 分數(shù)提高了 3%。

令人難以置信的是,我們的 LoRA checkpoint 只有 84MB,而且性能比對更小的模型進行全模型微調(diào)后的 checkpoint 更好。





審核編輯:劉清

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權轉(zhuǎn)載。文章觀點僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學習之用,如有內(nèi)容侵權或者其他違規(guī)問題,請聯(lián)系本站處理。 舉報投訴
  • PLM
    PLM
    +關注

    關注

    2

    文章

    150

    瀏覽量

    22200
  • AWS
    AWS
    +關注

    關注

    0

    文章

    444

    瀏覽量

    26643
  • LoRa模塊
    +關注

    關注

    5

    文章

    156

    瀏覽量

    15400
  • pytorch
    +關注

    關注

    2

    文章

    813

    瀏覽量

    14930

原文標題:使用 LoRA 和 Hugging Face 高效訓練大語言模型

文章出處:【微信號:zenRRan,微信公眾號:深度學習自然語言處理】歡迎添加關注!文章轉(zhuǎn)載請注明出處。

收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評論

    相關推薦
    熱點推薦

    零基礎手寫大模型資料2026

    間通信開銷,通常采用NCCL等高效通信庫。 四、技術演進:從手寫原型到工業(yè)級模型 手寫大模型的核心價值在于理解技術本質(zhì),而工業(yè)級實現(xiàn)需解決更多工程問題:混合精度訓練(FP16/FP32
    發(fā)表于 05-01 17:44

    HM博學谷狂野AI大模型第四期

    。例如,數(shù)據(jù)并行(DDP)與模型并行是如何在多 GPU 集群中協(xié)同工作,梯度累積與混合精度訓練又是如何在節(jié)省顯存的同時保證計算精度。更重要的是,課程將深入剖析 PEFT(參數(shù)高效微調(diào))技術,如
    發(fā)表于 05-01 17:30

    Edge Impulse 喚醒詞模型訓練 | 技術集結

    今天,將手把手帶領學習如何訓練一個語音關鍵詞模型部署到嵌入式硬件上,采用Edgi-Talk平臺適配EdgeImpulse,當然原理在其他的ARM嵌入式平臺也是通用的。讓我們看看如何讓
    的頭像 發(fā)表于 04-20 10:05 ?1248次閱讀
    Edge Impulse 喚醒詞<b class='flag-5'>模型</b><b class='flag-5'>訓練</b> | 技術集結

    NVIDIA Alpamayo 1模型Hugging Face平臺下載量已突破10萬次

    NVIDIA Alpamayo 1 在 Hugging Face 的下載量已突破 10 萬次,且仍在持續(xù)增長,已成為 Hugging Face 平臺下載量最高的機器人
    的頭像 發(fā)表于 03-04 16:27 ?1010次閱讀

    什么是大模型,智能體...?大模型100問,快速全面了解!

    一、概念篇1.什么是大模型?大模型是指參數(shù)規(guī)模巨大(通常達到數(shù)十億甚至萬億級別)、使用海量數(shù)據(jù)訓練而成的人工智能模型。2.什么是大語言
    的頭像 發(fā)表于 02-02 16:36 ?1154次閱讀
    什么是大<b class='flag-5'>模型</b>,智能體...?大<b class='flag-5'>模型</b>100問,快速全面了解!

    NVIDIA推出面向語言、機器人和生物學的全新開源AI技術

    NVIDIA 秉持對開源的長期承諾,推出了面向語言、機器人和生物學的全新開源 AI 技術,為構建開源生態(tài)系統(tǒng)做出貢獻,擴展 AI 的普及并推動創(chuàng)新。NVIDIA 正將這些模型、數(shù)據(jù)和訓練框架貢獻給
    的頭像 發(fā)表于 11-06 11:49 ?1325次閱讀

    在Ubuntu20.04系統(tǒng)中訓練神經(jīng)網(wǎng)絡模型的一些經(jīng)驗

    本帖欲分享在Ubuntu20.04系統(tǒng)中訓練神經(jīng)網(wǎng)絡模型的一些經(jīng)驗。我們采用jupyter notebook作為開發(fā)IDE,以TensorFlow2為訓練框架,目標是訓練一個手寫數(shù)字識
    發(fā)表于 10-22 07:03

    NVIDIA開源Audio2Face模型及SDK

    NVIDIA 現(xiàn)已開源 Audio2Face 模型與 SDK,讓所有游戲和 3D 應用開發(fā)者都可以構建并部署帶有先進動畫的高精度角色。NVIDIA 開源 Audio2Face訓練
    的頭像 發(fā)表于 10-21 11:11 ?1037次閱讀
    NVIDIA開源Audio2<b class='flag-5'>Face</b><b class='flag-5'>模型</b>及SDK

    借助NVIDIA Megatron-Core大模型訓練框架提高顯存使用效率

    隨著模型規(guī)模邁入百億、千億甚至萬億參數(shù)級別,如何在有限顯存中“塞下”訓練任務,對研發(fā)和運維團隊都是巨大挑戰(zhàn)。NVIDIA Megatron-Core 作為流行的大模型訓練框架,提供了靈
    的頭像 發(fā)表于 10-21 10:55 ?1429次閱讀
    借助NVIDIA Megatron-Core大<b class='flag-5'>模型</b><b class='flag-5'>訓練</b>框架提高顯存使用效率

    什么是AI模型的推理能力

    NVIDIA 的數(shù)據(jù)工廠團隊為 NVIDIA Cosmos Reason 等 AI 模型奠定了基礎,該模型近日在 Hugging Face 的物理推理
    的頭像 發(fā)表于 09-23 15:19 ?1515次閱讀

    ai_cube訓練模型最后部署失敗是什么原因?

    ai_cube訓練模型最后部署失敗是什么原因?文件保存路徑里也沒有中文 查看AICube/AI_Cube.log,看看報什么錯?
    發(fā)表于 07-30 08:15

    利用自壓縮實現(xiàn)大型語言模型高效縮減

    隨著語言模型規(guī)模日益龐大,設備端推理變得越來越緩慢且耗能巨大。一個直接且效果出人意料的解決方案是剪除那些對任務貢獻甚微的完整通道(channel)。我們早期的研究提出了一種訓練階段的方法——自壓
    的頭像 發(fā)表于 07-28 09:36 ?682次閱讀
    利用自壓縮實現(xiàn)大型<b class='flag-5'>語言</b><b class='flag-5'>模型</b><b class='flag-5'>高效</b>縮減

    沐曦MXMACA軟件平臺在大模型訓練方面的優(yōu)化效果

    在如今的人工智能浪潮中,大規(guī)模語言模型(上百億乃至千億參數(shù))正迅速改變著我們的工作和生活。然而,訓練這些龐大的模型往往面臨“算力不足、顯存不夠用、通信太慢”等諸多挑戰(zhàn)。
    的頭像 發(fā)表于 07-03 14:09 ?2444次閱讀
    沐曦MXMACA軟件平臺在大<b class='flag-5'>模型</b><b class='flag-5'>訓練</b>方面的優(yōu)化效果

    make sence成的XML文件能上傳到自助訓練模型上嗎?

    make sence成的XML文件能上傳到自助訓練模型上嗎
    發(fā)表于 06-23 07:38

    商湯科技日日新V6大模型斬獲“雙料第一” 一項國內(nèi)榜首,一個全球第一

    衛(wèi)冕“雙冠”! 通用語言能力并列國內(nèi)榜首、多模態(tài)能力全球最強,商湯「日日新V6」近期斬獲“雙料第一”。 5月28日,權威大模型測評機構SuperCLUE《中文大模型基準測評2025年5月報告》全新
    的頭像 發(fā)表于 05-30 11:13 ?1753次閱讀
    商湯科技日日新V6大<b class='flag-5'>模型</b>斬獲“雙料第一” 一項國內(nèi)榜首,一個全球第一
    沾益县| 福州市| 揭西县| 凉山| 晋中市| 金阳县| 乐业县| 黄石市| 宁晋县| 固安县| 吉木萨尔县| 乃东县| 河西区| 阿尔山市| 建始县| 辰溪县| 雷山县| 阿坝县| 名山县| 赤城县| 申扎县| 镇远县| 若羌县| 蒲江县| 汨罗市| 镇江市| 禹城市| 和硕县| 汾阳市| 广西| 永安市| 庆云县| 循化| 凯里市| 天峨县| 漾濞| 南投市| 永城市| 晋江市| 永和县| 临洮县|