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]]])
相关推荐
weisian1511 分钟前
进阶篇-8-数学篇-7--特征值与特征向量:AI特征提取的核心逻辑
人工智能·pca·特征值·特征向量·降维
Java程序员 拥抱ai3 分钟前
撰写「从0到1构建下一代游戏AI客服」系列技术博客的初衷
人工智能
186******205317 分钟前
AI重构项目开发全流程:效率革命与实践指南
人工智能·重构
森之鸟16 分钟前
多智能体系统开发入门:用鸿蒙实现设备间的AI协同决策
人工智能·harmonyos·m
铁蛋AI编程实战23 分钟前
大模型本地轻量化微调+端侧部署实战(免高端GPU/16G PC可运行)
人工智能·架构·开源
铁蛋AI编程实战23 分钟前
最新版 Kimi K2.5 完整使用教程:从入门到实战(开源部署+API接入+多模态核心功能)
人工智能·开源
开源技术26 分钟前
如何将本地LLM模型与Ollama和Python集成
开发语言·python
weixin_4370446426 分钟前
Netbox批量添加设备——堆叠设备
linux·网络·python
我有医保我先冲27 分钟前
AI 时代 “任务完成“ 与 “专业能力“ 的区分:理论基础、行业影响与个人发展策略
人工智能·python·机器学习
林深现海27 分钟前
【刘二大人】PyTorch深度学习实践笔记 —— 第一集:深度学习全景概述(超详细版)
pytorch·笔记·深度学习