v9.1.1
Menu

Feed-Forward Network

easyFREETransformer ComponentsLLM 1: Foundations

Implement a transformer feed-forward network (FFN).

The FFN applies two linear transformations with a ReLU activation in between: FFN(x)=ReLU(xW1+b1)W2+b2\text{FFN}(x) = \text{ReLU}(xW_1 + b_1)W_2 + b_2

For simplicity, use no biases (b1=0, b2=0). Use numpy seed 42 to generate W1 and W2.

Input: ffn(d, d_ff, x)

  • d: model dimension
  • d_ff: FFN hidden dimension
  • x: NumPy input vector of shape (d,)

Output: Return the output vector of shape (d,); it is printed rounded to 4 decimal places.

Generate weights: np.random.seed(42), W1 = np.random.randn(d, d_ff) * 0.1, W2 = np.random.randn(d_ff, d) * 0.1

Example

Input
2 4
1.0 -1.0
Output
-0.0169 -0.0007
Reasoning
  • Inputs: d=2d = 2, dff=4d_{ff} = 4 and x=[1,−1]x = [1, -1]. So W1W_1 is 2×42 \times 4 (expands the vector to 4 hidden units) and W2W_2 is 4×24 \times 2 (projects back to 2), both drawn from the seeded standard normal and scaled by 0.10.1.
  • First layer: with x=[1,−1]x = [1, -1], hidden unit kk is (row 1 of W1W_1) minus (row 2), e.g. h1=0.0497−(−0.0234)=0.0731h_1 = 0.0497 - (-0.0234) = 0.0731. All four: [0.0731, 0.0096, −0.0932, 0.0756][0.0731,\ 0.0096,\ -0.0932,\ 0.0756].
  • ReLU replaces the negative unit with 00: [0.0731, 0.0096, 0, 0.0756][0.0731,\ 0.0096,\ 0,\ 0.0756].
  • Second layer: output jj is ∑khk(W2)kj\sum_k h_k (W_2)_{kj}. For j=1j = 1: −0.00343−0.00044+0−0.01303=−0.01691-0.00343 - 0.00044 + 0 - 0.01303 = -0.01691; for j=2j = 2: 0.00397−0.00045+0−0.00425=−0.000730.00397 - 0.00045 + 0 - 0.00425 = -0.00073.
  • Output: -0.0169 -0.0007, a vector of length d=2d = 2 again, rounded to 4 decimal places.
  • Notice the third hidden unit contributes nothing, and an all-zero input gives an all-zero output since there are no biases.

Constraints

  • 1 <= d <= 10, 1 <= d_ff <= 20
  • Use np.random.seed(42) for weight initialization
  • Scale weights by 0.1
  • ReLU: max(0, x)
  • Round to 4 decimal places

Learn this in

More from LLM 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.