• Docs >
  • Compiling GPT2 using the Torch-TensorRT torch.compile frontend
Shortcuts

使用Torch-TensorRT torch.compile前端编译GPT2

这个例子展示了使用Torch-TensorRT的torch.compile前端优化的最先进模型GPT2。在编译之前请安装以下依赖项

pip install -r requirements.txt

GPT2 是一种因果(单向)变压器,通过在非常大的文本数据语料库上进行语言建模进行预训练。在这个例子中,我们使用 HuggingFace 上提供的 GPT2 模型,并对其应用 torch.compile 来获取图的图形模块表示。Torch-TensorRT 将此图转换为优化的 TensorRT 引擎。

导入必要的库

import torch
import torch_tensorrt
from transformers import AutoModelForCausalLM, AutoTokenizer

定义必要的参数

Torch-TensorRT 需要 GPU 才能成功编译模型。 MAX_LENGTH 是生成令牌的最大长度。这对应于输入提示的长度 + 生成的新令牌的数量

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 推理

对示例输入提示进行标记化并获取pytorch模型输出

prompt = "I enjoy walking with my cute dog"
model_inputs = tokenizer(prompt, return_tensors="pt")
input_ids = model_inputs["input_ids"].cuda()

generate() API 的 AutoModelForCausalLM 类用于使用贪婪解码进行自回归生成。

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来标记它。 我们提供了这个值的(最小,最大)范围,以便TensorRT提前知道要优化的值。 通常,这将是模型的上下文长度。我们从min=2开始,因为0/1 specialization

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模型进行贪婪解码的自回归生成循环 第一个令牌生成使用TensorRT编译模型,第二个令牌 遇到重新编译(这是当前的一个问题,将在未来解决)

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 秒)

Gallery generated by Sphinx-Gallery