딥러닝의 발전으로 인해 자연어 처리(NLP)와 같은 분야에서 혁신적인 모델들이 등장하고 있습니다. 그 중에서도 트랜스포머(Transformer) 모델은 self-attention 메커니즘을 통해 놀라운 성능을 보여주고 있습니다. 이번 포스트에서는 self-attention의 기본 개념과 원리를 설명하고, 그 중요성을 살펴보겠습니다.

1. Self-Attention의 기본 개념 🧠
Self-Attention은 입력 시퀀스의 각 요소가 다른 모든 요소와 상호작용하여 중요한 정보를 학습할 수 있게 하는 메커니즘입니다. 이는 각 단어(토큰)가 문맥(context)을 이해하고, 해당 문맥 내에서 자신이 얼마나 중요한지를 결정할 수 있게 합니다.
- 입력 시퀀스: 예를 들어, 문장 "The cat sat on the mat"가 입력 시퀀스라면, 각 단어는 시퀀스 내의 다른 모든 단어와 관계를 형성합니다.
 - 어텐션 스코어(Attention Score): 각 단어 쌍 간의 유사도를 계산하여 어텐션 스코어를 만듭니다.
 - 어텐션 가중치(Attention Weight): 어텐션 스코어를 정규화하여 각 단어의 중요도를 나타내는 가중치를 만듭니다.
 
2. Self-Attention의 수학적 원리 📐
Self-Attention은 다음과 같은 순서로 동작합니다.
1. 쿼리(Query), 키(Key), 밸류(Value): 입력 벡터 XX에서 쿼리 QQ, 키 KK, 밸류 VV를 생성합니다.

2. 어텐션 스코어(Attention Score): 쿼리와 키의 내적(dot product)을 통해 어텐션 스코어를 계산합니다.

3. 어텐션 가중치(Attention Weight): 소프트맥스(softmax) 함수를 통해 어텐션 스코어를 정규화하여 가중치를 계산합니다.
4. 출력(Output): 가중치와 밸류의 가중합을 통해 최종 출력을 생성합니다.
3. Self-Attention의 중요성 🌟
Self-Attention은 여러 가지 장점을 가지고 있습니다.
- 병렬 처리: Self-Attention은 순차적이지 않기 때문에 병렬 처리가 가능합니다. 이는 모델의 학습 속도를 크게 향상시킵니다.
 - 긴 시퀀스 처리: Self-Attention은 긴 시퀀스에서도 중요한 정보를 효과적으로 학습할 수 있습니다.
 - 유연성: 다양한 입력 길이에 대해 유연하게 적용될 수 있습니다.
 
4. Self-Attention의 실제 활용 예제 📊
트랜스포머 모델은 Self-Attention 메커니즘을 활용하여 놀라운 성능을 발휘합니다. 여기서는 Self-Attention을 활용한 간단한 트랜스포머 인코더 블록을 구현해보겠습니다.
import tensorflow as tf
from tensorflow.keras.layers import Dense, LayerNormalization
class MultiHeadSelfAttention(tf.keras.layers.Layer):
    def __init__(self, d_model, num_heads):
        super(MultiHeadSelfAttention, self).__init__()
        self.num_heads = num_heads
        self.d_model = d_model
        assert d_model % self.num_heads == 0
        self.depth = d_model // self.num_heads
        self.wq = Dense(d_model)
        self.wk = Dense(d_model)
        self.wv = Dense(d_model)
        self.dense = Dense(d_model)
    def split_heads(self, x, batch_size):
        x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))
        return tf.transpose(x, perm=[0, 2, 1, 3])
    def call(self, v, k, q, mask):
        batch_size = tf.shape(q)[0]
        q = self.wq(q)  # (batch_size, seq_len, d_model)
        k = self.wk(k)  # (batch_size, seq_len, d_model)
        v = self.wv(v)  # (batch_size, seq_len, d_model)
        q = self.split_heads(q, batch_size)  # (batch_size, num_heads, seq_len_q, depth)
        k = self.split_heads(k, batch_size)  # (batch_size, num_heads, seq_len_k, depth)
        v = self.split_heads(v, batch_size)  # (batch_size, num_heads, seq_len_v, depth)
        scaled_attention, attention_weights = self.scaled_dot_product_attention(q, k, v, mask)
        scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3])  # (batch_size, seq_len_q, num_heads, depth)
        concat_attention = tf.reshape(scaled_attention, (batch_size, -1, self.d_model))  # (batch_size, seq_len_q, d_model)
        output = self.dense(concat_attention)  # (batch_size, seq_len_q, d_model)
        return output, attention_weights
    def scaled_dot_product_attention(self, q, k, v, mask):
        matmul_qk = tf.matmul(q, k, transpose_b=True)  # (..., seq_len_q, seq_len_k)
        dk = tf.cast(tf.shape(k)[-1], tf.float32)
        scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)
        if mask is not None:
            scaled_attention_logits += (mask * -1e9)
        attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1)
        output = tf.matmul(attention_weights, v)  # (..., seq_len_q, depth_v)
        return output, attention_weights
Self-Attention 메커니즘은 트랜스포머 모델의 핵심 구성 요소로, 병렬 처리, 긴 시퀀스 처리, 유연성 등 여러 장점을 가지고 있습니다. 이를 통해 자연어 처리, 번역, 텍스트 생성 등 다양한 분야에서 혁신적인 성능을 발휘할 수 있습니다. 이번 포스트에서는 Self-Attention의 기본 개념과 동작 원리를 살펴보았습니다. 다음 포스트에서도 더 흥미로운 주제로 찾아뵙겠습니다.
'데이터사이언스(Data Science) > ML & DL' 카테고리의 다른 글
| 머신러닝 알고리즘 가이드: 종류와 강점, 약점 분석 📊 (3) | 2024.12.29 | 
|---|---|
| [머신러닝] 머신러닝 성능 200% 올리는 비법! 🤖✨ 피처 엔지니어링 꿀팁 공개! (1) | 2024.12.08 | 
| [Deep Learning] LSTM (Long Short-Term Memory) 이해하기 📘🤖 (1) | 2024.06.12 | 
| [Deep Learning] 딥러닝 RNN (Recurrent Neural Network)의 기초 이해하기 (1) | 2024.06.11 | 
| [Deep Learning] 딥러닝 다중 라벨 분류의 손실 함수: Binary Cross-Entropy (2) | 2024.05.31 |