LayerNorm and RMSNorm
Lesson: The Full Transformer — Encoder + DecoderCheat sheetTrack: Deep learning coreTrack: Transformers from scratch
Problem
A transformer normalizes the vector of each token before attention and before the feed forward block. LayerNorm centers each vector and divides it by its standard deviation. RMSNorm skips the centering and divides by the root mean square. Modern LLMs use RMSNorm because it is cheaper and works as well.
Task
Write two functions.
layer_norm(x, gamma, beta, eps=1e-5)returns LayerNorm ofxover the last axis.rms_norm(x, weight, eps=1e-6)returns RMSNorm ofxover the last axis.
For each vector x of length D along the last axis:
The variance is the biased variance. It divides by D, not by D - 1. The eps goes inside the square root in both functions.
Input and output
| Name | Type | Shape | Meaning |
|---|---|---|---|
x | float array | (..., D) | the vectors to normalize, with zero or more leading axes |
gamma | float array | (D,) | the LayerNorm scale of each feature |
beta | float array | (D,) | the LayerNorm shift of each feature |
weight | float array | (D,) | the RMSNorm scale of each feature |
eps | float | the small number added inside the square root |
- Both functions return a float array with the shape of
x.
Constraints
xhas 1 to 4 axes.1 <= D <= 1024.- A vector can be constant or all zeros. The output must not contain NaN.
- Do not change the input arrays.
- Use numpy only.
Examples
pythonx = np.array([[1.0, 2.0, 3.0, 4.0], [2.0, -2.0, 0.0, 4.0]])
gamma = np.array([1.0, 1.0, 2.0, 0.5])
beta = np.array([0.0, 0.5, 0.0, -1.0])
layer_norm(x, gamma, beta)text[[-1.34163542 0.05278819 0.89442361 -0.32918229]
[ 0.44721315 -0.84163944 -0.8944263 -0.32918028]]pythonrms_norm(x, gamma)text[[ 0.36514835 0.73029669 2.19089008 0.73029669]
[ 0.81649651 -0.81649651 0. 0.81649651]]Hints
4 hintsSolution and notes
LockedPass every check with Submit to open the reference solution and the notes.
Run it on your computer
Clone the repository, install numpy and run the same checks in a terminal:
python3 scripts/practice/run.py layer-norm-rms-norm my_answer.py
python3 scripts/practice/run.py layer-norm-rms-norm my_answer.py --examplesStart my_answer.py from starter.py.
Your code is saved in this browser as you type. On a phone you can read and edit the code, but the checks are easier to use on a desktop.
Keyboard shortcuts
- Ctrl Enter
- Run the examples
- Ctrl Shift Enter
- Submit
- Tab / Shift Tab
- Indent or outdent the lines
- Esc then Tab
- Move the focus out of the editor
- Alt H
- Show the next hint
On a Mac, use Cmd in place of Ctrl.
Select Run to check the examples, or Submit to run every check.