One Number Defines a Rung
Part I of Cartesia's "From Tokens to Bytes" builds its BPE Transformer ladder so that the depth L fixes everything else, and counts only causal attention FLOPs. Implement the ladder and our FLOPs count.
ladder_rung(L, vocab=128000)
- Raise
ValueError if L < 1.
- Hidden size D: the multiple of 128 nearest to 75L. When 75L sits exactly halfway between two multiples, round up.
- Heads: L, each of dimension 128, so the attention width is dattn=128L (one key/value head per query head).
- FFN (SwiGLU intermediate size) F: the multiple of 128 nearest to 3.6D.
- Backbone parameters: L⋅(4⋅D⋅dattn+3⋅D⋅F) (Q, K, V, O plus three SwiGLU matrices; norms ignored).
- Total parameters: backbone +2⋅vocab⋅D (untied embedding and output head).
- Return a dict with keys
"layers", "d_model", "heads", "head_dim", "ffn", "backbone_params", "total_params" (all ints).
forward_flops_per_token(L, seq_len, causal=True, vocab=128000)
- Matrix multiplies cost 2 FLOPs per multiply-add. Count 2⋅(backbone+vocab⋅D) for the backbone and output head (the embedding lookup is free).
- Add the attention scores, averaged over the
seq_len =T positions of a sequence. Causal: position t (0-indexed) attends to t+1 keys, which costs 4dattn(t+1) per layer for QK⊤ and AV, an average of 2dattn(T+1) per token per layer. Non-causal: 4dattnT per token per layer.
- Return an
int.
flops_per_byte(L, seq_len, bytes_per_token, causal=True, train=False, vocab=128000)
- Forward FLOPs per token divided by
bytes_per_token, as a float. With train=True, count training as 3 times the forward pass.
Hints
- Watch the attention width: it is 128L, not D.
round() in Python sends halves to the even neighbour, which is not the tie rule here.