PyTorch torch.addbmm Function


Pytorch torch 参考手册PyTorch torch Reference Manual

torch.addbmmIt is a function in PyTorch used to add the results of batch matrix multiplication to an input matrix. It performs matrix multiplication on each pair of matrices in batch1 and batch2, sums all results, and then adds them to input.

Function Definition

torch.addbmm(input, batch1, batch2, *, beta=1.0, alpha=1.0, out=None)

Parameters:

  • input(Tensor): The input matrix, which is added to the result.
  • batch1(Tensor): The first batch matrix, with shape (b, n, m).
  • batch2(Tensor): The second batch matrix, with shape (b, m, p).
  • beta(float, optional): Coefficient multiplied by input, default is 1.0.
  • alpha(float, optional): Coefficient multiplied by the result of batch1 @ batch2, default is 1.0.
  • out(Tensor, optional): The output tensor.

Return Value:

  • torch.Tensor: Returns the sum of the batch matrix multiplication result and the input matrix.

Usage Example

Example

import torch

# Create the input matrix and batch matrices
input = torch.randn(3, 3)
batch1 = torch.randn(10, 3, 4)
batch2 = torch.randn(10, 4, 3)

# Execute addbmm
result = torch.addbmm(input, batch1, batch2)

print("Input matrix shape:", input.shape)
print("Batch matrix 1 shape:", batch1.shape)
print("Batch matrix 2 shape:", batch2.shape)
print("Result shape:", result.shape)
print(result)

The output result is:

输入矩阵形状: torch.Size([3, 3])
批量矩阵1形状: torch.Size([10, 3, 4])
批量矩阵2形状: torch.Size([10, 4, 3])
结果形状: torch.Size([3, 3])
tensor([[-0.2875, -0.6518,  0.1207],
        [-0.2746,  0.5563, -0.2281],
        [ 0.3315,  0.1649,  0.2145]])

Pytorch torch 参考手册PyTorch torch Reference Manual

Other Extensions