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]]])
相关推荐
sell-cloud1 小时前
Prompt Engineering要凉了?Fable 5.5能“猜“意图,但银行正在封杀AI Agent——企业AI的真正护城河是什么
人工智能·prompt
Navicat中国3 小时前
Navicat 18 内置 AI 助手让数据库开发从繁琐操作迈向智能协作
大数据·人工智能·数据库开发
4SAPI3 小时前
多模型请求路由怎么设计?成本、速度和能力如何平衡
人工智能·python·gateway·php
魔乐社区3 小时前
翼芯・智算测试与适配优化专区,让国产算力“选得准、跑得通、用得好“
人工智能·开源·大模型
XCDoris5 小时前
郴州logo设计机构
大数据·人工智能·python
Goboy5 小时前
一个人带三个Agent,我用全新TRAE从0到1搭了个资讯周刊站
人工智能·trae
俊哥V5 小时前
每日 AI 研究简报 · 2026-10-19
人工智能·ai
AI_AGENT_DEV_AI5 小时前
AI英语教培智能体的开发
人工智能
物联网软硬件开发-轨物科技6 小时前
【技术白皮书】光伏清检一体化机器人系统解决方案技术白皮书
大数据·运维·网络·人工智能·机器人
gCode Teacher 格码致知6 小时前
Pandas教学-17:Series与Dataframe的关系
开发语言·python·pandas