参考自:Accelerate inference of text-to-image diffusion models
默认使用diffusers
1.bfloat16
使用 torch.bfloat16 或者torch.float16,降低数据精度能加快推理速度,并且对结果的影响也很小。
如果GPU的内存不足,也可以使用torch.bfloat16 或者torch.float16,能降低内存占用。
pipe = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.bfloat16
).to("cuda")
2.SDPA
scaled_dot_product_attention,在diffusers中已经默认使用。
scores = torch.matmul(Q, K.transpose(-1, -2)) / np.sqrt(d_k)
将scores除以d_k的平方根(np.sqrt(d_k)),这就是所谓的缩放,已经是transformers的默认操作了。
3.torch.compile
需要PyTorch 2 以上版本。第一次编译会很慢,编译好了推理会提速很多。
from diffusers import StableDiffusionXLPipeline
import torch
torch._inductor.config.conv_1x1_as_mm = True
torch._inductor.config.coordinate_descent_tuning = True
torch._inductor.config.epilogue_fusion = False
torch