← 문제 목록/Scaled Dot-Product Attention Scores [medium]
문제 해설

Scaled Dot-Product Attention Scores [medium]

선형대수 · medium

preview

Scaled Dot-Product Attention Scores [medium]

v1 batched outer 는 각 샘플의 outer product. 실제 트랜스포머에서 더 자주 등장하는 것은 attention score:

S[b,i,j]=Qb,i,:Kb,j,:dS[b, i, j] = \frac{Q_{b, i, :} \cdot K_{b, j, :}}{\sqrt{d}}

  • QQ shape (B, L_q, d): 쿼리 (각 위치별 벡터)
  • KK shape (B, L_k, d): 키
  • 결과 SS shape (B, L_q, L_k): 모든 query·key 쌍의 scaled inner product.

Softmax 적용 전 단계. 이 점수에 소프트맥스를 씌우면 attention weight 가 된다 (다른 문제에서 다룸).

왜 scale 하나?

dd 가 클수록 dot product 의 분산이 dd 에 비례해 커짐. Softmax 는 큰 값에서 saturation 됨 → gradient 가 사라짐. 1/d1/\sqrt{d} 로 나누면 분산이 O(1)O(1) 로 유지 → 안정적 학습 (Vaswani et al. 2017, "Attention is All You Need").

효율 구현

명시적 루프 없이 한 줄:

scores = Q @ K.transpose(0, 2, 1) / np.sqrt(d)

(B, L_q, d) @ (B, d, L_k) = (B, L_q, L_k) — numpy 의 배치 행렬곱 자연 지원.

과제

함수 attention_scores(Q, K) 를 완성하세요.

  • 반환: shape (B, L_q, L_k).
  • 힌트: Q @ K.swapaxes(-1, -2) / np.sqrt(d)swapaxes 또는 transpose.

테스트 케이스

#이름검증
1shape (B, L_q, L_k)
2Q=K (self-attention) → 대각이 max
3QiQiQ_i \cdot Q_i 가 양수 (self-similarity)
4수치: 손계산 가능한 toy
5B=1, L_q=1, L_k=1 → 스칼라 (B, 1, 1)
6scale 효과: dd 커져도 output 분산 안정
7einsum 'bqd,bkd->bqk' 와 일치 (scale 적용 후)
코드 작성
Loading...
실행 결과

코드를 작성하고 Run 을 눌러보세요.