在python中利用pytorch 2.0实现高效的批处理矩阵乘法,核心方法是使用 torch.bmm 函数或支持广播的 @ 运算符。你需要确保输入张量的维度匹配,即形状为 (b, m, k) 和 (b, k, n) 的张量相乘,得到 (b, m, n) 的结果。pytorch 2.0 通过 torch.compile 进一步加速了这一过程,它会将计算图编译为优化的内核代码,从而减少cpu-gpu通信开销并提升吞吐量。

torch.bmm 与 @ 算符在批量场景下的性能差异是什么
torch.bmm 是专为三维张量设计的批量矩阵乘法函数,而 @ 算符在 PyTorch 中会自动检测维度并进行广播。对于标准的批量矩阵乘法,两者在底层调用相同的 cuBLAS 内核,因此性能几乎无差异。但 @ 算符更灵活,能处理非批量维度的广播,而 torch.bmm 要求严格匹配批量维度。在使用 torch.compile 时,@ 算符通常能更好地被优化器识别为批量操作。

import torch
import time
def benchmark_bmm(matrices_a, matrices_b):
# 预热
_ = torch.bmm(matrices_a, matrices_b)
torch.cuda.synchronize()
start = time.time()
for _ in range(100):
result = torch.bmm(matrices_a, matrices_b)
torch.cuda.synchronize()
end = time.time()
return (end - start) / 100
def benchmark_matmul(matrices_a, matrices_b):
# 预热
_ = matrices_a @ matrices_b
torch.cuda.synchronize()
start = time.time()
for _ in range(100):
result = matrices_a @ matrices_b
torch.cuda.synchronize()
end = time.time()
return (end - start) / 100
# 示例输入: B=32, M=64, K=128, N=256
B, M, K, N = 32, 64, 128, 256
matrices_a = torch.randn(B, M, K, device='cuda')
matrices_b = torch.randn(B, K, N, device='cuda')
print(f"bmm avg time: {benchmark_bmm(matrices_a, matrices_b):.6f}s")
print(f"@ avg time: {benchmark_matmul(matrices_a, matrices_b):.6f}s")
print(f"Results equal: {torch.allclose(torch.bmm(matrices_a, matrices_b), matrices_a @ matrices_b)}")如何使用 torch.compile 进一步优化批量矩阵乘法
torch.compile 是 PyTorch 2.0 引入的核心特性,它通过后端编译器(如 Inductor)将 Python 代码转换为高度优化的 C++/CUDA 代码。对于批量矩阵乘法,它可以融合多个操作、消除临时变量分配,并利用特定的硬件指令。只需将包含 bmm 或 @ 的函数包裹在 torch.compile 中即可生效。首次运行会有编译开销,但后续迭代速度显著提升。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;

import torch
def optimized_batch_mm(a, b):
return a @ b
# 编译函数
compiled_batch_mm = torch.compile(optimized_batch_mm)
# 示例输入
B, M, K, N = 32, 64, 128, 256
a = torch.randn(B, M, K, device='cuda')
b = torch.randn(B, K, N, device='cuda')
# 首次运行触发编译
result_compiled = compiled_batch_mm(a, b)
# 后续运行享受加速
for _ in range(10):
result_compiled = compiled_batch_mm(a, b)
print(f"Compiled result shape: {result_compiled.shape}")
print(f"Matches standard: {torch.allclose(result_compiled, a @ b)}")当批量维度 B 较小时,批量矩阵乘法是否仍然高效
当批量维度 B 较小时(例如 B ),批量矩阵乘法的效率可能会下降,因为 GPU 的并行线程块无法被充分填充,导致算力利用率不足。此时,传统的循环逐对相乘可能反而更快,或者需要考虑使用 <code>torch.vmap 进行虚拟批量处理。此外,小批量场景下 CPU-GPU 数据传输的固定开销占比更大,成为瓶颈。建议在小批量时评估是否合并批次或使用其他优化策略。

















