注意
轉到頁面底部 下載完整的示例程式碼
使用 Torch-TensorRT torch.compile 前端編譯 GPT2¶
本示例展示瞭如何使用 Torch-TensorRT 的 torch.compile 前端最佳化最先進的 GPT2 模型。在編譯前安裝以下依賴項
pip install -r requirements.txt
GPT2 是一個因果(單向)Transformer 模型,使用大量文字語料庫進行語言建模預訓練。在本示例中,我們使用 HuggingFace 上提供的 GPT2 模型,並對其應用 torch.compile 以獲取圖模組的圖表示。Torch-TensorRT 將此圖轉換為最佳化的 TensorRT 引擎。
匯入所需庫¶
import torch
import torch_tensorrt
from transformers import AutoModelForCausalLM, AutoTokenizer
定義所需引數¶
Torch-TensorRT 需要 GPU 才能成功編譯模型。MAX_LENGTH 是生成 token 的最大長度。這等於輸入提示的長度加上生成的新 token 數量。
MAX_LENGTH = 32
DEVICE = torch.device("cuda:0")
模型定義¶
我們使用 AutoModelForCausalLM 類從 hugging face 載入預訓練的 GPT2 模型。Torch-TRT 當前不支援 kv_cache,因此設定為 use_cache=False。
with torch.no_grad():
tokenizer = AutoTokenizer.from_pretrained("gpt2")
model = (
AutoModelForCausalLM.from_pretrained(
"gpt2",
pad_token_id=tokenizer.eos_token_id,
use_cache=False,
attn_implementation="eager",
)
.eval()
.cuda()
)
PyTorch 推理¶
對示例輸入提示進行 tokenization 並獲取 PyTorch 模型輸出。
prompt = "I enjoy walking with my cute dog"
model_inputs = tokenizer(prompt, return_tensors="pt")
input_ids = model_inputs["input_ids"].cuda()
AutoModelForCausalLM 類的 generate() API 用於使用貪婪解碼進行自迴歸生成。
pyt_gen_tokens = model.generate(
input_ids,
max_length=MAX_LENGTH,
use_cache=False,
pad_token_id=tokenizer.eos_token_id,
)
Torch-TensorRT 編譯和推理¶
輸入序列長度是動態的,因此我們使用 torch._dynamo.mark_dynamic API 對其進行標記。我們為該值提供一個 (min, max) 範圍,以便 TensorRT 提前知道要最佳化的值範圍。通常,這將是模型的上下文長度。由於 0/1 特殊化,我們從 min=2 開始。
torch._dynamo.mark_dynamic(input_ids, 1, min=2, max=1023)
model.forward = torch.compile(
model.forward,
backend="tensorrt",
dynamic=None,
options={
"enabled_precisions": {torch.float32},
"disable_tf32": True,
"min_block_size": 1,
},
)
使用 TensorRT 模型進行貪婪解碼的自迴歸生成迴圈。生成第一個 token 時,模型會使用 TensorRT 進行編譯;而生成第二個 token 時會遇到重新編譯(這是目前一個問題,將來會解決)。
trt_gen_tokens = model.generate(
inputs=input_ids,
max_length=MAX_LENGTH,
use_cache=False,
pad_token_id=tokenizer.eos_token_id,
)
解碼 PyTorch 和 TensorRT 的輸出句子¶
print(
"Pytorch model generated text: ",
tokenizer.decode(pyt_gen_tokens[0], skip_special_tokens=True),
)
print("=============================")
print(
"TensorRT model generated text: ",
tokenizer.decode(trt_gen_tokens[0], skip_special_tokens=True),
)
輸出句子應如下所示
"""
Pytorch model generated text: I enjoy walking with my cute dog, but I'm not sure if I'll ever be able to walk with my dog. I'm not sure if I'll
=============================
TensorRT model generated text: I enjoy walking with my cute dog, but I'm not sure if I'll ever be able to walk with my dog. I'm not sure if I'll
"""
指令碼總執行時間: ( 0 分 0.000 秒)