torch_bmm验算及代码测试

文章目录

  • [1. torch_bmm](#1. torch_bmm)
  • [2. pytorch源码](#2. pytorch源码)

1. torch_bmm

torch.bmm的作用是基于batch_size的矩阵乘法,torch.bmm的作用是对应batch位置的矩阵相乘,比如,

  • mat1的第1个位置和mat2的第1个位置进行矩阵相乘得到mat3的第1个位置
  • mat1的第2个位置和mat2的第2个位置进行矩阵相乘得到mat3的第2个位置

2. pytorch源码

python 复制代码
import torch
import torch.nn as nn
import torch.nn.functional as F

torch.set_printoptions(precision=3, sci_mode=False)

if __name__ == "__main__":
    run_code = 0
    batch_size = 2
    mat1_h = 3
    mat1_w = 4
    mat1_total = batch_size * mat1_w * mat1_h
    mat2_h = 4
    mat2_w = 5
    mat2_total = batch_size * mat2_w * mat2_h
    mat1 = torch.arange(mat1_total).reshape((batch_size, mat1_h, mat1_w))
    mat2 = torch.arange(mat2_total).reshape((batch_size, mat2_h, mat2_w))
    mat3 = torch.bmm(mat1, mat2)
    print(f"mat1=\n{mat1}")
    print(f"mat2=\n{mat2}")
    print(f"mat3=\n{mat3}")
  • 结果:
python 复制代码
mat1=
tensor([[[ 0,  1,  2,  3],
         [ 4,  5,  6,  7],
         [ 8,  9, 10, 11]],

        [[12, 13, 14, 15],
         [16, 17, 18, 19],
         [20, 21, 22, 23]]])
mat2=
tensor([[[ 0,  1,  2,  3,  4],
         [ 5,  6,  7,  8,  9],
         [10, 11, 12, 13, 14],
         [15, 16, 17, 18, 19]],

        [[20, 21, 22, 23, 24],
         [25, 26, 27, 28, 29],
         [30, 31, 32, 33, 34],
         [35, 36, 37, 38, 39]]])
mat3=
tensor([[[  70,   76,   82,   88,   94],
         [ 190,  212,  234,  256,  278],
         [ 310,  348,  386,  424,  462]],

        [[1510, 1564, 1618, 1672, 1726],
         [1950, 2020, 2090, 2160, 2230],
         [2390, 2476, 2562, 2648, 2734]]])
相关推荐
半tour费29 分钟前
TextCNN-NPU移植与性能优化实战
python·深度学习·分类·cnn·华为云
普通网友34 分钟前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python
百锦再44 分钟前
第17章 模式与匹配
开发语言·后端·python·rust·django·内存·抽象
普通网友1 小时前
Python函数定义与调用:编写可重用代码的基石
jvm·数据库·python
TDengine (老段)1 小时前
优化 TDengine IDMP 面板编辑的几种方法
人工智能·物联网·ai·时序数据库·tdengine·涛思数据
普通网友1 小时前
使用Python进行PDF文件的处理与操作
jvm·数据库·python
MZ_ZXD0011 小时前
springboot流浪动物救助平台-计算机毕业设计源码08780
java·spring boot·后端·python·spring·flask·课程设计
十步杀一人_千里不留行2 小时前
解释器模式:为 LLM 构建迷你 DSL 解释器,实现 Prompt 编排语言
python·prompt·解释器模式
数据的世界012 小时前
Visual Studio 2026 正式发布:AI 原生 IDE 与性能革命的双向突破
ide·人工智能·visual studio
这儿有一堆花2 小时前
python视觉开发
开发语言·python