C.W.K.
Stream
Lesson 07 of 07 · published

실전 — Custom Transformer block

~8 min · subclass

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

Transformer block: MultiHeadAttention + LayerNorm + FFN + LayerNorm + skip. Subclassed Layer 로 자연스럽게 짤 수 있어. __init__ 에 attn / ffn / norm 인스턴스, callx = norm1(x + attn(x)); x = norm2(x + ffn(x)) — pre-norm 또는 post-norm 골라.

이 block 한 개를 N 번 쌓으면 Transformer encoder. 본인 Subclass 라서 LoRA, sparse attention, RoPE 등 변형 자유로워. 외부 라이브러리 import 없이 paper-fresh idea 구현 가능.

Code

class <span class="dc">TransformerBlock</span>(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

vanilla Transformer encoder block 을 Subclassed Layer 로 구현. 4 개 쌓아. 작은 synthetic seq2seq task (예: sequence 뒤집기) 학습. 동작하는지 확인.

Progress

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

댓글 0

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

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