A computation graph records computation steps and their data dependencies. An operation node tells you what to do, and an arrow says which step uses the result. The simplest way to read it is to follow the arrows and ask: whose result does this step need?
Suppose a function takes two numbers x and y and evaluates the expression below. Look first at the central plus sign. The left and right terms are calculated before being added together.
This time the inputs are x = 2, y = 2. Draw each addition, subtraction and multiplication as a separate node and put the value passed to the next step beside its arrow:
flowchart TD
A["x + 3 = 5"] -->|5| L["左项:5 × 4 = 20"]
B["5 − 1 = 4"] -->|4| L
C["x + 3 = 5"] -->|5| D["减去 y:5 − 2 = 3"]
D -->|3| R["右项:3 × 6 = 18"]
E["2 + 4 = 6"] -->|6| R
L -->|20| O["相加:20 + 18 = 38"]
R -->|18| O
classDef fixed fill:#fff1d6,stroke:#8a5a12,color:#3e2b0e
classDef shared fill:#e6f1fa,stroke:#376784,color:#173b53
class B,E fixed
class A,C shared
Reading backward from the left term, multiplication waits for both 5 and 4. The right branch can start at the same time. At the top are two opportunities for improvement:
- The two yellow steps can run in advance. Whatever the next inputs,
5 − 1is always 4 and2 + 4is always 6. The compiler can substitute constants while preparing the program, saving one subtraction and one addition on each call. This is constant folding.1 - The two blue steps can become one. Both terms add 3 to the same
x. This time the result is 5. It can change next time, but within one call the two occurrences are identical. Compute it once and send the result along two arrows, saving another addition. This is common subexpression elimination.2
Use the same inputs after these changes. Follow the blue node’s two outgoing arrows: the left side multiplies 5 directly by 4, while the right subtracts y from that same 5 and multiplies by 6.
flowchart TD
S["只算一次:x + 3 = 5"] -->|5| L["乘常量 4:5 × 4 = 20"]
S -->|5| D["减去 y:5 − 2 = 3"]
D -->|3| R["乘常量 6:3 × 6 = 18"]
L -->|20| O["相加:20 + 18 = 38"]
R -->|18| O
classDef shared fill:#e6f1fa,stroke:#376784,color:#173b53
class S shared
Count the operations: eight arithmetic operations per call drop to five. With x = 7, y = 2 next time, the blue node recomputes 10. The branches produce 10 × 4 = 40 and (10 − 2) × 6 = 48, and the output is 88. The constants 4 and 6 can be reused indefinitely. The blue result is shared only within the current call.
📓 Note. Must a computation graph be a directed acyclic graph (DAG)? Not necessarily. It depends on whether a node represents a particular execution of an operation or part of a program that can execute repeatedly. Following arrows in the two diagrams above never returns to the start, hence “acyclic.”
Start at zero and add one three times. Drawing this execution gives each addition its own node:
0 → add 1 → add 1 → add 1, without a cycle. PyTorch autograd records operations from one execution in this way. Drawing the loop program itself can instead use a single “add 1” node with an edge back to the loop entry for the next iteration. Early TensorFlow represented loops with such back edges.34
I encountered this same question while studying how to distribute neural networks across GPUs. Once one GPU finishes its half, can it start the next step, or must it wait for data from another GPU? An AI compiler turns model code into programs hardware can execute. It follows the graph to find who needs a result, then decides which device computes it and when data moves.
In model code, what travels along an arrow?
An arrow in the arithmetic graph carried one number, such as 5. In a model it can carry an entire table of numbers. Suppose the model reads two tokens (short pieces of text), each represented by four numbers. In input table x at the top left, the first token has row [1, −2, 3, 0] and the second [0, 1, −1, 2]. That is 2 rows × 4 columns.
Follow the arrows down from the top left. Each row on the left always corresponds to the same token. The two tables on the right are weights. Each column specifies how to compute one output from the input, and both tokens use the same coefficients.
- Why does the first layer have eight columns? The first column of
w1is[1, 0, 0, 0]. Multiply it elementwise by the first row ofxand sum:1×1 + (−2)×0 + 3×0 + 0×0 = 1. This fills the upper-left cell offirst. Each of eight weight columns computes one number for this token, so its row has eight cells. Fill the second token’s row the same way. - What travels from first to hidden? In yellow, the first row’s −2 and −4 become 0. ReLU changes each negative number to zero and copies everything else. Input and output are both two by eight. A function that transforms values in this way is an activation function.
- How does the second layer return to four columns? The green column in
w2has eight ones, one for each value in ahiddenrow. Multiply the first row elementwise by one and add to obtain 12, then repeat for the second row to obtain 9. These form the first output column. Each remaining weight column yields another output column.
In section 1.1 of Principles and Implementation of Backpropagation in Computation Graphs, Zhang Juefei writes “同一个计算可以用不同的计算图描述” (“the same computation can be described with different computation graphs”). In figures 4 and 6, inputs and weights originally drawn individually are grouped into two nodes, each representing a row of numbers. To see where our top-left 1 came from, expand the four multiplications and sum. To see only which table the next layer awaits, one matrix multiplication node suffices.5
In code, @ denotes this row-of-the-left-table by column-of-the-right-table matrix multiplication. forward computes from input to output, a direction called the forward pass.
from jax.nn import relu
def forward(x, w1, w2):
first = x @ w1 # (2×4) 乘 (4×8),得到 2×8
hidden = relu(first) # 替换负数,保留 2×8
out = hidden @ w2 # (2×8) 乘 (8×4),得到 2×4
return out
The code uses JAX, a Python library that records and transforms array operations. A compiler calls operations such as multiplication or ReLU operators and the numeric arrays passed between them tensors. The hidden arrow to the second multiplication means that multiplication must read the two-by-eight table on its left. Whether it has to cross devices depends on which GPUs hold its values.6
How does a handwritten digit become a prediction in a computation graph?
Zhang Juefei gave a recognition example using MNIST handwritten digits. Each image has 28 × 28 pixels, flattened into a 784-row, one-column input. The diagram below redraws the node dimensions from the original. Follow the middle arrows through the layers to see the length of the column passed forward.5
flowchart TB
X["一张图片的像素<br/>784 × 1"] --> A["第一层:矩阵乘法 → 加偏置 → ReLU"]
W1["权重 90 × 784<br/>偏置 90 × 1"] --> A
A -->|"90 × 1"| B["第二层:矩阵乘法 → 加偏置 → ReLU"]
W2["权重 20 × 90<br/>偏置 20 × 1"] --> B
B -->|"20 × 1"| C["输出层:矩阵乘法 → 加偏置"]
W3["权重 10 × 20<br/>偏置 10 × 1"] --> C
C -->|"10 个分数"| P["SoftMax:换成 10 个概率"]
C -->|"同一组分数"| L["CrossEntropyWithSoftMax<br/>计算正确类别的损失"]
T["正确标签 10 × 1<br/>正确数字的位置是 1,其余是 0"] --> L
The bias in each layer adds one number to each output after multiplication. The ten final scores correspond to digits 0–9. Prediction follows the left branch: convert the scores to probabilities summing to one and pick the digit with the greatest probability. Training follows the right branch, which takes the same scores and the correct label, converts the scores to probabilities internally and computes cross-entropy. Lower probability on the correct digit means higher loss. Redrawn from the network diagram in Zhang Juefei’s article, showing adjacent multiplication, addition and activation as one layer.5
Our earlier two-layer example also passes an intermediate table to the next layer. After distributing it across two GPUs, the arrow raises another question: can the next layer begin with its local half?
Each GPU has four values. How does the second layer proceed?
Zoom in on hidden → second-layer multiplication → output. Each GPU holds four intermediate values and the layer computes four outputs. Focus on the first output, 12. Split the weights by rows and each GPU handles half the inputs before summing partial results. Split by columns and each GPU handles half the outputs. GPU A then needs all eight values before it can compute 12 on its own.7
Each pale yellow box is a cross-GPU exchange. The upper half exchanges two contributions to the same output and adds corresponding positions (all-reduce). The lower half exchanges values belonging to different positions and concatenates them in order (all-gather).
Now count the data transferred for two tokens. For each exchange count how many numbers one GPU receives from the other, then multiply by four bytes per number.8
| When must one GPU wait for the other? | Layout 1: half the inputs per GPU | Layout 2: half the outputs per GPU |
|---|---|---|
| Before starting the second layer | 0 bytes, since it has the four values it needs | 2 tokens × 4 missing values × 4 bytes = 32 bytes |
| Before delivering the full output | 2 tokens × 4 output partial sums × 4 bytes = 32 bytes | 2 tokens × 2 missing outputs × 4 bytes = 16 bytes |
| Total received per GPU | 32 bytes in one exchange | 48 bytes in two exchanges |
Look one node further ahead. Suppose the next layer needs only the first two outputs on GPU A and the last two on B. Layout 2 can stop at the blue and green boxes: A and B already have their respective results. Gathering the outputs is unnecessary and each GPU receives 16 fewer bytes. A fresh comparison must also recalculate layout 1 for the new output requirements.
What is cost-based compiler optimization?
Given two correct layouts, the compiler first eliminates plans that exceed GPU memory, estimates the durations of those remaining and selects the shorter estimated total. This is cost-based optimization. The method used to estimate computation, communication and waiting time is a cost model. Cost is measured as time here, with memory as a hard constraint.8
A transfer has two time costs. One is the fixed overhead of starting an exchange, even for a single number. The other grows with data size and can be estimated as bytes divided by effective bytes per second. Suppose we now process 2,000 tokens, 1,000 times the table above. Assume each exchange takes 3 microseconds to start and, when both directions operate concurrently, each direction transfers 16,000 bytes per microsecond. We can estimate communication time on paper:
| Layout | Startup | Moving data | Total |
|---|---|---|---|
| 1, exchange partial sums | 1 × 3 μs | 32,000 ÷ 16,000 = 2 μs | 5 μs |
| 2, gather twice | 2 × 3 μs | 48,000 ÷ 16,000 = 3 μs | 9 μs |
These are hypothetical teaching values. If both layouts take equal time for local multiplication and both must stop for transfers, the compiler chooses the first. If the second matrix shape suits the GPU better and saves 6 microseconds of multiplication, its compute savings exceed the extra 4 microseconds of communication and the choice reverses.8
How do we know how much faster a multiplication can be? Even on the same GPU, the same multiplication can use different tile sizes. Trying every candidate on hardware is slow. The open-source Ansor system first ranks implementations with a cost model, times a subset on target hardware, then updates the model from measurements to guide the next round. Our table used a formula for two-GPU transfers. Ansor learns which implementations may run faster. They estimate different parts of the work.9
Once a layout is chosen, how do the two GPUs actually run it?
With the open-source Alpa system, we can trace our same three lines of model logic from source to execution.6108
- Record operations. Given input shapes and types, say “two rows by four columns of floats,” JAX can trace the function and record “multiply, take nonnegative values elementwise, multiply again” and the inputs and outputs of each step. Other concrete values with the same shapes and operations can use the same record.
- Express the operations as instructions a compiler can rewrite. For
hidden @ w2, the instruction multiplies and accumulates across eight intermediate features, retaining two token and four output positions. This internal form is an intermediate representation (IR). JAX’s tracedjaxprand XLA’s HLO are intermediate representations at different stages.611 - Choose devices and layouts for each step. Within a device group Alpa considers both the operator’s cost and the cost of handing data to its successor. Our 32 versus 48 bytes illustrate two handoff choices. For larger models, early and late layers can use separate device groups. The first group can process the next microbatch while the second continues the previous one: pipeline parallelism. Alpa also searches where to split the stages and how many GPUs each gets.8
- Write the layout into the program and execute it on each GPU. The source contains just
out = hidden @ w2. For layout 1 the compiler can rewrite it in two steps. Multiply locally using four local columns ofhiddenand four matching weight rows. Sum across GPUs using all-reduce to add both partial tables cell by cell. Both GPUs run the same instructions on different data. The first cell is 4 on A and 8 on B, and both receive 12 after reduction. This is what GSPMD partitioning does in this example. XLA’s hardware backend converts local operations to GPU instructions or library calls, and Alpa launches workers via Ray to execute them.12811
How do you check that partitioning preserved the result? The Alpa tutorial runs one single-device and one parallel training step with identical initial weights and inputs, then compares the updated weights. That checks the backward pass and weight update as well.10
📓 Note. The Alpa paper names two search methods. For within-group layouts, integer programming models selecting or declining each candidate and seeks the lowest-cost combination within constraints. For pipeline stage boundaries across groups, dynamic programming remembers the cost of partitioning shorter networks under a device budget and tries appending another stage, avoiding a fresh calculation for every full partition.8
Why keep intermediate values after computing a prediction during training?
Together the two GPUs produced the first token’s first output, 12. If prediction alone were the goal, we could deliver it now. Training asks another question: if the correct answer is 10, how should the weights change to bring the next prediction closer to 10?
Read the lower half of this textbook diagram left to right. Input x goes through the first multiplication to produce z, negatives are zeroed to obtain h, and multiplication by the second weights produces prediction o. These correspond to first, hidden and out above. The gap between the prediction and target y is measured by a number L, the loss. The figure also adds a penalty s for large weights, so training minimizes the total at the far right, J = L + s.13
Boxes hold values and circles perform operations. φ corresponds to ReLU in our example. Look first at the lower multiplication from h to the prediction. We will follow one weight to see how it affects that prediction. Figure 4.7.1 from the Chinese edition of Dive into Deep Learning, with a white background added.13
How does 12 change with a weight? One term that contributed to 12 was 3 × 1. The 3 is in the third cell of the first hidden row and the 1 is its second-layer weight. Change just that weight from 1 to 0.9. The term falls from 3 to 2.7 and the prediction from 12 to 11.7. A 0.1 drop in the weight produces a 0.3 drop in prediction because the number multiplying it was 3.
Training can exploit this relationship directly. Working backward from J, calculate how sensitive the score is to the prediction, then multiply by 3 to obtain this weight’s contribution to the score through that prediction. If the weight affects other predictions or the penalty above, add the contributions returning along each path. Computing the objective’s rate of change with respect to each weight in this way is backpropagation. Together those rates form the gradient. A framework knows the derivative rules for primitive operations and can chain them along the graph to compute derivatives with respect to inputs or weights automatically. This is automatic differentiation. Working backward from a single loss uses its reverse mode.513
flowchart TD
H["第一层算出 hidden,其中一格是 3"] --> F["前向用一次:3 × 权重,参与算出预测 12"]
F --> J["根据预测和正确答案算损失,得到总分"]
J --> B["反向算这个权重的梯度"]
H -->|"反向又要读同一个 3"| B
When the backward pass gets here, where does that 3 come from? If hidden stayed in GPU memory during the forward pass, the backward pass can read it. Our table has 2 rows × 8 columns at 4 bytes per number, requiring 64 bytes. If released after forward use, it must be recovered by rerunning the first multiplication and ReLU from retained inputs and weights. A compiler comparing training plans must ask how many tables must coexist until backward use, and which are cheapest to recompute if they do not fit.138
📓 Note. Why add two backward contributions when one number was used twice? Consider the first token’s four outputs
[12, 3, 9, 0]. The 3 inhiddencontributed to both the first output 12 and the third output 9, each with weight 1. To isolate these paths, add those two outputs to get 21. Increase just the intermediate value from 3 to 4: the two outputs become 13 and 10 and their sum becomes 23. Forward, one value travels along two arrows. Backward, for the derivative of the sum with respect to that value, each arrow returns 1 and together they give 2. Zhang Juefei’s figure 11 shows just this fork.5
Alpa, XLA and TVM are all compiler systems. Which problem does each solve?
| Question about the graph | Corresponding open-source implementation |
|---|---|
| Which weight rows should each GPU take in the second layer? Should early and late layers use separate device groups? | Alpa searches for divisions of work and includes the transfers needed for layout changes.8 |
| Once the local matrix tile is known, how can the GPU compute it efficiently? | XLA optimizes tensor operations and generates hardware-specific code. Alpa reuses its partitioning and compilation capabilities.118 |
| Can the first multiplication and zeroing of negatives run together, avoiding an intermediate write and read? | The original TVM paper studied fusion of adjacent operations as well as how to schedule work within a multiplication on different hardware.14 |
Which step does operator fusion save? Follow the second cell of the first row in layer one. Multiplication gives −2 and ReLU must turn it into 0. Assuming ReLU alone uses the multiplication result during inference, the two approaches are as follows.1411
flowchart TD
I["同一份输入 x 和权重 w1"]
I -->|分开执行| M["乘法算出 first<br/>这一格是 −2"]
M -->|写出 64 字节| T["显存中的中间表 first<br/>2 行 × 8 列"]
T -->|读回 64 字节| R["ReLU 把 −2 改成 0"]
I -->|融合执行| F["同一个 GPU 函数里<br/>每算好一块乘积就做 ReLU<br/>这一格从 −2 直接变成 0"]
R --> O["写出结果表 hidden<br/>同一格都是 0"]
F --> O
classDef temp fill:#fff1d6,stroke:#8a5a12,color:#3e2b0e
class T temp
The yellow box contains 2 × 8 = 16 values at four bytes each. Fusion avoids one write and one read of first, a total of 128 bytes. Both routes still write hidden at the end.
One question remains open to experiment: is the plan predicted fastest on an idle machine still fastest when another job uses the GPU interconnect? Fix the model, input shape and two layouts. Record predicted and measured times on an idle machine, then add a competing transfer and compare actual rankings. A reversal would indicate missing waiting time in the original cost model. The Proteus simulator accounts for transfers sharing bandwidth, providing a prediction for comparison.15
Further reading: How Alpa searches for stage partitions and compares against manual plans · How Ray allocates GPUs to workers
References
Footnotes
-
OpenXLA Project. (n.d.). HLO passes. OpenXLA documentation. Constant Folding: replacing compile-time evaluable expressions with constants ↩
-
LLVM Project. (n.d.). Passes. MLIR documentation. CSE: merging repeated subexpressions ↩
-
PyTorch contributors. (n.d.). A gentle introduction to torch.autograd. PyTorch Tutorials. Computational Graph: one forward-execution DAG and reverse traversal. ↩
-
TensorFlow authors. (2017, November 1). Implementation of control flow in TensorFlow. TensorFlow design document. NextIteration back edge in a while loop. ↩
-
张觉非. (n.d.). Principles and Implementation of Backpropagation in Computation Graphs. Zhihu column. Section 1.1, figures 4–6 and quoted paragraph; Section 2, two gradient paths in figure 11; MNIST example, probability and loss branches. ↩ ↩2 ↩3 ↩4 ↩5
-
JAX authors. (n.d.). Ahead-of-time lowering and compilation. JAX documentation. Tracing, lowering and compilation stages ↩ ↩2 ↩3
-
Shoeybi, M., et al. (2019). Megatron-LM: Training multi-billion parameter language models using model parallelism. arXiv. Section 3, adjacent linear layers in figure 3a ↩
-
Zheng, L., et al. (2022). Alpa: Automating inter- and intra-operator parallelism for distributed deep learning. OSDI. Sections 3–6, search, costs and runtime ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10
-
Zheng, L., et al. (2020). Ansor: Generating high-performance tensor programs for deep learning. OSDI. Search in section 3 and cost model in section 5 ↩
-
Alpa contributors. (n.d.). Alpa quickstart. GitHub. Training step and numerical comparison with a single device ↩ ↩2
-
OpenXLA Project. (n.d.). XLA architecture. OpenXLA documentation. Compilation pipeline and hardware backends ↩ ↩2 ↩3 ↩4
-
Xu, Y., et al. (2021). GSPMD: General and scalable parallelization for ML computation graphs. arXiv. Sharding annotations, single-program multiple-data execution and matrix multiplication rewriting ↩
-
Zhang, A., Lipton, Z. C., Li, M., & Smola, A. J. (n.d.). Forward Propagation, Backward Propagation and Computational Graphs. Dive into Deep Learning, Chinese edition, section 4.7. Figure 4.7.1, backpropagation and saving intermediate values during training · Original SVG · Textbook license. The figure retains CC BY-SA 4.0. ↩ ↩2 ↩3 ↩4
-
Chen, T., et al. (2018). TVM: An automated end-to-end optimizing compiler for deep learning. OSDI. Paper and authors’ presentation ↩ ↩2
-
Duan, J., et al. (2023). Proteus: Simulating the performance of distributed DNN training. arXiv. Simulation of bandwidth sharing and compute/communication overlap ↩