본문 바로가기
C.W.K.
Stream
Lesson 07 of 07 · published

실전 — 사용자 정의 Transformer 블록

~8 min · subclass

Level 0Keras 도제
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

트랙의 개념을 한 블록에 모아

이 Transformer 인코더 블록은 이 트랙에서 배운 내용을 한꺼번에 사용해. Layer를 상속하고 Dropout 하위 레이어에 training 값을 전달하며 Functional 모델에 기본 레이어처럼 넣을 수 있어. 내부에는 multi-head self-attention, 2층 feed-forward network, LayerNormalization 두 개, Dropout 두 개가 있고 call()에서 연결해.

두 하위 블록을 잔차 연결로 감싸

첫 하위 블록은 입력에 self-attention을 적용하고 결과를 원래 입력에 더해 out1 = norm1(inputs + attn_output)을 만들어. 이 건너뛰기 연결로 기울기가 Attention을 넘어 흐를 수 있어. 두 번째 하위 블록은 feed-forward network를 통과한 값에 자신의 입력을 다시 더해. 두 LayerNormalization은 각 블록을 안정시키고 잔차 연결은 여러 블록을 깊게 쌓아도 학습할 수 있게 해.

이 예제는 덧셈 뒤에 정규화하는 post-norm 방식이야. 현대 변형은 정규화를 하위 레이어 앞에 두는 pre-norm으로 깊은 모델의 학습을 더 안정시키기도 해. 이 블록을 N번 쌓으면 Transformer 인코더가 돼. 소스를 직접 갖고 있으므로 RoPE, sparse attention, LoRA 어댑터, grouped-query attention 같은 연구 변형도 외부 라이브러리를 갈라내지 않고 클래스 안에서 수정할 수 있어.

Code

Layer를 상속해 만든 Transformer 인코더 블록·python
class TransformerBlock(keras.layers.Layer):
    def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1, **kwargs):
        super().__init__(**kwargs)
        self.att = layers.MultiHeadAttention(
            num_heads=num_heads, key_dim=embed_dim
        )
        self.ffn = keras.Sequential([
            layers.Dense(ff_dim, activation="relu"),
            layers.Dense(embed_dim),
        ])
        self.norm1 = layers.LayerNormalization(epsilon=1e-6)
        self.norm2 = layers.LayerNormalization(epsilon=1e-6)
        self.dropout1 = layers.Dropout(rate)
        self.dropout2 = layers.Dropout(rate)

    def call(self, inputs, training=False):
        attn_output = self.att(inputs, inputs)
        attn_output = self.dropout1(attn_output, training=training)
        out1 = self.norm1(inputs + attn_output)
        ffn_output = self.ffn(out1)
        ffn_output = self.dropout2(ffn_output, training=training)
        return self.norm2(out1 + ffn_output)

External links

Exercise

기본 Transformer 인코더 블록을 Layer 상속으로 구현하고 네 개를 쌓아. 시퀀스 뒤집기 같은 작은 합성 seq2seq 과제로 학습해 동작을 확인해.

Progress

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

댓글 0

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

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