Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Attention Mechanism

Attention Mechanism

The attention mechanism (Attention Mechanism) is an important technique in deep learning that mimics the way attention is allocated in human visual and cognitive processes. Just as you unconsciously focus your attention on keywords when reading, the attention mechanism enables neural networks to dynamically focus on the most relevant parts of the input data.

Basic concepts

The core idea of the attention mechanism is:Dynamically assign different weights according to the importance of different parts of the input to the current task. This weight assignment is not fixed but is dynamically computed based on the context.

Mathematical Expression

The attention mechanism can usually be expressed as:

Attention(Q, K, V) = softmax(QK^T/√d_k)V

Where:

Why do we need the attention mechanism?

  1. Solve the long-range dependency problem: traditional RNNs struggle to capture relationships between distant words
  2. Parallel computing capability: compared with the sequential processing of RNNs, attention can be computed in parallel
  3. Interpretability: attention weights can intuitively show what the model focuses on

Self-Attention Mechanism (Self-Attention)

Self-attention is a special form of the attention mechanism that allows each element in the input sequence to establish connections with all other elements in the sequence.

How It Works

  1. For each element in the input sequence, compute its similarity score with all elements
  2. Use the softmax function to convert these scores into weights (between 0 and 1)
  3. Use these weights to compute a weighted sum of the corresponding values to obtain the output

Example

Simplified self-attention implementation example

import

torch

import

torch.

nn

.

functional

as

F

def

self_attention

(

query

,

key

,

value

)

:

    scores

=

torch.

matmul

(

query

,

key.

transpose

(

2

,

1

)

)

/

(

query.

size

(

1

)

**

0.5

)

    weights

=

F.

softmax

(

scores

,

dim

=

1

)

   

return

torch.

matmul

(

weights

,

value

)

Advantages of self-attention

  1. Global context awareness: every position can directly access information from all positions in the sequence
  2. Position independence: does not depend on sequence order, suitable for processing various structured data
  3. Efficient computation: compared with the O(n) complexity of RNNs, self-attention can be computed in parallel

Multi-Head Attention

Multi-head attention is an extension of self-attention that runs the attention mechanism multiple times in parallel and then concatenates the results.

Structural components

  1. Multiple attention heads: typically uses 8 or more parallel attention heads
  2. Linear transformation layers: each head has its own Q, K, V transformation matrices
  3. Concatenation and output: concatenate the outputs of each head and pass them through a linear layer

Advantages of multi-head attention

  1. Capture different relationships: each head can learn to focus on different aspects of relationships
  2. Enhanced expressive power: stronger feature extraction capability than single-head attention
  3. Stable training: the combination of multiple heads can reduce the model's reliance on specific patterns

Example

Multi-head attention implementation example

class

MultiHeadAttention

(

nn.

Module

)

:

   

def

init

(

self

,

d_model

,

num_heads

)

:

       

super

(

)

.

init

(

)

       

self

.

d_model

=

d_model

       

self

.

num_heads

=

num_heads

       

self

.

d_k

=

d_model // num_heads

       

       

self

.

W_q

=

nn.

Linear

(

d_model

,

d_model

)

       

self

.

W_k

=

nn.

Linear

(

d_model

,

d_model

)

       

self

.

W_v

=

nn.

Linear

(

d_model

,

d_model

)

       

self

.

W_o

=

nn.

Linear

(

d_model

,

d_model

)

   

   

def

forward

(

self

,

query

,

key

,

value

)

:

        batch_size

=

query.

size

(

0

)

       

       

Linear transformation and splitting into multiple heads

        Q

=

self

.

W_q

(

query

)

.

view

(

batch_size

,

1

,

self

.

num_heads

,

self

.

d_k

)

        K

=

self

.

W_k

(

key

)

.

view

(

batch_size

,

1

,

self

.

num_heads

,

self

.

d_k

)

        V

=

self

.

W_v

(

value

)

.

view

(

batch_size

,

1

,

self

.

num_heads

,

self

.

d_k

)

       

       

Compute attention

        scores

=

torch.

matmul

(

Q

,

K.

transpose

(

2

,

1

)

)

/

(

self

.

d_k

**

0.5

)

        weights

=

F.

softmax

(

scores

,

dim

=

1

)

        output

=

torch.

matmul

(

weights

,

V

)

       

       

Concatenate multiple heads and output

        output

=

output.

transpose

(

1

,

2

)

.

contiguous

(

)

.

view

(

batch_size

,

1

,

self

.

d_model

)

       

return

self

.

W_o

(

output

)


Applications of the attention mechanism in NLP

The attention mechanism has become a core component of modern NLP systems, especially in the Transformer architecture.

Main application scenarios

  1. Machine translation:

  2. The classic Seq2Seq with Attention model
  3. Allows the model to focus on the most relevant parts of the source sentence when generating each target word
  4. - The classic Seq2Seq with Attention model - Allows the model to focus on the most relevant parts of the source sentence when generating each target word
    1. Text summarization:

    2. Identify key information in the original text through attention weights
    3. Generative summarization models use self-attention to capture global relationships in long documents
    4. - Identify key information in the original text through attention weights - Generative summarization models use self-attention to capture global relationships in long documents
      1. Question answering systems:

      2. Cross-attention between the question and the document
      3. Helps the model locate text fragments relevant to the question
      4. - Cross-attention between the question and the document - Helps the model locate text fragments relevant to the question
        1. Language models:

        2. GPT series models use masked self-attention
        3. Allows each word to attend to all preceding words
        4. - GPT series models use masked self-attention - Allows each word to attend to all preceding words

          Practical case: attention in BERT

          BERT (Bidirectional Encoder Representations from Transformers) is a typical representative that uses the attention mechanism:

          1. Bidirectional self-attention: considers both left and right context simultaneously
          2. 12/24-layer Transformer: stacks multi-head attention layers
          3. Pre-training tasks: learn general representations through masked language model and next sentence prediction tasks

          Example

          Use the HuggingFace Transformers library to call BERT

          from

          transformers

          import

          BertModel

          ,

          BertTokenizer

          tokenizer

          =

          BertTokenizer.

          from_pretrained

          (

          'bert-base-uncased'

          )

          model

          =

          BertModel.

          from_pretrained

          (

          'bert-base-uncased'

          )

          inputs

          =

          tokenizer

          (

          "Hello, my dog is cute"

          ,

          return_tensors

          =

          "pt"

          )

          outputs

          =

          model

          (

          **inputs

          )

          Obtain attention weights

          attention

          =

          outputs.

          attentions

           

          Contains the attention weights of each layer


          Variants and extensions of the attention mechanism

          1. Scaled Dot-Product Attention

          2. Additive Attention

          3. Local Attention

          4. Sparse Attention


          Practical Exercise

          Exercise 1: Implement a basic attention mechanism

          Example

          import

          torch

          import

          torch.

          nn

          as

          nn

          import

          torch.

          nn

          .

          functional

          as

          F

          class

          SimpleAttention

          (

          nn.

          Module

          )

          :

             

          def

          init

          (

          self

          ,

          hidden_size

          )

          :

                 

          super

          (

          SimpleAttention

          ,

          self

          )

          .

          init

          (

          )

                 

          self

          .

          attention

          =

          nn.

          Linear

          (

          hidden_size

          ,

          1

          )

             

             

          def

          forward

          (

          self

          ,

          encoder_outputs

          )

          :

                 

          encoder_outputs: [batch_size, seq_len, hidden_size]

                  attention_scores

          =

          self

          .

          attention

          (

          encoder_outputs

          )

          .

          squeeze

          (

          2

          )

           

          [batch_size, seq_len]

                  attention_weights

          =

          F.

          softmax

          (

          attention_scores

          ,

          dim

          =

          1

          )

                  context_vector

          =

          torch.

          bmm

          (

          attention_weights.

          unsqueeze

          (

          1

          )

          ,

          encoder_outputs

          )

           

          [batch_size, 1, hidden_size]

                 

          return

          context_vector.

          squeeze

          (

          1

          )

          ,

          attention_weights

          Exercise 2: Visualize attention weights

          Example

          import

          matplotlib.

          pyplot

          as

          plt

          import

          seaborn

          as

          sns

          def

          plot_attention

          (

          attention_weights

          ,

          source_tokens

          ,

          target_tokens

          )

          :

              plt.

          figure

          (

          figsize

          =

          (

          10

          ,

          8

          )

          )

              sns.

          heatmap

          (

          attention_weights

          ,

                          xticklabels

          =

          source_tokens

          ,

                          yticklabels

          =

          target_tokens

          ,

                          cmap

          =

          "YlGnBu"

          )

              plt.

          xlabel

          (

          "Source Tokens"

          )

              plt.

          ylabel

          (

          "Target Tokens"

          )

              plt.

          title

          (

          "Attention Weights Visualization"

          )

              plt.

          show

          (

          )

          Example usage

          source

          =

          [

          "The"

          ,

          "cat"

          ,

          "sat"

          ,

          "on"

          ,

          "the"

          ,

          "mat"

          ]

          target

          =

          [

          "Le"

          ,

          "chat"

          ,

          "s'est"

          ,

          "assis"

          ,

          "sur"

          ,

          "le"

          ,

          "tapis"

          ]

          attention

          =

          torch.

          rand

          (

          7

          ,

          6

          )

           

          Simulated attention weights

          plot_attention

          (

          attention

          ,

          source

          ,

          target

          )


          Summary and further learning

          The attention mechanism has become a cornerstone technique of modern deep learning, especially in the field of NLP. To study in depth:

          1. Read the original papers:

          2. "Attention Is All You Need" (Vaswani et al., 2017)
          3. "Neural Machine Translation by Jointly Learning to Align and Translate" (Bahdanau et al., 2015)
          4. - "Attention Is All You Need" (Vaswani et al., 2017) - "Neural Machine Translation by Jointly Learning to Align and Translate" (Bahdanau et al., 2015)
            1. Suggested hands-on projects:

            2. Implement a complete Transformer model
            3. Use the attention mechanism to improve existing models
            4. Analyze the impact of different attention variants on performance
            5. - Implement a complete Transformer model - Use the attention mechanism to improve existing models - Analyze the impact of different attention variants on performance
              1. Extended application areas:

              2. Visual attention in computer vision
              3. Cross-modal attention in multimodal learning
              4. Graph attention mechanisms in graph neural networks
              5. - Visual attention in computer vision - Cross-modal attention in multimodal learning - Graph attention mechanisms in graph neural networks

                The development of the attention mechanism is still ongoing; understanding its core principles will help you better master modern deep learning techniques.