$$ \newcommand{\dint}{\mathrm{d}} \newcommand{\vphi}{\boldsymbol{\phi}} \newcommand{\vpi}{\boldsymbol{\pi}} \newcommand{\vpsi}{\boldsymbol{\psi}} \newcommand{\vomg}{\boldsymbol{\omega}} \newcommand{\vsigma}{\boldsymbol{\sigma}} \newcommand{\vzeta}{\boldsymbol{\zeta}} \renewcommand{\vx}{\mathbf{x}} \renewcommand{\vy}{\mathbf{y}} \renewcommand{\vz}{\mathbf{z}} \renewcommand{\vh}{\mathbf{h}} \renewcommand{\b}{\mathbf} \renewcommand{\vec}{\mathrm{vec}} \newcommand{\vecemph}{\mathrm{vec}} \newcommand{\mvn}{\mathcal{MN}} \newcommand{\G}{\mathcal{G}} \newcommand{\M}{\mathcal{M}} \newcommand{\N}{\mathcal{N}} \newcommand{\S}{\mathcal{S}} \newcommand{\diag}[1]{\mathrm{diag}(#1)} \newcommand{\diagemph}[1]{\mathrm{diag}(#1)} \newcommand{\tr}[1]{\text{tr}(#1)} \renewcommand{\C}{\mathbb{C}} \renewcommand{\R}{\mathbb{R}} \renewcommand{\E}{\mathbb{E}} \newcommand{\D}{\mathcal{D}} \newcommand{\inner}[1]{\langle #1 \rangle} \newcommand{\innerbig}[1]{\left \langle #1 \right \rangle} \newcommand{\abs}[1]{\lvert #1 \rvert} \newcommand{\norm}[1]{\lVert #1 \rVert} \newcommand{\two}{\mathrm{II}} \newcommand{\GL}{\mathrm{GL}} \newcommand{\Id}{\mathrm{Id}} \newcommand{\grad}[1]{\mathrm{grad} \, #1} \newcommand{\gradat}[2]{\mathrm{grad} \, #1 \, \vert_{#2}} \newcommand{\Hess}[1]{\mathrm{Hess} \, #1} \newcommand{\T}{\text{T}} \newcommand{\dim}[1]{\mathrm{dim} \, #1} \newcommand{\partder}[2]{\frac{\partial #1}{\partial #2}} \newcommand{\rank}[1]{\mathrm{rank} \, #1} $$

Filippov neural networks with Keras

Networks with kinks, ties and hard routing: Filippov sets, graphs of switching operators and one gradient per selection, with Keras exercises.

Learning goals: recognize switching operators in modern networks; compute a Filippov set and extension; read the active graph of a network; find the gradients of the admissible selections.

Context and objectives

Course

Networks that are not differentiable, or not even continuous

Backpropagation, Gradient×Input and every gradient-based explanation assume that the network is differentiable. Modern networks are not: a ReLU has a kink, max-pooling has ties, and the hard-routed Mixture-of-Experts blocks of large language models (a router picks the experts, as in Switch Transformers, Mixtral or DeepSeek) are outright discontinuous: when the router changes its mind, the output jumps from one expert’s value to another’s. At such a point the derivative does not exist, and Clarke’s generalized gradient, designed for locally Lipschitz functions, is not defined for a function that jumps.

The article Relevance Propagation as Entropic Optimal Transport on Filippov Neural Networks (O. Gibaru and E. Nyiri, arXiv:2611.05594) builds its foundation on a classical tool of discontinuous dynamics, Filippov regularization: at a switching point, instead of one value and one derivative, keep the set of values and derivatives of the branches that meet there. A network becomes a directed acyclic graph of Filippov operators, and every notion of the article (admissible branch selections, active graph, path gradients) is defined on this graph.

This course is the first half of that foundation, with small Keras and NumPy programs. The second half, relevance propagation as an entropic projection, is the course Neural networks explainability with Keras.

A router sends the input to one of two experts; the output of the block jumps when the router changes its choice
A hard-routed Mixture-of-Experts block: the router scores $g_1,g_2$ select one expert, and the output jumps where the choice changes.
Exercise

Objectives to carry out

  1. Compute the Filippov set of a hard-routed Mixture-of-Experts block and of a ReLU kink, and see what Keras hides at a switching point (Part 1).
  2. Build the running example of the article as a Keras model, read its contributions and active graph, and find one gradient per branch selection (Part 2).
  3. Deliver a short report with numbers and a discussion of limits (Part 3).

Each part starts with a short course (definitions, statements, a proof) and proposes small exercises with a light Python starting code (TO DO lines). Each correction, folded just after, is commented line by line. Try the exercise before opening it.

Course

How to work: environment

Install tensorflow==2.21.0 numpy matplotlib in an isolated environment (checked with Python 3.12 and TensorFlow CPU 2.21). No download is needed: the running example is a network with 13 weights. Run the blocks in order in one notebook or session: the exercises reuse earlier functions.

PythonCode provided · imports and the weights of the running example
import numpy as npimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersSEED = 0keras.utils.set_random_seed(SEED)np.set_printoptions(precision=4, suppress=True)# The running example of the article: inputs i1, i2, bias b1 -> hidden ReLU h1, h2 -> outputs o1, o2 (linear),# with a bias b2 on the outputs and a skip edge i1 -> o1. The bias nodes have the value +1.WEIGHTS = {    ("i1", "h1"): 1.0, ("i2", "h1"): 2.0, ("b1", "h1"): 0.0,    ("i1", "h2"): -1.0, ("i2", "h2"): 1.0, ("b1", "h2"): 1.0,    ("h1", "o1"): 1.0, ("h2", "o1"): 2.0, ("b2", "o1"): 0.0, ("i1", "o1"): 1.0,    ("h1", "o2"): -1.0, ("h2", "o2"): 2.0, ("b2", "o2"): -1.0,}INPUTS, HIDDEN, OUTPUTS = ["i1", "i2", "b1", "b2"], ["h1", "h2"], ["o1", "o2"]ORDER = ["i1", "i2", "b1", "b2", "h1", "h2", "o1", "o2"]     # a topological order of the graph

Part 1 · Switching operators and the Filippov set

Course

Switching operators

DefinitionPiecewise-$C^1$ switching operator

An operator $\Phi:\Omega\to\mathbb R^m$ is a switching operator if $\Omega\subset\mathbb R^n$ is covered, up to a set $\Sigma$ of measure zero (the switching region), by disjoint open regions $\Omega^{(k)}$ on each of which $\Phi$ coincides with a $C^1$ map $\Phi^{(k)}$, the branch $k$. The active index set of $x$ is $J(x)=\{k:\ x\in\overline{\Omega^{(k)}}\}$: the branches that meet at $x$.

Three operators of modern networks have this form.

  • ReLU, $\max(z,0)$: two branches, $0$ and $z$, which agree in value at the kink $z=0$ but have different derivatives ($0$ and $1$).
  • Max-pooling, $\max_iz_i$: one branch $z_k$ per coordinate; at a tie the values agree, the gradients $e_k$ differ.
  • Hard-routed Mixture-of-Experts: scores $g_1,\dots,g_M$ select the expert $r(z)\in\arg\max_jg_j(z)$ and $\Phi(z)=E_{r(z)}(z)$. At a routing tie the experts need not agree: the output jumps.

Example of the article: two experts $E_1(z)=z+1$ and $E_2(z)=2z-1$ routed by $g_1(z)=z$, $g_2(z)=-z$. Then $\Phi=E_1$ for $z>0$, $\Phi=E_2$ for $z<0$, and $\Sigma=\{0\}$ with $\Phi^{(1)}(0)=1$, $\Phi^{(2)}(0)=-1$.

TheoremFilippov regularization

Let $\mathcal F[\Phi](x)$ be the set of all limits of convex combinations of values of $\Phi$ near $x$, ignoring any set of measure zero. Then, for every $x$,

\[\mathcal F[\Phi](x)=\operatorname{co}\{\Phi^{(k)}(x):\ k\in J(x)\},\]

and likewise the Filippov extension of the pair (value, derivative) is $\operatorname{co}\{(\Phi^{(k)}(x),D\Phi^{(k)}(x)):k\in J(x)\}$. At a regular point ($J(x)$ a single index) it is the single classical pair $(\Phi(x),D\Phi(x))$.

Proof

Sketch. Fix $x$ and $k\in J(x)$. Since $\Phi^{(k)}$ is $C^1$ in a full neighborhood of $x$ and $x$ lies in the closure of $\Omega^{(k)}$, there are points $y\to x$ inside $\Omega^{(k)}$, and $\Phi(y)=\Phi^{(k)}(y)\to\Phi^{(k)}(x)$ (likewise $D\Phi(y)\to D\Phi^{(k)}(x)$). So $\Phi^{(k)}(x)$ belongs to $\mathcal F[\Phi](x)$, which is convex: this gives “$\supset$”. Conversely, a branch $k\notin J(x)$ has $x\notin\overline{\Omega^{(k)}}$, so for $\delta$ small the ball $B(x,\delta)$ meets only the regions $\Omega^{(k)}$, $k\in J(x)$, up to a null set, and the values of $\Phi$ there lie in the closed convex hull of the active branch values (continuity of the branches). Taking the intersection over $\delta>0$ and over null sets gives “$\subset$”. $\square$

On the example, $\mathcal F[\Phi](0)=\operatorname{co}\{1,-1\}=[-1,1]$ and the extension is the segment $\operatorname{co}\{(1,1),(-1,2)\}$ in the (value, derivative) plane. For a ReLU kink the value part collapses to the point $\{0\}$ and only the derivative part, $[0,1]$, remains set-valued.

A hard-routed mixture of two experts: the output jumps from -1 to 1 at z = 0; the Filippov set is the whole segment
The hard-routing example: $\Phi$ jumps across $z=0$. The Filippov set at the routing boundary is the whole segment $[-1,1]$.
Exercise

Exercise 1.1 · a hard-routed block in Keras, and what Keras sees at the tie

  1. Write a Keras layer that routes a scalar $z$ to one of the two experts by the arg-max of the scores $(z,-z)$.
  2. Evaluate it just left of $0$, at $0$ and just right of $0$, and plot it on $[-1,1]$.
  3. Differentiate the layer at $z=0$ with tf.GradientTape and note which branch it follows.
PythonStarting code · a hard-routing layer
class HardMoE(layers.Layer):    """Two experts E1(z) = z + 1 and E2(z) = 2z - 1, routed by the scores g1(z) = z and g2(z) = -z."""    def call(self, z):        scores = tf.concat([z, -z], axis=-1)                       # routing scores g_1, g_2        route = ...  # TO DO: index of the expert with the largest score        experts = tf.concat([z + 1.0, 2.0 * z - 1.0], axis=-1)     # the values of the two experts        return ...  # TO DO: keep the value of the selected expertmoe = HardMoE()z = np.array([[-1e-6], [0.0], [1e-6]], dtype="float32")print("values near the routing boundary:", moe(z).numpy().ravel(), "(a jump from -1 to 1)")zs = np.linspace(-1, 1, 401, dtype="float32")[:, None]plt.plot(zs, moe(zs).numpy(), ".", ms=2); plt.xlabel("z"); plt.ylabel("MoE(z)"); plt.show()zt = tf.Variable([[0.0]])with tf.GradientTape() as tape:    out = moe(zt)print("Keras at z = 0: value", out.numpy().ravel(), ", derivative", tape.gradient(out, zt).numpy().ravel(), "(one branch only)")
Show the correction
PythonComplete solution · routing and the derivative at the tie
# A custom Keras layer that routes each input to ONE expert, as a hard-routed Mixture-of-Experts block does.class HardMoE(layers.Layer):    """Two experts E1(z) = z + 1 and E2(z) = 2z - 1, routed by the scores g1(z) = z and g2(z) = -z."""    def call(self, z):        scores = tf.concat([z, -z], axis=-1)                       # routing scores g_1, g_2        # argmax returns the index of the largest score; at a tie (z = 0) it returns the first index: an arbitrary choice.        route = tf.argmax(scores, axis=-1)  # index of the expert with the largest score        experts = tf.concat([z + 1.0, 2.0 * z - 1.0], axis=-1)     # the values of the two experts        # tf.gather with batch_dims=1 picks, for each row, the value of the expert chosen by the router.        return tf.gather(experts, route, batch_dims=1)[:, None]  # keep the value of the selected expertmoe = HardMoE()z = np.array([[-1e-6], [0.0], [1e-6]], dtype="float32")print("values near the routing boundary:", moe(z).numpy().ravel(), "(a jump from -1 to 1)")zs = np.linspace(-1, 1, 401, dtype="float32")[:, None]plt.plot(zs, moe(zs).numpy(), ".", ms=2); plt.xlabel("z"); plt.ylabel("MoE(z)"); plt.show()# The gradient at the tie follows the chosen branch only: Keras cannot tell us that two branches are possible.zt = tf.Variable([[0.0]])with tf.GradientTape() as tape:    out = moe(zt)print("Keras at z = 0: value", out.numpy().ravel(), ", derivative", tape.gradient(out, zt).numpy().ravel(), "(one branch only)")

The layer returns $-1$, then $1$, then $1$ near the boundary: a jump from $-1$ to $1$. At $z=0$ the arg-max tie returns the first index, so Keras reports value $1$ and derivative $1$: one branch only. The value $-1$ of the other expert, and its derivative $2$, are invisible to automatic differentiation.

Exercise

Exercise 1.2 · the Filippov set of the block

  1. Write the active index set of a point: the experts that tie for the maximum score (with a small tolerance).
  2. Compute the Filippov set (an interval) and the pairs (value, derivative) of the active branches.
  3. Print them at $z=-0.5$, $0$ and $0.5$.
PythonStarting code · Filippov set
# The branches Phi^(k) of the operator: value and derivative of each expert, and the routing scoresexperts = [lambda z: z + 1.0, lambda z: 2.0 * z - 1.0]slopes = [1.0, 2.0]scores = [lambda z: z, lambda z: -z]def active_set(z, tol=1e-9):    """Indices k whose routing region has z in its closure: the largest scores, up to a tolerance."""    g = np.array([s(z) for s in scores])    return ...  # TO DO: the experts that tie for the maximum scoredef filippov(z):    J = active_set(z)    values = ...  # TO DO: the value of each active branch    pairs = ...  # TO DO: the pair (value, derivative) of each active branch    return J, (min(values), max(values)), pairsfor z in [-0.5, 0.0, 0.5]:    J, interval, pairs = filippov(z)    print(f"z = {z:4.1f}: active branches {J}, Filippov set {interval}, pairs {pairs}")
Show the correction
PythonComplete solution · active branches, interval and pairs
# The branches Phi^(k) of the operator: value and derivative of each expert, and the routing scoresexperts = [lambda z: z + 1.0, lambda z: 2.0 * z - 1.0]slopes = [1.0, 2.0]scores = [lambda z: z, lambda z: -z]# J(z) = indices of the branches whose routing region has z in its closure, i.e. the experts that tie for the maximum score.def active_set(z, tol=1e-9):    """Indices k whose routing region has z in its closure: the largest scores, up to a tolerance."""    g = np.array([s(z) for s in scores])    return [k for k in range(len(g)) if g[k] >= g.max() - tol]  # the experts that tie for the maximum scoredef filippov(z):    J = active_set(z)    # At a switching point the Filippov set is the convex hull of the branch values: in 1D an interval [min, max].    values = [experts[k](z) for k in J]  # the value of each active branch    # The Filippov EXTENSION keeps the value and the derivative together, branch by branch: a segment in the (value, derivative) plane.    pairs = [(experts[k](z), slopes[k]) for k in J]  # the pair (value, derivative) of each active branch    return J, (min(values), max(values)), pairsfor z in [-0.5, 0.0, 0.5]:    J, interval, pairs = filippov(z)    print(f"z = {z:4.1f}: active branches {J}, Filippov set {interval}, pairs {pairs}")

At the regular points $\pm0.5$ the set is a single value; at $z=0$ both branches are active and the set is $[-1,1]$, with the pairs $(1,1)$ and $(-1,2)$, exactly the numbers of the article.

Exercise

Exercise 1.3 · the ReLU kink

  1. Write the two branches of the ReLU and compute their values at $z=0$.
  2. Compute the set of derivatives at the kink and the one-sided derivatives.
  3. Compare with the gradient returned by Keras at $z=0$.
PythonStarting code · ReLU as a switching operator
# ReLU as a switching operator with two branches: Phi^(1)(z) = 0 (z < 0) and Phi^(2)(z) = z (z > 0)branches = [lambda z: 0.0 * z, lambda z: z]derivs = [0.0, 1.0]values_at_kink = ...  # TO DO: the values of the two branches at the kink z = 0jacobian_set = ...  # TO DO: the convex hull of the two derivativesprint("values at z = 0:", values_at_kink, "-> a single value: the output of a ReLU network does not branch")print("derivatives at z = 0:", jacobian_set, "-> a whole interval")h = 1e-6left = (max(-h, 0) - max(-2 * h, 0)) / h                             # derivative from the leftright = (max(2 * h, 0) - max(h, 0)) / h                              # derivative from the rightprint("one-sided derivatives:", left, right)zt = tf.Variable(0.0)with tf.GradientTape() as tape:    y = tf.nn.relu(zt)print("Keras gradient at the kink:", tape.gradient(y, zt).numpy(), "(a convention: one point of [0, 1])")
Show the correction
PythonComplete solution · one value, an interval of derivatives
# ReLU as a switching operator with two branches: Phi^(1)(z) = 0 (z < 0) and Phi^(2)(z) = z (z > 0)branches = [lambda z: 0.0 * z, lambda z: z]derivs = [0.0, 1.0]# Both branches of the ReLU give 0 at the kink: the value does not branch, only the derivative does.values_at_kink = {branches[k](0.0) for k in range(2)}  # the values of the two branches at the kink z = 0jacobian_set = (min(derivs), max(derivs))  # the convex hull of the two derivativesprint("values at z = 0:", values_at_kink, "-> a single value: the output of a ReLU network does not branch")print("derivatives at z = 0:", jacobian_set, "-> a whole interval")h = 1e-6# One-sided differences: the slope is 0 on the left and 1 on the right; the Filippov (and Clarke) Jacobian is their convex hull [0, 1].left = (max(-h, 0) - max(-2 * h, 0)) / h                             # derivative from the leftright = (max(2 * h, 0) - max(h, 0)) / h                              # derivative from the rightprint("one-sided derivatives:", left, right)zt = tf.Variable(0.0)with tf.GradientTape() as tape:    y = tf.nn.relu(zt)print("Keras gradient at the kink:", tape.gradient(y, zt).numpy(), "(a convention: one point of [0, 1])")

The value is the single point $\{0\}$: the output of a ReLU network never branches. The derivative set is $[0,1]$, and Keras returns $0$, one point of this interval by convention. Which point is returned changes the attribution computed from the gradient, as Part 2 shows.

Part 2 · A network is a DAG: the running example in Keras

Course

A feed-forward network as a directed acyclic graph

DefinitionNetwork as a DAG

The nodes are the inputs $\mathcal I$, bias nodes $\mathcal B$ (value $+1$), hidden nodes $\mathcal H$ and outputs $\mathcal O$. Each edge $(u,v)$ has a weight $w_{u,v}$ and carries the contribution $z_{u,v}=w_{u,v}\,x_u$. A node sums the contributions it receives, $\tilde z_v=\sum_{u\to v}z_{u,v}$, and applies its operator (the identity for an output, a ReLU for a hidden node here). A bias is therefore a weight like the others. The active graph $G(x)$ keeps the nodes with a nonzero value and the edges of nonzero weight between them.

At a kink, a node can be inactive and its edges leave the active graph. The running example of the article has two inputs, a bias on the hidden layer, two ReLU nodes, two linear outputs, a bias on the outputs and a skip edge $i_1\to o_1$. Its weights are in the figure; at $x=(-2,1)$ the sum entering $h_1$ is exactly $0$: this is a kink, $h_1$ is inactive, and $h_2=4$, $o_1=6$, $o_2=7$.

The running example: inputs, two ReLU hidden nodes, two outputs, bias nodes, a skip edge, with weights and values at x = (-2, 1)
The running example at the switching point $x=(-2,1)$. Dashed edges leave the active graph.
Exercise

Exercise 2.1 · the running example as a Keras model

  1. Build the network with the functional API: a ReLU Dense layer for $h_1,h_2$, the concatenation $(h_1,h_2,i_1,i_2)$ and a linear Dense layer for the outputs.
  2. The weights are given in the starting code. Check that the outputs are $(6,7)$ at $x=(-2,1)$ and $(6,-2)$ at $x=(1,1)$.
PythonStarting code · Keras model of the running example
def build_network():    x = keras.Input(shape=(2,), name="inputs")                                 # i1, i2    hidden = ...  # TO DO: two ReLU nodes h1, h2 with the weights of the article    both = layers.Concatenate()([hidden, x])                                   # h1, h2, i1, i2 feed the outputs    out = ...  # TO DO: two linear outputs o1, o2 (with the skip edge i1 -> o1)    return keras.Model(x, out)model = build_network()# weights of the article: rows i1, i2 and columns h1, h2; bias b1 -> (h1, h2)model.get_layer("hidden").set_weights([np.array([[1.0, -1.0], [2.0, 1.0]]), np.array([0.0, 1.0])])# rows h1, h2, i1, i2 and columns o1, o2; bias b2 -> (o1, o2)model.get_layer("outputs").set_weights([np.array([[1.0, -1.0], [2.0, 2.0], [1.0, 0.0], [0.0, 0.0]]), np.array([0.0, -1.0])])for x in [(-2.0, 1.0), (1.0, 1.0)]:    print(x, "->", model(np.array([x], dtype="float32")).numpy().ravel())print("expected: (-2, 1) -> (6, 7) and (1, 1) -> (6, -2)")
Show the correction
PythonComplete solution · the network with the weights of the article
# Functional API: the skip edge i1 -> o1 and the direct inputs of the outputs are obtained by concatenating the hidden layer with the inputs.def build_network():    x = keras.Input(shape=(2,), name="inputs")                                 # i1, i2    hidden = layers.Dense(2, activation="relu", name="hidden")(x)  # two ReLU nodes h1, h2 with the weights of the article    # Concatenation (h1, h2, i1, i2): the output layer then has four inputs, so a weight matrix of shape (4, 2).    both = layers.Concatenate()([hidden, x])                                   # h1, h2, i1, i2 feed the outputs    out = layers.Dense(2, name="outputs")(both)  # two linear outputs o1, o2 (with the skip edge i1 -> o1)    return keras.Model(x, out)model = build_network()# weights of the article: rows i1, i2 and columns h1, h2; bias b1 -> (h1, h2)# Keras kernels have shape (inputs, units): row = source node, column = target node. The bias vector is the weight of the bias node.model.get_layer("hidden").set_weights([np.array([[1.0, -1.0], [2.0, 1.0]]), np.array([0.0, 1.0])])# rows h1, h2, i1, i2 and columns o1, o2; bias b2 -> (o1, o2)model.get_layer("outputs").set_weights([np.array([[1.0, -1.0], [2.0, 2.0], [1.0, 0.0], [0.0, 0.0]]), np.array([0.0, -1.0])])for x in [(-2.0, 1.0), (1.0, 1.0)]:    print(x, "->", model(np.array([x], dtype="float32")).numpy().ravel())print("expected: (-2, 1) -> (6, 7) and (1, 1) -> (6, -2)")

A Keras kernel has shape (inputs, units): rows are source nodes and columns target nodes, so the matrices are exactly the weights of the figure. The skip edge $i_1\to o_1$ is the weight $1$ in the row of $i_1$ of the output kernel.

Exercise

Exercise 2.2 · contributions and the active graph

  1. Write the forward pass on the graph (dictionary of node values, ReLU on the hidden nodes, linear outputs).
  2. Compute the contributions $z_{u,v}=w_{u,v}x_u$.
  3. Build the active graph: the active nodes and the edges of nonzero weight between active nodes. Compare $x=(-2,1)$ and $x=(1,1)$.
PythonStarting code · forward pass and active graph
def forward(x):    """Node values of the running example: dictionary node -> value (the biases have the value 1)."""    v = {"i1": x[0], "i2": x[1], "b1": 1.0, "b2": 1.0}    for h in HIDDEN:        total = sum(WEIGHTS[(u, h)] * v[u] for u in ["i1", "i2", "b1"])      # sum of the incoming contributions        v[h] = ...  # TO DO: ReLU    for o in OUTPUTS:        v[o] = ...  # TO DO: linear output: sum of the contributions    return vdef contributions(x):    v = forward(x)    return ...  # TO DO: z_{u,v} = w_{u,v} x_udef active_graph(x):    v = forward(x)    nodes = [n for n in ORDER if v[n] != 0.0]                                # active nodes: nonzero value    edges = ...  # TO DO: edges with a nonzero weight between active nodes    return nodes, edgesfor x in [(-2.0, 1.0), (1.0, 1.0)]:    nodes, edges = active_graph(x)    print("x =", x, "values", {n: v for n, v in forward(x).items() if n in HIDDEN + OUTPUTS})    print("   inactive nodes:", [n for n in ORDER if n not in nodes], "| active edges:", len(edges), "of", len(WEIGHTS))
Show the correction
PythonComplete solution · values, contributions and active edges
# The biases b1 and b2 are nodes of value 1, so that a bias is a weight like the others (a DAG with bias nodes).def forward(x):    """Node values of the running example: dictionary node -> value (the biases have the value 1)."""    v = {"i1": x[0], "i2": x[1], "b1": 1.0, "b2": 1.0}    for h in HIDDEN:        total = sum(WEIGHTS[(u, h)] * v[u] for u in ["i1", "i2", "b1"])      # sum of the incoming contributions        # ReLU: the value of a hidden node is max(sum of incoming contributions, 0).        v[h] = max(total, 0.0)  # ReLU    for o in OUTPUTS:        v[o] = sum(w * v[u] for (u, t), w in WEIGHTS.items() if t == o)  # linear output: sum of the contributions    return v# The contribution z_{u,v} = w_{u,v} x_u is what node u sends to node v along the edge (u, v).def contributions(x):    v = forward(x)    return {(u, t): w * v[u] for (u, t), w in WEIGHTS.items()}  # z_{u,v} = w_{u,v} x_udef active_graph(x):    v = forward(x)    # A node is active when its value is nonzero: a ReLU at 0 (a kink) is inactive, and so are the edges leaving it.    nodes = [n for n in ORDER if v[n] != 0.0]                                # active nodes: nonzero value    edges = [(u, t) for (u, t), w in WEIGHTS.items() if w != 0.0 and u in nodes and t in nodes]  # edges with a nonzero weight between active nodes    return nodes, edgesfor x in [(-2.0, 1.0), (1.0, 1.0)]:    nodes, edges = active_graph(x)    print("x =", x, "values", {n: v for n, v in forward(x).items() if n in HIDDEN + OUTPUTS})    print("   inactive nodes:", [n for n in ORDER if n not in nodes], "| active edges:", len(edges), "of", len(WEIGHTS))

At $x=(-2,1)$ the node $h_1$ is inactive and only $7$ of the $13$ edges are active (the five edges of $h_1$ and the two zero-weight edges are out): this is the picture of the article. At the regular input $x=(1,1)$ every node is active and $11$ edges remain (the two zero-weight edges are still out).

Course

One gradient per selection

DefinitionSelection and path-gradient

A selection $\kappa$ chooses one active branch at every switching node. Once a selection is fixed, the network is differentiable and its gradient is the sum, over the paths from an input to the output, of the products of the branch derivatives and weights along the path. Different selections give different gradients; their convex hull is the gradient part of the Filippov extension.

At the kink $x=(-2,1)$, the node $h_1$ has two selections: the constant branch (gate $0$) or the identity branch (gate $1$). Both give the same values $h_1=0$, $o_1=6$, but not the same derivatives. Automatic differentiation silently picks one.

Exercise

Exercise 2.3 · the Filippov gradient at the kink

  1. Differentiate $o_1$ at $x=(-2,1)$ with the gate of $h_1$ frozen at $0$, then at $1$.
  2. Deduce the Filippov gradient set of $o_1$ with respect to $(i_1,i_2)$.
  3. Compare with the gradient that Keras returns for the model of Exercise 2.1.
PythonStarting code · one gradient per selection
def o1_with_gate(x, gate):    """o1 as a function of (i1, i2) when the gate of h1 is frozen at 0 or 1 (a selection kappa of the branch of h1)."""    i1, i2 = x    h1 = gate * (1.0 * i1 + 2.0 * i2 + 0.0)               # branch 1: the constant 0; branch 2: the sum of the inputs    h2 = max(-1.0 * i1 + 1.0 * i2 + 1.0, 0.0)             # h2 is on its linear branch near x = (-2, 1)    return 1.0 * h1 + 2.0 * h2 + 1.0 * i1x0 = np.array([-2.0, 1.0])                                  # the kink: the sum entering h1 is exactly 0for gate in [0.0, 1.0]:    xt = tf.Variable(x0, dtype=tf.float32)    with tf.GradientTape() as tape:        i1, i2 = xt[0], xt[1]        h1 = ...  # TO DO: frozen branch of h1        h2 = tf.nn.relu(-i1 + i2 + 1.0)        o1 = h1 + 2.0 * h2 + i1    print(f"selection kappa_h1 = {int(gate)}: gradient of o1 at the kink =", tape.gradient(o1, xt).numpy())xt = tf.Variable(x0, dtype=tf.float32)with tf.GradientTape() as tape:    o1 = ...  # TO DO: the Keras model of Exercise 2.1print("Keras gradient at the kink:", tape.gradient(o1, xt).numpy(), "(one selection among the two)")
Show the correction
PythonComplete solution · two selections, two gradients
# A selection kappa of the branch of h1: gate 0 = the constant branch, gate 1 = the linear branch. Both agree on the value at the kink.def o1_with_gate(x, gate):    """o1 as a function of (i1, i2) when the gate of h1 is frozen at 0 or 1 (a selection kappa of the branch of h1)."""    i1, i2 = x    # Freezing the gate makes the network differentiable: we get one gradient per selection.    h1 = gate * (1.0 * i1 + 2.0 * i2 + 0.0)               # branch 1: the constant 0; branch 2: the sum of the inputs    h2 = max(-1.0 * i1 + 1.0 * i2 + 1.0, 0.0)             # h2 is on its linear branch near x = (-2, 1)    return 1.0 * h1 + 2.0 * h2 + 1.0 * i1x0 = np.array([-2.0, 1.0])                                  # the kink: the sum entering h1 is exactly 0for gate in [0.0, 1.0]:    xt = tf.Variable(x0, dtype=tf.float32)    with tf.GradientTape() as tape:        i1, i2 = xt[0], xt[1]        h1 = gate * (i1 + 2.0 * i2)  # frozen branch of h1        h2 = tf.nn.relu(-i1 + i2 + 1.0)        o1 = h1 + 2.0 * h2 + i1    print(f"selection kappa_h1 = {int(gate)}: gradient of o1 at the kink =", tape.gradient(o1, xt).numpy())xt = tf.Variable(x0, dtype=tf.float32)with tf.GradientTape() as tape:    o1 = model(xt[None])[0, 0]  # the Keras model of Exercise 2.1# Keras returns the gradient of ONE selection (relu(0) has derivative 0), hiding the other one.print("Keras gradient at the kink:", tape.gradient(o1, xt).numpy(), "(one selection among the two)")

The gate $0$ gives the gradient $(-1,2)$ and the gate $1$ gives $(0,4)$. The Filippov gradient set is the segment between them: $[-1,0]$ for $i_1$ and $[2,4]$ for $i_2$, the intervals of the article. Keras returns $(-1,2)$, the selection of the gate $0$ only.

Part 3 · Deliverables and limits

Exercise

Build a defensible report

  1. Explain, with the example $E_1=z+1$, $E_2=2z-1$, why automatic differentiation hides information at a routing tie, and give the Filippov set and the Filippov extension.
  2. Reproduce the proof of the Filippov theorem for a switching operator of your choice (a max of three affine functions in dimension 1, for instance).
  3. For the running example at another switching point (for instance $x=(0,-1)$ or $x=(-2,1)$ with other weights), list the active graph, the selections and the Filippov gradient set of an output.
  4. Extension: build a two-layer network with a hard-routed block, train it as usual, and report, at inputs close to a routing boundary, the set of admissible values of the output.

Deliver a rerunnable notebook, a table of results, the figures and a discussion of limits.

Course

What these experiments do not show

The running example has 13 weights, and the router of the example is one-dimensional: the programs explain the mechanics of Filippov sets, not the behaviour of a large Mixture-of-Experts model. Filippov sets are a tool for analysis at switching points: Keras models are trained with the usual single selection and the gradient that automatic differentiation returns is one point of the Filippov set, not the set. The article develops the full measure-theoretic formalization (null sets, locally finite families of regions, admissible selections over a whole network) and the calculus of path gradients, which are only outlined here. Because the switching region has measure zero, a randomly drawn input is almost surely a regular point: the phenomena of this course matter for inputs on a routing boundary, which are rare but decisive (adversarial or borderline cases, quantized or discretized inputs).

References and related learning

Course

The article and related work