Нейронная сеть — это не магия. Это три операции, повторённые много раз: умножить таблицу чисел на столбец чисел, изогнуть результат простой функцией и подправить числа, когда ответ оказался неверным. Если вы когда-нибудь заполняли шаблон настроек или суммировали столбец в таблице, нужные навыки у вас уже есть. Мы всё сделаем вручную на маленьких числах, и каждый результат можно проверить на бумаге.
Чтобы получить одну ячейку результата, возьмите строку левой матрицы и столбец правой, перемножьте их попарно и сложите произведения. Проведите пальцем: вдоль строки, вниз по столбцу и к ячейке ответа. Этот путь и есть треугольник.
A=(1324),B=(5768)
Верхняя левая: строка 1 со столбцом 1 даёт 1⋅5+2⋅7=19.
Верхняя правая: строка 1 со столбцом 2 даёт 1⋅6+2⋅8=22.
Нижняя левая: строка 2 со столбцом 1 даёт 3⋅5+4⋅7=43.
Нижняя правая: строка 2 со столбцом 2 даёт 3⋅6+4⋅8=50.
AB=(19432250)
Взгляд системного администратора. Одна строка весов, умноженная на столбец входа, — это один «нейрон». Слой — та же операция, запущенная параллельно; именно поэтому графические процессоры (graphics processing units, GPU), созданные для таких расчётов, считают искусственный интеллект (artificial intelligence, AI; ИИ). Порядок важен: AB обычно не равно BA.
2. Функции активации: изгиб
Одни только умножение и сложение остаются прямой линией, а стопка прямых линий снова даёт прямую. Функция активации изгибает выход, чтобы сеть могла учить кривые.
ReLU (rectified linear unit, выпрямленный линейный блок):ReLU(x)=max(0,x). Отрицательные входы становятся нулём, положительные проходят без изменений. Это похоже на правило межсетевого экрана: ниже нуля — отбросить, выше — пропустить.
Сигмоида (sigmoid):σ(x)=1+e−x1. Сжимает любое число в промежуток от 0 до 1, поэтому удобна как вероятность.
GELU (Gaussian error linear unit, линейный блок с гауссовой ошибкой):GELU(x)=x⋅Φ(x), где Φ — функция распределения стандартного нормального закона. Распространённое приближение: 0.5x(1+tanh(2/π(x+0.044715x3))). Это гладкий ReLU, который пропускает небольшие отрицательные значения; его используют многие современные языковые модели.
x
ReLU
Сигмоида
GELU
−2
0
0.1192
−0.0455
−1
0
0.2689
−0.1587
0
0
0.5000
0
1
1
0.7311
0.8413
2
2
0.8808
1.9545
3. Градиентный спуск: один маленький шаг вниз
Обучение — это подстройка веса w, чтобы ошибка, которую называют функцией потерь (loss), становилась меньше. Правило такое:
wnew=w−η⋅∂w∂L
Производная показывает, куда идти в гору, поэтому шаг делают в другую сторону. Размер шага η, скорость обучения (learning rate), задаёт, насколько большим будет шаг.
Крошечный пример. Модель y^=w⋅x, функция потерь L=(y^−y)2. Вход x=2, правильный ответ y=4, начальный вес w=1 и скорость обучения η=0.1.
Предсказание: y^=1⋅2=2. Потери: (2−4)2=4.
Градиент: ∂w∂L=2(y^−y)x=2⋅(−2)⋅2=−8.
Обновление: wnew=1−0.1⋅(−8)=1.8.
Проверка: y^=1.8⋅2=3.6, и потери падают до (3.6−4)2=0.16.
Один шаг снизил потери с 4 до 0.16. Обучение настоящей модели — тот же шаг, повторённый миллиарды раз по миллиардам весов. Слишком большая скорость обучения — и вы перескакиваете цель, как агрессивный автомасштабировщик, который качается туда-сюда.
4. Полный крошечный прямой проход (2 входа → 2 скрытых → 1 выход)
Вход:x=(12).
Скрытый слой (каждая строка — один скрытый нейрон):
W1=(0.51−10.5),b1=(00.5)
Нейрон 1: 0.5⋅1+(−1)⋅2+0=−1.5.
Нейрон 2: 1⋅1+0.5⋅2+0.5=2.5.
ReLU: h=(max(0,−1.5)max(0,2.5))=(02.5). Нейрон 1 для этого входа выключен.
Выходной слой:W2=(10.8) и b2=−1.
z=1⋅0+0.8⋅2.5+(−1)=1.0.
Сигмоида: σ(1.0)=0.7311.
Результат: сеть говорит «да» с уверенностью 73.11%. Всё это — одна строка:
y^=σ(W2ReLU(W1x+b1)+b2)
Вот и весь «прямой проход» (forward pass). Обучение (раздел 3) подстраивает каждое число в W1, b1, W2 и b2, пока выходы не совпадут с примерами.
5. Предсказание следующего токена: "the sky is" → "blue"
Языковая модель превращает текст в числа, делает прямой проход и выдаёт оценку для каждого слова, которое знает.
Фраза "the sky is blue" становится (0,1,2,3). По слову "is" (идентификатор 2) мы хотим предсказать идентификатор 3.
Шаг 2: эмбеддинг (embedding, векторное представление). Каждый идентификатор указывает на выученный вектор. Пусть токен 2 ("is") отображается в e=(11).
Шаг 3: логиты (logits, сырые оценки). Умножаем на выходную матрицу, по одной строке на слово словаря, снова тем же треугольником «строка на столбец»:
Шаг 4: softmax (функция мягкого максимума) превращает оценки в вероятности.
pi=∑jezjezi
e0.1=1.1052, e0.5=1.6487, e−0.2=0.8187, e2.2=9.0250. Сумма равна 12.5976.
Вероятности: the 8.77%, sky 13.09%, is 6.50%, blue 71.64%.
Модель выбирает "blue". При обучении функция потерь равна −ln(0.7164)=0.3335, и градиентный спуск подталкивает Wout и эмбеддинг так, чтобы в следующий раз "blue" набрал ещё больше. Настоящие модели делают ровно это: словарь около 100 000 токенов, векторы из тысяч чисел и много слоёв между ними, которые смотрят на всё предложение, а не на одно слово.
6. Пример побольше: больше токенов, три измерения
В разделе 5 был словарь из 4 слов и векторы из 2 чисел. Теперь возьмём 8 токенов и 3 измерения, чтобы увидеть две вещи: близкие по смыслу слова оказываются рядом, а контекст решает, какое слово идёт следующим.
Шаг 1: словарь и обучающие фразы. Три фразы: "the sky is blue", "the grass is green", "the sun is hot".
Токен
the
sky
is
blue
grass
green
sun
hot
Идентификатор
0
1
2
3
4
5
6
7
Фраза "the grass is green" становится последовательностью (0,4,2,5).
Шаг 2: что значат три измерения. Каждый токен — это точка в трёхмерном пространстве, как точка (x,y,z) в комнате. Для учебного примера мы дали каждой оси понятный смысл:
d1 — «это цвет»;
d2 — «наверху, в небе» (плюс) или «внизу, на земле» (минус);
d3 — «тепло» (плюс) или «прохлада» (минус).
Оговорка. Настоящие модели сами выучивают свои измерения, и отдельная ось почти никогда не означает что-то одно понятное человеку. Измерений у них не 3, а тысячи. Смысл несёт направление всего вектора, а не одна координата.
Шаг 3: таблица эмбеддингов E (8 × 3). Слово "the" здесь ничего не добавляет, поэтому его вектор нулевой. Вектор "is" говорит «дальше будет описание: цвет или температура».
Токен
d1 цвет
d2 небо (+) / земля (−)
d3 тепло (+) / прохлада (−)
the
0
0
0
sky
0
2
0
is
1
0
1
blue
2
1
−1
grass
0
−2
0
green
2
−1
0
sun
0
2
2
hot
0
0
2
Шаг 4: насколько близки два слова. Скалярное произведение (dot product) — тот же «треугольник»: перемножаем координаты попарно и складываем. Косинусное сходство (cosine similarity) делит его на длины векторов и даёт число от −1 (противоположны) до 1 (одно направление):
a⋅b=a1b1+a2b2+a3b3
cos(a,b)=∥a∥∥b∥a⋅b
∥a∥=a⋅a
blue⋅green=2⋅2+1⋅(−1)+(−1)⋅0=3
cos=653=0.5477
Пара
Скалярное произведение
Квадраты длин
Косинус
blue · green
3
6, 5
0.5477
sky · sun
4
4, 8
0.7071
green · hot
0
5, 4
0.0000
blue · hot
−2
6, 4
−0.4082
sky · grass
−4
4, 4
−1.0000
Два цвета близки (0.5477), "sky" и "sun" оба «наверху» (0.7071), а "blue" и "hot" смотрят в разные стороны (−0.4082). "sky" и "grass" противоположны (−1.0000): одно наверху, другое внизу.
Шаг 5: выходная матрица Wout (8 × 3). Одна строка на каждый токен словаря. Логит токена равен скалярному произведению его строки на вектор контекста c. Токены, которые в наших фразах никогда не идут после "is", получили одну и ту же отрицательную строку.
Строка
the
sky
is
blue
grass
green
sun
hot
w1
−1
−1
−1
2
−1
2
−1
−2
w2
0
0
0
2
0
−2
0
0
w3
−1
−1
−1
−1
−1
−1
−1
3
(Таблица показана повёрнутой: каждый столбец — это строка Wout для одного токена.)
Шаг 6: одного "is" мало. Если смотреть только на "is", то c=eis=(1,0,1). Логиты: blue =2+0−1=1, green =2+0−1=1, hot =−2+0+3=1, у остальных пяти −2. Три кандидата получают ровно поровну:
Одна и та же матрица Wout даёт "blue" после "the sky is" и "green" после "the grass is". Изменился только контекст. Функция потерь (перекрёстная энтропия, cross-entropy) для правильного ответа мала: −ln151.8579148.4132=0.0229 в обоих случаях. Если бы правильным ответом после "the sky is" было "green", потеря была бы −ln151.8579e−3=8.0229, и градиентный спуск (раздел 3) сильно сдвинул бы веса.
Третья фраза работает так же: csun=(1,2,3), логит "hot" равен −2+0+9=7, логит "blue" равен 3, и "hot" получает 98.19% (потеря 0.0182).
Сумма или среднее. Если вместо суммы взять среднее (разделить c на 3), победители те же, но уверенность ниже: "blue" 55.01%, "green" 55.01%, "hot" 70.94%. Настоящие трансформеры используют внимание (attention): это тоже взвешенное среднее векторов контекста, только веса не равны, а выучиваются, чтобы важные слова, например "sky", весили больше, чем "the".
7. Кратко
Умножение матриц — основная операция: строка на столбец, сумма.
Активации (ReLU, сигмоида, GELU) изгибают выход, чтобы сеть учила не только прямые линии.
Градиентный спуск сдвигает каждый вес против градиента: w←w−η∂L/∂w.
Прямой проход — это умножить, добавить смещение (bias), активировать и повторить.
Предсказание следующего токена — тот же прямой проход, который заканчивается softmax по словарю.
Больше токенов и измерений: близкие слова — близкие векторы (косинусное сходство), а сумма эмбеддингов контекста выбирает следующее слово: "blue" после "the sky is", "green" после "the grass is".
Вывод для безопасности. Модель — это только числа, выученные из данных. Отравите данные или подмените веса — и выход изменится, а строки кода, которую можно рецензировать, нет. Поэтому файлы моделей и обучающие данные заслуживают той же проверки целостности, что и двоичные файлы.
Все числа в этом занятии — учебные примеры. Они заново пересчитаны скриптом 17 ноября 2026 года; числа округлены до 4 знаков после запятой, проценты — до 2.
8. Замечание
Прокл приводит слова Евклида царю Птолемею: к геометрии нет царского пути («Комментарий к первой книге „Начал“ Евклида»). Понимание работы важнее сертификата, и оно всегда с собой.
A neural network is not magic. It's three operations repeated many times: multiply a table of numbers by a list of numbers, bend the result with a simple function, and nudge the numbers whenever the answer was wrong. If you've ever written a config template or summed a column in a spreadsheet, you already have the skills. We'll do everything by hand with small numbers, and each result can be checked on paper.
1. Matrix multiplication: the row-by-column "triangle"
To get one cell of the result, take a row from the left matrix and a column from the right one, multiply them pair by pair, and add the products. Trace it with your finger: across the row, down the column, then to the answer cell. That path is the triangle.
A=(1324),B=(5768)
Top-left: row 1 with column 1 gives 1⋅5+2⋅7=19.
Top-right: row 1 with column 2 gives 1⋅6+2⋅8=22.
Bottom-left: row 2 with column 1 gives 3⋅5+4⋅7=43.
Bottom-right: row 2 with column 2 gives 3⋅6+4⋅8=50.
AB=(19432250)
Sysadmin view. One row of weights times an input column is one "neuron". A layer is the same operation run in parallel, which is why GPUs (graphics processing units), built for exactly this, run artificial intelligence (AI). Order matters: AB is usually not BA.
2. Activation functions: the bend
Multiplying and adding alone stays a straight line, and stacking straight lines still gives a straight line. An activation function bends the output so the network can learn curves.
ReLU (rectified linear unit):ReLU(x)=max(0,x). Negative inputs become 0 and positive ones pass through unchanged. It behaves like a firewall rule: drop below zero, allow above.
Sigmoid:σ(x)=1+e−x1. It squeezes any number into the range 0 to 1, which makes it handy as a probability.
GELU (Gaussian error linear unit):GELU(x)=x⋅Φ(x), where Φ is the standard normal cumulative distribution. A common approximation is 0.5x(1+tanh(2/π(x+0.044715x3))). It's a smooth ReLU that lets small negatives leak through, and many modern language models use it.
x
ReLU
Sigmoid
GELU
−2
0
0.1192
−0.0455
−1
0
0.2689
−0.1587
0
0
0.5000
0
1
1
0.7311
0.8413
2
2
0.8808
1.9545
3. Gradient descent: one small step downhill
Learning means adjusting a weight w so the error, called the loss, gets smaller. Here's the rule:
wnew=w−η⋅∂w∂L
The derivative tells you which way is uphill, so you step the other way. The step size η, the learning rate, controls how big the step is.
Tiny example. The model is y^=w⋅x, with loss L=(y^−y)2. Take input x=2, correct answer y=4, starting weight w=1 and learning rate η=0.1.
Prediction: y^=1⋅2=2. Loss: (2−4)2=4.
Gradient: ∂w∂L=2(y^−y)x=2⋅(−2)⋅2=−8.
Update: wnew=1−0.1⋅(−8)=1.8.
Check: y^=1.8⋅2=3.6, and the loss falls to (3.6−4)2=0.16.
One step cut the loss from 4 to 0.16. Training a real model is this same step repeated billions of times over billions of weights. Set the learning rate too large and you overshoot, the way an aggressive autoscaler oscillates.
4. A full tiny forward pass (2 inputs → 2 hidden → 1 output)
Input:x=(12).
Hidden layer (each row is one hidden neuron):
W1=(0.51−10.5),b1=(00.5)
Neuron 1: 0.5⋅1+(−1)⋅2+0=−1.5.
Neuron 2: 1⋅1+0.5⋅2+0.5=2.5.
ReLU: h=(max(0,−1.5)max(0,2.5))=(02.5). Neuron 1 is switched off for this input.
Output layer:W2=(10.8) and b2=−1.
z=1⋅0+0.8⋅2.5+(−1)=1.0.
Sigmoid: σ(1.0)=0.7311.
Result: the network says "yes" with 73.11% confidence. The whole thing is one line:
y^=σ(W2ReLU(W1x+b1)+b2)
That's all a "forward pass" is. Training (section 3) adjusts every number in W1, b1, W2 and b2 until the outputs match the examples.
5. Next-token prediction: "the sky is" → "blue"
A language model turns text into numbers, runs a forward pass, and outputs a score for every word it knows.
Step 1: token IDs. The vocabulary is a lookup table:
Token
ID
the
0
sky
1
is
2
blue
3
"the sky is blue" becomes (0,1,2,3). Given "is" (ID 2), we want to predict ID 3.
Step 2: embedding. Each ID points to a learned vector. Say token 2 ("is") maps to e=(11).
Step 3: logits. Multiply by the output matrix, one row per vocabulary word, using the row-by-column triangle again:
e0.1=1.1052, e0.5=1.6487, e−0.2=0.8187, e2.2=9.0250. The sum is 12.5976.
Probabilities: the 8.77%, sky 13.09%, is 6.50%, blue 71.64%.
The model picks "blue". During training the loss is −ln(0.7164)=0.3335, and gradient descent nudges Wout and the embedding so "blue" scores even higher next time. Real models do exactly this, with a vocabulary of about 100,000 tokens, vectors of thousands of numbers, and many layers in between that look at the whole sentence instead of one word.
6. Bigger example: more tokens, three dimensions
Section 5 used a 4-word vocabulary and vectors of 2 numbers. Now we take 8 tokens and 3 dimensions to see two things: words with similar meaning end up close together, and context decides which word comes next.
Step 1: vocabulary and training sentences. Three sentences: "the sky is blue", "the grass is green", "the sun is hot".
Token
the
sky
is
blue
grass
green
sun
hot
ID
0
1
2
3
4
5
6
7
"the grass is green" becomes the sequence (0,4,2,5).
Step 2: what three dimensions mean. Each token is a point in 3D space, like a point (x,y,z) in a room. For teaching, we gave each axis a readable meaning:
d1 is "this is a color";
d2 is "up in the sky" (plus) or "down on the ground" (minus);
d3 is "warm" (plus) or "cool" (minus).
Caveat. Real models learn their own dimensions, and a single axis almost never means one human-readable thing. They use thousands of dimensions, not 3. Meaning lives in the direction of the whole vector, not in one coordinate.
Step 3: the embedding table E (8 × 3). In this example "the" adds nothing, so its vector is all zeros. The vector for "is" says "a description comes next: a color or a temperature".
Token
d1 color
d2 sky (+) / ground (−)
d3 warm (+) / cool (−)
the
0
0
0
sky
0
2
0
is
1
0
1
blue
2
1
−1
grass
0
−2
0
green
2
−1
0
sun
0
2
2
hot
0
0
2
Step 4: how close two words are. The dot product is the same "triangle": multiply coordinates pair by pair and add. Cosine similarity divides it by the vector lengths and gives a number from −1 (opposite) to 1 (same direction):
a⋅b=a1b1+a2b2+a3b3
cos(a,b)=∥a∥∥b∥a⋅b
∥a∥=a⋅a
blue⋅green=2⋅2+1⋅(−1)+(−1)⋅0=3
cos=653=0.5477
Pair
Dot product
Lengths²
Cosine
blue · green
3
6, 5
0.5477
sky · sun
4
4, 8
0.7071
green · hot
0
5, 4
0.0000
blue · hot
−2
6, 4
−0.4082
sky · grass
−4
4, 4
−1.0000
The two colors are close (0.5477), "sky" and "sun" are both "up there" (0.7071), and "blue" and "hot" point different ways (−0.4082). "sky" and "grass" are opposite (−1.0000): one is up, the other is down.
Step 5: the output matrix Wout (8 × 3). One row per vocabulary token. A token's logit is the dot product of its row with the context vector c. Tokens that never follow "is" in our sentences share the same negative row.
Row
the
sky
is
blue
grass
green
sun
hot
w1
−1
−1
−1
2
−1
2
−1
−2
w2
0
0
0
2
0
−2
0
0
w3
−1
−1
−1
−1
−1
−1
−1
3
(The table is shown turned on its side: each column is one token's row of Wout.)
Step 6: "is" alone is not enough. Looking only at "is", c=eis=(1,0,1). Logits: blue =2+0−1=1, green =2+0−1=1, hot =−2+0+3=1, and −2 for the other five. Three candidates get exactly equal shares:
The same Wout gives "blue" after "the sky is" and "green" after "the grass is". Only the context changed. The cross-entropy loss for the right answer is small: −ln151.8579148.4132=0.0229 in both cases. If the right answer after "the sky is" had been "green", the loss would be −ln151.8579e−3=8.0229, and gradient descent (section 3) would move the weights hard.
The third sentence works the same way: csun=(1,2,3), the "hot" logit is −2+0+9=7, the "blue" logit is 3, and "hot" gets 98.19% (loss 0.0182).
Sum or average. Averaging instead of summing (dividing c by 3) keeps the same winners with less confidence: "blue" 55.01%, "green" 55.01%, "hot" 70.94%. Real transformers use attention, which is also a weighted average of the context vectors, except the weights are learned rather than equal, so important words such as "sky" count for more than "the".
7. Summary
Matrix multiplication is the core operation: row times column, summed.
Activations (ReLU, sigmoid, GELU) bend the output, so the network can learn more than straight lines.
Gradient descent steps each weight against its gradient: w←w−η∂L/∂w.
A forward pass is multiply, add bias, activate, and repeat.
Next-token prediction is the same forward pass ending in softmax over the vocabulary.
More tokens and dimensions: similar words get similar vectors (cosine similarity), and the summed context embeddings pick the next word: "blue" after "the sky is", "green" after "the grass is".
Security takeaway. A model is only numbers learned from data. Poison the data or tamper with the weights and the output changes, with no line of code to review. That's why model files and training data deserve the same integrity checks as binaries.
All numbers in this lesson are worked examples. They were recomputed by script on Nov 17, 2026, rounded to 4 decimal places, with percentages to 2.
8. A note
Proclus records that Euclid told Ptolemy there is no royal road to geometry (Commentary on the First Book of Euclid’s Elements). Understanding of the work is better than a certificate, and you carry it with you.
Una red neuronal no es magia. Son tres operaciones repetidas muchas veces: multiplicar una tabla de números por una lista de números, doblar el resultado con una función sencilla y ajustar los números cada vez que la respuesta fue incorrecta. Si alguna vez ha escrito una plantilla de configuración o sumado una columna en una hoja de cálculo, ya tiene las habilidades necesarias. Lo haremos todo a mano con números pequeños, y cada resultado puede comprobarse en papel.
1. Multiplicación de matrices: el «triángulo» de fila por columna
Para obtener una celda del resultado, tome una fila de la matriz izquierda y una columna de la derecha, multiplíquelas par por par y sume los productos. Siga el recorrido con el dedo: a lo largo de la fila, hacia abajo por la columna y luego hasta la celda de la respuesta. Ese recorrido es el triángulo.
Arriba a la izquierda: la fila 1 con la columna 1 da 1⋅5+2⋅7=19.
Arriba a la derecha: la fila 1 con la columna 2 da 1⋅6+2⋅8=22.
Abajo a la izquierda: la fila 2 con la columna 1 da 3⋅5+4⋅7=43.
Abajo a la derecha: la fila 2 con la columna 2 da 3⋅6+4⋅8=50.
Visión de administrador de sistemas. Una fila de pesos por una columna de entrada es una «neurona». Una capa es la misma operación ejecutada en paralelo, y por eso las GPU (unidades de procesamiento gráfico), concebidas exactamente para esto, impulsan la inteligencia artificial (IA). El orden importa: AB normalmente no es igual a BA.
2. Funciones de activación: la curva
Multiplicar y sumar por sí solos siguen dando una línea recta, y apilar líneas rectas sigue dando una línea recta. Una función de activación curva la salida para que la red pueda aprender curvas.
ReLU (unidad lineal rectificada):ReLU(x)=max(0,x). Las entradas negativas se vuelven 0 y las positivas pasan sin cambios. Se comporta como una regla de firewall: descartar por debajo de cero, permitir por encima.
Sigmoide:σ(x)=1+e−x1. Comprime cualquier número al rango de 0 a 1, lo que la hace útil como probabilidad.
GELU (unidad lineal de error gaussiano):GELU(x)=x⋅Φ(x), donde Φ es la distribución normal estándar acumulada. Una aproximación habitual es 0.5x(1+tanh(2/π(x+0.044715x3))). Es una ReLU suave que deja pasar pequeños valores negativos, y muchos modelos de lenguaje modernos la utilizan.
ReLU
Sigmoide
GELU
−2
0
0.1192
−0.0455
−1
0
0.2689
−0.1587
0
0
0.5000
0
1
1
0.7311
0.8413
2
2
0.8808
1.9545
3. Descenso del gradiente: un pequeño paso cuesta abajo
Aprender significa ajustar un peso w para que el error, llamado pérdida, disminuya. Esta es la regla:
La derivada indica hacia dónde sube la pendiente, de modo que se da el paso en sentido contrario. El tamaño del paso η, la tasa de aprendizaje, controla su magnitud.
Un ejemplo mínimo. El modelo es y^=w⋅x, con pérdida L=(y^−y)2. Tome la entrada x=2, la respuesta correcta y=4, el peso inicial w=1 y la tasa de aprendizaje η=0.1.
Predicción: y^=1⋅2=2. Pérdida: (2−4)2=4.
Gradiente: ∂w∂L=2(y^−y)x=2⋅(−2)⋅2=−8.
Actualización: wnew=1−0.1⋅(−8)=1.8.
Comprobación: y^=1.8⋅2=3.6, y la pérdida baja a (3.6−4)2=0.16.
Un solo paso redujo la pérdida de 4 a 0.16. Entrenar un modelo real es este mismo paso repetido miles de millones de veces sobre miles de millones de pesos. Si se fija la tasa de aprendizaje demasiado alta, se pasa de largo, como un autoescalador agresivo que oscila.
4. Un pase hacia adelante completo en miniatura (2 entradas → 2 ocultas → 1 salida)
Entrada:x=(12).
Capa oculta (cada fila es una neurona oculta):
Neurona 1: 0.5⋅1+(−1)⋅2+0=−1.5.
Neurona 2: 1⋅1+0.5⋅2+0.5=2.5.
ReLU: h=(max(0,−1.5)max(0,2.5))=(02.5). La neurona 1 queda apagada para esta entrada.
Capa de salida:W2=(10.8) y b2=−1.
.
Sigmoide: σ(1.0)=0.7311.
Resultado: la red dice «sí» con un 73.11 % de confianza. Todo se resume en una línea:
Eso es todo lo que es un «pase hacia adelante». El entrenamiento (sección 3) ajusta cada número de W1, b1, W2 y b2 hasta que las salidas coinciden con los ejemplos.
5. Predicción del siguiente token: «the sky is» → «blue»
Un modelo de lenguaje convierte el texto en números, ejecuta un pase hacia adelante y devuelve una puntuación para cada palabra que conoce.
Paso 1: identificadores de token. El vocabulario es una tabla de consulta:
Token
ID
the
0
sky
1
is
2
blue
3
«the sky is blue» («el cielo es azul») se convierte en (0,1,2,3). Dado «is» (ID 2), queremos predecir el ID 3.
Paso 2: incrustación. Cada ID apunta a un vector aprendido. Digamos que el token 2 («is») se asigna a e=(11).
Paso 3: logits. Multiplique por la matriz de salida, con una fila por cada palabra del vocabulario, usando de nuevo el triángulo de fila por columna:
Paso 4: softmax convierte las puntuaciones en probabilidades.
e0.1=1.1052, e0.5=1.6487, e−0.2=0.8187, e2.2=9.0250. La suma es 12.5976.
Probabilidades: the 8.77 %, sky 13.09 %, is 6.50 %, blue 71.64 %.
El modelo elige «blue». Durante el entrenamiento, la pérdida es −ln(0.7164)=0.3335, y el descenso del gradiente ajusta Wout y la incrustación para que «blue» obtenga una puntuación aún más alta la próxima vez. Los modelos reales hacen exactamente esto, con un vocabulario de unos 100 000 tokens, vectores de miles de números y muchas capas intermedias que examinan la oración completa en lugar de una sola palabra.
6. Un ejemplo más grande: más tokens, tres dimensiones
La sección 5 usó un vocabulario de 4 palabras y vectores de 2 números. Ahora tomamos 8 tokens y 3 dimensiones para ver dos cosas: las palabras de significado parecido quedan cerca unas de otras, y el contexto decide cuál es la palabra siguiente.
Paso 1: vocabulario y oraciones de entrenamiento. Tres oraciones: «the sky is blue» (el cielo es azul), «the grass is green» (el pasto es verde), «the sun is hot» (el sol es caliente).
Token
the
sky
is
blue
grass
green
sun
hot
ID
0
1
2
3
4
5
6
7
«the grass is green» se convierte en la secuencia (0,4,2,5).
Paso 2: qué significan tres dimensiones. Cada token es un punto en el espacio 3D, como un punto (x,y,z) en una habitación. Con fines didácticos, dimos a cada eje un significado legible:
d1 es «esto es un color»;
d2 es «arriba en el cielo» (más) o «abajo en el suelo» (menos);
d3 es «cálido» (más) o «frío» (menos).
Advertencia. Los modelos reales aprenden sus propias dimensiones, y un solo eje casi nunca significa algo legible para una persona. Usan miles de dimensiones, no 3. El significado reside en la dirección del vector completo, no en una sola coordenada.
Paso 3: la tabla de incrustaciones E (8 × 3). En este ejemplo, «the» no aporta nada, así que su vector es todo ceros. El vector de «is» dice: «a continuación viene una descripción: un color o una temperatura».
Token
d1 color
d2 cielo (+) / suelo (−)
d3 cálido (+) / frío (−)
the
0
0
0
sky
0
2
0
is
1
0
1
blue
2
1
−1
grass
0
−2
0
green
2
−1
0
sun
0
2
2
hot
0
0
2
Paso 4: qué tan cerca están dos palabras. El producto punto es el mismo «triángulo»: se multiplican las coordenadas par por par y se suma. La similitud del coseno lo divide entre las longitudes de los vectores y da un número de −1 (opuestos) a 1 (misma dirección):
Par
Producto punto
Longitudes²
Coseno
blue · green
3
6, 5
0.5477
sky · sun
4
4, 8
0.7071
green · hot
0
5, 4
0.0000
blue · hot
−2
6, 4
−0.4082
sky · grass
−4
4, 4
−1.0000
Los dos colores están cerca (0.5477), «sky» y «sun» están ambos «allá arriba» (0.7071), y «blue» y «hot» apuntan en direcciones distintas (−0.4082). «sky» y «grass» son opuestos (−1.0000): uno está arriba y el otro abajo.
Paso 5: la matriz de salida Wout (8 × 3). Una fila por cada token del vocabulario. El logit de un token es el producto punto de su fila con el vector de contexto c. Los tokens que nunca siguen a «is» en nuestras oraciones comparten la misma fila negativa.
Fila
the
sky
is
blue
grass
green
sun
hot
−1
−1
−1
2
−1
2
−1
−2
0
0
0
2
0
−2
0
0
−1
−1
−1
−1
−1
−1
−1
3
(La tabla se muestra de lado: cada columna es la fila de Wout de un token.)
Paso 6: «is» por sí solo no basta. Mirando solo «is», c=eis=(1,0,1). Logits: blue =2+0−1=1, green =2+0−1=1, hot =−2+0+3=1 y −2 para los otros cinco. Tres candidatos reciben partes exactamente iguales:
Los otros cinco tokens obtienen 1.53 % cada uno. El modelo no puede elegir: ¿blue, green o hot?
Paso 7: añadir contexto. La forma más sencilla es sumar las incrustaciones de todas las palabras del contexto:
Ahora multiplique Wout por c con el mismo «triángulo». Por ejemplo, «blue» después de «the sky is»: 2⋅1+2⋅2+(−1)⋅1=5.
Token
Logit, «the sky is»
Probabilidad
Logit, «the grass is»
Probabilidad
the, sky, is, grass, sun (cada uno)
−2
0.09%
−2
0.09%
blue
5
97.73%
−3
0.03%
green
−3
0.03%
5
97.73%
hot
1
1.79%
1
1.79%
El mismo Wout da «blue» después de «the sky is» y «green» después de «the grass is». Solo cambió el contexto. La pérdida de entropía cruzada para la respuesta correcta es pequeña: −ln151.8579148.4132=0.0229 en ambos casos. Si la respuesta correcta después de «the sky is» hubiera sido «green», la pérdida sería −ln151.8579e−3=8.0229, y el descenso del gradiente (sección 3) movería los pesos con fuerza.
La tercera oración funciona igual: csun=(1,2,3), el logit de «hot» es −2+0+9=7, el logit de «blue» es 3, y «hot» obtiene un 98.19 % (pérdida 0.0182).
Suma o promedio. Promediar en lugar de sumar (dividir c entre 3) conserva los mismos ganadores con menos confianza: «blue» 55.01 %, «green» 55.01 %, «hot» 70.94 %. Los transformadores reales usan atención, que también es un promedio ponderado de los vectores de contexto, solo que los pesos se aprenden en lugar de ser iguales, de modo que palabras importantes como «sky» cuentan más que «the».
7. Resumen
La multiplicación de matrices es la operación central: fila por columna, sumado.
Las activaciones (ReLU, sigmoide, GELU) curvan la salida para que la red pueda aprender algo más que líneas rectas.
El descenso del gradiente mueve cada peso en contra de su gradiente: w←w−η∂L/∂w.
Un pase hacia adelante consiste en multiplicar, sumar el sesgo, activar y repetir.
La predicción del siguiente token es el mismo pase hacia adelante, que termina en un softmax sobre el vocabulario.
Más tokens y dimensiones: las palabras parecidas obtienen vectores parecidos (similitud del coseno), y las incrustaciones de contexto sumadas eligen la palabra siguiente: «blue» después de «the sky is», «green» después de «the grass is».
Conclusión de seguridad. Un modelo son solo números aprendidos de datos. Si se envenenan los datos o se manipulan los pesos, la salida cambia, sin ninguna línea de código que revisar. Por eso los archivos de modelos y los datos de entrenamiento merecen las mismas comprobaciones de integridad que los binarios.
Todos los números de esta lección son ejemplos resueltos. Se recalcularon mediante un script el 17 nov 2026, redondeados a 4 decimales, con porcentajes a 2.
GELU(Gaussian error linear unit、ガウス誤差線形ユニット):GELU(x)=x⋅Φ(x)。ここでΦは、標準正規分布の累積分布関数です。よく使われる近似は0.5x(1+tanh(2/π(x+0.044715x3)))です。なめらかなReLUで、小さな負の値を少し通します。多くの最新の言語モデルが使っています。