AI Wiki中文/EN

Computational graphs

计算图

Represent dependencies, trace forward values and reverse contributions, and understand shared variables, topological order, and memory costs.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The same x appears twice

Evaluate L=(xy+x)2L=(xy+x)^2 at x=2,y=3x=2,y=3. Split it into u=xy=6u=xy=6, v=u+x=8v=u+x=8, and L=v×v=64L=v\times v=64. This decomposition records dependencies, determines when each intermediate is available, and identifies contributions needed during differentiation.

Trace the dependencies of one computation
x = 2y = 3u = xy = 6v = u + x = 8L = v × v = 64Accumulate both operand uses

On narrow screens, scroll sideways; use arrow keys after focusing the diagram.

Values match the worked example. The reverse calculation starts at L and propagates local contributions against the arrows.

Input xx enters both the product xyxy and the later addition u+xu+x. Value vv 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 LL, define an adjoint vˉ=∂L/∂v\bar v=\partial L/\partial v for each intermediate. Start with Lˉ=1\bar L=1 and accumulate a contribution from each use:

aˉ+=zˉ∂z∂a(z=ϕ(a,…)).\bar a\mathrel{+}=\bar z\frac{\partial z}{\partial a}\qquad(z=\phi(a,\ldots)).

The addition assignment matters: every downstream use contributes. For L=v×vL=v\times v, each input contributes v=8v=8, giving vˉ=16\bar v=16. Addition passes 16 to uu and directly to xx. Multiplication u=xyu=xy contributes another 16y=4816y=48 to xx and 16x=3216x=32 to yy. Therefore:

∂L∂x=64,∂L∂y=32.\frac{\partial L}{\partial x}=64,\qquad \frac{\partial L}{\partial y}=32.

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 O(V+E)O(V+E) time and store O(V+E)O(V+E) 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

  1. If the last operation becomes loss = v + v, what is the derivative with respect to vv? Answer: 2, with one contribution from each input.
  2. Can the row computing uu precede the definition of xx? Answer: no; its dependency is unavailable.
  3. What happens if parents are stored as a deduplicated set while only one multiplication contribution is propagated per parent? Answer: v*v loses one contribution unless its local derivatives were correctly combined first.
  4. 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?

Choose one answer

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

  1. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  2. 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:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.