PyTorch torch.addbmm Function
PyTorch torch reference manual
torch.addbmm is a function in PyTorch used to add the result of batched matrix multiplication to an input matrix. It performs matrix multiplication on each pair of matrices in batch1 and batch2, then sums all the results and 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 of matrices, with shape (b, n, m).batch2(Tensor): the second batch of matrices, with shape (b, m, p).beta(float, optional): a coefficient by which input is multiplied, defaulting to 1.0.alpha(float, optional): a coefficient by which the result of batch1 @ batch2 is multiplied, defaulting to 1.0.out(Tensor, optional): the output tensor.
Return Value:
torch.Tensor: returns the sum of the batched matrix multiplication result and the input matrix.
Usage examples
Example
import
torch
Create the input matrix and the batches of matrices
input
=
torch.
randn
(
3
,
3
)
batch1
=
torch.
randn
(
10
,
3
,
4
)
batch2
=
torch.
randn
(
10
,
4
,
3
)
Perform addbmm
result
=
torch.
addbmm
(
input
,
batch1
,
batch2
)
(
"Input matrix shape:"
,
input
.
shape
)
(
"Batch 1 matrix shape:"
,
batch1.
shape
)
(
"Batch 2 matrix shape:"
,
batch2.
shape
)
(
"Result shape:"
,
result.
shape
)
(
result
)
The output 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]])