v9.1.1
Menu

Complete Mixer Block with Residuals

hardPROMLP-MixerNeural Networks, ArchitectureAdvanced Architectures

A complete MLP-Mixer block combines token mixing and channel mixing with residual connections:

X1=X+TokenMix(X)X_1 = X + \text{TokenMix}(X) X2=X1+ChannelMix(X1)X_2 = X_1 + \text{ChannelMix}(X_1)

Where:

  • TokenMix: Wtoken⋅XW_{\text{token}} \cdot X (mix across N tokens)
  • ChannelMix: GELU(X1W1) W2\text{GELU}(X_1 W_1)\, W_2, a two-layer MLP with no biases applied per-token (use the tanh-approximate GELU defined in the starter code)

The residual connections ensure stable training and allow the network to learn identity mappings when beneficial.

Task: Implement a complete Mixer block with both mixing stages and residual connections.

Example

Input
X (2×2), W_token=zeros, W1=I, W2=I
Output
X + 0 + GELU(X) = X + GELU(X)
Reasoning
  • Inputs: XX is a 2×22 \times 2 matrix of 2 tokens (rows) by 2 channels (columns), here [1234]\begin{bmatrix}1 & 2\\ 3 & 4\end{bmatrix}. WtokenW_{\text{token}} is the 2×22 \times 2 zero matrix, and both channel weights W1,W2W_1, W_2 are the 2×22 \times 2 identity, so the hidden width is H=D=2H = D = 2.
  • Token mixing: each new token row is a weighted blend of all token rows, ∑jwij xj\sum_j w_{ij}\, x_j. With every weight zero the blend is the zero matrix, so X1=X+0=XX_1 = X + 0 = X.
  • Channel mixing: each token row is multiplied by W1W_1, passed through GELU entry by entry, then multiplied by W2W_2. With identity weights, ChannelMix(X1)(X_1) is just GELU of every entry: GELU(1)≈0.8412\text{GELU}(1) \approx 0.8412, GELU(2)≈1.9546\text{GELU}(2) \approx 1.9546, GELU(3)≈2.9964\text{GELU}(3) \approx 2.9964, GELU(4)≈3.9999\text{GELU}(4) \approx 3.9999.
  • Output: X2=X1+GELU(X1)X_2 = X_1 + \text{GELU}(X_1), a 2×22 \times 2 matrix like the input: [[1.8412, 3.9546], [5.9964, 7.9999]] (rounded to 4 decimal places).
  • Notice: for large positive xx, GELU(x)≈x\text{GELU}(x) \approx x, so entries approach 2x2x. The residuals keep XX even when a stage contributes nothing.

Constraints

  • Input XX: Shape (N,D)(N, D)
  • WtokenW_{\text{token}}: Shape (N,N)(N, N)
  • W1W_1: Shape (D,H)(D, H) for channel MLP
  • W2W_2: Shape (H,D)(H, D) for channel MLP

Learn this in

More from Advanced Architectures

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.