PIXELBANKv8.2.1
Menu

Transformer Block Forward Pass

Implement a single transformer block forward pass.

A transformer block consists of:

  1. Multi-head self-attention with residual connection and layer norm: x = LayerNorm(x + Attention(x))
  2. Feed-forward network with residual connection and layer norm: x = LayerNorm(x + FFN(x))

For simplicity:

  • Single-head attention (h=1), no projection weights
  • FFN: ReLU(x @ W1) @ W2 with np.random.seed(42), scale 0.1
  • LayerNorm: (x - mean) / sqrt(var + 1e-5), no affine params
  • d_ff = 4 * d

Input:

  • Line 1: n d (sequence length, model dimension)
  • Next n lines: input matrix X

Output: Output matrix after one transformer block, rounded to 4 decimal places.

Example:

Input:
2 2
1 0
0 1
Output:
[ 0.9998 -0.9998]
[-0.9998  0.9998]
Reasoning:
  • First, we calculate the self-attention: since it's single-head attention with no projection weights, Attention(x) simplifies to xxTx \cdot x^T normalized by the square root of the sequence length (2\sqrt{2}). For the input matrix X=[1001]X = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}, Attention(x) becomes [1001]\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}.
  • Then, we apply the layer norm to the sum of x and Attention(x): x=x+Attention(x)meanvar+1e5x = \frac{x + Attention(x) - mean}{\sqrt{var + 1e-5}}. Since x+Attention(x)=[2002]x + Attention(x) = \begin{bmatrix} 2 & 0 \\ 0 & 2 \end{bmatrix}, mean=1mean = 1, and var=0var = 0, xx becomes [2121]/0+1e5[1001]\begin{bmatrix} 2 - 1 \\ 2 - 1 \end{bmatrix} / \sqrt{0 + 1e-5} \approx \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}, but due to the specifics of the layer norm calculation, it actually results in [1001]\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}.
  • Next, the feed-forward network (FFN) is applied: FFN(x)=ReLU(xW1)W2FFN(x) = ReLU(x \cdot W1) \cdot W2. Given dff=4d=8d_{ff} = 4 \cdot d = 8, W1W1 is a 2×82 \times 8 matrix and W2W2 is an 8×28 \times 2 matrix, both initialized with \np.random.seed(42)\np.random.seed(42) and scale 0.10.1. After computation, FFN(x)FFN(x) is calculated and then added to xx.
  • Finally, another layer norm is applied to the sum of xx and FFN(x)FFN(x), resulting in the output matrix after one transformer block, which after computation and rounding to 4 decimal places gives the output: $\begin{bmatrix} 0.9998 & -0.9998 \ -0.9998 & 0.9998 \end{b

Constraints:

  • 1 <= n <= 5, 2 <= d <= 8
  • Single head attention (no projections)
  • d_ff = 4 * d
  • Layer norm with ε=1e-5, no affine
  • np.random.seed(42) before generating FFN weights
  • Round to 4 decimal places
Editor

Test Results

0/0
Run code to see test results.