Add, Then Level

TransformersMedium+20 XP+20

Add, Then Level

Every sublayer in a transformer block hands its result to the same two-step wrapper: add, then normalize. The sublayer's output is added back onto the vectors that went into it — nothing is replaced — and the sum is rescaled so the numbers cannot drift as the stack gets deeper.

Task: write add_and_norm(x, sublayer_out, gamma, beta), returning the wrapped output, rounded to 4 decimal places.

argumentshapewhat it is
xnnn vectors of length dddwhat went into the sublayer
sublayer_outnnn vectors of length dddwhat the sublayer produced
gammalength dddthe learned scale, shared by every position
betalength dddthe learned shift, shared by every position

Take one position iii at a time. Write uiu_iui​ for sublayer_out[i], and work from that position's own ddd slots:

r=xi+ui,m=1d∑j=1drj,s=1d∑j=1d(rj−m)2+10−5r = x_i + u_i, \qquad m = \frac{1}{d}\sum_{j=1}^{d} r_j, \qquad s = \sqrt{\frac{1}{d}\sum_{j=1}^{d} (r_j - m)^2 + 10^{-5}}r=xi​+ui​,m=d1​∑j=1d​rj​,s=d1​∑j=1d​(rj​−m)2+10−5​

outputij=γj⋅rj−ms+βj\text{output}_{ij} = \gamma_j \cdot \frac{r_j - m}{s} + \beta_joutputij​=γj​⋅srj​−m​+βj​

  • The spread divides the squared deviations by ddd, not by d−1d - 1d−1.
  • The 10−510^{-5}10−5 inside the square root is there so a position whose slots happen to be all equal does not divide by zero.
  • γ\gammaγ and β\betaβ are the same two vectors for every position.

This is the "add & norm" that appears twice in every transformer block. The add is what gives the original vectors a clear path through all ninety-six layers instead of being shrunk away; the norm is what stops a harmless-looking drift of a third per layer compounding into numbers no optimizer can work with.

8.0
2.0
14.0
4.0
6.0
12.0
mean 7.7spread 4.2

Subtract the mean, divide by the spread. The pattern of which slots are big and small survives; only the scale changes.

Examples

x = [[1.0, 2.0, 3.0], [4.0, 0.0, -1.0]]
sublayer_out = [[0.5, -0.5, 1.0], [1.0, 1.0, 1.0]]
gamma = [1.0, 1.0, 1.0]
beta = [0.0, 0.0, 0.0]
returns [[-0.7071, -0.7071, 1.4142], [1.3887, -0.4629, -0.9258]]
x = [[0.2, -0.4, 1.0, 0.6], [1.5, 1.5, -0.5, 0.0]]
sublayer_out = [[0.8, 0.4, -1.0, 0.4], [0.5, -1.5, 0.5, 1.0]]
gamma = [2.0, 0.5, 1.0, 1.5]
beta = [0.1, -0.2, 0.0, 1.0]
returns [[2.1, -0.7, -1.0, 2.5], [3.1151, -0.6523, -0.9045, 1.4523]]

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