The neural notebook
← All chapters

IV-06 / Part II · Learning, Backpropagation and Optimization

Computational Graphs and Local Derivatives

Follow one stored quantity through three operand edges, then distinguish local sensitivities from a total loss gradient.

Review the ideas this chapter uses

A calculation can use the same number more than once. Suppose you multiply an input by a weight, then use that product both in a sum and in a square. If you change the original product, all its uses change together. A drawing that forgets one use will later give the wrong answer about how the final loss changes.

We will turn this small calculation into a computational graph: a record of which values each operation reads. Start with the solved example, then inspect the two square operands separately. The graph is the real calculation behind the displayed numbers.

Compute it yourself

Follow values, then inspect one edge

These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.

Complete results from this trace’s starting inputs

Starting inputs for these results
x
2
w
0.5
b
1
y
1
loss2
prediction3
q1
r2

loss 2. prediction 3. q 1. r 2. Forward: shared product q. Store q once. Its value is read by three outgoing operand edges.. q 1

Forward: shared product q

q=w*x

Store q once. Its value is read by three outgoing operand edges.

Inputs

w
0.5
x
2

Outputs

q
1

Forward values and operand edges

One stored q has three outgoing edges: r_q, s_left and s_right. Each line names an operand slot. The highlighted trace edge follows Calculation step; Inspect operand edge selects a separate edge to examine.

s_left: ds/dq_left=q_right; local factor = 1. Hold the other operand fixed; this is an edge sensitivity, not a total loss gradient.

Scalar DAG with two distinct square operand edgesw and x produce q. q feeds r once and s twice, through s_left and s_right. r also reads b. r and s produce prediction; prediction minus y produces error; half its square produces loss. Values and edge factors are listed in the tables below.w0.5x2q1b1r2s1prediction3y1error2loss2s_lefts_rightArrows point from stored input values toward their consumers.

Node values are the complete forward calculation. Local derivative steps inspect one edge without changing those values.

Stored node values, logical shape [1,1]
NodeValue
w0.5
x2
q1
b1
r2
s1
prediction3
y1
error2
loss2
One local factor for each operand edge
Edge / operand IDStored source → consumerPartial derivativeLocal factor
q_ww → qdq/dw=x2
q_xx → qdq/dx=w0.5
r_qq → rdr/dq=11
r_bb → rdr/db=11
s_leftq → sds/dq_left=q_right1
s_rightq → sds/dq_right=q_left1
prediction_rr → predictiondp/dr=11
prediction_ss → predictiondp/ds=11
error_predictionprediction → errorde/dp=11
error_yy → errorde/dy=-1-1
loss_errorerror → lossdL/de=error2
Inspect tensor shapes and full precision

All computed outputs

loss
2
prediction
3
q
1
r
2
s
1
error
2
errorSquare
4
x
2
w
0.5
b
1
y
1
local_q_w
2
local_q_x
0.5
local_r_q
1
local_r_b
1
local_s_left
1
local_s_right
1
local_prediction_r
1
local_prediction_s
1
local_error_prediction
1
local_error_y
-1
local_loss_error
2

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

loss

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: loss; local_* denotes one operand edge.

Storage indexValue
02

prediction

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: prediction; local_* denotes one operand edge.

Storage indexValue
03

q

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: q; local_* denotes one operand edge.

Storage indexValue
01

r

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: r; local_* denotes one operand edge.

Storage indexValue
02

s

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: s; local_* denotes one operand edge.

Storage indexValue
01

error

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: error; local_* denotes one operand edge.

Storage indexValue
02

errorSquare

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: errorSquare; local_* denotes one operand edge.

Storage indexValue
04

x

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: x; local_* denotes one operand edge.

Storage indexValue
02

w

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: w; local_* denotes one operand edge.

Storage indexValue
00.5

b

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: b; local_* denotes one operand edge.

Storage indexValue
01

y

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: y; local_* denotes one operand edge.

Storage indexValue
01

local_q_w

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_q_w; local_* denotes one operand edge.

Storage indexValue
02

local_q_x

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_q_x; local_* denotes one operand edge.

Storage indexValue
00.5

local_r_q

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_r_q; local_* denotes one operand edge.

Storage indexValue
01

local_r_b

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_r_b; local_* denotes one operand edge.

Storage indexValue
01

local_s_left

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_s_left; local_* denotes one operand edge.

Storage indexValue
01

local_s_right

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_s_right; local_* denotes one operand edge.

Storage indexValue
01

local_prediction_r

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_prediction_r; local_* denotes one operand edge.

Storage indexValue
01

local_prediction_s

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_prediction_s; local_* denotes one operand edge.

Storage indexValue
01

local_error_prediction

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_error_prediction; local_* denotes one operand edge.

Storage indexValue
01

local_error_y

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_error_y; local_* denotes one operand edge.

Storage indexValue
0-1

local_loss_error

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · Explicit scalar DAG: local_loss_error; local_* denotes one operand edge.

Storage indexValue
02

forward_q.q

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_q: q=w*x

Storage indexValue
01

forward_r.r

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_r: r=q+b

Storage indexValue
02

forward_s.s

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_s: s=q_left*q_right; q_left=q_right=q

Storage indexValue
01

forward_prediction.prediction

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_prediction: prediction=r+s

Storage indexValue
03

forward_error.error

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_error: error=prediction-y

Storage indexValue
02

forward_loss.errorSquare

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_loss: loss=error*error/2

Storage indexValue
04

forward_loss.loss

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward_loss: loss=error*error/2

Storage indexValue
02

local_q_w.localFactor

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · local_q_w: dq/dw=x

Storage indexValue
02

local_q_x.localFactor

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · local_q_x: dq/dx=w

Storage indexValue
00.5

local_r_q.localFactor

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · local_r_q: dr/dq=1

Storage indexValue
01

local_r_b.localFactor

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · local_r_b: dr/db=1

Storage indexValue
01

local_s_left.localFactor

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · local_s_left: ds/dq_left=q_right

Storage indexValue
01

local_s_right.localFactor

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · local_s_right: ds/dq_right=q_left

Storage indexValue
01

local_prediction_r.localFactor

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · local_prediction_r: dp/dr=1

Storage indexValue
01

local_prediction_s.localFactor

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · local_prediction_s: dp/ds=1

Storage indexValue
01

local_error_prediction.localFactor

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · local_error_prediction: de/dp=1

Storage indexValue
01

local_error_y.localFactor

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · local_error_y: de/dy=-1

Storage indexValue
0-1

local_loss_error.localFactor

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · local_loss_error: dL/de=error

Storage indexValue
02

Seek forward_q through forward_loss, then inspect local_s_left and local_s_right. Changing an input recomputes this same graph and returns the trace to its first step.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. The stored q currently equals 1. How does s=q*q use it?
2. Using current w=0.5 and x=2, which value is q?
3. For current q=1, what is the local factor on s_left alone?
4. Current prediction=3. What happens to prediction if only Target y changes?
5. Set w=0, x=2, b=0, y=1. Both square factors become zero. Does prediction still respond locally to q?

Choose Inspect operand edge to compare s_left and s_right. Use Calculation step to walk from forward_q to forward_loss, then through the local derivative steps. Changing Weight w recomputes every dependent value; Reset example restores the hand example. Graph nodes show the completed forward values, while the selected trace explains one operation at a time.

Name the values before tracing them

An input xx is the number supplied to the model. A weight ww multiplies it, and a bias bb supplies an offset. The target yy is the desired answer. Only ww and bb are model parameters, although all four numbers are editable here so that you can investigate dependencies.

A node is one stored value. An edge connects a stored value to an operation that reads it. An operand is one input slot of an operation: multiplication has a left slot and a right slot. We give those slots separate names even when they read the same node.

Here is the entire model, in evaluation order:

q=wx,r=q+b,s=q q,q=wx,\qquad r=q+b,\qquad s=q\,q, p=r+s,e=p−y,L=e22.p=r+s,\qquad e=p-y,\qquad L=\frac{e^2}{2}.

The temporary names q,r,sq,r,s label intermediate values. The prediction pp is called prediction in code. Signed error ee is called error; loss LL is called loss. Loss scores disagreement with the target; it is not another prediction. The factor one half is our declared half-squared-error convention, with one example and no averaging.

Every node contains one scalar, meaning one real number. Its logical tensor shape is [1,1]: one scalar row and one scalar column, not one batch of many features. The inspector also stores scalar local factors in this shape. There are no implicit transposes or hidden batches in this lesson.

The graph is directed because an edge points from an input value toward its consumer. It is acyclic because following those arrows never returns to an earlier node. The abbreviation DAG means directed acyclic graph. This lets us evaluate each operation after its inputs are ready.

Calculate every forward node by hand

Defaults are x=2,w=1/2,b=1,y=1x=2,w=1/2,b=1,y=1. First form the shared product:

q=12⋅2=1.q=\frac12\cdot2=1.

Store that one result. The linear branch adds bias, while the square branch multiplies two reads of qq:

r=1+1=2,s=(1)(1)=1.r=1+1=2,\qquad s=(1)(1)=1.

Combine the branches, compare with the target, then score the error:

p=2+1=3,e=3−1=2,p=2+1=3,\qquad e=3-1=2, e2=2⋅2=4,L=4/2=2.e^2=2\cdot2=4,\qquad L=4/2=2.

The loss happens to equal the error here, but they mean different things. Set the target to four: prediction remains three, error becomes negative one, and loss becomes one half. The target cannot change q,r,sq,r,s or prediction because none of those operations reads it.

The outgoing uses of qq are called fan-out. There are three operand edges: r_q, s_left, and s_right. We have not calculated three independent products wxwx. We stored qq once and read it three times. That distinction is essential when we later combine sensitivities.

What a local derivative asks

A derivative is a rate of change at the current values. A partial derivative varies one operand while holding the other operands fixed. The symbol ∂\partial in ∂q/∂w\partial q/\partial w signals that held-fixed condition. “Local” means that we ask about one operation, before following consequences through the rest of the graph.

For q=wxq=wx, imagine increasing ww by a small amount hh, while keeping xx fixed. The new product is (w+h)x=wx+hx(w+h)x=wx+hx. Its change is hxhx, so its change per unit hh is xx. Thus

∂q∂w=x=2,∂q∂x=w=12.\frac{\partial q}{\partial w}=x=2, \qquad \frac{\partial q}{\partial x}=w=\frac12.

The symbol hh denotes a hypothetical small increment; it is not an extra state variable or an executed numerical experiment. In the local trace you can see the actual named operands w and x, so the factor two has an inspectable origin.

For addition, increasing either operand by hh increases the sum by hh. Therefore both edges into r=q+br=q+b have local factor one. Both edges into p=r+sp=r+s do too. Subtraction behaves differently for its second operand: increasing yy decreases e=p−ye=p-y, giving factor negative one.

Edge IDLocal derivativeAt the default
q_w∂q/∂w=x\partial q/\partial w=x22
q_x∂q/∂x=w\partial q/\partial x=w1/21/2
r_q, r_beach addition operand has factor 111,11,1
s_leftother square operand, qq11
s_rightother square operand, qq11
prediction_r, prediction_seach addition operand has factor 111,11,1
error_prediction, error_yprediction factor 11, target factor −1-11,−11,-1
loss_error∂L/∂e=e\partial L/\partial e=e22

The half-square is a single unary operation: its one input is error. Algebra gives ((e+h)2−e2)/(2h)=e+h/2((e+h)^2-e^2)/(2h)=e+h/2, which approaches ee as hh approaches zero. Hence its local derivative is error. We do not create two extra square operand edges for this explicitly unary node.

Why the two square edges each carry q

Temporarily write a product as f(a,c)=acf(a,c)=ac, with left operand aa and right operand cc. Holding cc fixed gives ∂f/∂a=c\partial f/\partial a=c. Holding aa fixed gives ∂f/∂c=a\partial f/\partial c=a.

Our operation feeds the same stored qq into both positions, so s_left has factor q_right and s_right has factor q_left. At the default each factor is one. They are separate sensitivities for separate input slots.

Why the combined square derivative is 2q

If the original stored qq changes by hh, both reads change together:

(q+h)(q+h)=q2+qh+hq+h2.(q+h)(q+h)=q^2+qh+hq+h^2.

Subtracting q2q^2 and dividing by hh gives q+q+hq+q+h, which approaches 2q2q. The two first-order terms are exactly the two operand-edge contributions. The h2h^2 term vanishes after division and taking the limit. Putting 2q2q on each edge would count both terms twice.

This is a useful distinction between a stored variable and a temporarily independent operand slot. Local factors describe each slot separately. A total derivative with respect to the shared stored variable must combine all affected slots. The next chapter performs that combination explicitly for loss.

Local factors do not yet answer the loss question

At the default, local_q_w is two. That says how quickly qq changes with ww. It does not say that loss changes at rate two. Weight also influences the rest of the graph, including three routes from qq toward prediction. To obtain a loss gradient we must multiply factors along routes and add contributions where routes share a source.

A gradient collects total loss derivatives for specified inputs or parameters. This chapter deliberately shows local factors without calling them that gradient. Inspect the local_s_left output: it depends on qq, so changing bias or target leaves it unchanged even though those edits can change loss. Local and total sensitivity answer different questions.

A counterexample makes the distinction sharp. Set x=2,w=0,b=0,y=1x=2,w=0,b=0,y=1. Then q=0,r=0,s=0,p=0,e=−1,L=1/2q=0,r=0,s=0,p=0,e=-1,L=1/2. Both square factors are zero. Nevertheless the linear edge r_q still has factor one. It would be wrong to declare the entire graph insensitive to qq after looking only at the square.

Read the actual numerical source

The chapter file below calls forward_dag, then appends one local derivative step per declared operand edge. It uses named consumer operands when showing each factor. There is no automatic differentiation library and no optimizer.

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV-06: forward nodes and actual operand-edge local derivatives."""
from dag_reference import DEFAULT_DAG, EDGES, forward_dag, guarded, step, result, run

DEFAULT_IV06 = dict(DEFAULT_DAG)


@guarded
def derive_iv06(state):
    """Evaluate one bounded DAG; inspect each edge holding other slots fixed."""
    outputs, steps = forward_dag(state)
    for identifier, source, target, formula in EDGES:
        # The consumer's named operands reveal the factor, e.g. x in dq/dw=x.
        operands = next(operation["inputs"] for operation in steps if operation["id"] == "forward_" + target)
        steps.append(step("local_" + identifier, "Local derivative: " + identifier, formula,
                          f"Hold the other operand slot fixed. This edge factor is not the total loss derivative with respect to {source}.",
                          operands, {"localFactor": outputs["local_" + identifier]}))
    return result(outputs, steps)


if __name__ == "__main__":
    run(derive_iv06, DEFAULT_IV06)

The complete sibling helper contains the NumPy binary64 arithmetic, edge declarations, bounded validation, tensor records and JSON entry point. Keep both files together for later use.

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""Book IV-06/07: explicit scalar DAG and small JSON/tensor helpers.

No autodiff engine: every operand edge and its local derivative is declared.
Keep this sibling beside iv06.py and iv07.py for their later execution.
"""
import argparse
from functools import wraps
import json
import sys
import numpy as np

DEFAULT_DAG = {"x": 2, "w": 0.5, "b": 1, "y": 1}
EDGES = [
    ("q_w", "w", "q", "dq/dw=x"),
    ("q_x", "x", "q", "dq/dx=w"),
    ("r_q", "q", "r", "dr/dq=1"),
    ("r_b", "b", "r", "dr/db=1"),
    ("s_left", "q", "s", "ds/dq_left=q_right"),
    ("s_right", "q", "s", "ds/dq_right=q_left"),
    ("prediction_r", "r", "prediction", "dp/dr=1"),
    ("prediction_s", "s", "prediction", "dp/ds=1"),
    ("error_prediction", "prediction", "error", "de/dp=1"),
    ("error_y", "y", "error", "de/dy=-1"),
    ("loss_error", "error", "loss", "dL/de=error"),
]
REVERSE_EDGES = ["loss_error", "error_prediction", "error_y", "prediction_r", "prediction_s",
                 "r_b", "r_q", "s_left", "s_right", "q_w", "q_x"]


class ParseFault(ValueError):
    """Owned JSON syntax/profile failure, separate from numerical validation."""


_JSON_INT = int


def _members(pairs):
    value = {}
    for key, member in pairs:
        if key in value:
            raise ParseFault("Duplicate JSON object members are not allowed.")
        value[key] = member
    return value


def _constant(token):
    raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")


def _integer(token):
    if token == "-0":
        return -0.0
    try:
        return _JSON_INT(token)
    except ValueError as error:
        if type(error) is not ValueError:
            raise
        raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from error


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def finite(value, label):
    if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        number = np.float64(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not np.isfinite(number):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return number


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return {"status": "unavailable", "code": error.code, "reason": str(error)}
        except (OverflowError, FloatingPointError) as error:
            return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
        except (TypeError, AttributeError) as error:
            return {"status": "unavailable", "code": "UNAVAILABLE", "reason": str(error)}
    return call


def adjoint_key(node):
    return "adj" + node[0].upper() + node[1:]


def step(identifier, label, equation, explanation, inputs, outputs):
    return {"id": identifier, "label": label, "equation": equation, "explanation": explanation,
            "inputs": {key: float(finite(value, key)) for key, value in inputs.items()},
            "outputs": {key: float(finite(value, key)) for key, value in outputs.items()}}


def forward_dag(state):
    # JSON objects supply own keys; require a concrete dict and never fill missing fields.
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "State must be a JSON object.")
    values = {}
    for key in DEFAULT_DAG:
        if key not in state:
            raise NumericalFault("NONFINITE", f"{key} must be an own finite field.")
        value = finite(state[key], key)
        if value < -100 or value > 100:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between -100 and 100.")
        values[key] = value
    x, w, b, y = (values[key] for key in DEFAULT_DAG)
    # Store the product once; both square slots read precisely this q.
    q = finite(w * x, "q")
    r = finite(q + b, "r")
    s = finite(q * q, "s")
    prediction = finite(r + s, "prediction")
    error = finite(prediction - y, "error")
    error_square = finite(error * error, "errorSquare")
    loss = finite(error_square / np.float64(2), "loss")
    outputs = {"loss": loss, "prediction": prediction, "q": q, "r": r, "s": s,
               "error": error, "errorSquare": error_square, "x": x, "w": w, "b": b, "y": y,
               "local_q_w": x, "local_q_x": w, "local_r_q": 1, "local_r_b": 1,
               "local_s_left": q, "local_s_right": q, "local_prediction_r": 1,
               "local_prediction_s": 1, "local_error_prediction": 1, "local_error_y": -1,
               "local_loss_error": error}
    steps = [
        step("forward_q", "Forward: shared product q", "q=w*x", "Store q once. Its value is read by three outgoing operand edges.", {"w": w, "x": x}, {"q": q}),
        step("forward_r", "Forward: linear branch r", "r=q+b", "The linear branch keeps a direct path from q to prediction.", {"q": q, "b": b}, {"r": r}),
        step("forward_s", "Forward: tied product s", "s=q_left*q_right; q_left=q_right=q", "s_left and s_right are distinct operand slots reading the same q node.", {"q_left": q, "q_right": q}, {"s": s}),
        step("forward_prediction", "Forward: combine branches", "prediction=r+s", "Both branches contribute to one scalar prediction.", {"r": r, "s": s}, {"prediction": prediction}),
        step("forward_error", "Forward: signed error", "error=prediction-y", "The target enters here, after prediction.", {"prediction": prediction, "y": y}, {"error": error}),
        step("forward_loss", "Forward: half-squared loss", "loss=error*error/2", "This unary half-square has one error edge with local derivative error.", {"error": error}, {"errorSquare": error_square, "loss": loss}),
    ]
    return outputs, steps


def tensor(identifier, shape, axes, values, provenance):
    # All shapes here are fixed by the lesson, not user-provided tensor shapes.
    return {"id": identifier, "shape": shape, "axes": axes, "dtype": "float64",
            "values": [float(finite(value, identifier)) for value in values],
            "provenance": provenance, "precision": 8}


def result(outputs, steps, extra_tensors=None):
    tensors = [tensor(key, [1, 1], ["scalar_row", "scalar_column"], [value],
                      f"Explicit scalar DAG: {key}; local_* denotes one operand edge.")
               for key, value in outputs.items()]
    for operation in steps:
        for key, value in operation["outputs"].items():
            tensors.append(tensor(f'{operation["id"]}.{key}', [1, 1], ["scalar_row", "scalar_column"],
                                  [value], f'{operation["id"]}: {operation["equation"]}'))
    return {"status": "defined", "outputs": {key: float(finite(value, key)) for key, value in outputs.items()},
            "steps": steps, "tensors": tensors + (extra_tensors or [])}


def run(derive, defaults):
    """Later owner CLI: default, complete JSON argument, or '-' for JSON stdin."""
    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            output = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
        else:
            output = derive(state)
    else:
        state = dict(defaults)
        output = derive(state)
    # Direct DAG calls retain extra-field compatibility; the CLI admits only declared fields.
    if output["status"] == "defined" and any(key not in defaults for key in state):
        output = {"status": "unavailable", "code": "INVALID_INPUT", "reason": "Only the declared scalar fields are supported."}
    print(json.dumps(output, allow_nan=False, separators=(",", ":")))

The authored CLI accepts no argument for defaults, one complete JSON object, or - to read that object from standard input. For example, the full-state form is:

python3 code/python/p02/iv06.py '{"x":2,"w":0.5,"b":1,"y":1}'

A partial object is rejected rather than filled from defaults. Required fields must be finite numbers between negative one hundred and one hundred. The CLI accepts only the declared fields; direct TypeScript and Python derivation calls ignore extra fields. Browser source also requires own fields, so inherited properties cannot stand in for supplied inputs. Intermediate arithmetic is checked for finiteness.

Carry the dependency story forward

The graph is a small, self-authored polynomial example. It is differentiable everywhere; it contains no ReLU kink and requires no chosen subgradient. Binary64 storage can round arbitrary decimal edits, whereas the displayed hand example uses exactly representable binary fractions. Display formatting never feeds later operations.

Use the five graded questions to check the shared-node vocabulary, calculate a current forward value and local factor, predict a target edit, and investigate the zero-square counterexample. Each explanation points back to a particular dependency.

  • A stored node can supply several distinct operand edges.
  • Forward order evaluates consumers only after their operands exist.
  • A local partial derivative holds the other operand slots fixed.
  • The two square edges each carry qq; their combined effect is 2q2q.
  • A zero factor on one route says nothing by itself about another route.

Revisit losses and targets and computational graphs and automatic differentiation if needed. Next we traverse these same edges backward, adding all contributions to the shared node before continuing toward its inputs.