Self-attention: запрос, ключ и значение
Позвольте каждому токену смотреть на любой другой токен
«Self-attention: запрос, ключ и значение» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Tokens That Talk
In a sequence, the meaning of one word depends on others. Self-attention lets every token look at every other token to gather the context it needs.
Three Roles per Token
Each token plays three roles: a query that asks, a key that answers, and a value that carries content. These come from the same word, used three ways.
The Query
A token's query describes what it is looking for. Think of it as the question this word is asking about the rest of the sentence.
The Key
Every token also exposes a key, a label advertising what it offers. A query is compared against all keys to find good matches.
The Value
Once a match is found, the value is the actual information that gets passed along. Keys decide how much, values decide what.
Make Q, K, V
You build queries, keys, and values by projecting the input through three learned linear layers. Same input, three different weight matrices.
q = self.W_q(x)
k = self.W_k(x)
v = self.W_v(x)Score by Similarity
To see how well a query matches a key, you take their dot product. A bigger score means the two tokens are more relevant to each other.
scores = q @ k.transpose(-2, -1)Scores to Weights
Raw scores become attention weights with softmax, so each query's weights are positive and sum to one across all keys.
weights = scores.softmax(dim=-1)Blend the Values
The output for each token is a weighted sum of all values, mixed by the attention weights. Relevant tokens contribute more.
out = weights @ vWhy It Beats RNNs
Self-attention connects any two tokens in one step, so distance does not matter. This parallel view is why transformers handle long context so well.
Learned, Not Fixed
The Q, K, V projections are trained by gradient descent. The network learns what to ask, what to advertise, and what to share, all from data.
Quick Check
Let's test how attention combines its pieces.
Recap
You learned that self-attention turns each token into a query, key, and value, scores query-key matches, and blends values by softmax weights. Nice work!
Часто задаваемые вопросы
Урок «Self-attention: запрос, ключ и значение» бесплатный?
Да — полный текст урока «Self-attention: запрос, ключ и значение» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.
Чему я научусь в уроке «Self-attention: запрос, ключ и значение»?
Позвольте каждому токену смотреть на любой другой токен Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Deep Learning Academy?
Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Self-attention: запрос, ключ и значение»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Deep Learning Academy?
Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Self-attention: запрос, ключ и значение
- Масштабированное скалярное произведение и несколько голов
- Позиционное кодирование порядка
- Соберите блок энкодера Transformer