PyTorch torch.chain_matmul function
PyTorch torch reference manual
torch.chain_matmul is a function in PyTorch used to compute the chained multiplication of multiple matrices. It minimizes computational cost by choosing the optimal order of matrix multiplications.
Function definition
torch.chain_matmul(*matrices, out=None)
Parameters:
matrices(Tensor): The input sequence of matrices.out(Tensor, optional): the output tensor.
Return Value:
torch.Tensor: Returns the result of multiplying all the matrices.
Usage examples
Example
import
torch
Create multiple matrices
A
=
torch.
randn
(
10
,
20
)
B
=
torch.
randn
(
20
,
30
)
C
=
torch.
randn
(
30
,
40
)
D
=
torch.
randn
(
40
,
50
)
Chained matrix multiplication
result
=
torch.
chain_matmul
(
A
,
B
,
C
,
D
)
(
"Shape of matrix A:"
,
A.
shape
)
(
"Shape of matrix B:"
,
B.
shape
)
(
"Shape of matrix C:"
,
C.
shape
)
(
"Shape of matrix D:"
,
D.
shape
)
(
"Result shape:"
,
result.
shape
)
The output is:
矩阵 A 形状: torch.Size([10, 20])
矩阵 B 形状: torch.Size([20, 30])
矩阵 C 形状: torch.Size([30, 40])
矩阵 D 形状: torch.Size([40, 50])
结果形状: torch.Size([10, 50])
Example - Using a list
import
torch
A list of matrices
matrices
=
[
torch.
randn
(
10
,
20
)
,
torch.
randn
(
20
,
30
)
,
torch.
randn
(
30
,
40
)
]
Use the list as the argument
result
=
torch.
chain_matmul
(
*matrices
)
(
"Result shape:"
,
result.
shape
)