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
None
{'output_shape': [2, 3, 5], 'matches_bmm': True, 'batch_size': 2, 'first_element': 3.8424}- Inputs: a fixed random seed produces two stacks of matrices: is (two matrices) and is (two matrices). The leading axis is the batch.
- Math: each batch slice is multiplied on its own, . The shared index (length 4) is summed away, while , and survive, so is , giving
output_shape[2, 3, 5]andbatch_size2. - Worked entry: pairs row 0 of the first matrix, , with column 0 of the first matrix, : , rounded to 4 decimal places as
3.8424. - Check: a dedicated batched matrix product computes the same numbers, so
matches_bmmisTrue. - Notice that the batch index is never summed: slice 0 of only ever meets slice 0 of .
Constraints
- Use 'bij,bjk->bik' notation
- Verify against torch.bmm
- Batch dimension preserved