📘
Matrix Multiplication with Einsum
Problem Statement
Use torch.einsum to perform matrix multiplication.
Background
Einstein summation (einsum) is a compact notation for tensor operations. The key idea is that repeated indices are summed over, while indices that appear in the output are preserved.
Your Task
The starter code creates matrices A (2x3) and B (3x2). Use torch.einsum to compute the matrix product of A and B.
The verification against torch.matmul is pre-filled.
Output Format
Returns a dictionary with "result", "shape", and "matches_matmul".
Example:
Input:
None
Output:
{'result': [[58.0, 64.0], [139.0, 154.0]], 'shape': [2, 2], 'matches_matmul': True}Reasoning:
- We create matrix A =
[[1, 2, 3], [4, 5, 6]]and matrix B =[[7, 8], [9, 10], [11, 12]]. - We compute C = A @ B using
torch.einsum('ij,jk->ik', A, B), which performs matrix multiplication by summing over the shared index j: Cik=∑jAijBjk. - The resulting matrix C is computed as: C=[1∗7+2∗9+3∗114∗7+5∗9+6∗111∗8+2∗10+3∗124∗8+5∗10+6∗12]=[5813964154].
- We verify the result by comparing it with
torch.matmul(A, B), which yields the same result, so"matches_matmul"isTrue.
Constraints:
- Use torch.einsum with 'ij,jk->ik'
- Verify against torch.matmul
- Return as nested list
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.