Drill · 手撕

Drill: Attention from scratch

可运行的 from-scratch 实现 + 测试。目标:每一行都能在面试里推导和辩护。 Runnable from-scratch implementation with tests — derive and defend every line.

数学 / The math

注意力对一组 query 在一组 key-value 上做加权聚合:

Attn(Q,K,V)=softmax ⁣(QKdk)V\mathrm{Attn}(Q,K,V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V

复杂度 / Complexity

文件

python test_attention.py        # 或 python -m pytest test_attention.py

追问分层 / Stratified follow-ups