22.8 Elementwise kernels in C: RMSNorm, RoPE, SiLU-mul, embedding, add, argmax
A transformer forward pass is mostly matmuls and attention, but between them sit six small operations: embedding lookup, normalization, rotary position encoding, gated activation, residual addition, and greedy selection. None of them is hard to write, and each is fast as long as it touches every element once. What makes them worth a section is that each has one detail that silently changes the model’s output when you get it wrong: where goes, which entries RoPE pairs, how SiLU behaves at large gates, and how argmax breaks ties. Get one wrong and the numbers still look plausible; the tokens are simply different.
Concepts from other sections (15)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- RoPE: rotary position embedding, which rotates queries and keys by position to encode relative position. Read more: 5.3 Model landscape and lifecycle
- interleaved layout: sin at column and cos at column , the pair layout of the paper. Read more: 11.4 Positional encodings: sinusoidal, learned
- Attention scaling: a factor applied to both tables, multiplying every score by . Read more: 13.3 Rotary Position Embeddings
- absolute position: , the position of a query row in the whole sequence rather than in the current call. Read more: 22.5 FlashAttention forward in C
- sigmoid: , mapping the real line into , with . Read more: 7.3 Activation Functions and Their Derivatives in Mathematics
- Newton’s method: the iteration , jumping to the zero of the tangent line. Read more: 7.2 Newton’s Method in Mathematics
- batch invariance: the property that a kernel’s output bits do not depend on how the work was split or scheduled. Read more: 22.2 Thread pool and tl_parallel_for
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3 in Mathematics
- Residual connection: computing so that layers learn a residual and gradients flow directly. Read more: Chapter 2: Deep Learning
- Half layout: pair is ; used by Hugging Face Llama-family checkpoints. Read more: 13.3 Rotary Position Embeddings
- tie rule: the fixed backtrace preference (diagonal, deletion, insertion) that makes the S, D, I split deterministic. Read more: 15.5 Multimodal eval metrics: WER, CER, VQA, captions, zero-shot
- YaRN: a per-pair ramp between keeping and dividing frequencies, by turns over the trained context, plus a temperature . Read more: 13.4 Context Extension: PI, NTK, YaRN, Llama 3 Scaling, and ALiBi
- Residual stream: the running sum a Transformer block adds its attention and MLP outputs to. Read more: 13.4 Variance propagation and initialization in Mathematics
- greedy decoding: taking the single most likely token at every step; a beam of size 1. Read more: 10.4 Beam search, generic over a step function
- SwiGLU: the gated MLP with silu on the gate (Llama, SmolLM2). Read more: 13.2 Gated MLPs: SwiGLU and GeGLU
This section implements all six as standalone C routines, with the Python definitions from earlier in the book as the behavioral reference. They complete the C kernel set of this chapter, whose point is that a C backend can generate the same tokens as numpy. The Python and Rust engine paths keep their own implementations; these routines are useful as independent, carefully specified examples.
The specifications are RMSNorm from Pre-LN and RMSNorm and rope_cos_sin and apply_rope from RoPE; Gated MLPs: SwiGLU and GeGLU is good background for SiLU-mul. The kernels call tl_rsqrtf from Fast inverse square root in standalone C and tl_expf from Polynomial approximation and range reduction, both in Mathematics, and the shared support layer from C runtime support and an arena allocator with marks. The contract is elementwise.h under c/ABI.md, and the reference solution is elementwise.c: tl_rmsnorm_f32, tl_rope_f32 (half and interleaved layouts, partial rotary, attention scaling), tl_silu_mul_f32, tl_embedding_f32, tl_add_f32, and tl_argmax_f32. Try to predict each line of the solution before you read it.
Learning objectives
- Implement RMSNorm with inside the root, in place, with each row’s bits independent of the batch.
- Implement RoPE for both the half and interleaved layouts, with partial rotary and attention scaling, reading each pair before writing it.
- Write SiLU in the one form that saturates to the right limit at both ends without NaN.
- Implement embedding, residual add, and an argmax whose tie and NaN rules match the sampling contract.
RMSNorm
Section titled “RMSNorm”The section uses this notation:
| Symbol | Meaning | Type / shape |
|---|---|---|
| one row (a token’s hidden state) | float[d] | |
| the RMSNorm gain | float[d] | |
| a small constant that keeps the root away from 0 | float | |
| , the mean of squares | scalar | |
tokens, heads, head width of a RoPE input [T, H, D] | int64_t | |
d_rot, the rotated width (even, ) | int64_t | |
| the absolute position of token | int32_t | |
inv_freq[i], the frequency of pair , | float[r/2] | |
| the rotation angle of pair at token | float | |
attn_scaling, YaRN’s factor on cos and sin (1 otherwise) | float | |
| the logistic sigmoid |
RMSNorm rescales a row to unit root mean square, then applies a learned gain:
In C that is one pass to accumulate in float32 in increasing , one call to tl_rsqrtf (Newton’s method) for , and one pass to write . Three properties follow. Because the order of the sum is fixed per row, a row’s result is the same whether the call normalizes 1 row or 64; that is batch invariance, ABI rule 10. Because the sum is complete before the first write, y == x works. And goes inside the root: a zero row then gives , never , and Llama’s checkpoints were trained that way.
RoPE rotates pairs of a query or key vector by an angle proportional to its position. Pair of token is rotated by :
A rotation keeps the pair’s length (times ), and the dot product of a query rotated by and a key rotated by depends only on , so attention sees relative position.
Three details of the contract decide whether you match a given checkpoint. The first is the layout, which says which entries form pair . Layout 0 (“half”, used by HF Llama and SmolLM2) pairs ; layout 1 (“interleaved”, used by Meta’s code and the RoPE paper) pairs . Both are the same rotation on a permuted vector, which is why HF’s conversion script permutes the rows of q_proj and k_proj. The second is partial rotary: only the first entries of each head rotate, and entries to pass through. The third is the angle, which is formed once per (token, pair) in double precision and rounded to float. That equals float32 float32 for every position below , the same angle the Python code computes. One angle serves all heads, so the loop order is token, pair, head.
Both members of a pair must be read before either is written; computing from the new is a different, and wrong, map.
SiLU-mul
Section titled “SiLU-mul”Llama’s MLP computes , and the middle step is elementwise:
Written this way it is safe at both ends. For , and . For , overflows to (tl_expf saturates above 88.7), and , the right limit. The algebraically equal computes at .
Embedding, add, and argmax
Section titled “Embedding, add, and argmax”The remaining three are short. Embedding copies row ids[t] of a [V, d] table, so the source starts at element ids[t] * d. The contract makes the caller check ids against , since the kernel cannot know . Add is the residual connection, , usually in place. Argmax picks the greedy token (temperature 0 in the sampling contract, spec/sampling.md): the largest value, the lowest index among equal values (a strict > while scanning forward), NaN entries skipped, and when there is no number at all, so the caller reports an error instead of emitting token 0.
Working it by hand
Section titled “Working it by hand”Each kernel has a small example that pins its definition.
For RMSNorm, take , , . Then , , and , so .
For RoPE in the half layout, take , , , position 1, and . The pairs are at and at :
| Pair | ||||
|---|---|---|---|---|
| , | 0.5403023 | 0.8414710 | ||
| , | 0.9999500 | 0.0099998 |
Written back to positions 0, 2 and 1, 3, the result is . With the interleaved layout the pairs are and , and the result is .
For SiLU-mul, take gate and up . Then , , and ; times up, .
For argmax, take . The value 7 first appears at index 1, and index 2 is not strictly greater, so the answer is 1.
A correct implementation reproduces all four to float32 precision.
The interface
Section titled “The interface”/* tinyllm/elementwise.h: void, the caller guarantees valid pointers and sizes */void tl_rmsnorm_f32(const float *x, const float *w, float *y, int64_t rows, int64_t d, float eps);void tl_rope_f32(float *x, const int32_t *pos, int64_t T, int64_t H, int64_t D, int64_t d_rot, const float *inv_freq, float attn_scaling, int layout /* 0 half, 1 interleaved */);void tl_silu_mul_f32(const float *gate, const float *up, float *y, int64_t n);void tl_embedding_f32(const float *table, const int32_t *ids, float *out, int64_t n, int64_t d);void tl_add_f32(const float *a, const float *b, float *y, int64_t n);int32_t tl_argmax_f32(const float *x, int64_t n); /* lowest index on ties; NaN skipped; -1 if none */From Python, declare each with restype None (or c_int32 for argmax) on the loader.
Building it step by step
Section titled “Building it step by step”Every kernel here reads each element once and does work with it, so the only performance requirement is a single pass with no temporaries. Correctness is the hard part, because each kernel has one detail that silently changes the model.
RMSNorm needs the full sum of squares before any output, so it is two passes over one row: accumulate, then scale. Since the first pass finishes before the second writes, y == x is safe. Keeping the accumulator per row and summing in increasing makes each row independent of the batch, and putting inside the root is the trained definition and makes a zero row give zeros. RoPE’s angle depends on (token, pair), not on the head, so computing cos and sin once per (token, pair) and looping heads innermost does the transcendental work times instead of . The layout only changes which two indices form pair ; the rotation is the same. And a rotation is a map of the pair as a whole, so both entries must be read into locals before either is overwritten.
SiLU must be written in the one form whose overflow lands on the right limit, : at the denominator becomes and the quotient . Argmax’s tie rule and NaN rule are part of the sampling contract, so that greedy outputs match Python and Rust exactly: strict >, skip NaN, when nothing is a number.
RMSNorm
Section titled “RMSNorm”The accumulator ss is declared inside the row loop, the division by happens before adding , and tl_rsqrtf gives the reciprocal root directly:
void tl_rmsnorm_f32(const float *x, const float *w, float *y, int64_t rows, int64_t d, float eps) { if (rows <= 0 || d <= 0) return; for (int64_t r = 0; r < rows; r++) { const float *xr = x + r * d; float *yr = y + r * d; float ss = 0.0f; /* per row: no batch dependence */ for (int64_t i = 0; i < d; i++) ss += xr[i] * xr[i]; /* fixed order, increasing i */ float inv = tl_rsqrtf(ss / (float)d + eps); /* mean of squares, eps INSIDE the root */ for (int64_t i = 0; i < d; i++) yr[i] = xr[i] * inv * w[i]; /* safe when y == x */ }}On the worked example’s row, ss = 25, ss / d = 12.5, and inv = 0.2828427.
The angle is formed in double and rounded once, so it equals the float32 product Python computes; attn_scaling is folded into c and s; and the layout picks the pair indices:
const int64_t half = d_rot / 2; /* pairs live inside d_rot only */ for (int64_t t = 0; t < T; t++) { for (int64_t i = 0; i < half; i++) { float angle = (float)((double)pos[t] * (double)inv_freq[i]); /* one rounding */ float c = (float)cos((double)angle) * attn_scaling; /* mu folded in */ float s = (float)sin((double)angle) * attn_scaling; for (int64_t h = 0; h < H; h++) { /* one angle, every head */ float *xh = x + (t * H + h) * D; /* [T, H, D] */ int64_t ia = layout ? 2 * i : i; /* interleaved: (2i, 2i+1) */ int64_t ib = layout ? 2 * i + 1 : i + half; /* half: (i, i + r/2) */ float a = xh[ia], b = xh[ib]; /* both read before either write */ xh[ia] = a * c - b * s; xh[ib] = a * s + b * c; } } }Entries from d_rot to D - 1 are never indexed, because the largest index is d_rot - 1 in both layouts. The partial-rotary tail therefore passes through untouched, and inv_freq is read only for i < d_rot / 2.
SiLU-mul, embedding, and add
Section titled “SiLU-mul, embedding, and add”These are one line each; what matters is the form of the SiLU and the row offset in the embedding:
y[i] = g / (1.0f + tl_expf(-g)) * up[i]; /* g -> -inf: g / inf = -0, never NaN */
memcpy(out + t * d, table + (int64_t)ids[t] * d, (size_t)d * sizeof(float)); /* row ids[t] */
for (int64_t i = 0; i < n; i++) y[i] = a[i] + b[i]; /* y may be a: element i read first */The cast (int64_t)ids[t] before multiplying matters: ids[t] * d in 32 bits would overflow for large vocabularies times width.
Argmax
Section titled “Argmax”best starts at (no number seen), NaN is skipped before comparing, and the comparison is strict:
int32_t tl_argmax_f32(const float *x, int64_t n) { int32_t best = -1; /* -1: empty or all NaN, caller reports the error */ for (int64_t i = 0; i < n; i++) { if (isnan(x[i])) continue; /* a NaN never wins, even in first place */ if (best < 0 || x[i] > x[best]) best = (int32_t)i; /* strict >: ties to lowest index */ } return best;}A row of all returns 0: is a number, so the first entry becomes best and nothing is strictly greater. The full solution is elementwise.c.
Why this design
Section titled “Why this design”Every kernel is time and extra space. RMSNorm reads each row twice, which is cheap because the row fits in cache, and RoPE does cos and sin evaluations.
Each choice has a rejected alternative. agrees on ordinary rows, but on tiny rows the result differs from what the model was trained with, and the zero-row case is no longer the clean . A precomputed cos/sin table per position is what production does and saves the transcendentals, but it needs memory sized by the maximum context and a cache policy; here the angle per (token, pair) is cheap relative to the head loop, and computing it directly keeps the kernel stateless. Computing sigmoid(g) as 1 / (1 + e^{-g}) and then multiplying by g is also safe, but the algebraically equal is not ( at ); the chosen form has one division and a correct limit at both ends. And argmax returns rather than 0 on an empty or all-NaN row because token 0 is a real token, and returning it would hide a numerical failure upstream as a plausible output.
What can go wrong
Section titled “What can go wrong”The tests pin each kernel’s one critical detail:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| the hand examples | unit | the worked examples for RMSNorm, RoPE, SiLU-mul, argmax | the definitions are the agreed ones |
| inside the root | boundary | with gives 0.7071; a zero row gives zeros | tiny-norm rows, Llama’s trained form |
| independent, in-place RMSNorm rows | property | every row alone equals the row in a batch of up to 12, bit for bit; y == x | batched decode in continuous batching |
| interleaved RoPE, position 0 | unit | the interleaved worked example; position 0 is the identity | loading Meta-layout weights |
| partial rotary and scaling | unit | the tail past d_rot untouched; doubles the pair; [T, H, D] indexing | GPT-NeoX style partial rotary, YaRN |
| RoPE is a rotation | property | every pair keeps its length, random shapes and positions, both layouts | no half-updated pairs, no wrong partners |
| SiLU saturates without NaN | boundary | gates , give the right limits | large activations in trained MLPs |
| embedding gathers rows | unit | repeated and out-of-order ids | the first op of the forward |
| add in place | unit | with y == a | the residual stream |
| argmax ties, NaN, empty | boundary | ties to the lowest index, NaN skipped, for all NaN or empty, all gives 0 | greedy decoding parity |
RMSNorm has four classic mistakes. Putting outside the root, , is correct on ordinary rows and wrong on tiny ones, so it drifts from the trained model; use tl_rsqrtf(ss / d + eps). Not dividing the sum of squares by shrinks every output by ; write ss / (float)d. Forgetting the gain gives the right shape at the wrong scale; multiply by w[i]. Declaring the sum of squares once per call instead of per row normalizes row 2 by rows 1 and 2 together, so results depend on the batch; declare float ss = 0.0f inside the row loop.
Warning: Swapping the RoPE layouts gives plausible numbers and the wrong attention pattern on HF weights. Layout 0 pairs ; layout 1 pairs .
RoPE has more. Rotating by (a sign flipped) mirrors relative positions and degrades the model’s outputs; the solution computes , . Computing from the new changes lengths, so it is not a rotation; read a and b into locals first. Rotating all entries when d_rot < D scrambles the pass-through tail and reads inv_freq past its end; index pairs only within d_rot. Ignoring attn_scaling makes YaRN-extended models lose their temperature correction; fold it into c and s.
The last group covers the other kernels. Writing SiLU as a plain sigmoid, or with instead of , gives the wrong MLP, or instead of at large gates; write g / (1 + tl_expf(-g)) * up. Reading the embedding row at ids[t] instead of ids[t] * d makes every token read a slice of row 0 or 1; use table + (int64_t)ids[t] * d. An argmax with >= sends ties to the last index, so greedy output differs from Python; use strict >. An argmax without the NaN check lets a NaN in first place win forever; skip with isnan before comparing. And returning 0 for an empty or all-NaN row makes the engine emit token 0 instead of reporting the error; start best at .
Where this leads
Section titled “Where this leads”These kernels rest on the shared status, error, and allocator support from the runtime support layer, on tl_rsqrtf for the of RMSNorm and tl_expf for the of SiLU from Mathematics, and on the Python specifications in Pre-LN and RMSNorm and RoPE. Looking forward, the Rust forward pass in the serving part of the book calls the same six operations in its own independent Rust implementation, starting with the model runner.
Production systems fuse these operations to save memory traffic:
| This solution | Production equivalent | What it adds | Where to look |
|---|---|---|---|
| separate RMSNorm and add | fused add + RMSNorm (vLLM fused_add_rms_norm) | one pass that adds the residual and normalizes, halving memory traffic | vLLM csrc/layernorm_kernels.cu |
RoPE with cos per call | cached cos/sin tables and fused QK rotation | precomputed tables per position, rotation fused into the QKV projection epilogue | llama.cpp ggml_rope_ext; FlashInfer rope.cuh |
| scalar SiLU | vectorized SwiGLU with a polynomial exp | SIMD over 8 or 16 lanes | ggml ggml_vec_swiglu_f32 |
| argmax | fused sampling kernels | argmax and top-k inside the final matmul’s epilogue | FlashInfer sampling.cuh |
Further reading
Section titled “Further reading”- Zhang and Sennrich, “Root Mean Square Layer Normalization” (2019).
- Su et al., “RoFormer” (2021), section 3.4.
- Shazeer, “GLU Variants Improve Transformer” (2020).
Key terms
Section titled “Key terms”- elementwise kernel: a kernel that reads each element once and does constant work with it, so it is bound by memory bandwidth.
- RMSNorm: normalization by followed by a learned per-channel gain.
- RoPE layout: the rule for which two entries of a head form a rotated pair: half or interleaved .
- partial rotary: rotating only the first entries of each head and passing the rest through.
- SiLU: , the activation in SwiGLU.
- greedy argmax: selecting the largest logit, with ties broken to the lowest index and NaN skipped.
Summary
Section titled “Summary”- Each kernel touches every element once, so it is bound by memory bandwidth, not arithmetic: one pass, no temporaries, and outputs that may alias their first input.
- RMSNorm puts inside the root, , and its sum of squares runs in a fixed order per row, so a row’s bits never depend on its batch.
- RoPE is a rotation of pairs, and which entries form a pair is the layout: for HF Llama, for Meta’s code; both members are read before either is written.
- SiLU saturates without NaN when written : at the exponential overflows to and the quotient is .
- Greedy argmax breaks ties to the lowest index and skips NaN, the rule the Python sampler and the Rust engine share.
Review questions
Section titled “Review questions”- Why is
y == xsafe for RMSNorm but would not be for a one-pass “running” normalization?Answer
The first loop finishes the sum of squares before the second loop writes anything, so overwriting $x_i$ cannot change `inv`. A one-pass scheme that wrote outputs while still accumulating would read some already-normalized values. - Why does the solution loop over heads innermost in RoPE?
Answer
The angle $p_t \omega_i$ does not depend on the head, so cos and sin are computed once per (token, pair) and reused across all $H$ heads. - What map do you get if is computed from the new ?
Answer
$b' = a'\sin\theta + b\cos\theta$, which is not the rotation: the pair's length changes and the dot products no longer depend only on the position difference. - Why is SiLU at equal to and not NaN in this code?
Answer
`tl_expf(10^4)` saturates to $+\infty$, so the denominator is $+\infty$ and $g / \infty = -0$. Then $-0 \cdot u$ is a signed zero, which is the correct limit of $g\,\sigma(g)$. - Why must argmax use strict
>?Answer
Scanning forward, `>=` would let a later equal value take over, sending ties to the highest index. The sampling contract says lowest index, and every engine must agree to produce the same greedy tokens. - In the RMSNorm test with and , why is each output (with ) about 0.7071 rather than 1?
Answer
$\overline{x^2} = 10^{-6}$, so the root is $\sqrt{10^{-6} + 10^{-6}} = \sqrt{2} \times 10^{-3}$ and $y = 10^{-3} / (\sqrt{2} \times 10^{-3}) = 1/\sqrt{2} \approx 0.7071$. With $\varepsilon$ outside the root the answer would be $10^{-3}/(10^{-3} + 10^{-6}) \approx 0.999$, which is why this test distinguishes the two forms.