PyTorch torch.baddbmm function
PyTorch torch reference manual
torch.baddbmm is a function in PyTorch used to perform batched matrix multiplication and add the result to an input batched matrix. It multiplies each pair of matrices in batch1 and batch2, then adds the corresponding matrix in input.
Function definition
torch.baddbmm(input, batch1, batch2, *, beta=1.0, alpha=1.0, out=None)
Parameters:
input(Tensor): The input batched matrix, of shape (b, n, p).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 batched matrix, of shape (b, n, p).
Usage examples
Example
import
torch
Create the input batched matrix and batched matrices
input
=
torch.
randn
(
10
,
3
,
3
)
batch1
=
torch.
randn
(
10
,
3
,
4
)
batch2
=
torch.
randn
(
10
,
4
,
3
)
Perform baddbmm
result
=
torch.
baddbmm
(
input
,
batch1
,
batch2
)
(
"Input batched matrix shape:"
,
input
.
shape
)
(
"Batch 1 matrix shape:"
,
batch1.
shape
)
(
"Batch 2 matrix shape:"
,
batch2.
shape
)
(
"Result shape:"
,
result.
shape
)
(
result
[
0
]
)
Print the first result
The output is:
输入批量矩阵形状: torch.Size([10, 3, 3])
批量矩阵1形状: torch.Size([10, 3, 4])
批量矩阵2形状: torch.Size([10, 4, 3])
结果形状: torch.Size([10, 3, 3])
tensor([[-1.0917, 0.0174, -0.6599],
[ 1.0403, -0.3905, -0.6314],
[ 0.0988, -0.3047, 0.4841]])