Lion Cipher Lab

Build scaled dot-product attention in NumPy, and prove the causal mask stops future leakage

Why it matters

Attention is the part of a transformer that decides which earlier tokens each token reads from, and almost every language model a security team touches is built on it. Most people only ever call it through a library, so its two most common bugs stay invisible. A causal mask written slightly wrong lets the model read the future while it trains. Nothing crashes. The training numbers just look better than they should, and the model gets worse when it is used for real. A padding mask written slightly wrong makes a log line's result depend on how long its neighbour in the batch was. In this lab…

What you'll learn

Steps in this lab

  1. The words first: tokens, embeddings, query, key, value, softmax, heads, masks - and what is random here
  2. Open a terminal, make a folder, install NumPy and SciPy
  3. Write attention.py from the paper's equations, and logdata.py for the synthetic log lines
  4. Softmax overflows unless you subtract the maximum - then four sanity checks before trusting the code
  5. OPTIONAL: check your attention against PyTorch's scaled_dot_product_attention
  6. Why divide by sqrt(d_k): measure saturation and the vanishing gradient with and without it
  7. Prove the causal mask: change a future token and measure the past - then catch four mask bugs
  8. What future leakage does to a model's numbers: it looks better in training and is worse in use
  9. Padding masks on a batch of log lines - and the two places the mask is not enough
  10. Honest negative 1: attention weights are not an explanation - two different patterns, one output
  11. Honest negative 2: the n x n score matrix - time it from 128 to 4,096 tokens, then tile it
  12. Do it better: what a pro checks in any attention code, when to write your own, and clean up

Open the full interactive lab →