Train an attention-based next-token model
Wire a training step through a tiny causal attention model.
What’s going wrong
Original LLM Architecture lab. Implement the missing behavior in solve(data) and keep the supplied JSON interface. Use Python’s standard library.
Input x is a nonempty sequence of fixed token vectors. q, k and v are D×H projection matrices, head is H×V, targets supplies one next-token class or −1 per position, and lr is the SGD rate. Project x into Q, K and V, apply causal scaled dot-product attention, project into vocabulary logits, and compute mean cross-entropy on valid targets. Differentiate through the head and attention using the supplied attention_grad helper. Return pre-update loss and logits plus updated q, k, v and head. No residual or FFN in this training fixture.
Small, well-formed JSON inputs and standard-library Python arithmetic. Keep full precision during computation. The supplied output wrapper rounds results to six decimal places.
Expected behavior
Wire a training step through a tiny causal attention model.
Reproduction
{"x":[[1,2],[2,1]],"q":[[1,0],[0,1]],"k":[[1,0],[0,1]],"v":[[1,0],[0,1]],"head":[[1,0],[0,1]],"targets":[0,1],"lr":0.1}{"loss":1.095256,"logits":[[1,2],[1.669762,1.330238]],"head":[[0.98779,0.01221],[0.034258,0.965742]],"q":[[0.98173,0.01827],[-0.009135,1.009135]],"k":[[0.98173,-0.009135],[0.01827,1.009135]],"v":[[0.98779,0.01221],[0.034258,0.965742]]}{"x":[[1,2],[2,1]],"q":[[1,0],[0,1]],"k":[[1,0],[0,1]],"v":[[1,0],[0,1]],"head":[[1,0],[0,1]],"targets":[-1,-1],"lr":0.1}{"loss":0,"logits":[[1,2],[1.669762,1.330238]],"head":[[1,0],[0,1]],"q":[[1,0],[0,1]],"k":[[1,0],[0,1]],"v":[[1,0],[0,1]]}{"x":[[1,2]],"q":[[1,0],[0,1]],"k":[[1,0],[0,1]],"v":[[1,0],[0,1]],"head":[[1,0],[0,1]],"targets":[0],"lr":0.1}{"loss":1.313262,"logits":[[1,2]],"head":[[1.073106,-0.073106],[0.146212,0.853788]],"q":[[1,0],[0,1]],"k":[[1,0],[0,1]],"v":[[1.073106,-0.073106],[0.146212,0.853788]]}Before you begin
- Python functions, lists and dictionaries
Need a nudge?
Reveal one investigation hint at a time. Try each clue before opening the next.
Read the report, then sign in to start your investigation.