<acronym id="s8ci2"><small id="s8ci2"></small></acronym>
<rt id="s8ci2"></rt><rt id="s8ci2"><optgroup id="s8ci2"></optgroup></rt>
<acronym id="s8ci2"></acronym>
<acronym id="s8ci2"><center id="s8ci2"></center></acronym>
0
  • 聊天消息
  • 系統消息
  • 評論與回復
登錄后你可以
  • 下載海量資料
  • 學習在線課程
  • 觀看技術視頻
  • 寫文章/發帖/加入社區
會員中心
創作中心

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

3天內不再提示

怎樣使用Accelerate庫在多GPU上進行LLM推理呢?

冬至子 ? 來源:思否AI ? 作者:思否AI ? 2023-12-01 10:24 ? 次閱讀

大型語言模型(llm)已經徹底改變了自然語言處理領域。隨著這些模型在規模和復雜性上的增長,推理的計算需求也顯著增加。為了應對這一挑戰利用多個gpu變得至關重要。

所以本文將在多個gpu上并行執行推理,主要包括:Accelerate庫介紹,簡單的方法與工作代碼示例和使用多個gpu的性能基準測試。

本文將使用多個3090將llama2-7b的推理擴展在多個GPU上

基本示例

我們首先介紹一個簡單的示例來演示使用Accelerate進行多gpu“消息傳遞”。

from accelerate import Accelerator
 from accelerate.utils import gather_object
 
 accelerator = Accelerator()
 
 # each GPU creates a string
 message=[ f"Hello this is GPU {accelerator.process_index}" ] 
 
 # collect the messages from all GPUs
 messages=gather_object(message)
 
 # output the messages only on the main process with accelerator.print() 
 accelerator.print(messages)

輸出如下:

['Hello this is GPU 0', 
   'Hello this is GPU 1', 
   'Hello this is GPU 2', 
   'Hello this is GPU 3', 
   'Hello this is GPU 4']

多GPU推理

下面是一個簡單的、非批處理的推理方法。代碼很簡單,因為Accelerate庫已經幫我們做了很多工作,我們直接使用就可以:

from accelerate import Accelerator
 from accelerate.utils import gather_object
 from transformers import AutoModelForCausalLM, AutoTokenizer
 from statistics import mean
 import torch, time, json
 
 accelerator = Accelerator()
 
 # 10*10 Prompts. Source: https://www.penguin.co.uk/articles/2022/04/best-first-lines-in-books
 prompts_all=[
     "The King is dead. Long live the Queen.",
     "Once there were four children whose names were Peter, Susan, Edmund, and Lucy.",
     "The story so far: in the beginning, the universe was created.",
     "It was a bright cold day in April, and the clocks were striking thirteen.",
     "It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.",
     "The sweat wis lashing oafay Sick Boy; he wis trembling.",
     "124 was spiteful. Full of Baby's venom.",
     "As Gregor Samsa awoke one morning from uneasy dreams he found himself transformed in his bed into a gigantic insect.",
     "I write this sitting in the kitchen sink.",
     "We were somewhere around Barstow on the edge of the desert when the drugs began to take hold.",
 ] * 10
 
 # load a base model and tokenizer
 model_path="models/llama2-7b"
 model = AutoModelForCausalLM.from_pretrained(
     model_path,    
     device_map={"": accelerator.process_index},
     torch_dtype=torch.bfloat16,
 )
 tokenizer = AutoTokenizer.from_pretrained(model_path)   
 
 # sync GPUs and start the timer
 accelerator.wait_for_everyone()
 start=time.time()
 
 # divide the prompt list onto the available GPUs 
 with accelerator.split_between_processes(prompts_all) as prompts:
     # store output of generations in dict
     results=dict(outputs=[], num_tokens=0)
 
     # have each GPU do inference, prompt by prompt
     for prompt in prompts:
         prompt_tokenized=tokenizer(prompt, return_tensors="pt").to("cuda")
         output_tokenized = model.generate(**prompt_tokenized, max_new_tokens=100)[0]
 
         # remove prompt from output 
         output_tokenized=output_tokenized[len(prompt_tokenized["input_ids"][0]):]
 
         # store outputs and number of tokens in result{}
         results["outputs"].append( tokenizer.decode(output_tokenized) )
         results["num_tokens"] += len(output_tokenized)
 
     results=[ results ] # transform to list, otherwise gather_object() will not collect correctly
 
 # collect results from all the GPUs
 results_gathered=gather_object(results)
 
 if accelerator.is_main_process:
     timediff=time.time()-start
     num_tokens=sum([r["num_tokens"] for r in results_gathered ])
 
     print(f"tokens/sec: {num_tokens//timediff}, time {timediff}, total tokens {num_tokens}, total prompts {len(prompts_all)}")

使用多個gpu會導致一些通信開銷:性能在4個gpu時呈線性增長,然后在這種特定設置中趨于穩定。當然這里的性能取決于許多參數,如模型大小和量化、提示長度、生成的令牌數量和采樣策略,所以我們只討論一般的情況

1 GPU: 44個token /秒,時間:225.5s

2 gpu: 88個token /秒,時間:112.9s

3 gpu: 128個token /秒,時間:77.6s

4 gpu: 137個token /秒,時間:72.7s

5 gpu: 119個token /秒,時間:83.8s

在多GPU上進行批處理

現實世界中,我們可以使用批處理推理來加快速度。這會減少GPU之間的通訊,加快推理速度。我們只需要增加prepare_prompts函數將一批數據而不是單條數據輸入到模型即可:

from accelerate import Accelerator
 from accelerate.utils import gather_object
 from transformers import AutoModelForCausalLM, AutoTokenizer
 from statistics import mean
 import torch, time, json
 
 accelerator = Accelerator()
 
 def write_pretty_json(file_path, data):
     import json
     with open(file_path, "w") as write_file:
         json.dump(data, write_file, indent=4)
 
 # 10*10 Prompts. Source: https://www.penguin.co.uk/articles/2022/04/best-first-lines-in-books
 prompts_all=[
     "The King is dead. Long live the Queen.",
     "Once there were four children whose names were Peter, Susan, Edmund, and Lucy.",
     "The story so far: in the beginning, the universe was created.",
     "It was a bright cold day in April, and the clocks were striking thirteen.",
     "It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.",
     "The sweat wis lashing oafay Sick Boy; he wis trembling.",
     "124 was spiteful. Full of Baby's venom.",
     "As Gregor Samsa awoke one morning from uneasy dreams he found himself transformed in his bed into a gigantic insect.",
     "I write this sitting in the kitchen sink.",
     "We were somewhere around Barstow on the edge of the desert when the drugs began to take hold.",
 ] * 10
 
 # load a base model and tokenizer
 model_path="models/llama2-7b"
 model = AutoModelForCausalLM.from_pretrained(
     model_path,    
     device_map={"": accelerator.process_index},
     torch_dtype=torch.bfloat16,
 )
 tokenizer = AutoTokenizer.from_pretrained(model_path)   
 tokenizer.pad_token = tokenizer.eos_token
 
 # batch, left pad (for inference), and tokenize
 def prepare_prompts(prompts, tokenizer, batch_size=16):
     batches=[prompts[i:i + batch_size] for i in range(0, len(prompts), batch_size)]  
     batches_tok=[]
     tokenizer.padding_side="left"     
     for prompt_batch in batches:
         batches_tok.append(
             tokenizer(
                 prompt_batch, 
                 return_tensors="pt", 
                 padding='longest', 
                 truncation=False, 
                 pad_to_multiple_of=8,
                 add_special_tokens=False).to("cuda") 
             )
     tokenizer.padding_side="right"
     return batches_tok
 
 # sync GPUs and start the timer
 accelerator.wait_for_everyone()    
 start=time.time()
 
 # divide the prompt list onto the available GPUs 
 with accelerator.split_between_processes(prompts_all) as prompts:
     results=dict(outputs=[], num_tokens=0)
 
     # have each GPU do inference in batches
     prompt_batches=prepare_prompts(prompts, tokenizer, batch_size=16)
 
     for prompts_tokenized in prompt_batches:
         outputs_tokenized=model.generate(**prompts_tokenized, max_new_tokens=100)
 
         # remove prompt from gen. tokens
         outputs_tokenized=[ tok_out[len(tok_in):] 
             for tok_in, tok_out in zip(prompts_tokenized["input_ids"], outputs_tokenized) ] 
 
         # count and decode gen. tokens 
         num_tokens=sum([ len(t) for t in outputs_tokenized ])
         outputs=tokenizer.batch_decode(outputs_tokenized)
 
         # store in results{} to be gathered by accelerate
         results["outputs"].extend(outputs)
         results["num_tokens"] += num_tokens
 
     results=[ results ] # transform to list, otherwise gather_object() will not collect correctly
 
 # collect results from all the GPUs
 results_gathered=gather_object(results)
 
 if accelerator.is_main_process:
     timediff=time.time()-start
     num_tokens=sum([r["num_tokens"] for r in results_gathered ])
 
     print(f"tokens/sec: {num_tokens//timediff}, time elapsed: {timediff}, num_tokens {num_tokens}")

可以看到批處理會大大加快速度。

1 GPU: 520 token /sec,時間:19.2s

2 gpu: 900 token /sec,時間:11.1s

3 gpu: 1205個token /秒,時間:8.2s

4 gpu: 1655 token /sec,時間:6.0s

5 gpu: 1658 token /sec,時間:6.0s

總結

截止到本文為止,llama.cpp,ctransformer還不支持多GPU推理,好像llama.cpp在6月有個多GPU的merge,但是我沒看到官方更新,所以這里暫時確定不支持多GPU。如果有小伙伴確認可以支持多GPU請留言。

huggingface的Accelerate包則為我們使用多GPU提供了一個很方便的選擇,使用多個GPU推理可以顯著提高性能,但gpu之間通信的開銷隨著gpu數量的增加而顯著增加。

聲明:本文內容及配圖由入駐作者撰寫或者入駐合作網站授權轉載。文章觀點僅代表作者本人,不代表電子發燒友網立場。文章及其配圖僅供工程師學習之用,如有內容侵權或者其他違規問題,請聯系本站處理。 舉報投訴
  • GPU芯片
    +關注

    關注

    1

    文章

    303

    瀏覽量

    5709
  • 自然語言處理

    關注

    1

    文章

    511

    瀏覽量

    13256
  • LLM
    LLM
    +關注

    關注

    0

    文章

    218

    瀏覽量

    249
收藏 人收藏

    評論

    相關推薦

    對比解碼在LLM上的應用

    為了改進LLM推理能力,University of California聯合Meta AI實驗室提出將Contrastive Decoding應用于多種任務的LLM方法。實驗表明,所提方法能有效改進
    發表于 09-21 11:37 ?424次閱讀
    對比解碼在<b class='flag-5'>LLM</b>上的應用

    怎樣對STM32標準的SlaveMode選項進行設置

    怎樣對STM32標準的SlaveMode選項進行設置?有哪些設置步驟?
    發表于 11-24 07:51

    YOLOv5s算法RK3399ProD上的部署推理流程是怎樣

    YOLOv5s算法RK3399ProD上的部署推理流程是怎樣的?基于RK33RK3399Pro怎樣使用NPU進行加速
    發表于 02-11 08:15

    RK3399Pro硬件上進行make編譯報錯怎么辦

    RK3399Pro硬件上進行make編譯報錯怎么辦?怎樣去解決這個問題?
    發表于 02-14 06:11

    如何對RK GPU進行調試

    如何對RK GPU進行調試?有哪些技巧?
    發表于 02-15 07:21

    怎樣阿里云物聯網平臺上進行單片機程序的編寫

    阿里云物聯網平臺是怎樣設置的?怎樣阿里云物聯網平臺上進行單片機程序的編寫?
    發表于 02-22 06:04

    充分利用Arm NN進行GPU推理

    Arm擁有跨所有處理器的計算IP。而且,無論您要在GPU,CPU還是NPU上進行ML推理,都可以一個通用框架下使用它們:Arm NN。Arm NN是適用于CPU,
    發表于 04-11 17:33

    請問RK3399pro中間計算時能否調用GPU的一些現成數據或函數來計算

    一些操作,放射變換,旋轉等,請問這中間計算能否調用GPU的一些現成數據或函數來計算? 如何調用? 謝謝!
    發表于 05-09 15:26

    請問一下rknn推理參數該怎樣去設置

    rknn推理參數設置然后進行推理,推理的結果會把三張圖片的結果合并在一個list中,需要我們自己將其分割開:最終其結果和單張
    發表于 07-22 15:38

    如何判斷推理何時由GPU或NPUiMX8MPlus上運行?

    當我為 TFLite 模型運行基準測試時,有一個選項 --nnapi=true我如何知道 GPU 和 NPU 何時進行推理?謝謝
    發表于 03-20 06:10

    PyTorch教程13.5之在多個GPU上進行訓練

    電子發燒友網站提供《PyTorch教程13.5之在多個GPU上進行訓練.pdf》資料免費下載
    發表于 06-05 14:18 ?0次下載
    PyTorch教程13.5之在多個<b class='flag-5'>GPU</b><b class='flag-5'>上進行</b>訓練

    mlc-llm對大模型推理的流程及優化方案

    比如RWKV和給定的device信息一起編譯為TVM中的runtime.Module(在linux上編譯的產物就是.so文件)提供mlc-llm的c++推理接口調用 。
    發表于 09-26 12:25 ?529次閱讀
    mlc-<b class='flag-5'>llm</b>對大模型<b class='flag-5'>推理</b>的流程及優化方案

    Hugging Face LLM部署大語言模型到亞馬遜云科技Amazon SageMaker推理示例

    ?本篇文章主要介紹如何使用新的Hugging Face LLM推理容器將開源LLMs,比如BLOOM大型語言模型部署到亞馬遜云科技Amazon SageMaker進行推理的示例。我們將
    的頭像 發表于 11-01 17:48 ?558次閱讀
    Hugging Face <b class='flag-5'>LLM</b>部署大語言模型到亞馬遜云科技Amazon SageMaker<b class='flag-5'>推理</b>示例

    自然語言處理應用LLM推理優化綜述

    當前,業界在將傳統優化技術引入 LLM 推理的同時,同時也在探索從大模型自回歸解碼特點出發,通過調整推理過程和引入新的模型結構來進一步提升推理性能。
    發表于 04-10 11:48 ?209次閱讀
    自然語言處理應用<b class='flag-5'>LLM</b><b class='flag-5'>推理</b>優化綜述

    利用NVIDIA組件提升GPU推理的吞吐

    本實踐中,唯品會 AI 平臺與 NVIDIA 團隊合作,結合 NVIDIA TensorRT 和 NVIDIA Merlin HierarchicalKV(HKV)將推理的稠密網絡和熱 Embedding 全置于 GPU 上進行
    的頭像 發表于 04-20 09:39 ?275次閱讀
    亚洲欧美日韩精品久久_久久精品AⅤ无码中文_日本中文字幕有码在线播放_亚洲视频高清不卡在线观看
    <acronym id="s8ci2"><small id="s8ci2"></small></acronym>
    <rt id="s8ci2"></rt><rt id="s8ci2"><optgroup id="s8ci2"></optgroup></rt>
    <acronym id="s8ci2"></acronym>
    <acronym id="s8ci2"><center id="s8ci2"></center></acronym>