16  Additional Material: Representations and Automatic Differentiation

Constructive XOR, gradient flow, autodiff, and Kolmogorov–Arnold representations

Author

Noel Danz

16.1 Beyond the first multilayer perceptron

The main chapter introduced nonlinear hidden layers, derived gradients for a two-layer MLP, and used backpropagation to train a model on XOR. Here we investigate why these constructions work and what changes when we make them larger. We will explicitly construct an XOR network, examine gradient flow through depth, implement a tiny automatic differentiation engine, compare differentiation modes, and look more closely at Kolmogorov–Arnold representations.

This page is optional. Each section contains an exercise followed by a collapsible worked solution. We use column-vector observations and the same distinction as the main chapter: backpropagation computes gradients; an optimizer uses them to update parameters. The examples use elementary calculus and NumPy; no deep-learning framework is required.

16.2 Constructing XOR rather than learning it

The main chapter showed that stacking affine transformations cannot produce a nonlinear decision boundary. It also suggested the feature \(\phi(x)=(x_1-x_2)^2\), which separates XOR. We can go further: explicitly choose the weights of a two-layer ReLU network that solves the four XOR observations.

For \(x_1,x_2\in\{0,1\}\), define

\[ \begin{aligned} h_1 &= \operatorname{ReLU}(x_1-x_2),\\ h_2 &= \operatorname{ReLU}(x_2-x_1),\\ s(x)&=h_1+h_2. \end{aligned} \]

The identity \(\operatorname{ReLU}(t)+\operatorname{ReLU}(-t)=|t|\) gives \(s(x)=|x_1-x_2|\). Therefore \(s(x)\) is exactly the XOR label on the four binary inputs. In matrix form,

\[ W_1=\begin{pmatrix}1&-1\\-1&1\end{pmatrix},\quad b_1=\begin{pmatrix}0\\0\end{pmatrix},\quad W_2=\begin{pmatrix}1&1\end{pmatrix},\quad b_2=0. \]

This is a two-layer MLP with two hidden ReLU units and a scalar score output. If we want a binary classifier, we can threshold the score at \(1/2\). If we want a probability-like output, we can apply \(\sigma(k(s-1/2))\) for \(k>0\). The latter approaches 0 or 1 as \(k\) grows but does not attain those values at finite \(k\).

16.2.1 Exercise 1

  1. Calculate both hidden activations and the output for all four XOR inputs.
  2. Describe the hidden representation of the two positive-class observations. Why can the final affine layer separate them from the negative class?
  3. What does the network output at \((0.2,0.8)\)? Does solving four training observations uniquely determine the desired function between them?

1.1 The hidden vectors are \((0,0)^\top\), \((0,1)^\top\), \((1,0)^\top\), and \((0,0)^\top\), respectively. Summing their coordinates gives \(0,1,1,0\).

1.2 The two positive observations activate different hidden units; both negative observations map to the origin. The output score \(h_1+h_2\) separates the positive representations using a threshold of \(1/2\).

1.3 The score is \(|0.2-0.8|=0.6\). Many nonlinear functions agree on the four corners of the unit square but disagree elsewhere. Training-set agreement alone does not specify generalization between observations.

Read further: The main chapter’s XOR experiment demonstrates a learned solution; compare its decision surface with this hand-constructed one.

16.3 Why gradients vanish or grow with depth

The chain rule in the main chapter explains how gradients move backwards through layers. Repeating it also reveals why deep networks can be difficult to optimize. Consider a scalar chain

\[a_0=x,\qquad a_l=\phi(w_la_{l-1}),\quad l=1,\ldots,d.\]

For a scalar loss \(L(a_d)\), the chain rule gives

\[ \frac{\partial L}{\partial x} =\frac{\partial L}{\partial a_d} \prod_{l=1}^{d}\left[\phi'(w_la_{l-1})w_l\right]. \]

The backward signal is a product of local derivatives. If each factor has magnitude below one, it may shrink exponentially with depth; if factors are consistently larger than one, it may grow rapidly. Real networks use matrices, so the analogous expression is a product of transposed weight matrices and activation Jacobians. Individual gradient components can also cancel, and the size of a matrix product depends on its directions, not only on the magnitudes of its entries.

For sigmoid, \(\sigma'(z)=\sigma(z)(1-\sigma(z))\leq1/4\). Saturated sigmoid units have derivatives close to zero. For ReLU, the derivative is 1 on the positive branch and 0 on the negative branch (with a chosen convention at zero). Thus ReLU avoids the sigmoid’s small positive-branch slope but can entirely block a gradient through an inactive unit. Neither activation automatically eliminates all gradient-flow problems.

16.3.1 Exercise 2

  1. Let \(\phi\) be the identity and all \(w_l=0.8\). Calculate \(\partial a_d/\partial x\) for \(d=1,5,20\).
  2. Repeat with \(w_l=1.2\). What changes?
  3. Suppose every layer instead uses ReLU, all weights are positive, and the forward preactivations are positive. What is the derivative? What happens if one intermediate preactivation is strictly negative?

2.1 The derivative is \(0.8^d\), giving \(0.8\), \(0.32768\), and approximately \(0.01153\). The input sensitivity decays exponentially.

2.2 The derivative is \(1.2^d\), giving \(1.2\), \(2.48832\), and approximately \(38.34\). It grows exponentially.

2.3 On the positive branch each ReLU contributes derivative 1, so the derivative is the product of the weights. A strictly negative intermediate preactivation sets that unit’s local derivative to zero; in this scalar chain the complete input derivative becomes zero. In a multi-unit network, other active paths can still carry gradients.

Read further: Goodfellow, Bengio, and Courville, Deep Learning, chapters 6 and 8, discuss gradient propagation, initialization, and optimization (online book).

16.4 Building a tiny reverse-mode autodiff engine

In the main chapter, PyTorch records tensor operations and calls .backward() to differentiate a scalar loss. The same principle can be implemented with scalar values and a computation graph. Every node needs a numerical value, a gradient accumulator, its parent nodes, and a local backward rule. We must traverse the graph in reverse topological order so that all contributions to a node’s gradient have arrived before propagating further.

Consider \(f(x,y)=xy+x^2\). The value \(x\) is used along two paths, so its gradient must accumulate contributions:

\[ \frac{\partial f}{\partial x}=y+2x,\qquad \frac{\partial f}{\partial y}=x \]

Here is a minimal implementation for addition and multiplication. It is intended to expose the mechanism, not to replace a production autodiff library.

class Value:
    def __init__(self, data, parents=(), backward=None):
        self.data = float(data)
        self.grad = 0.0
        self.parents = tuple(parents)
        self._backward = backward or (lambda: None)

    def __add__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data + other.data, (self, other))
        def backward():
            self.grad += out.grad
            other.grad += out.grad
        out._backward = backward
        return out

    __radd__ = __add__

    def __mul__(self, other):
        other = other if isinstance(other, Value) else Value(other)
        out = Value(self.data * other.data, (self, other))
        def backward():
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad
        out._backward = backward
        return out

    __rmul__ = __mul__

    def backward(self):
        order, visited = [], set()
        def visit(node):
            if id(node) in visited:
                return
            visited.add(id(node))
            for parent in node.parents:
                visit(parent)
            order.append(node)
        visit(self)
        for node in order:
            node.grad = 0.0
        self.grad = 1.0
        for node in reversed(order):
            node._backward()

x, y = Value(2), Value(3)
f = x*y + x*x
f.backward()
assert (f.data, x.grad, y.grad) == (10., 7., 2.)

The graph is built during the forward evaluation. Each local backward rule knows only its immediate operation, not the complete expression. Notice the += operations: without accumulation, the two paths leading to x would overwrite each other. The reset in this small implementation makes each backward() call independent; PyTorch instead accumulates leaf gradients unless they are cleared explicitly.

16.4.1 Exercise 3

  1. Draw the computation graph for \(f(x,y)=xy+x^2\) and annotate the intermediate values for \(x=2,y=3\).
  2. Explain why replacing += with = in the local backward rules produces incorrect results for reused variables.
  3. Extend Value with a tanh() operation. Its local derivative is \(1-\tanh^2(z)\). Test the gradient of \(g(x)=\tanh(x^2)\) at \(x=1\) against the analytic derivative.

3.1 Two multiplication nodes compute \(xy=6\) and \(x^2=4\); an addition node computes 10. The two multiplication nodes both point back to the same x node.

3.2 The first product contributes \(y=3\) to \(\partial f/\partial x\) and the second contributes \(2x=4\). The correct result is their sum, 7; assignment would lose a contribution. The repeated parent in x*x must also contribute twice.

3.3 One possible implementation is:

import math

def tanh(self):
    out = Value(math.tanh(self.data), (self,))
    def backward():
        self.grad += (1 - out.data**2) * out.grad
    out._backward = backward
    return out

Value.tanh = tanh
z = Value(1.)
g = (z*z).tanh()
g.backward()
expected = 2 * (1 - math.tanh(1)**2)
assert np.isclose(z.grad, expected)

The analytic result is \(g'(x)=2x[1-\tanh^2(x^2)]\), giving approximately \(0.83995\) at \(x=1\).

Read further: The PyTorch autograd introduction describes how a production framework records and differentiates computations.

16.5 Forward mode, reverse mode, and numerical gradient checking

Automatic differentiation is not the same as finite differences. For a function \(f:\mathbb{R}^n\to\mathbb{R}^m\), forward mode propagates input perturbations through the computation; one pass produces a Jacobian–vector product \(J_fv\). Reverse mode propagates output sensitivities backwards; one pass produces a vector–Jacobian product \(J_f^\top u\). Both apply exact chain-rule identities, up to floating-point arithmetic.

For a scalar loss with many parameters (\(m=1\), large \(n\)), one reverse pass gives its complete parameter gradient, which explains why reverse mode is so useful for MLP training. When the input dimension is small and there are many outputs, forward mode may be more attractive. This comparison concerns the number of directional passes; actual runtime and memory also depend on the program and implementation.

Gradient checking uses finite differences as an independent debugging reference. For a scalar function and parameter \(\theta_i\), the central-difference estimate is

\[ \frac{\partial L}{\partial\theta_i}\approx \frac{L(\theta+\varepsilon e_i)-L(\theta-\varepsilon e_i)}{2\varepsilon}. \]

The truncation error is typically \(O(\varepsilon^2)\) for a sufficiently smooth function, but very small \(\varepsilon\) can increase floating-point cancellation error. Gradient checking is therefore useful for verifying a few coordinates of a manual backward pass, not as a replacement for backpropagation during training. At nondifferentiable points such as the ReLU kink, central differences need not agree with a framework’s selected derivative.

16.5.1 Exercise 4

  1. Let \(f(x_1,x_2)=(x_1^2+x_2,\,x_1x_2)\). Calculate its Jacobian at \((2,3)\).
  2. Calculate \(J_f(2,3)(1,-1)^\top\) and \(J_f(2,3)^\top(1,2)^\top\). Explain which corresponds to forward mode and which to reverse mode.
  3. For \(L(w)=w^3\), calculate the central-difference estimate at \(w=2\) with \(\varepsilon=0.1\). Compare it with the exact derivative.

4.1 \(J_f=\begin{pmatrix}2x_1&1\\x_2&x_1\end{pmatrix}\), so at \((2,3)\) it is \(\begin{pmatrix}4&1\\3&2\end{pmatrix}\).

4.2 The Jacobian–vector product is \((3,1)^\top\), a forward-mode directional derivative. The transposed Jacobian–vector product is \((10,5)^\top\), a reverse-mode pullback of output sensitivities.

4.3 The estimate is \((2.1^3-1.9^3)/0.2=12.01\). The exact derivative is \(3w^2=12\). The discrepancy is the finite-difference approximation error.

Read further: Baydin et al., Automatic Differentiation in Machine Learning: a Survey (arXiv), gives a broader treatment of differentiation modes and their computational trade-offs.

16.6 Kolmogorov–Arnold representations and networks

The main chapter’s Universal Approximation Theorem concerns approximation by a network of affine combinations and fixed nonlinear activation functions. Its tangent on the Kolmogorov–Arnold Representation Theorem (KART)(Kolmogorov 1957) points to a different decomposition: a continuous multivariate function on a compact cube can be expressed using finite sums and compositions of continuous univariate functions. In the notation of the chapter, a representative form is

\[ f(x_1,\ldots,x_n) =\sum_{q=1}^{2n+1}\Phi_q\!\left(\sum_{p=1}^n\phi_{q,p}(x_p)\right). \]

The striking point is not that we have eliminated nonlinearities, but that the constituent functions each take one scalar argument. This motivates Kolmogorov–Arnold Networks (KANs), which place trainable univariate functions on edges rather than using only scalar weights followed by fixed activations. The theorem establishes a representation, not an optimization algorithm, an efficient parameter count, or a guarantee of generalization. In particular, the continuous functions guaranteed by the theorem need not be convenient to approximate with a finite practical parameterization.

A simple example already shows the idea. On \([0,1]^2\), the function \(f(x_1,x_2)=x_1^2+x_2^2\) is a sum of two univariate functions. The interaction \(g(x_1,x_2)=x_1x_2\) can also be expressed using only univariate squares and sums:

\[x_1x_2=\frac{(x_1+x_2)^2-x_1^2-x_2^2}{2}.\]

This identity is not a proof of the general theorem; it is a small illustration of how composition can create interactions between variables.

16.6.1 Exercise 5

  1. Identify the univariate functions needed to represent \(f(x_1,x_2)=x_1^2+x_2^2\) as a sum.
  2. Verify the identity for \(x_1x_2\) by expanding the square. Which operation combines information from both inputs?
  3. Explain why the existence of a Kolmogorov–Arnold representation does not imply that a KAN will train faster than an MLP on a given dataset.

5.1 Choose \(\phi_1(t)=t^2\) and \(\phi_2(t)=t^2\), then \(f=\phi_1(x_1)+\phi_2(x_2)\).

5.2 Since \((x_1+x_2)^2=x_1^2+2x_1x_2+x_2^2\), subtracting the individual squares and dividing by two gives \(x_1x_2\). The inner addition \(x_1+x_2\) combines the inputs before the outer squaring operation.

5.3 A representation theorem says a suitable representation exists. Training speed depends on the chosen finite function parameterization, initialization, optimization, data, and implementation. None of those is determined by existence alone.

Read further: Kolmogorov’s original superposition theorem and its refinements provide the mathematical background; Liu et al., KAN: Kolmogorov–Arnold Networks (arXiv), introduces the contemporary architecture. Read claims about practical superiority as empirical questions, not consequences of the representation theorem.

16.7 Connecting the results

The XOR construction shows how hidden nonlinear features can make a previously inseparable problem separable. The gradient-product analysis explains why the same composition can complicate optimization. A tiny autodiff engine demonstrates how local chain-rule operations are reused efficiently, while the comparison of differentiation modes clarifies why reverse-mode backpropagation fits scalar-loss training. Finally, Kolmogorov–Arnold representations show that the MLP is not the only way to organize nonlinear function approximation.

For further practice, pick one of these examples and change an assumption: replace ReLU with tanh in the XOR construction, introduce a shared subexpression in the autodiff graph, or test finite differences at a nondifferentiable point. Before running code, predict which equation or conclusion must change.