BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Attention and transformers6 of 23 in topic

396. GPT decoder: causal self-attention for one head

MediumAttention and transformers
Asked atAmazonAnthropicAppleByteDance

You are writing the attention layer of a small GPT-style decoder. During training the model reads a whole sentence at once and, at every position, predicts the next token. If position 3 could look at position 4, it would just copy the answer, and the model would learn nothing. The causal mask stops that: token i may attend only to tokens 0..i.

Write causal_attention(Q, K, V) for one attention head.
- Q and K have shape (seq_len, d_k). V has shape (seq_len, d_v). d_v can differ from d_k.
- Inputs can be NumPy arrays or nested Python lists. Convert with np.asarray(x, dtype=float).

Steps:
1. scores = Q @ K.T / sqrt(d_k). Scale by the query/key width, not the value width or the sequence length.
2. Set scores[i, j] to -inf wherever j > i (the future). Keep the diagonal: a token always sees itself.
3. Softmax each row. Subtract the row max first: trained models can produce scores in the hundreds, and exp(800) overflows.
4. Return weights @ V, shape (seq_len, d_v).

Edge cases: seq_len can be 1 (the output is V itself). Row 0 always equals V[0].

Functiondef causal_attention(Q, K, V)
Play with it

One query attending over four keys

Drag the query. Keys closer in direction to it get bigger weights after the softmax.

-202-4-2024k0k1k2k3queryoutput
k0: score 2.47
86.2%
k1: score 0.35
10.3%
k2: score -0.88
3.0%
k3: score -2.83
0.4%

Drag the query. Score = q·k / √2, weights = softmax of the scores, output = weighted average of the vectors (keys are used as values here). Example vectors, not from a model.

Example 1

Input: causal_attention([[1.0, 0.0], [1.0, 0.0]], [[1.0, 0.0], [1.0, 0.0]], [[1.0, 2.0], [3.0, 4.0]])

Output: [[1.0, 2.0], [2.0, 3.0]]

Explanation: Row 1 sees both keys equally, so it averages the two value rows.

Example 2

Input: Q = [[0.3, -1.2]], K = [[2.0, 0.5]], V = [[7.0, -1.0, 4.0]]

Output: [[7.0, -1.0, 4.0]]

Constraints

  • K has shape (seq_len, d_k)
  • V has shape (seq_len, d_v)
  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 8 tests to be accepted.
Hint 1

np.triu(ones, 1) marks the future positions.

Hint 2

Put -inf there before the row softmax.

Understand the idea

Attention lets each token build its output as a weighted average of value vectors, where the weights come from how well its query matches each key. In a language model a token must not peek at future tokens, like a student who may only read earlier pages of the exam. Worked example with d = 1 (so sqrt(d) = 1): Q = [[1], [1]], K = [[0], [2]], V = [[10], [20]]. Row 0 may only see itself, so its weight is 1 and its output is 10. Row 1 scores are 1*0 = 0 and 1*2 = 2. Softmax of [0, 2] is about [0.119, 0.881], so its output is 0.119*10 + 0.881*20 = 18.81.

scores = Q K^T / sqrt(d); set scores[i, j] = -inf when j > i; softmax each row after subtracting its max; output = weights V

Every decoder-only LLM such as GPT or Llama runs this inside each attention head.

Topics
Attention and transformersLLM architecture track
Companies11
  • Amazon a candidate reported this question Amazon Machine Learning Engineer Interview | Screna AI
  • Anthropic a candidate reported this question Anthropic: One-layer transformer in NumPy (CircleCoder)
  • Apple a candidate reported this question Apple Machine Learning Engineer Interview | Screna AI
  • ByteDance a candidate reported this question TikTok Machine Learning Engineer Interview (questions, process, prep)
  • DeepMind a candidate reported this question Google DeepMind interview guide (landedjobs/ai-interview-guides)
  • Google a candidate reported this question Google Interview Prep (Deep-ML)
  • Meta a candidate reported this question Meta Research Engineer Interview Guide (Dataford)
  • Microsoft a candidate reported this question Microsoft Senior Applied Scientist (L63) Interview Experience
  • Mistral the topic appears in interview reports Mistral AI Interview Guide 2026: European Frontier Lab, Open-Weight Strategy, MoE, and La Plateforme
  • OpenAI a candidate reported this question OpenAI Interview Process & Questions (2026) (TrueInterview)
  • Uber a candidate reported this question Uber Interview Questions — Page 13 | Screna AI

From public interview reports and guides. Not affiliated with or endorsed by these companies.

Similar questions
  • Split and merge attention headsMedium
  • Build the ALiBi attention bias for every headMedium
  • Apply a key padding mask in batched attentionMedium
  • Bucket relative positions like T5Medium
All Attention and transformers problems
Report
396 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
import numpy as np
​
def causal_attention(Q, K, V):
# your code here
pass
​
causal_attention(_Q, _K, _V)[0]

This case uses generated data, so it runs as written. Press + to add your own case.

Run checks these cases in your browser, no sign-in needed. Submit checks all 8 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS