📘
Transformer Block Forward Pass
Implement a single transformer block forward pass.
A transformer block consists of:
- Multi-head self-attention with residual connection and layer norm: x = LayerNorm(x + Attention(x))
- 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 x⋅xT normalized by the square root of the sequence length (2). For the input matrix X=[1001],Attention(x)becomes [1001]. - Then, we apply the layer norm to the sum of
xandAttention(x): x=var+1e−5x+Attention(x)−mean. Since x+Attention(x)=[2002], mean=1, and var=0, x becomes [2−12−1]/0+1e−5≈[1001], but due to the specifics of the layer norm calculation, it actually results in [1001]. - Next, the feed-forward network (FFN) is applied: FFN(x)=ReLU(x⋅W1)⋅W2. Given dff=4⋅d=8, W1 is a 2×8 matrix and W2 is an 8×2 matrix, both initialized with \np.random.seed(42) and scale 0.1. After computation, FFN(x) is calculated and then added to x.
- Finally, another layer norm is applied to the sum of x and 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
Python 3.13.1
Test Results
0/0Run code to see test results.