v9.1.1
Menu

Batch Matrix Multiplication with Einsum

mediumPROEinsum OperationsPyTorch Advanced

Problem Statement

Use einsum for batched matrix multiplication.

Background

Batched operations perform independent computations for each element along the batch dimension. Einsum handles this naturally by including a batch index that is preserved (not summed over).

Your Task

The starter code creates batched tensors A (2x3x4) and B (2x4x5). Use torch.einsum to compute batched matrix multiplication.

The verification against torch.bmm is pre-filled.

Output Format

Returns a dictionary with "output_shape", "matches_bmm", "batch_size", and "first_element".

Example

Input
None
Output
{'output_shape': [2, 3, 5], 'matches_bmm': True, 'batch_size': 2, 'first_element': 3.8424}
Reasoning
  • Inputs: a fixed random seed produces two stacks of matrices: AA is 2×3×42 \times 3 \times 4 (two 3×43 \times 4 matrices) and BB is 2×4×52 \times 4 \times 5 (two 4×54 \times 5 matrices). The leading axis bb is the batch.
  • Math: each batch slice is multiplied on its own, Cbik=∑jAbijBbjkC_{bik} = \sum_{j} A_{bij} B_{bjk}. The shared index jj (length 4) is summed away, while bb, ii and kk survive, so CC is 2×3×52 \times 3 \times 5, giving output_shape [2, 3, 5] and batch_size 2.
  • Worked entry: C000C_{000} pairs row 0 of the first AA matrix, [1.9269,1.4873,0.9007,−2.1055][1.9269, 1.4873, 0.9007, -2.1055], with column 0 of the first BB matrix, [0.0349,0.6872,0.0499,−1.2862][0.0349, 0.6872, 0.0499, -1.2862]: 0.06727+1.02200+0.04495+2.70815≈3.842380.06727 + 1.02200 + 0.04495 + 2.70815 \approx 3.84238, rounded to 4 decimal places as 3.8424.
  • Check: a dedicated batched matrix product computes the same numbers, so matches_bmm is True.
  • Notice that the batch index is never summed: slice 0 of AA only ever meets slice 0 of BB.

Constraints

  • Use 'bij,bjk->bik' notation
  • Verify against torch.bmm
  • Batch dimension preserved

Learn this in

More from PyTorch Advanced

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.