Blocos de Multi-Head Attention no transformer original.
Fonte: https://arxiv.org/abs/1706.03762.
Semelhante ao uso de múltiplos kernels em CNNs para gerar diferentes feature maps.
Multi-Head Attention. Fonte: The AI Edge.
Multi-Head Attention. Fonte: Jeremy Jordan.
import numpy as np
# Exemplos de embeddings para 4 palavras usando One-Hot Encoding
word_embeddings = {
'the': np.array([1, 0, 0]),
'cat': np.array([0, 1, 0]),
'sat': np.array([0, 0, 1]),
'on': np.array([1, 1, 0])
}
# Converte palavras em embeddings
def get_embedding(word):
return word_embeddings.get(word)
# Calcula os embeddings
sentence = ['the', 'cat', 'sat', 'on']
embeddings = np.array([get_embedding(word) for word in sentence])
print("Embeddings:\n", embeddings)
Fonte: https://kostyanuman.substack.com/p/understanding-the-attention-mechanism.
def softmax(x):
return np.exp(x) / np.sum(np.exp(x), axis=0)
def self_attention(embeddings):
# Calcula o produto escalar dos embeddings
scores = np.dot(embeddings, embeddings.T)
# Aplica a softmax para obter os pesos de atenção
attention_weights = softmax(scores)
# Calcula a soma ponderada dos embeddings
output = np.dot(attention_weights, embeddings)
return output, attention_weights
# Calcula a auto‑atenção
output, attention_weights = self_attention(embeddings)
print("Pesos de Atenção:\n", attention_weights)
print("Saída da Auto-Atenção:\n", output)
Fonte: https://kostyanuman.substack.com/p/understanding-the-attention-mechanism.
def multi_head_attention(embeddings, num_heads=2):
head_outputs = []
for _ in range(num_heads):
output, _ = self_attention(embeddings)
head_outputs.append(output)
# Concatena as saídas de todas as cabeças
return np.concatenate(head_outputs)
# Calcula a atenção multi‑cabeça
multi_head_output = multi_head_attention(embeddings)
print("Saída da Atenção Multi-Cabeça:\n", multi_head_output)
Fonte: https://kostyanuman.substack.com/p/understanding-the-attention-mechanism.
def feedforward_network(x):
# Rede feed‑forward simples com uma camada oculta
# Pesos da camada oculta
W1 = np.random.rand(x.shape[1], x.shape[1] * 2)
# Viéses da camada oculta
b1 = np.random.rand(x.shape[1] * 2)
# Pesos da camada de saída
W2 = np.random.rand(x.shape[1] * 2, x.shape[1])
# Viéses da camada de saída
b2 = np.random.rand(x.shape[1])
# Ativação ReLU
hidden_layer = np.maximum(0, np.dot(x, W1) + b1)
output_layer = np.dot(hidden_layer, W2) + b2
return output_layer
# Passa as features de MHA pela rede (FC)
final_output = feedforward_network(multi_head_output)
print("Saída Final:\n", final_output)
Fonte: https://kostyanuman.substack.com/p/understanding-the-attention-mechanism.
Multi-Head Attention. Fonte: Jeremy Jordan.