بتل کد Battle Codeدارد باز می‌شود…

A Word's New Meaning چالش 4 از جلسه‌ی 57، متوسط

تابع attend(Q, K, V) را کامل کن که وزن‌ها را با attention_weights (آماده است) بگیرد و معنی تازه‌ی همه‌ی کلمه‌ها را برگرداند: W @ V. خروجی سه خط: بردار قدیم it یعنی [0. 0. 1. 0.]، بردار تازه‌ی it یعنی [0.54 0.15 0.05 0.19] و بردار تازه‌ی cat یعنی [0.21 0.2 0.11 0.13].

import numpy as np

tokens = ["the", "cat", "drank", "the", "milk", "because", "it", "was", "thirsty"]
X = np.array([
    [0.0, 0.0, 0.0, 0.0],
    [1.0, 0.0, 0.0, 0.0],
    [0.3, 0.6, 0.0, 0.0],
    [0.0, 0.0, 0.0, 0.0],
    [0.0, 1.0, 0.0, 0.0],
    [0.0, 0.0, 0.0, 0.0],
    [0.0, 0.0, 1.0, 0.0],
    [0.0, 0.0, 0.0, 0.2],
    [0.6, 0.2, 0.0, 1.0],
])
Wq = np.zeros((4, 4))
Wq[2, 0] = 4.0
Q = X @ Wq
K = X @ np.eye(4)
V = X @ np.eye(4)


def attention_weights(Q, K):
    S = Q @ K.T / np.sqrt(Q.shape[1])
    e = np.exp(S)
    return e / e.sum(axis=1, keepdims=True)


def attend(Q, K, V):
    W = attention_weights(Q, K)
    # mix the values with the weights
    return None


out = attend(Q, K, V)
print(X[tokens.index("it")])
print(np.round(out[tokens.index("it")], 2))
print(np.round(out[tokens.index("cat")], 2))

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 57: توجه (attention) با مثال ساده · چالش بعدی: Two Heads

بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال