The Wayback Machine - https://web.archive.org/web/20261119014047/https://www.geeksforgeeks.org/artificial-intelligence/ml-attention-mechanism/

Attention Mechanism in ML

Last Updated : 22 Oct, 2026

The attention mechanism allows models to focus on the most important parts of input data by assigning different weights to different elements. This helps prioritize relevant information instead of treating everything equally and forms the core of models like Transformers and BERT.

frame_4008
  • It improves how models handle long sequences in data.
  • It helps capture relationships between distant elements in a sequence.

Types

  • Soft Attention: A differentiable mechanism that assigns continuous weights to input elements, typically using softmax. It is widely used in NLP and Transformer-based models.
  • Hard Attention: A non-differentiable approach that selects specific input parts, often using sampling and specialized training methods such as reinforcement learning.
  • Self-Attention: Enables each input element to attend to other elements in the same sequence.
  • Multi-Head Attention: Uses multiple attention heads to capture different relationships from different representation subspaces.
  • Additive Attention: Uses a feed-forward neural network to calculate attention scores instead of directly using dot-product similarity.

Working

Step 1: Input Encoding

In an encoder-decoder attention setup, the input sequence is first processed by an encoder such as an RNN, LSTM or GRU to generate hidden states representing the input context. In Transformer-based attention, the input embeddings are instead transformed directly into queries, keys and values.

Step 2: Query, Key and Value Vectors

Each input representation is transformed into:

  • Query (Q): Represents what information the model is looking for.
  • Key (K): Represents the features used to determine how relevant each input element is.
  • Value (V): Contains the information that is aggregated based on the attention weights.

These vectors are obtained through learned linear transformations of the input representations.

Step 3: Similarity Computation

The model computes a similarity score between the query and each key to determine the relevance of each input element. Common approaches include dot product, scaled dot product and additive scoring.

For scaled dot-product attention:

\mathrm{Score}(Q,K) = \frac{QK^{\top}}{\sqrt{d_k}}

Where:

  • Q: Query matrix
  • K: Key matrix
  • dₖ: Dimension of the key vectors

Step 4: Attention Weights Calculation: The similarity scores are passed through a softmax function to convert them into normalized attention weights:

α = softmax (Score(Q,K))

These weights indicate the relative importance assigned to each input element.

Step 5: Weighted Sum: The attention weights are used to compute a weighted sum of the value vectors:

C = \sum_i \alpha_i V_i

Here:

  • C: Context or attention output
  • αᵢ: Attention weight for the i-th input
  • Vᵢ: Value vector of the i-th input

Step 6: Context Vector: The resulting context vector summarizes the information emphasized by the attention mechanism and is passed to subsequent layers or, in encoder-decoder models, to the decoder.

Step 7: Output Generation: In an encoder-decoder model, the decoder combines the attention output with its current state to generate the next output token. In self-attention, the attention output is passed to subsequent layers of the model.

Architecture

Attention is a mechanism used within architectures like encoder-decoder models to improve how information is processed. It works alongside components such as the encoder and decoder by helping the model focus on the most relevant parts of the input.

string_constant_pool_5
Encoder-Decoder with Attention

1. Encoder

The Encoder processes the input sequence like a sentence and converts it into a series of hidden states that represent contextual information about each token.

  • It typically uses RNNs, LSTMs, GRUs or Transformer-based architectures.
  • For a sequence of inputs x0, x1, x2, x3, the encoder generates hidden representations:

h0 , h1 , h2 , h3

  • Each hidden state captures both the current input and information from previous time steps:

h_t =f(h_{t-1},x_t)

  • These hidden states are then passed to the attention layer to calculate which parts of the input are most relevant to the current output step.

2. Attention Mechanism

The Attention component determines how much importance should be given to each encoder hidden state when generating a particular word in the output. Its main goal is to create a context vector C_t ​, which captures the most relevant information from the encoder outputs for the current decoding step.

Step 1: Alignment Score: The decoder's current hidden state S_{t} and each encoder hidden state h_{i} are used to compute alignment scores e_{t, i}:

e_{t,i}=g(S_t,h_i )

Here:

  • S_t ​: decoder hidden state at time step t
  • h_i​: encoder hidden state for input token i
  • g: Scoring function that computes the alignment score

The scoring function can use approaches such as additive attention or dot-product attention.

Step 2: Softmax Normalization: The alignment scores are normalized using a softmax function to produce attention weights \alpha_{t,i }​:

\alpha_{t,i} = \frac{\exp(e_{t,i})}{\sum_{k=1}^{T_s} \exp(e_{t,k})}

Here:

  • \alpha_{t,i}: Attention weight indicating the importance of encoder position i.
  • T_s :​ Total number of source tokens.

Step 3: Context Vector Generation: Once attention weights are obtained, they are used to compute a weighted sum of encoder hidden states, forming the context vector C_t :

C_t = \sum_{i=1}^{T_s} \alpha_{t,i} \, h_i

Here:

  • C_t : context vector summarizing encoder outputs
  • \alpha_{t,i}: attention weights
  • h_i : encoder hidden states

This vector represents the most relevant information from the input sentence needed to predict the next output word.

3. Decoder

The Decoder uses both the context vector C_t ​ from the attention layer and its own previous hidden state S_t to generate the next output word.

At each decoding step:

  1. The decoder receives C_t ​ and the previous predicted word.
  2. It produces a new hidden state S_{t+1} and predicts the next token.
  3. This process repeats for each word in the target sequence.

Mathematically:

y_t =\text{Decoder}(y_{t-1},S_t,C_t)

Here:

  • y_{t-1}​: previously generated token
  • S_t : decoder hidden state
  • C_t ​: context vector

This allows the decoder to focus on different parts of the source sequence at each decoding step.

Improvement Using Attention Mechanism

Traditional deep learning models like RNNs, LSTMs and CNNs have limitations when handling long or complex dependencies. The attention mechanism enhances their effectiveness as follows:

  • RNNs/LSTMs: These models compress the entire input into one vector, causing information loss over long sequences. Attention dynamically focuses on the relevant parts, resolving long-term dependency issues.
  • CNNs: They have fixed receptive fields and attention enables global dependencies, helping capture relationships beyond local patterns.
  • Seq2Seq Models: Replace single context vectors with multiple dynamic ones, improving translation accuracy.
  • General Advantage: Helps assign different importance weights to inputs, avoiding equal treatment of all tokens or features.
  • Transformers: Attention is the core mechanism in Transformers through self-attention, this removes sequential processing limitations of RNNs which improves efficiency and scalability.

Implementation in Python

Step 1: Define the Attention Class

  • self.attn: transforms combined decoder hidden state and encoder outputs into an intermediate energy vector
  • self.v: converts the energy vector into a single score for each time step
  • hidden.unsqueeze().repeat(): aligns decoder hidden state with all encoder time steps
  • torch.bmm(v, energy): computes attention scores
  • softmax: converts scores into attention weights (probabilities)
  • torch.bmm(...): generates the context vector as a weighted sum of encoder outputs
Python
import torch
import torch.nn as nn
import torch.nn.functional as F


class Attention(nn.Module):
    def __init__(self, hidden_dim):
        super(Attention, self).__init__()
        self.attn = nn.Linear(hidden_dim * 2, hidden_dim)
        self.v = nn.Parameter(torch.rand(hidden_dim))

    def forward(self, hidden, encoder_outputs):
        batch_size = encoder_outputs.shape[0]
        seq_len = encoder_outputs.shape[1]
        hidden = hidden.unsqueeze(1).repeat(1, seq_len, 1)
        energy = torch.tanh(
            self.attn(torch.cat((hidden, encoder_outputs), dim=2)))
        energy = energy.permute(0, 2, 1)
        v = self.v.repeat(batch_size, 1).unsqueeze(1)
        attention_scores = torch.bmm(v, energy).squeeze(1)
        attention_weights = F.softmax(attention_scores, dim=1)
        context = torch.bmm(attention_weights.unsqueeze(1), encoder_outputs)
        return context, attention_weights

Step 2: Create Sample Input

  • torch.manual_seed(0): makes the random tensors deterministic so outputs are repeatable.
  • encoder_outputs: stands in for the sequence of encoder hidden states.
  • decoder_hidden: the current decoder hidden state used as the Query to compute attention.
Python
torch.manual_seed(0)

batch_size = 1
seq_len = 4
hidden_dim = 8
encoder_outputs = torch.randn(batch_size, seq_len, hidden_dim)
decoder_hidden = torch.randn(batch_size, hidden_dim)

Step 3: Initialize and Run Attention

Attention(hidden_dim): constructs the attention module with the chosen hidden dimension.

Calling the module returns:

  • context: the context vector of shape [batch, 1, hidden_dim].
  • attn_weights: the attention distribution over the seq_len encoder steps (shape [batch, seq_len]).
Python
attention = Attention(hidden_dim)
context, attn_weights = attention(decoder_hidden, encoder_outputs)

Step 4: Inspect Result

  • Inspecting attn_weights shows which encoder positions the module focused on (values sum to 1 across the sequence).
  • context is the weighted sum of encoder outputs which we will pass into the decoder to inform the next prediction.
Python
print("Encoder Outputs:\n", encoder_outputs)
print("\nDecoder Hidden State:\n", decoder_hidden)
print("\nAttention Weights:\n", attn_weights)
print("\nContext Vector:\n", context)

Output:

Screenshot-2025-10-28-145011
Result

You can download source code from here.

Applications

  • Machine Translation: Focuses on relevant words while generating each output word.
  • Text Summarization: Helps identify important information for generating concise summaries.
  • Image Captioning: Attends to relevant image regions when generating descriptions.
  • Sentiment Analysis and NER: Helps assign greater weight to important words or entities.
  • Speech Recognition: Focuses on relevant audio frames during transcription.

Limitations

  • Computationally expensive for long sequences, especially in standard self-attention.
  • Standard self-attention has quadratic time and memory complexity with respect to sequence length.
  • Attention weights do not always provide a reliable explanation of model decisions.
  • Large attention-based models can require substantial computational resources and training data.
Comment

Explore