Out Wide and Back Again

TransformersEasy+10 XP+10

Out Wide and Back Again

Inside every transformer block, right after attention, sits the feed-forward sublayer. It takes the vector at one position, widens it, applies a non-linearity, and narrows it back to its original width:

hidden=ReLU(x W1+b1),out=hidden  W2+b2\text{hidden} = \text{ReLU}(x\,W_1 + b_1), \qquad \text{out} = \text{hidden}\;W_2 + b_2hidden=ReLU(xW1​+b1​),out=hiddenW2​+b2​

If each position's vector holds ddd numbers and the wide middle holds hhh:

  • W1W_1W1​ has ddd rows and hhh columns, and b1b_1b1​ holds hhh numbers.
  • W2W_2W2​ has hhh rows and ddd columns, and b2b_2b2​ holds ddd numbers.
  • ReLU sets every negative number to 0 and leaves the rest alone.

Written out, hidden value jjj is ReLU(∑ixi W1[i][j]+b1[j])\text{ReLU}\left(\sum_i x_i\, W_1[i][j] + b_1[j]\right)ReLU(∑i​xi​W1​[i][j]+b1​[j]) and output value kkk is ∑jhiddenj W2[j][k]+b2[k]\sum_j \text{hidden}_j\, W_2[j][k] + b_2[k]∑j​hiddenj​W2​[j][k]+b2​[k].

The same weights are used at every position, and each position is handled on its own. No position's output depends on any other position.

Task: write feed_forward(x, w1, b1, w2, b2).

  • x is a sequence: a list of nnn position vectors, each a list of ddd numbers.
  • w1 and w2 are lists of rows; b1 and b2 are plain lists.
  • Return a list of nnn output vectors, each of ddd numbers, with every value rounded to 4 decimal places.
in (512)
one vector arrives

The width in the middle is where the work happens. Coming back to the original size is what keeps the block stackable.

Examples

x = [[2.0, 1.0]]
w1 = [[1.0, -1.0, 0.5, 0.0], [0.0, 1.0, 0.5, -1.0]]
b1 = [0.0, 0.0, -1.0, 0.5]
w2 = [[1.0, 0.0], [0.0, 1.0], [2.0, -1.0], [-1.0, 1.0]]
b2 = [0.1, -0.2]
returns [[3.1, -0.7]]
x = [[-1.0, 3.0], [2.0, 1.0], [0.0, 0.0]]
w1 = [[1.0, -1.0, 0.5, 0.0], [0.0, 1.0, 0.5, -1.0]]
b1 = [0.0, 0.0, -1.0, 0.5]
w2 = [[1.0, 0.0], [0.0, 1.0], [2.0, -1.0], [-1.0, 1.0]]
b2 = [0.1, -0.2]
returns [[0.1, 3.8], [3.1, -0.7], [-0.4, 0.3]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run