torch.matmul() VS torch.einsum()

torch.matmul():标准的矩阵乘法

  • 向量-向量(点积)

    python 复制代码
    a = torch.randn(3)  # [3]
    b = torch.randn(3)  # [3]
    c = torch.matmul(a, b)  # 点积,标量输出
  • 矩阵-向量

    python 复制代码
    A = torch.randn(3, 4)  # [3, 4]
    x = torch.randn(4)     # [4]
    y = torch.matmul(A, x) # [3]
  • 矩阵-矩阵

    python 复制代码
    A = torch.randn(3, 4)  # [3, 4]
    B = torch.randn(4, 5)  # [4, 5]
    C = torch.matmul(A, B) # [3, 5]
  • 批量矩阵乘法(更高维张量)

    python 复制代码
    A = torch.randn(2, 3, 4)  # [B, M, K]
    B = torch.randn(2, 4, 5)  # [B, K, N]
    C = torch.matmul(A, B)     # [B, M, N]

    torch.einsum:爱因斯坦求和约定(更通用的张量运算工具)

  • 矩阵乘法

    python 复制代码
    A = torch.randn(3, 4)
    B = torch.randn(4, 5)
    C = torch.einsum("ik,kj->ij", A, B)  # 等价于 A @ B
    
    A = torch.randn(2, 3, 4)  # [B, M, K]
    B = torch.randn(2, 4, 5)  # [B, K, N]
    C = torch.einsum("bik,bkj->bij", A, B)  # [B, M, N]
    
    a = torch.randn(3)
    b = torch.randn(3)
    c = torch.einsum("i,i->", a, b)  # 点积,标量输出
  • 转置

    python 复制代码
    A = torch.randn(3, 4)
    B = torch.einsum("ij->ji", A)  # 等价于 A.T
  • 对角线提取

  • 张量收缩(Tensor Contraction)(高阶张量乘法)

    python 复制代码
    A = torch.randn(2, 3, 4, 5)
    B = torch.randn(2, 4, 5, 6)
    C = torch.einsum("abcd,abde->abce", A, B)  # 对 d 维度收缩
  • 广播运算

torch.matmul torch.einsum
灵活性 仅支持矩阵乘法类操作 支持任意张量运算(转置、收缩等)
可读性 直观(A @ B 需要熟悉爱因斯坦求和约定
性能 高度优化(推荐用于标准矩阵乘法) 灵活但可能稍慢
广播支持
批量处理 自动支持 需显式指定批量维度
相关推荐
AI_gurubar1 小时前
大模型教机器人叠衣服:2025年”语言理解+多模态融合“的智能新篇
人工智能·机器人
XINVRY-FPGA3 小时前
EPM240T100I5N Altera FPGA MAX II CPLD
人工智能·嵌入式硬件·fpga开发·硬件工程·dsp开发·射频工程·fpga
HuggingFace3 小时前
开源开发者须知:欧盟《人工智能法案》对通用人工智能模型的最新要求
人工智能
Coovally AI模型快速验证4 小时前
农田扫描提速37%!基于检测置信度的无人机“智能抽查”路径规划,Coovally一键加速模型落地
深度学习·算法·yolo·计算机视觉·transformer·无人机
媒体人8884 小时前
GEO 优化专家孟庆涛:技术破壁者重构 AI 时代搜索逻辑
大数据·人工智能
小菜AI科技5 小时前
Windsurf 评测:这款 人工智能 IDE 是你需要的颠覆性工具吗?
人工智能
RaymondZhao345 小时前
【全面推导】策略梯度算法:公式、偏差方差与进化
人工智能·深度学习·算法·机器学习·chatgpt
yzx9910135 小时前
小程序开发APP
开发语言·人工智能·python·yolo
AKAMAI5 小时前
通过自动化本地计算磁盘与块存储卷加密保护数据安全
人工智能·云计算
Caven776 小时前
【pytorch】reshape的使用
pytorch·python