Computational graphs
计算图
Represent dependencies, trace forward values and reverse contributions, and understand shared variables, topological order, and memory costs.
computational-graphsThe same x appears twice
Evaluate at . Split it into , , and . This decomposition records dependencies, determines when each intermediate is available, and identifies contributions needed during differentiation.
On narrow screens, scroll sideways; use arrow keys after focusing the diagram.
Input enters both the product and the later addition . Value appears as both inputs to the final multiplication. Recording connectivity while losing operand multiplicity can omit a derivative path or halve a contribution.
Follow dependencies forward and contributions backward
An expanded feedforward computation can be a directed acyclic graph: nodes represent values or operations, and edges represent dependencies. A topological order ensures that every node’s inputs are available before it is evaluated. Independent nodes may exchange positions, but an unavailable input cannot be used. D2L, Section 5.3
For scalar output , define an adjoint for each intermediate. Start with and accumulate a contribution from each use:
The addition assignment matters: every downstream use contributes. For , each input contributes , giving . Addition passes 16 to and directly to . Multiplication contributes another to and to . Therefore:
A reverse traversal should process a node after all its downstream contributions arrive. Propagating immediately after just one edge contributes can send an incomplete gradient. Saving required forward values and traversing in reverse topological order provides a direct arrangement. MML, Section 5.6
A graph interpreter for addition and multiplication
This complete Python program accepts a short program already ordered by dependencies. Each name is assigned once. Repeated use of the same input remains as two operand positions in the parent list.
def evaluate(program):
values, parents = {}, {}
for name, op, *args in program:
if name in values:
raise ValueError("duplicate value name")
if op == "input":
values[name], parents[name] = args[0], []
continue
a, b = args
if a not in values or b not in values:
raise ValueError("dependencies must be evaluated first")
if op == "add":
values[name] = values[a] + values[b]
parents[name] = [(a, 1), (b, 1)]
elif op == "mul":
values[name] = values[a] * values[b]
parents[name] = [(a, values[b]), (b, values[a])]
else:
raise ValueError("unknown operation")
return values, parents
def backward(program, parents, output):
gradient = {row[0]: 0 for row in program}
gradient[output] = 1
for name, *_ in reversed(program):
for parent, local in parents[name]:
gradient[parent] += gradient[name] * local
return gradient
program = [("x", "input", 2), ("y", "input", 3),
("u", "mul", "x", "y"), ("v", "add", "u", "x"),
("loss", "mul", "v", "v")]
values, parents = evaluate(program)
g = backward(program, parents, "loss")
assert values["loss"] == 64
assert g["v"] == 16 and g["x"] == 64 and g["y"] == 32
assert len(parents["loss"]) == 2
assert backward(program, parents, "loss") == g
For these constant-cost scalar primitives, forward and reverse passes take time and store values and use records. Tensor nodes require a more realistic cost model: one matrix product may cost more than many scalar nodes.
Loops, mutation, and missing history
Source-code loops need not produce cyclic evaluation graphs. A particular execution can unroll iterations into distinct value nodes. Long loops can nevertheless require substantial storage. Checkpointing trades recomputation of some forward values for reduced memory.
Overwriting an intermediate in place can destroy information needed by the reverse pass. A multiplication’s derivative with respect to one input needs the other input’s forward-time value. Reading a subsequently modified value gives the wrong result. Frameworks track versions, disallow some mutations, or preserve required copies.
Graphs may contain stopped gradients, discrete operations, and custom derivatives. A numerical dependency does not guarantee that a mathematical derivative will be propagated along it. Inspect forward dependencies and differentiation rules separately when debugging training.
Check reuse and scheduling
- If the last operation becomes
loss = v + v, what is the derivative with respect to ? Answer: 2, with one contribution from each input. - Can the row computing precede the definition of ? Answer: no; its dependency is unavailable.
- What happens if parents are stored as a deduplicated set while only one multiplication contribution is propagated per parent? Answer:
v*vloses one contribution unless its local derivatives were correctly combined first. - Should requesting the same gradient twice automatically double it? Answer: not mathematically. An implementation must specify whether buffers are reset or intentionally accumulated. This example creates fresh buffers each time.
Which optimizations use the graph?
Common-subexpression reuse, parallel scheduling, operator fusion, and checkpointing exploit computational dependencies. Automatic differentiation additionally supplies local derivative rules. Understanding the graph helps separate model behavior, disconnected derivative paths, incorrect cache reuse, and execution-performance problems.
Make a prediction, then check
For L=v×v at v=8, why is the reverse contribution 16?
Learning objectives
- Evaluate in topological order, then accumulate gradients in reverse order.
- Explain how repeated operands, saved values, and in-place mutation affect gradients.
Prerequisites & connections
Explore related knowledge →References
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020 - Forward Propagation, Backward Propagation, and Computational Graphs
D2L authors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Recalculated u=6, v=8, L=64, and adjoints v=16, x=64, y=32; ran the interpreter and checked repeated operands and fresh buffers on repeated calls.
- Checked topological order, overwritten forward-value risks, scalar O(V+E) versus tensor-node costs, and the SVG’s two uses of v and displayed values.
- Compared arguments, numbers, examples, limitations, and exercise answers across languages; structural validation separately compares display formulas, code, sources, and sections. No independent human peer review.
Source locations checked:
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · §5.6, PDF p. 165 onward: backpropagation and computation
- Forward Propagation, Backward Propagation, and Computational Graphs · §5.3: forward/backward propagation and computational graphs
Related topics