注意
跳轉到末尾 下載完整示例程式碼
使用 torch.compile 後端編譯 Stable Diffusion 模型¶
本互動式指令碼旨在作為使用 torch.compile 後端在 Stable Diffusion 模型上執行 Torch-TensorRT 工作流程的示例。下面展示了一個示例輸出
匯入與模型定義¶
import torch
import torch_tensorrt
from diffusers import DiffusionPipeline
model_id = "CompVis/stable-diffusion-v1-4"
device = "cuda:0"
# Instantiate Stable Diffusion Pipeline with FP16 weights
pipe = DiffusionPipeline.from_pretrained(
model_id, revision="fp16", torch_dtype=torch.float16
)
pipe = pipe.to(device)
backend = "torch_tensorrt"
# Optimize the UNet portion with Torch-TensorRT
pipe.unet = torch.compile(
pipe.unet,
backend=backend,
options={
"truncate_long_and_double": True,
"enabled_precisions": {torch.float32, torch.float16},
},
dynamic=False,
)
推理¶
prompt = "a majestic castle in the clouds"
image = pipe(prompt).images[0]
image.save("images/majestic_castle.png")
image.show()
指令碼總執行時間:( 0 分鐘 0.000 秒)