v9.1.1
Menu

Tensor Contraction with Einsum

mediumPROEinsum OperationsPyTorch Advanced

Problem Statement

Use einsum for advanced tensor contractions: Frobenius inner product, row-wise dot products, and column sums.

Background

Indices that appear on the left but not the right are summed over. By controlling which indices appear in the output, you can express a variety of reductions and contractions.

Your Task

The starter code creates matrices A and B. Use einsum to compute three operations: the Frobenius inner product (element-wise multiply and sum all), row-wise dot products (sum along columns only), and column sums of A.

Output Format

Returns a dictionary with "frobenius", "row_dots", and "col_sums".

Example

Input
None
Output
{'frobenius': 70.0, 'row_dots': [17.0, 53.0], 'col_sums': [4.0, 6.0]}
Reasoning
  • Inputs: the function builds two fixed 2×22 \times 2 float matrices, A=(1234)A = \begin{pmatrix}1 & 2\\ 3 & 4\end{pmatrix} and B=(5678)B = \begin{pmatrix}5 & 6\\ 7 & 8\end{pmatrix}. Index ii picks the row and jj the column, so AijA_{ij} and BijB_{ij} sit in the same cell.
  • Frobenius inner product: multiply matching cells and sum over both indices, ∑i,jAijBij=5+12+21+32=70\sum_{i,j} A_{ij}B_{ij} = 5 + 12 + 21 + 32 = 70. No index survives, so frobenius is a single scalar, 70.0.
  • Row-wise dot products: keep ii and sum over jj only, ri=∑jAijBijr_i = \sum_j A_{ij}B_{ij}. Row 0 gives 1⋅5+2⋅6=171 \cdot 5 + 2 \cdot 6 = 17, row 1 gives 3⋅7+4⋅8=533 \cdot 7 + 4 \cdot 8 = 53, so row_dots is [17.0, 53.0], one value per row.
  • Column sums of A: only AA is involved; keep jj and sum over ii, cj=∑iAijc_j = \sum_i A_{ij}, giving 1+3=41 + 3 = 4 and 2+4=62 + 4 = 6, so col_sums is [4.0, 6.0].
  • Notice that the row dots add up to the Frobenius value (17+53=7017 + 53 = 70): summing out ii afterwards finishes the full contraction. The indices you keep decide the output's shape.

Constraints

  • 'ij,ij->' for Frobenius inner product
  • 'ij,ij->i' for row-wise dots
  • 'ij->j' for column sums

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.