Route tokens with Mixture-of-Depths

Why it matters Mixture-of-Depths cuts transformer FLOPs per forward pass by skipping easy tokens.

Mixture-of-Depths lets only the top fraction of tokens go through a block; the rest skip it via the residual.

Write mod_route(x, router_w, block_fn, capacity). x is (T, d), router_w is (d,). Scores r = x @ router_w. Pick the k = max(1, int(capacity * T)) tokens with the highest scores (stable on ties by index). For those, output x + r_i * block_fn(x_i) (block_fn maps a (k, d) array to (k, d)); others output x unchanged. Return the (T, d) output.

Signaturedef mod_route(x, router_w, block_fn, capacity)

Example

with capacity 1.0 every token is processed.

Understand the idea

Mixture-of-Depths saves compute by letting only some tokens pass through a block. A router gives every token a score, the top k tokens are processed, and all others skip the block through the residual and come out unchanged. Multiplying the block output by the router score puts the router on the gradient path so it can learn. Worked example: x = [[1], [2], [3], [4]], router_w = [0.5], so r = [0.5, 1.0, 1.5, 2.0]. capacity 0.5 gives k = max(1, int(0.5 * 4)) = 2, so tokens 3 and 2 are picked. With a block that doubles its input, token 2 becomes 3 + 1.5 * 6 = 12 and token 3 becomes 4 + 2.0 * 8 = 20. Output [[1], [2], [12], [20]]. With capacity 0.1, int(0.4) = 0, so k is lifted to 1. Rule: r = x @ router_w; k = max(1, int(capacity * T)); choose the k highest scores with a stable order on ties; call block_fn once on the selected rows; out = copy of x, and selected rows become x_i + r_i * block_fn(x_i). Used in: research on adaptive compute transformers that spend less work on easy tokens.

Shapes and data flow

x (T, d) @ w (d,) -> r (T,)
top k ids -> x[idx] (k, d) -> block -> scaled by r[idx]
scatter back -> (T, d)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplemod_route(_x, _w, np.tanh, 1.0)
  • Sample 2: halfmod_route(_x, _w, np.tanh, 0.5)