Skip to content
Medium Framework

Einstein Summation

The trace of a square matrix is the sum of its main diagonal, from top left to bottom right. Compute one trace for each matrix in a batch using einsum.

Your task

Implement batch_trace(x) for a floating-point tensor of shape (batch, n, n). Return a vector of shape (batch,), preserving x's dtype and device and leaving x unchanged. Keep the batch dimension even when there is only one matrix.

output[b] = sum(x[b, i, i] for i from 0 to n-1)

For matrices [[1, 9], [8, 4]] and [[2, 7], [6, 5]], return [5, 7]. The traces are 1 + 4 = 5 and 2 + 5 = 7. Values outside the main diagonal do not contribute, even if they are larger than the diagonal values.

Read the einsum expression

Use torch.einsum('bii->b', x) or jnp.einsum('bii->b', x).

  • b names the batch axis.
  • The two occurrences of i in the same input select matching row and column positions: x[b, 0, 0], x[b, 1, 1], and so on.
  • The output keeps b and omits i, so the diagonal entries are summed within each matrix while the batch entries stay separate.

Repeating a label selects a diagonal; omitting that label from the output requests the sum. These are two distinct parts of the notation. Do not sum all matrix entries, use the opposite diagonal, or reduce the whole batch to one number. The trace uses signed values, not their absolute values.

The diagram below uses the same two matrices as the worked example.

Loading visualization…