v9.1.1
Menu

Implement Bilinear Form with Einsum

hardPROEinsum OperationsPyTorch Advanced

Problem Statement

Use einsum to compute a batched bilinear form x^T A y.

Background

A bilinear form computes x^T A y where x and y are vectors and A is a matrix. With einsum, you can express this contraction over multiple indices in a single call.

Your Task

The starter code creates x (3x4), A (4x4), and y (3x4). Use einsum to compute the batched bilinear form x^T A y, producing one scalar per batch element.

Output Format

Returns a dictionary with "results" (one scalar per batch), "shape", and "first_result".

Example

Input
None
Output
{'results': [1.0, 6.0, 136.0], 'shape': [3], 'first_result': 1.0}
Reasoning
  • Inputs: xx and yy are batches of three 4-dimensional vectors (row bb is xbx_b or yby_b), and AA is a single 4×44 \times 4 matrix with entries 11 to 1616, shared by every batch element.
  • Math: for each bb, the bilinear form is xbTAyb=∑i∑jxbiAijybjx_b^T A y_b = \sum_i \sum_j x_{bi} A_{ij} y_{bj}. Both ii and jj are summed away; only bb survives.
  • b=0b=0: x0=y0=e1x_0 = y_0 = e_1 (the first unit vector), so only the term A11=1A_{11} = 1 survives, giving 1.01.0.
  • b=1b=1: x1=y1=e2x_1 = y_1 = e_2 picks out A22=6A_{22} = 6, giving 6.06.0.
  • b=2b=2: all-ones vectors keep every term, so the result is the sum of all entries of AA: row sums 10+26+42+58=13610 + 26 + 42 + 58 = 136.
  • Output: one scalar per batch element, so results is [1.0, 6.0, 136.0], shape is [3], and first_result is 1.0. Notice that with unit vectors eiTAeje_i^T A e_j simply reads entry (i,j)(i, j) of AA.

Constraints

  • Use 'bi,ij,bj->b' einsum notation
  • Batched computation
  • Fixed input values for determinism

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.