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

실전 — Custom Attention layer

~8 min · layers

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

Subclassed Layer + keras.ops 만 써서 attention 직접 짜. __init__ 에 num_heads / key_dim, build 에 q/k/v 의 weight, call 에 q/k/v 계산 → softmax(qk^T/sqrt(d)) → ·v → 최종 projection. 약 80 줄로 multi-head attention 완성.

이 layer 는 portable — keras.ops 만 써서 세 backend 다 동작. 본인이 짠 attention 의 weight 가 model.fit() 으로 학습되는 거 보면 *내 손으로* attention 만든 느낌이 와.

Code

class <span class="dc">SimpleAttention</span>(keras.layers.Layer):
    def __init__(self, units, **kwargs):
        super().__init__(**kwargs)
        self.units = units

    def build(self, input_shape):
        self.W_q = self.add_weight(
            shape=(input_shape[-1], self.units), name="query_weight"
        )
        self.W_k = self.add_weight(
            shape=(input_shape[-1], self.units), name="key_weight"
        )
        self.W_v = self.add_weight(
            shape=(input_shape[-1], self.units), name="value_weight"
        )

    def call(self, inputs):
        q = keras.ops.matmul(inputs, self.W_q)
        k = keras.ops.matmul(inputs, self.W_k)
        v = keras.ops.matmul(inputs, self.W_v)

        # Scaled dot-product attention
        scale = keras.ops.sqrt(
            keras.ops.cast(self.units, dtype="float32")
        )
        scores = keras.ops.matmul(q, keras.ops.transpose(k)) / scale
        weights = keras.ops.nn.softmax(scores)
        return keras.ops.matmul(weights, v)

External links

Exercise

keras.ops 만 써서 multi-head self-attention 을 Subclassed Layer 로 처음부터 구현. 같은 weight 로 keras.layers.MultiHeadAttention 과 출력이 tolerance 안에서 일치하는지 확인.

Progress

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

댓글 0

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

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