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]]])
相关推荐
Είναι η κοπέλα8 小时前
显存计算与模型选择:你的显卡能跑多大的模型
人工智能·pytorch·python·开源·conda
ROSF68688 小时前
2026 仿石漆乳液供应商:市场布局与行业发展态势梳理
大数据·人工智能·python
Ada's8 小时前
Skill is all you need
人工智能
青少儿编程课堂9 小时前
AC自动机多模式串匹配精讲:校园关键词巡检实战解析
c++·python·算法·bfs·信息学竞赛
Dawson Zhu9 小时前
《Agentic Design Patterns》第 1 章导读:提示词链(Prompt Chaining)
人工智能·语言模型·架构·aigc·agi
DP DPharness9 小时前
StudyMate 从安装到第一节课的完整操作路径
人工智能·websocket·网络协议·智能手机·dpharness
lingchen19069 小时前
MATLAB 单引号 `‘` 和双引号 `“`
人工智能
hhzz9 小时前
【YOLO 入门到精通 04】理解任务与模型家族:7 大 CV 任务与 YOLO26 选型指南
人工智能·python·深度学习·yolo·计算机视觉
2501_933670799 小时前
医药市场分析岗位适合应用统计学学生吗,需要考什么证
人工智能
Escalating_xu9 小时前
【Python】使用库:标准库、第三方库、pip、项目实战与程序打包
java·python·pip