CS336.wiki
CS336 中文实验手册/Transformer 架构
反馈与讨论
ASSIGNMENT 01 / 3.2

张量、Einsum 与批处理

2026 春季 · v26.0.3原文 p. 14–17对照 PDF ↗

3.2 批处理、Einsum 与高效计算#

Transformer 中许多计算都要对多个具有“批次性质”的输入执行相同操作,例如:

  • 批内样本: 每个样本都执行相同的 Transformer 前向计算。
  • 序列位置: RMSNorm、前馈网络等逐位置操作,对每个位置执行相同计算。
  • 注意力头: 多头注意力在每个头上独立执行同样的注意力操作。

理想的表达方式应能充分使用 GPU,并便于阅读。许多 PyTorch 运算允许张量开头带有额外的批次维,并高效地在这些维度上重复或广播计算。

例如,数据张量 DD 的形状是 (batch_size, sequence_length, d_model),矩阵 AA 的形状是 (d_model, d_model)。使用矩阵乘法 D @ A 就会高效地在前两个维度上批量执行向量与矩阵的乘法。

因此,应假设函数可能接收额外的批次维,并始终把它们放在张量形状的前部。若用多次 view、reshape、transpose 调整张量,代码容易繁琐,也很难看清各维度的意义。

更方便的方式是使用 torch.einsum,或者框架无关的 einops、einx。两个核心操作是:

  • einsum:对任意维度的输入执行张量收缩。
  • rearrange:重排、合并、拆分维度。

机器学习中的绝大多数运算都是维度调整与张量收缩,再配合偶尔使用的非线性函数,通常是逐元素函数。因此,einsum 记法能让大量代码更易读、更灵活。

课程强烈建议学习并使用 einsum。初学者先阅读 einops 基础文档;熟悉 einops 后可以学习更一般的 einx。课程环境已经安装二者。相比 einops,einx 经过的实际检验较少,遇到限制或缺陷时,可以退回 einops 加普通 PyTorch。

下面的示例是对文档的补充,应先阅读文档。

原文示例 einstein_example1

使用 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")
原文示例 einstein_example2

使用 einops.rearrange 进行广播操作

给定一批图像,要按不同缩放系数,为每张图生成 10 个亮度逐渐变化的版本。原文先通过重排添加单例维来广播相乘,再展示如何直接用一次 einsum 表达相同运算。

指导书原文
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"
)
原文示例 einstein_example3

使用 einops.rearrange 混合像素

假设图像张量形状为 (batch, height, width, channel),希望对每个通道独立地对全部像素做线性变换。变换矩阵 BB 的形状为 (height * width, height * width)。

原文比较了用 view 加 transpose 的做法、用 rearrange 与 einsum 的做法,以及用 einx.dot 一次完成的写法。第一种做法也可以加形状注释改善,但会更繁琐、容易产生与实现不一致的注释。einsum 记法使形状说明直接成为运算的一部分。

指导书原文
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)
指导书原文
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
)
指导书原文
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
)

einsum 不仅能处理任意数量的输入批次维,也有自文档化的优势:输入输出的相关形状更清楚。对其他张量,可以考虑用 jaxtyping 等库添加类型标注,它并不专属于 JAX。

作业 2 会进一步讨论 einsum 的性能影响。目前可以认为它们几乎总比替代写法更合适。

3.2.1 数学记法与内存顺序#

许多机器学习论文使用行向量,这与 NumPy、PyTorch 默认的行优先内存布局相适应。行向量的线性变换写作:

y=xW⊤(1) y=xW^\top \tag{1}

其中 W∈Rdout×dinW\in\mathbb{R}^{d_{\mathrm{out}}\times d_{\mathrm{in}}},x∈R1×dinx\in\mathbb{R}^{1\times d_{\mathrm{in}}}。增加最外侧维度即可形成批次,用 X∈Rbatch×dinX\in\mathbb{R}^{\mathrm{batch}\times d_{\mathrm{in}}} 替代 xx。

线性代数更常使用列向量:

y=Wx(2) y=Wx \tag{2}

此时 x∈Rdinx\in\mathbb{R}^{d_{\mathrm{in}}}。若在这种数学表达中批量处理输入,批次维需要放在最后,使用 X~∈Rdin×batch\widetilde X\in\mathbb{R}^{d_{\mathrm{in}}\times\mathrm{batch}}。

本指导书的数学表达主要使用列向量。 但若在 PyTorch 中用普通矩阵乘法实现,需要按照公式 1 的行向量约定转置矩阵。使用 einsum 并正确标记维度时,一般无需担心这个问题。

Matlab、Julia、Fortran 等语言或线性代数库通常采用列优先布局,批次维常放在最后;Python 及相关库则沿用 C 的行优先约定。

一起把这一章读得更好

发现翻译、公式或排版错误?欢迎反馈。概念疑问和学习心得,也可以在本章讨论中交流。

直接选中正文,点击旁边的「反馈这处错误」,即可在页内填写并提交,无需登录。
English original 展开本章英文原文 PDF 文本提取

下列文本提取自本地原版 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 账号。

正在加载本章讨论…

欢迎交流概念与阅读疑问,请勿发布作业完整实现或题目答案。

输入中文、英文术语或题号,例如 RoPE、检查点、train_bpe。