Skip to content

Attention

Abstract

Attention is a mechanism used by neural networks to select which words in a text to focus on more closely in order to correctly understand the meaning of a phrase and the relationships between words.

What is it?

Attention is a way for the model to weigh words in a sentence. For each word, the model calculates how important all other words are to it. Words with high importance receive a higher 'attention weight', and the model relies more heavily on them.

This mechanism forms the basis of the Transformer architecture, and thus all modern LLM.

Why is it needed?

Before the advent of attention, texts were often processed in order, word by word. This is how recurrent networks (RNN and LSTM) worked. This approach had a problem: the further apart words were, the worse the model understood their connection.

Attention solves this problem differently: the model looks at the entire sequence at once and decides for itself what is connected to what.

How it works with an example

Take the phrase:

'The cat drinks milk because it is hungry.'

Question: Who is 'it'? For a human, it's obvious that 'it' refers to the cat. But how does the model understand this?

It compares the word 'it' with all the words in the sentence and assigns them attention weights:

Word Importance to 'it'
Cat 0.82
drinks 0.02
milk 0.05
because 0.02
that 0.01
hungry 0.08

The highest weight goes to the word 'cat'. This is why the model connects 'it' to the cat.

Self-Attention

When the attention mechanism is applied within the same text, it is called Self-Attention. Each word 'looks' at other words in the same sentence, including itself.

For example, the word 'milk' may be connected to the word 'drinks', and 'hungry' to 'cat'. Self-Attention builds such a map of connections for all words simultaneously.

Key Concepts

  • Query, Key, Value — three projections through which words interact with each other. Roughly speaking: Query — 'what I am looking for', Key — 'what can be found in me', Value — 'what information I will transmit'.
  • Attention Weights — numbers showing the strength of the connection between words.
  • Multi-Head Attention — when the model runs several 'heads' of attention in parallel. Each head learns to notice different types of connections.

Why is it important?

Attention is the main reason why modern neural networks understand long texts, code, and dialogues so well. Thanks to attention, the model can connect meaning over distances of hundreds and thousands of tokens.

See Also