v9.1.1
Menu

Matrix Multiplication with Einsum

easyFREEEinsum OperationsPyTorch Advanced

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
  • Inputs: two fixed float matrices, A=[123456]A = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{bmatrix} (2×32 \times 3) and B=[789101112]B = \begin{bmatrix} 7 & 8 \\ 9 & 10 \\ 11 & 12 \end{bmatrix} (3×23 \times 2).
  • Math: label AA's axes i,ji, j and BB's axes j,kj, k. The shared index jj (length 3) is summed away; ii and kk survive: Cik=∑jAijBjkC_{ik} = \sum_j A_{ij} B_{jk}.
  • Row 1 of AA against each column of BB: 1⋅7+2⋅9+3⋅11=581 \cdot 7 + 2 \cdot 9 + 3 \cdot 11 = 58 and 1⋅8+2⋅10+3⋅12=641 \cdot 8 + 2 \cdot 10 + 3 \cdot 12 = 64.
  • Row 2: 4⋅7+5⋅9+6⋅11=1394 \cdot 7 + 5 \cdot 9 + 6 \cdot 11 = 139 and 4⋅8+5⋅10+6⋅12=1544 \cdot 8 + 5 \cdot 10 + 6 \cdot 12 = 154.
  • Output: result is [[58.0, 64.0], [139.0, 154.0]] (floats, like the inputs), shape is [2, 2] because only ii and kk remain, and matches_matmul is True since this index rule is ordinary matrix multiplication.
  • Notice: the summed index must have equal length (3) in both matrices, which is why 2×32 \times 3 times 3×23 \times 2 works.

Constraints

  • Use torch.einsum with 'ij,jk->ik'
  • Verify against torch.matmul
  • Return as nested list

Learn this in

More from PyTorch Advanced

solution.py

Test results

Sign in to run your code against the test cases.