PyTorch torch.addmm Function
PyTorch torch reference manual
torch.addmm is a function in PyTorch used to add the result of matrix multiplication to an input matrix. It performs the matrix multiplication mat1 @ mat2 and then adds the result to input.
Function definition
torch.addmm(input, mat1, mat2, *, beta=1.0, alpha=1.0, out=None)
Parameters:
input(Tensor): the input matrix, which is added to the result.mat1(Tensor): the first matrix, with shape (n, m).mat2(Tensor): the second matrix, with shape (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 mat1 @ mat2 is multiplied, defaulting to 1.0.out(Tensor, optional): the output tensor.
Return Value:
torch.Tensor: returns the sum of the matrix multiplication result and the input matrix, with shape (n, p).
Usage examples
Example
import
torch
Create the input matrix and the two matrices
input
=
torch.
randn
(
3
,
3
)
mat1
=
torch.
randn
(
3
,
4
)
mat2
=
torch.
randn
(
4
,
3
)
Perform addmm
result
=
torch.
addmm
(
input
,
mat1
,
mat2
)
(
"Input matrix shape:"
,
input
.
shape
)
(
"Matrix 1 shape:"
,
mat1.
shape
)
(
"Matrix 2 shape:"
,
mat2.
shape
)
(
"Result shape:"
,
result.
shape
)
(
result
)
The output is:
输入矩阵形状: torch.Size([3, 3])
矩阵1形状: torch.Size([3, 4])
矩阵2形状: torch.Size([4, 3])
结果形状: torch.Size([3, 3])
tensor([[ 0.4692, -0.2864, -0.6013],
[ 1.5525, 0.1233, -0.0182],
[-0.3956, 0.6267, 0.3580]])
Example - using the alpha and beta parameters
import
torch
input
=
torch.
randn
(
3
,
3
)
mat1
=
torch.
randn
(
3
,
4
)
mat2
=
torch.
randn
(
4
,
3
)
Use the alpha and beta parameters
result
=
torch.
addmm
(
input
,
mat1
,
mat2
,
beta
=
0.5
,
alpha
=
2.0
)
Equivalent to: result = 0.5 * input + 2.0 * (mat1 @ mat2)
(
result
)