Efficiently Computing x A x^T for Multiple Vectors Using einsum in PyTorch
Description: Learn how to compute quadratic forms xAx^T for many vectors efficiently using PyTorch's einsum with a clear and concise example.
---
This video is based on the question https://stackoverflow.com/q/78910189/ asked by the user 'BiriBora' ( https://stackoverflow.com/u/3741774/ ) and on the answer https://stackoverflow.com/a/78913532/ provided by the user 'Soudipta Dutta' ( https://stackoverflow.com/u/6037956/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.
Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Using einsum for transpose times matrix times transpose: x@ A@ x^T
Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/licensing
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/by-sa/4.0/ ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/by-sa/4.0/ ) license.
If anything seems off to you, please feel free to drop me a comment under this video.
---
The Problem: Computing Quadratic Forms for Many Vectors
Suppose you have multiple vectors arranged in a matrix B of shape (m, n), where each row corresponds to a vector x of size (1, n). You also have a square matrix A of size (n, n). The goal is to compute the quadratic form:
[[See Video to Reveal this Text or Code Snippet]]
for all m vectors efficiently, producing an output tensor of shape (m, 1).
Naive Approach: Looping Over Vectors
A straightforward (but slow) way is looping through each vector and computing the product manually:
[[See Video to Reveal this Text or Code Snippet]]
This method is easy but inefficient for large m due to Python-level loops.
Efficient Vectorized Solution Using einsum
PyTorch's einsum offers a concise and highly optimized way to express this computation without explicit loops:
[[See Video to Reveal this Text or Code Snippet]]
'bi' denotes batch vectors (b = batch index, i = vector dimension)
'ij' is the matrix A
'bj' is again batch vectors
This contraction computes each x_i A x_i^T efficiently in parallel and returns a vector with one scalar per batch.
Alternative Using tensordot and Diagonal Extraction
Another way is to use tensordot operations followed by extracting the diagonal:
[[See Video to Reveal this Text or Code Snippet]]
This computes the full matrix of pairwise x_i A x_j^T values, then extracts the diagonal for the desired result.
Summary
Use torch.einsum('bi,ij,bj->b', B, A, B) for a clean and efficient one-liner.
tensordot can also do the job but may be less efficient and requires diagonal extraction.
Avoid explicit loops for scalability.
Code Example
[[See Video to Reveal this Text or Code Snippet]]
This approach is memory-friendly and highly optimized for large batch computations. Close description
---
This video is based on the question https://stackoverflow.com/q/78910189/ asked by the user 'BiriBora' ( https://stackoverflow.com/u/3741774/ ) and on the answer https://stackoverflow.com/a/78913532/ provided by the user 'Soudipta Dutta' ( https://stackoverflow.com/u/6037956/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.
Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Using einsum for transpose times matrix times transpose: x@ A@ x^T
Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/licensing
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/by-sa/4.0/ ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/by-sa/4.0/ ) license.
If anything seems off to you, please feel free to drop me a comment under this video.
---
The Problem: Computing Quadratic Forms for Many Vectors
Suppose you have multiple vectors arranged in a matrix B of shape (m, n), where each row corresponds to a vector x of size (1, n). You also have a square matrix A of size (n, n). The goal is to compute the quadratic form:
[[See Video to Reveal this Text or Code Snippet]]
for all m vectors efficiently, producing an output tensor of shape (m, 1).
Naive Approach: Looping Over Vectors
A straightforward (but slow) way is looping through each vector and computing the product manually:
[[See Video to Reveal this Text or Code Snippet]]
This method is easy but inefficient for large m due to Python-level loops.
Efficient Vectorized Solution Using einsum
PyTorch's einsum offers a concise and highly optimized way to express this computation without explicit loops:
[[See Video to Reveal this Text or Code Snippet]]
'bi' denotes batch vectors (b = batch index, i = vector dimension)
'ij' is the matrix A
'bj' is again batch vectors
This contraction computes each x_i A x_i^T efficiently in parallel and returns a vector with one scalar per batch.
Alternative Using tensordot and Diagonal Extraction
Another way is to use tensordot operations followed by extracting the diagonal:
[[See Video to Reveal this Text or Code Snippet]]
This computes the full matrix of pairwise x_i A x_j^T values, then extracts the diagonal for the desired result.
Summary
Use torch.einsum('bi,ij,bj->b', B, A, B) for a clean and efficient one-liner.
tensordot can also do the job but may be less efficient and requires diagonal extraction.
Avoid explicit loops for scalability.
Code Example
[[See Video to Reveal this Text or Code Snippet]]
This approach is memory-friendly and highly optimized for large batch computations. Close description
