C.W.K.
Stream
Lesson 01 of 13 · published

직관 — attention은 soft dictionary lookup

~12 min · intuition, attention, qkv

Level 0Token
0 XP0/94 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

attention에 대한 가장 깔끔한 한 줄: soft하고 미분 가능한 dictionary lookup이다. 보통 Python dict는 exact key를 exact value로 매핑 — hit 아니면 miss. attention은 이걸 일반화해. 각 토큰이 query를 제시, context의 모든 토큰이 keyvalue를 제시, 출력은 모든 value의 가중합, query-key similarity로 가중.

이 한 수가 세 가지를 동시에 사: 미분 가능(학습 중 gradient 흐름), 병렬(n × n similarity 행렬을 단일 matmul로), 관계적(동사가 주어를 찾는 같은 연산이 대명사가 선행사를 찾는 것도 가능하게).

구성 요소 셋, 역할 셋

  • Query (Q): "지금 내가 뭘 찾고 있나?" — 묻는 토큰에서 생성.
  • Key (K): "나는 어떤 종류의 정보냐?" — 보이는 각 토큰에서 생성.
  • Value (V): "내가 attend되면 어떤 정보를 제공하냐?" — 마찬가지로 보이는 각 토큰에서 생성, 단 K와 달라도 됨.

왜 K와 V가 다를 수 있나: 매칭 기준("이 토큰이 내가 원하는 건가?")이 일단 보기로 결정한 뒤 추출하고 싶은 정보랑 다를 수 있어. K는 lookup signature, V는 payload. 분리하면 모델 표현력 증가.

Code

Attention as a soft dictionary·python
import torch, torch.nn.functional as F

def soft_lookup(query, keys, values, temperature=1.0):
    # query: (d,)
    # keys, values: (n, d)
    scores = (keys @ query) / temperature       # (n,)
    weights = F.softmax(scores, dim=-1)          # (n,) sum to 1
    return weights @ values                      # (d,)

# Hard dict: 'paris' returns France only.
# Soft dict: 'paris' returns 0.9 * France + 0.05 * Berlin + 0.05 * Rome
# (the 'paris' query embedding is closest to France's key embedding).

External links

Exercise

코드 스니펫대로 soft_lookup 구현, 그 다음 작은 합성 예제로 테스트 — '문서' 4개(랜덤 벡터), document 2와 90% 비슷하고 document 0과 10% 비슷한 query. 출력이 대략 0.9 * V[2] + 0.1 * V[0](softmax 후)인지 검증. 그 다음 temperature=0.1이랑 temperature=10 시도. 뭐가 변하나?

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.