下列文本提取自本地原版 PDF。图表和公式的准确布局请对照 PDF。
3.2 Remark: Batching, Einsum and Efficient Computation
Throughout the Transformer, we will be performing the same computation applied to many batch-like
inputs. Here are a few examples:
• Elements of a batch: we apply the same Transformer forward operation on each batch element.
• Sequence length: the “position-wise” operations like RMSNorm and feed-forward operate identically
on each position of a sequence.
• Attention heads: the attention operation is batched across attention heads in a “multi-headed”
attention operation.
It is useful to have an ergonomic way of performing such operations in a way that fully utilizes the GPU,
and is easy to read and understand. Many PyTorch operations can take in excess “batch-like” dimensions
at the start of a tensor and repeat/broadcast the operation across these dimensions efficiently.
For instance, say we are doing a position-wise, batched operation. We have a “data tensor” 𝐷 of shape
(batch_size, sequence_length, d_model), and we would like to do a batched vector-matrix multiply
against a matrix 𝐴 of shape (d_model, d_model). In this case, D @ A will do a batched matrix multiply,
which is an efficient primitive in PyTorch, where the (batch_size, sequence_length) dimensions are
batched over.
Because of this, it is helpful to assume that your functions may be given additional batch-like dimensions
and to keep those dimensions at the start of the PyTorch shape. To organize tensors so they can be
batched in this manner, they might need to be shaped using many steps of view, reshape and transpose.
This can be a bit of a pain, and it often gets hard to read what the code is doing and what the shapes of
your tensors are.
A more ergonomic option is to use einsum notation within torch.einsum, or rather use framework-
agnostic libraries like einops or einx. The two key ops are einsum, which can do tensor contractions with
arbitrary dimensions of input tensors, and rearrange, which can reorder, concatenate, and split arbitrary
dimensions. It turns out almost all operations in machine learning are some combination of dimension
juggling and tensor contraction with the occasional (usually pointwise) nonlinear function. This means
that a lot of your code can be more readable and flexible when using einsum notation.
We strongly recommend learning and using einsum notation for the class. Students who have not been
exposed to einsum notation before should use einops (docs here), and students who are already
comfortable with einops should learn the more general einx (here).4 Both packages are already installed
in the environment we’ve supplied.
Here we give some examples of how einsum notation can be used. These are a supplement to the
documentation for einops, which you should read first.
Example (einstein_example1): Batched matrix multiplication with einops.einsum
import torch
from einops import rearrange, einsum
## Basic implementation
Y = D @ A.T
# Hard to tell the input and output shapes and what they mean.
# What shapes can D and A have, and do any of these have unexpected behavior?
## Einsum is self-documenting and robust
# D A -> Y
Y = einsum(D, A, "batch sequence d_in, d_out d_in -> batch sequence d_out")
## Or, a batched version where D can have any leading dimensions but A is constrained.
Y = einsum(D, A, "... d_in, d_out d_in -> ... d_out")
Example (einstein_example2): Broadcasted operations with einops.rearrange
We have a batch of images, and for each image we want to generate 10 dimmed versions based on
some scaling factor:
images = torch.randn(64, 128, 128, 3) # (batch, height, width, channel)
dim_by = torch.linspace(start=0.0, end=1.0, steps=10)
## Reshape and multiply
dim_value = rearrange(dim_by, "dim_value -> 1 dim_value 1 1 1")
images_rearr = rearrange(images, "b height width channel -> b 1 height width channel")
dimmed_images = images_rearr * dim_value
## Or in one go:
dimmed_images = einsum(
images, dim_by,
"batch height width channel, dim_value -> batch dim_value height width channel"
)
4
It’s worth noting that while einops has a great amount of support, einx is not as battle-tested. You should feel free to
fall back to using einops with some more plain PyTorch if you find any limitations or bugs in einx.
Example (einstein_example3): Pixel mixing with einops.rearrange
Suppose we have a batch of images represented as a tensor of shape (batch, height, width,
channel), and we want to perform a linear transformation across all pixels of the image, but this
transformation should happen independently for each channel. Our linear transformation is
represented as a matrix 𝐵 of shape (height * width, height * width).
channels_last = torch.randn(64, 32, 32, 3) # (batch, height, width, channel)
B = torch.randn(32*32, 32*32)
## Rearrange an image tensor for mixing across all pixels
channels_last_flat = channels_last.view(
-1, channels_last.size(1) * channels_last.size(2), channels_last.size(3)
)
channels_first_flat = channels_last_flat.transpose(1, 2)
channels_first_flat_transformed = channels_first_flat @ B.T
channels_last_flat_transformed = channels_first_flat_transformed.transpose(1, 2)
channels_last_transformed = channels_last_flat_transformed.view(*channels_last.shape)
Instead, using einops:
height = width = 32
## Rearrange replaces clunky torch view + transpose
channels_first = rearrange(
channels_last,
"batch height width channel -> batch channel (height width)"
)
channels_first_transformed = einsum(
channels_first, B,
"batch channel pixel_in, pixel_out pixel_in -> batch channel pixel_out"
)
channels_last_transformed = rearrange(
channels_first_transformed,
"batch channel (height width) -> batch height width channel",
height=height, width=width
)
Or, if you’re feeling crazy: all in one go using einx.dot (einx equivalent of einops.einsum)
height = width = 32
channels_last_transformed = einx.dot(
"batch row_in col_in channel, (row_out col_out) (row_in col_in)"
"-> batch row_out col_out channel",
channels_last, B,
col_in=width, col_out=width
)
The first implementation here could be improved by placing comments before and after to
indicate what the input and output shapes are, but this is clunky and susceptible to bugs. With
einsum notation, documentation is implementation!
Einsum notation can handle arbitrary input batching dimensions, but also has the key benefit of being
self-documenting. It’s much clearer what the relevant shapes of your input and output tensors are in code
that uses einsum notation. For the remaining tensors, you can consider using Tensor type hints, for
instance using the jaxtyping library (not specific to JAX).
We will talk more about the performance implications of using einsum notation in assignment 2, but for
now know that they’re almost always better than the alternative!
3.2.1 Mathematical Notation and Memory Ordering
Many machine learning papers use row vectors in their notation, which result in representations that
mesh well with the row-major memory ordering used by default in NumPy and PyTorch. With row
vectors, a linear transformation looks like
𝑦 = 𝑥𝑊 ⊤ , (1)
for row-major 𝑊 ∈ ℝ𝑑out ×𝑑in and row-vector 𝑥 ∈ ℝ1×𝑑in . Notice that this lets us batch inputs by increasing
the outermost dimension of 𝑥, meaning we can substitute vector input 𝑥 for matrix input 𝑋 ∈ ℝbatch ×𝑑in .
In linear algebra it’s generally more common to use column vectors, where linear transformations look
like
𝑦 = 𝑊 𝑥, (2)
given a row-major 𝑊 ∈ ℝ𝑑out ×𝑑in and column-vector 𝑥 ∈ ℝ𝑑in . To batch the input in this setting, the batch
dimension to 𝑥 would have to come last, so 𝑥 would need to be replaced with a matrix 𝑋 ̃ ∈ ℝ𝑑in × batch .
We will use mostly column vectors for mathematical notation in this assignment, since math
generally follows this notation. You should keep in mind that if you want to use plain matrix
multiplication notation, you will have to apply matrices with a transpose as seen in the row vector
convention in Equation 1, since PyTorch uses row-major memory ordering. If you use einsum for your
linear algebra operations, this should be a non-issue as long as you label your axes correctly. As an aside,
it’s worth noting that other languages/linear algebra packages like Matlab, Julia and Fortran all use
column-major memory ordering, meaning batching dimensions come last, but Python and related
packages have adopted the C-standard of row-major ordering.
本章讨论
在 GitHub 查看记录 ↗