PIXELBANKv9.1.0
Menu

Batch Matrix Multiplication with Einsum

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': 0.1569}
Reasoning:
  • The function einsum_bmm_test() starts by seeding the random number generator with torch.manual_seed(42), ensuring reproducibility of the results.
  • It then creates two tensors A and B of shapes (2,3,4)(2, 3, 4) and (2,4,5)(2, 4, 5), respectively, using torch.randn, which generates random numbers.
  • The batched matrix multiplication is computed using torch.einsum('bij,bjk->bik', A, B), which performs the operation Cbij=∑jAbijBbjkC_{bij} = \sum_{j} A_{bij} B_{bjk}, resulting in a tensor of shape (2,3,5)(2, 3, 5).
  • The result is verified against torch.bmm(A, B), and since the implementation is correct, the comparison yields a match, leading to the output dictionary with the specified values, including the first element of the result tensor, which is 0.15690.1569 when rounded to 4 decimals.

Constraints:

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

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

0/0
Run code to see test results.
Batch Matrix Multiplication with Einsum - Medium | PixelBank