В занятии «Нейронная сеть вручную» мы посчитали всё на бумаге. Теперь повторим те же расчёты в коде, на своём ноутбуке, без графического процессора, без облака и без скачивания готовых моделей. Нужны только Python 3 и библиотека NumPy. Каждый фрагмент ниже — отдельный файл, который можно запустить; под ним показан настоящий вывод, и числа совпадают с бумажным занятием до последнего знака. В конце пойдём на шаг дальше: научим сеть с нуля и посмотрим, как одно изменённое число в файле модели меняет ответ.
1. Подготовка: Python 3 и NumPy в виртуальном окружении
Виртуальное окружение (virtual environment, venv) — это отдельная папка с собственными пакетами (готовыми библиотеками кода), которая не трогает системный Python. Команда activate переключает текущий терминал на это окружение. Установите NumPy (библиотеку для быстрых расчётов с массивами чисел) один раз через pip — установщик пакетов Python; дальше всё работает без сети.
Проверка: python -c "import numpy; print(numpy.__version__)" (ключ -c запускает программу из одной строки в кавычках). Для этого занятия мы использовали Python 3.13.5 и NumPy 2.5.4. Сохраните каждый фрагмент в файл (например, s1_matmul.py) и запустите командой python s1_matmul.py.
2. Умножение матриц: тройной цикл и оператор @
Повтор: одна ячейка результата — это строка на столбец, произведения складываются (раздел 1 бумажного занятия). Тройной цикл ниже — это ровно тот «треугольник»: i выбирает строку, j — столбец, k идёт вдоль них. NumPy делает то же самое оператором @ (оператор умножения матриц в Python: A @ B вычисляет произведение AB), только быстрее. Строка import numpy as np подключает NumPy под коротким именем np, а np.array превращает список списков в массив (array) — таблицу чисел NumPy.
Python
import numpy as np
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
def matmul(A, B):
rows, inner, cols = len(A), len(B), len(B[0])
C = [[0] * cols for _ in range(rows)]
for i in range(rows): # row of A
for j in range(cols): # column of B
for k in range(inner): # walk the "triangle"
C[i][j] += A[i][k] * B[k][j]
return C
print("by hand:", matmul(A, B))
print("numpy:\n", np.array(A) @ np.array(B))
print("BA:\n", np.array(B) @ np.array(A))
Ручной цикл и NumPy дают одно и то же AB: 19, 22, 43, 50. Последняя строка подтверждает, что BA=AB. Для больших матриц ручной цикл в Python медленный, а оператор @ (A @ B) передаёт работу оптимизированной библиотеке линейной алгебры. Поэтому дальше в занятии произведения матриц записаны как A @ B.
3. Функции активации: ReLU, сигмоида, GELU
Формулы те же, что в разделе 2 бумажного занятия. Для точного GELU нужна функция ошибок (error function, erf); она есть в стандартном модуле math, ничего ставить не нужно: Φ(x)=21(1+erf(x/2)). В коде np.maximum(0, x) — это ReLU сразу для каждого элемента массива, а np.exp — ex для каждого элемента.
Python
import math
import numpy as np
def relu(x):
return np.maximum(0, x)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def gelu(x): # exact form: x * Phi(x), Phi via the error function
return np.array([v * 0.5 * (1 + math.erf(v / math.sqrt(2))) for v in x])
def gelu_tanh(x): # common approximation
return 0.5 * x * (1 + np.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * x**3)))
x = np.array([-2.0, -1.0, 0.0, 1.0, 2.0])
print(" x ReLU sigmoid GELU")
for v, r, s, g in zip(x, relu(x), sigmoid(x), gelu(x)):
print(f"{v:+.0f} {r:4.0f} {s:.4f} {g:+.4f}")
print("max |GELU exact - tanh approx| =", f"{np.max(np.abs(gelu(x) - gelu_tanh(x))):.5f}")
Таблица совпадает с бумажной: сигмоида 0.1192, 0.2689, 0.5000, 0.7311, 0.8808; GELU −0.0455, −0.1587, 0, 0.8413, 1.9545. Приближение через tanh отличается от точной формы не больше чем на 0.00015 — как и сказано в бумажном занятии.
4. Один шаг градиентного спуска
Модель y^=w⋅x, потеря (y^−y)2, x=2, y=4, w=1, η=0.1 (раздел 3). Здесь η — скорость обучения (learning rate, в коде lr): насколько большой шаг делаем, а градиент — наклон потери: куда и как круто она растёт.
Python
x, y = 2.0, 4.0 # input and correct answer
w, lr = 1.0, 0.1 # starting weight, learning rate
y_hat = w * x
loss = (y_hat - y) ** 2
grad = 2 * (y_hat - y) * x
w_new = w - lr * grad
loss_new = (w_new * x - y) ** 2
print(f"y_hat={y_hat} loss={loss} grad={grad}")
print(f"w_new={w_new:.1f} y_hat_new={w_new * x:.1f} loss_new={loss_new:.2f}")
Градиент −8, новый вес 1.8, потеря падает с 4 до 0.16 — те же числа, что на бумаге. В разделе 7 этот же шаг крутится в цикле.
5. Прямой проход 2 → 2 → 1
Вся сеть из раздела 4 — четыре строки кода: умножить, добавить смещение (bias — постоянное число, которое прибавляется к нейрону), ReLU, затем выходной слой и сигмоида. W1 @ x — матрица, умноженная на столбец входа.
Python
import numpy as np
x = np.array([1.0, 2.0])
W1 = np.array([[0.5, -1.0],
[1.0, 0.5]])
b1 = np.array([0.0, 0.5])
W2 = np.array([1.0, 0.8])
b2 = -1.0
pre = W1 @ x + b1 # hidden layer before activation
h = np.maximum(0, pre) # ReLU
z = W2 @ h + b2 # output logit
y = 1 / (1 + np.exp(-z)) # sigmoid
print("pre-activation:", pre)
print("h (after ReLU):", h)
print(f"z = {z:.1f} y_hat = {y:.4f} ({100 * y:.2f}%)")
Вывод
pre-activation: [-1.5 2.5]
h (after ReLU): [0. 2.5]
z = 1.0 y_hat = 0.7311 (73.11%)
Нейрон 1 даёт −1.5 и выключается, нейрон 2 даёт 2.5, z=1.0, ответ 0.7311 (73.11%), как на бумаге.
6. Следующий токен: 4 слова, затем 8 токенов в трёх измерениях
6.1. Четыре слова (раздел 5). Эмбеддинг (embedding — вектор чисел, который заменяет слово) "is" равен (1,1), умножаем на Wout и получаем логиты (logits — сырые оценки, по одной на слово), а softmax превращает их в вероятности, которые в сумме дают 1.
Python
import numpy as np
vocab = ["the", "sky", "is", "blue"]
e = np.array([1.0, 1.0]) # embedding of "is" (ID 2)
W_out = np.array([[ 0.2, -0.1],
[ 0.5, 0.0],
[-0.3, 0.1],
[ 1.0, 1.2]])
z = W_out @ e
ez = np.exp(z)
p = ez / ez.sum()
print("logits:", np.round(z, 4))
print("e^z: ", np.round(ez, 4), " sum =", round(ez.sum(), 4))
for t, pi in zip(vocab, p):
print(f" {t:5s} {100 * pi:6.2f}%")
print("prediction:", vocab[int(np.argmax(p))], f" loss = {-np.log(p[3]):.4f}")
Вывод
logits: [ 0.1 0.5 -0.2 2.2]
e^z: [1.1052 1.6487 0.8187 9.025 ] sum = 12.5976
the 8.77%
sky 13.09%
is 6.50%
blue 71.64%
prediction: blue loss = 0.3335
6.2. Восемь токенов, три измерения (раздел 6). Те же таблицы E и Wout. Одна практическая деталь: в softmax мы вычитаем максимальный логит перед экспонентой. Вероятности от этого не меняются (множитель сокращается в числителе и знаменателе), зато на больших логитах не будет переполнения (числа, слишком большого, чтобы компьютер мог его сохранить). Так пишут softmax в реальном коде.
Python
import numpy as np
vocab = ["the", "sky", "is", "blue", "grass", "green", "sun", "hot"]
ID = {t: i for i, t in enumerate(vocab)}
# Embedding table E (8 x 3): d1 color, d2 sky(+)/ground(-), d3 warm(+)/cool(-)
E = np.array([[0, 0, 0], # the
[0, 2, 0], # sky
[1, 0, 1], # is
[2, 1, -1], # blue
[0, -2, 0], # grass
[2, -1, 0], # green
[0, 2, 2], # sun
[0, 0, 2]], # hot
dtype=float)
# Output matrix W_out (8 x 3): one row per token
neg = [-1, 0, -1]
W_out = np.array([neg, neg, neg, [2, 2, -1], neg, [2, -2, -1], neg, [-2, 0, 3]],
dtype=float)
def cosine(a, b):
return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
def softmax(z):
ez = np.exp(z - z.max()) # subtract the max: same result, no overflow
return ez / ez.sum()
print("cosine similarity:")
for a, b in [("blue", "green"), ("sky", "sun"), ("green", "hot"),
("blue", "hot"), ("sky", "grass")]:
va, vb = E[ID[a]], E[ID[b]]
print(f" {a:5s} . {b:5s} dot={va @ vb:+.0f} cos={cosine(va, vb):+.4f}")
def predict(words, target=None, average=False):
c = E[[ID[w] for w in words]].sum(axis=0)
if average:
c = c / len(words)
p = softmax(W_out @ c)
best = vocab[int(np.argmax(p))]
line = f" {' '.join(words):14s} c={np.round(c, 4)} -> {best} {100 * p.max():.2f}%"
if target:
line += f" loss={-np.log(p[ID[target]]):.4f}"
print(line)
return p
print("next-token prediction (sum of context embeddings):")
p_is = predict(["is"])
print(f" blue/green/hot {100 * p_is[ID['blue']]:.2f}% each, others {100 * p_is[ID['the']]:.2f}% each")
p_sky = predict(["the", "sky", "is"], "blue")
predict(["the", "grass", "is"], "green")
predict(["the", "sun", "is"], "hot")
print(f" wrong target 'green' after 'the sky is': loss={-np.log(p_sky[ID['green']]):.4f}")
print("averaging instead of summing:")
for words in (["the", "sky", "is"], ["the", "grass", "is"], ["the", "sun", "is"]):
predict(words, average=True)
Вывод
cosine similarity:
blue . green dot=+3 cos=+0.5477
sky . sun dot=+4 cos=+0.7071
green . hot dot=+0 cos=+0.0000
blue . hot dot=-2 cos=-0.4082
sky . grass dot=-4 cos=-1.0000
next-token prediction (sum of context embeddings):
is c=[1. 0. 1.] -> blue 30.78%
blue/green/hot 30.78% each, others 1.53% each
the sky is c=[1. 2. 1.] -> blue 97.73% loss=0.0229
the grass is c=[ 1. -2. 1.] -> green 97.73% loss=0.0229
the sun is c=[1. 2. 3.] -> hot 98.19% loss=0.0182
wrong target 'green' after 'the sky is': loss=8.0229
averaging instead of summing:
the sky is c=[0.3333 0.6667 0.3333] -> blue 55.01%
the grass is c=[ 0.3333 -0.6667 0.3333] -> green 55.01%
the sun is c=[0.3333 0.6667 1. ] -> hot 70.94%
Всё сходится с бумажным разделом 6:
Косинусы 0.5477, 0.7071, 0, −0.4082, −1.
С одним "is" три кандидата получают по 30.78%, остальные по 1.53%. argmax (номер самого большого значения) при равенстве берёт первый, поэтому печатается "blue", но ничьей это не отменяет.
С контекстом: "blue" 97.73%, "green" 97.73%, "hot" 98.19%; потери 0.0229, 0.0229, 0.0182; неверная цель даёт 8.0229.
При усреднении — 55.01%, 55.01%, 70.94%.
7. Шаг дальше: учим Wout с нуля
На бумаге Wout мы подобрали руками. Теперь пусть сеть найдёт его сама: начнём со случайных маленьких чисел и будем повторять шаг градиентного спуска из раздела 4 на трёх фразах. Эмбеддинги E оставим фиксированными.
Градиент в одну строку. Для контекста c, логитов z=Woutc, вероятностей p=softmax(z) и потери L=−lnpцель (бумажные разделы 5 и 6) производная по логитам удивительно проста:
∂z∂L=p−y
∂Wout∂L=(p−y)c⊤
Здесь y — вектор из нулей с единицей на месте правильного токена (one-hot). Смысл: правильному токену «недодали» 1−p, и его строку тянут к c; каждому неправильному «переплатили» p, и его строку отталкивают. Сокращение получается потому, что −ln и экспонента в softmax гасят друг друга. c⊤ — это c, записанный строкой, поэтому (p−y)c⊤ — таблица с одной строкой на каждый токен, как сама Wout.
Python
import numpy as np
vocab = ["the", "sky", "is", "blue", "grass", "green", "sun", "hot"]
ID = {t: i for i, t in enumerate(vocab)}
E = np.array([[0, 0, 0], [0, 2, 0], [1, 0, 1], [2, 1, -1],
[0, -2, 0], [2, -1, 0], [0, 2, 2], [0, 0, 2]], dtype=float)
sentences = ["the sky is blue", "the grass is green", "the sun is hot"]
X = np.array([E[[ID[w] for w in s.split()[:3]]].sum(axis=0) for s in sentences]) # 3 x 3 contexts
Y = np.zeros((3, 8))
for row, s in enumerate(sentences):
Y[row, ID[s.split()[3]]] = 1.0 # one-hot targets
def softmax_rows(Z):
EZ = np.exp(Z - Z.max(axis=1, keepdims=True))
return EZ / EZ.sum(axis=1, keepdims=True)
rng = np.random.default_rng(42) # fixed seed: same output every run
W_out = rng.normal(0, 0.1, size=(8, 3)) # random start, no hand-picked numbers
lr, steps = 0.1, 500
for step in range(steps + 1):
P = softmax_rows(X @ W_out.T) # forward pass, 3 x 8
loss = -np.mean(np.log(P[Y == 1])) # mean cross-entropy
if step % 100 == 0:
print(f"step {step:3d} loss {loss:.4f}")
grad = (P - Y).T @ X / len(X) # dL/dW_out = (p - y) c^T, averaged
W_out -= lr * grad # gradient descent step
P = softmax_rows(X @ W_out.T)
for s, p in zip(sentences, P):
ctx, target = " ".join(s.split()[:3]), s.split()[3]
print(f"{ctx:14s} -> {vocab[int(np.argmax(p))]:5s} {100 * p.max():.2f}% (target {target})")
np.save("w_out_trained.npy", W_out)
Вывод
step 0 loss 2.0857
step 100 loss 0.1362
step 200 loss 0.0680
step 300 loss 0.0450
step 400 loss 0.0336
step 500 loss 0.0268
the sky is -> blue 95.79% (target blue)
the grass is -> green 98.78% (target green)
the sun is -> hot 97.55% (target hot)
Потеря падает с 2.0857 (почти угадывание: ln8=2.0794) до 0.0268 за 500 шагов, и все три фразы предсказаны верно. Выученная матрица не совпадает с нашей ручной, но делает ту же работу: решений много, градиентный спуск находит одно из них. Зерно генератора (seed — начальное число, из которого генератор выводит все «случайные» числа) зафиксировано, поэтому при каждом запуске числа одинаковые. На другой версии NumPy случайные начальные числа могут немного отличаться, а с ними и промежуточные потери; итог — три верных ответа — тот же.
Последняя строка, np.save, записывает выученную матрицу в файл w_out_trained.npy — двоичный формат NumPy для одного массива; он понадобится в разделе 8. Попробуйте сами: поставьте скорость обучения lr = 1.0 или lr = 0.01 и сравните, как быстро падает потеря. Это тема будущего класса «Цикл обучения и кривые потерь».
8. Уголок безопасности: модель — это просто массив чисел
Файл модели — это массив весов. В нём нет логики, которую можно прочитать как код, поэтому подмену одного числа не заметит ни рецензент кода, ни сама программа. Сохраним ручную Wout из раздела 6 в файл, изменим в нём одно число и посмотрим на ответ после "the sky is".
original: blue 97.73% sha256 438549fa74cb0037
tampered: hot 88.03% sha256 a78d2d260e904fe1
hash matches the recorded one? False
Одно число (строка "hot", столбец d2: 0 → 3) подняло логит "hot" с 1 до 7, выше, чем у "blue" (5). Ответ сменился с "blue" 97.73% на "hot" 88.03%. Программа не упала и не выдала ошибку: она просто стала отвечать иначе. Изменился только отпечаток SHA-256 (Secure Hash Algorithm 256, 256-битный алгоритм безопасного хеширования). Хеш — короткая строка, вычисленная из каждого байта файла; если изменить хотя бы один байт, она меняется целиком.
Что делать на практике.
Записывайте хеш файла модели сразу после обучения или получения и храните его отдельно от самого файла.
Проверяйте хеш перед каждой загрузкой. Команда sha256sum вычисляет хеш, а с ключом -c сверяет файлы с сохранённым списком. Пример с файлом из раздела 7 (Linux; на macOS — shasum -a 256, в Windows PowerShell — Get-FileHash):
Терминал (bash)
sha256sum w_out_trained.npy > w_out_trained.npy.sha256 # record once
sha256sum -c w_out_trained.npy.sha256 # check before use
Вывод
w_out_trained.npy: OK
После изменения одного веса та же проверка печатает:
Вывод
w_out_trained.npy: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
Загружайте только массивы: np.load по умолчанию не исполняет встроенные объекты Python (allow_pickle=False; pickle — формат Python для сохранения целых объектов, который при загрузке может запустить код), и включать это без нужды не стоит.
Хеш доказывает, что файл не изменился, но не то, что он был хорош с самого начала. Происхождение обучающих данных — отдельный вопрос (см. «Вывод для безопасности» в бумажном занятии).
9. Кратко
Нужны только Python 3 и NumPy в виртуальном окружении; всё работает без сети и без графического процессора.
Тройной цикл и оператор умножения матриц @ дают одно и то же произведение; оператор @ быстрее.
Каждый бумажный расчёт — несколько строк кода с теми же числами: 19/22/43/50, 0.7311, 1.8 и 0.16, 71.64%, 97.73%.
Обучение — это шаг градиентного спуска в цикле; для softmax с перекрёстной энтропией градиент равен p−y.
Модель — массив чисел: одно изменённое число меняет ответ, поэтому файлы моделей проверяют по хешу SHA-256.
Следующие классы факультета (в планах). Факультет «Информатика» откроется, когда будут готовы три класса:
«Токенизатор вручную» — как текст превращается в идентификаторы токенов.
«Цикл обучения и кривые потерь» — скорость обучения, переобучение и как читать график потерь.
Весь вывод в этом занятии — настоящий: все фрагменты запущены 17 ноября 2026 года на Python 3.13.5 и NumPy 2.5.4. Числа разделов 2–6 совпадают с бумажным занятием; числа раздела 7 зависят от генератора случайных чисел.
10. Замечание
Леонардо да Винчи писал, что практика без знания подобна моряку, вышедшему в море без руля и компаса (записные книги / «Трактат о живописи»). Стройте сеть с пониманием, а не только запуская фрагмент.
In A neural network by hand we did everything on paper. Now we repeat the same calculations in code on your own laptop: no GPU (graphics processing unit), no cloud, no model downloads. All you need is Python 3 and the NumPy library. Each snippet below is a standalone file you can run; the real output is shown under it, and the numbers match the paper lesson to the last digit. At the end we go one step further: train the network from scratch, then see how one changed number in a model file changes the answer.
1. Setup: Python 3 and NumPy in a virtual environment
A virtual environment (venv) is a separate folder with its own packages (ready-made code libraries) that leaves the system Python alone. The activate command switches the current terminal to that environment. Install NumPy (a library for fast calculations on arrays of numbers) once with pip, Python's package installer; after that everything works offline.
Check it with python -c "import numpy; print(numpy.__version__)" (the -c flag runs the one-line program in quotes). We used Python 3.13.5 and NumPy 2.5.4 for this lesson. Save each snippet to a file (for example s1_matmul.py) and run it with python s1_matmul.py.
2. Matrix multiplication: the triple loop and the @ operator
Recap: one result cell is a row times a column, with the products added (section 1 of the paper lesson). The triple loop below is exactly that "triangle": i picks the row, j the column, and k walks along them. NumPy does the same with the @ operator (Python's matrix-multiplication operator: A @ B computes the product AB), only faster. The line import numpy as np loads NumPy under the short name np, and np.array turns a list of lists into an array, NumPy's table of numbers.
Python
import numpy as np
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
def matmul(A, B):
rows, inner, cols = len(A), len(B), len(B[0])
C = [[0] * cols for _ in range(rows)]
for i in range(rows): # row of A
for j in range(cols): # column of B
for k in range(inner): # walk the "triangle"
C[i][j] += A[i][k] * B[k][j]
return C
print("by hand:", matmul(A, B))
print("numpy:\n", np.array(A) @ np.array(B))
print("BA:\n", np.array(B) @ np.array(A))
The hand loop and NumPy give the same AB: 19, 22, 43, 50. The last line confirms BA=AB. For large matrices a hand-written Python loop is slow, while the @ operator (A @ B) hands the work to an optimized linear-algebra library. That is why the rest of the lesson writes matrix products as A @ B.
3. Activation functions: ReLU, sigmoid, GELU
The formulas are the same as in section 2 of the paper lesson. Exact GELU needs the error function (erf), which ships in the standard math module, so there's nothing to install: Φ(x)=21(1+erf(x/2)). In the code, np.maximum(0, x) is ReLU applied to every element of the array at once, and np.exp is ex for every element.
Python
import math
import numpy as np
def relu(x):
return np.maximum(0, x)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def gelu(x): # exact form: x * Phi(x), Phi via the error function
return np.array([v * 0.5 * (1 + math.erf(v / math.sqrt(2))) for v in x])
def gelu_tanh(x): # common approximation
return 0.5 * x * (1 + np.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * x**3)))
x = np.array([-2.0, -1.0, 0.0, 1.0, 2.0])
print(" x ReLU sigmoid GELU")
for v, r, s, g in zip(x, relu(x), sigmoid(x), gelu(x)):
print(f"{v:+.0f} {r:4.0f} {s:.4f} {g:+.4f}")
print("max |GELU exact - tanh approx| =", f"{np.max(np.abs(gelu(x) - gelu_tanh(x))):.5f}")
The table matches the paper one: sigmoid 0.1192, 0.2689, 0.5000, 0.7311, 0.8808; GELU −0.0455, −0.1587, 0, 0.8413, 1.9545. The tanh approximation differs from the exact form by at most 0.00015, as the paper lesson says.
4. One gradient descent step
Model y^=w⋅x, loss (y^−y)2, x=2, y=4, w=1, η=0.1 (section 3). Here η is the learning rate (lr in the code): how big a step we take, and the gradient is the slope of the loss: which way and how steeply it rises.
Python
x, y = 2.0, 4.0 # input and correct answer
w, lr = 1.0, 0.1 # starting weight, learning rate
y_hat = w * x
loss = (y_hat - y) ** 2
grad = 2 * (y_hat - y) * x
w_new = w - lr * grad
loss_new = (w_new * x - y) ** 2
print(f"y_hat={y_hat} loss={loss} grad={grad}")
print(f"w_new={w_new:.1f} y_hat_new={w_new * x:.1f} loss_new={loss_new:.2f}")
Gradient −8, new weight 1.8, and the loss falls from 4 to 0.16, the same numbers as on paper. In section 7 this same step runs in a loop.
5. The 2 → 2 → 1 forward pass
The whole network from section 4 is four lines of code: multiply, add bias (a constant added to each neuron), ReLU, then the output layer and sigmoid. W1 @ x is the matrix times the input column.
Python
import numpy as np
x = np.array([1.0, 2.0])
W1 = np.array([[0.5, -1.0],
[1.0, 0.5]])
b1 = np.array([0.0, 0.5])
W2 = np.array([1.0, 0.8])
b2 = -1.0
pre = W1 @ x + b1 # hidden layer before activation
h = np.maximum(0, pre) # ReLU
z = W2 @ h + b2 # output logit
y = 1 / (1 + np.exp(-z)) # sigmoid
print("pre-activation:", pre)
print("h (after ReLU):", h)
print(f"z = {z:.1f} y_hat = {y:.4f} ({100 * y:.2f}%)")
Output
pre-activation: [-1.5 2.5]
h (after ReLU): [0. 2.5]
z = 1.0 y_hat = 0.7311 (73.11%)
Neuron 1 gives −1.5 and switches off, neuron 2 gives 2.5, z=1.0, and the answer is 0.7311 (73.11%), as on paper.
6. Next token: 4 words, then 8 tokens in three dimensions
6.1. Four words (section 5). The embedding of "is" (the vector of numbers that stands for the word) is (1,1); multiplying by Wout gives logits (raw scores, one per word), and softmax turns them into probabilities that add up to 1.
Python
import numpy as np
vocab = ["the", "sky", "is", "blue"]
e = np.array([1.0, 1.0]) # embedding of "is" (ID 2)
W_out = np.array([[ 0.2, -0.1],
[ 0.5, 0.0],
[-0.3, 0.1],
[ 1.0, 1.2]])
z = W_out @ e
ez = np.exp(z)
p = ez / ez.sum()
print("logits:", np.round(z, 4))
print("e^z: ", np.round(ez, 4), " sum =", round(ez.sum(), 4))
for t, pi in zip(vocab, p):
print(f" {t:5s} {100 * pi:6.2f}%")
print("prediction:", vocab[int(np.argmax(p))], f" loss = {-np.log(p[3]):.4f}")
Output
logits: [ 0.1 0.5 -0.2 2.2]
e^z: [1.1052 1.6487 0.8187 9.025 ] sum = 12.5976
the 8.77%
sky 13.09%
is 6.50%
blue 71.64%
prediction: blue loss = 0.3335
Sum of exponentials 12.5976, "blue" 71.64%, loss 0.3335: it matches.
6.2. Eight tokens, three dimensions (section 6). Same E and Wout tables. One practical detail: in softmax we subtract the largest logit before exponentiating. The probabilities don't change (the factor cancels top and bottom), but large logits can't overflow (produce a number too large for the computer to store). That's how softmax is written in real code.
Python
import numpy as np
vocab = ["the", "sky", "is", "blue", "grass", "green", "sun", "hot"]
ID = {t: i for i, t in enumerate(vocab)}
# Embedding table E (8 x 3): d1 color, d2 sky(+)/ground(-), d3 warm(+)/cool(-)
E = np.array([[0, 0, 0], # the
[0, 2, 0], # sky
[1, 0, 1], # is
[2, 1, -1], # blue
[0, -2, 0], # grass
[2, -1, 0], # green
[0, 2, 2], # sun
[0, 0, 2]], # hot
dtype=float)
# Output matrix W_out (8 x 3): one row per token
neg = [-1, 0, -1]
W_out = np.array([neg, neg, neg, [2, 2, -1], neg, [2, -2, -1], neg, [-2, 0, 3]],
dtype=float)
def cosine(a, b):
return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
def softmax(z):
ez = np.exp(z - z.max()) # subtract the max: same result, no overflow
return ez / ez.sum()
print("cosine similarity:")
for a, b in [("blue", "green"), ("sky", "sun"), ("green", "hot"),
("blue", "hot"), ("sky", "grass")]:
va, vb = E[ID[a]], E[ID[b]]
print(f" {a:5s} . {b:5s} dot={va @ vb:+.0f} cos={cosine(va, vb):+.4f}")
def predict(words, target=None, average=False):
c = E[[ID[w] for w in words]].sum(axis=0)
if average:
c = c / len(words)
p = softmax(W_out @ c)
best = vocab[int(np.argmax(p))]
line = f" {' '.join(words):14s} c={np.round(c, 4)} -> {best} {100 * p.max():.2f}%"
if target:
line += f" loss={-np.log(p[ID[target]]):.4f}"
print(line)
return p
print("next-token prediction (sum of context embeddings):")
p_is = predict(["is"])
print(f" blue/green/hot {100 * p_is[ID['blue']]:.2f}% each, others {100 * p_is[ID['the']]:.2f}% each")
p_sky = predict(["the", "sky", "is"], "blue")
predict(["the", "grass", "is"], "green")
predict(["the", "sun", "is"], "hot")
print(f" wrong target 'green' after 'the sky is': loss={-np.log(p_sky[ID['green']]):.4f}")
print("averaging instead of summing:")
for words in (["the", "sky", "is"], ["the", "grass", "is"], ["the", "sun", "is"]):
predict(words, average=True)
Output
cosine similarity:
blue . green dot=+3 cos=+0.5477
sky . sun dot=+4 cos=+0.7071
green . hot dot=+0 cos=+0.0000
blue . hot dot=-2 cos=-0.4082
sky . grass dot=-4 cos=-1.0000
next-token prediction (sum of context embeddings):
is c=[1. 0. 1.] -> blue 30.78%
blue/green/hot 30.78% each, others 1.53% each
the sky is c=[1. 2. 1.] -> blue 97.73% loss=0.0229
the grass is c=[ 1. -2. 1.] -> green 97.73% loss=0.0229
the sun is c=[1. 2. 3.] -> hot 98.19% loss=0.0182
wrong target 'green' after 'the sky is': loss=8.0229
averaging instead of summing:
the sky is c=[0.3333 0.6667 0.3333] -> blue 55.01%
the grass is c=[ 0.3333 -0.6667 0.3333] -> green 55.01%
the sun is c=[0.3333 0.6667 1. ] -> hot 70.94%
Everything matches paper section 6:
Cosines 0.5477, 0.7071, 0, −0.4082, −1.
With "is" alone, three candidates get 30.78% each and the rest 1.53% each. On a tie argmax (the position of the largest value) takes the first one, so it prints "blue", but it's still a tie.
With context: "blue" 97.73%, "green" 97.73%, "hot" 98.19%; losses 0.0229, 0.0229, 0.0182; the wrong target gives 8.0229.
Averaging gives 55.01%, 55.01%, 70.94%.
7. One step further: learn Wout from scratch
On paper we picked Wout by hand. Now let the network find it: start from small random numbers and repeat the gradient descent step from section 4 on the three sentences. The embeddings E stay fixed.
The gradient in one line. For context c, logits z=Woutc, probabilities p=softmax(z) and loss L=−lnptarget (paper sections 5 and 6), the derivative with respect to the logits is surprisingly simple:
∂z∂L=p−y
∂Wout∂L=(p−y)c⊤
Here y is all zeros with a one at the correct token (one-hot). In words: the correct token was "short-changed" by 1−p, so its row is pulled toward c; each wrong token was "overpaid" by p, so its row is pushed away. It simplifies this neatly because the −ln and the exponential in softmax cancel. c⊤ is c written as a row, so (p−y)c⊤ is a table with one row per token, the same shape as Wout.
Python
import numpy as np
vocab = ["the", "sky", "is", "blue", "grass", "green", "sun", "hot"]
ID = {t: i for i, t in enumerate(vocab)}
E = np.array([[0, 0, 0], [0, 2, 0], [1, 0, 1], [2, 1, -1],
[0, -2, 0], [2, -1, 0], [0, 2, 2], [0, 0, 2]], dtype=float)
sentences = ["the sky is blue", "the grass is green", "the sun is hot"]
X = np.array([E[[ID[w] for w in s.split()[:3]]].sum(axis=0) for s in sentences]) # 3 x 3 contexts
Y = np.zeros((3, 8))
for row, s in enumerate(sentences):
Y[row, ID[s.split()[3]]] = 1.0 # one-hot targets
def softmax_rows(Z):
EZ = np.exp(Z - Z.max(axis=1, keepdims=True))
return EZ / EZ.sum(axis=1, keepdims=True)
rng = np.random.default_rng(42) # fixed seed: same output every run
W_out = rng.normal(0, 0.1, size=(8, 3)) # random start, no hand-picked numbers
lr, steps = 0.1, 500
for step in range(steps + 1):
P = softmax_rows(X @ W_out.T) # forward pass, 3 x 8
loss = -np.mean(np.log(P[Y == 1])) # mean cross-entropy
if step % 100 == 0:
print(f"step {step:3d} loss {loss:.4f}")
grad = (P - Y).T @ X / len(X) # dL/dW_out = (p - y) c^T, averaged
W_out -= lr * grad # gradient descent step
P = softmax_rows(X @ W_out.T)
for s, p in zip(sentences, P):
ctx, target = " ".join(s.split()[:3]), s.split()[3]
print(f"{ctx:14s} -> {vocab[int(np.argmax(p))]:5s} {100 * p.max():.2f}% (target {target})")
np.save("w_out_trained.npy", W_out)
Output
step 0 loss 2.0857
step 100 loss 0.1362
step 200 loss 0.0680
step 300 loss 0.0450
step 400 loss 0.0336
step 500 loss 0.0268
the sky is -> blue 95.79% (target blue)
the grass is -> green 98.78% (target green)
the sun is -> hot 97.55% (target hot)
The loss falls from 2.0857 (close to guessing: ln8=2.0794) to 0.0268 in 500 steps, and all three sentences are predicted correctly. The learned matrix differs from our hand-made one but does the same job: there are many solutions, and gradient descent finds one of them. The generator seed (the starting number the random generator derives all its numbers from) is fixed, so every run prints the same numbers. On another NumPy version the random starting numbers, and with them the intermediate losses, may differ slightly; the end result, three correct answers, stays the same.
The last line, np.save, writes the learned matrix to w_out_trained.npy, NumPy's binary file format for a single array; section 8 uses it. Try it: set the learning rate to lr = 1.0 or lr = 0.01 and compare how fast the loss falls. That's the topic of a future class, "Training loop and loss curves".
8. Security corner: a model is just an array of numbers
A model file is an array of weights. There's no logic in it to read like code, so a single changed number gets past both a code reviewer and the program itself. Let's save the hand-made Wout from section 6 to a file, change one number in it, and look at the answer after "the sky is".
original: blue 97.73% sha256 438549fa74cb0037
tampered: hot 88.03% sha256 a78d2d260e904fe1
hash matches the recorded one? False
One number (row "hot", column d2: 0 → 3) raised the "hot" logit from 1 to 7, above "blue" (5). The answer flipped from "blue" 97.73% to "hot" 88.03%. The program didn't crash or raise an error; it just answered differently. The only thing that gave it away was the SHA-256 (Secure Hash Algorithm, 256-bit) fingerprint. A hash is a short string computed from every byte of a file; change even one byte and it changes completely.
What to do in practice.
Record a model file's hash right after training or receiving it, and store it separately from the file.
Check the hash before every load. The sha256sum command computes the hash, and with -c it checks files against a saved list. An example with the file from section 7 (Linux; on macOS use shasum -a 256, in Windows PowerShell use Get-FileHash):
Terminal (bash)
sha256sum w_out_trained.npy > w_out_trained.npy.sha256 # record once
sha256sum -c w_out_trained.npy.sha256 # check before use
Output
w_out_trained.npy: OK
After one weight is changed, the same check prints:
Output
w_out_trained.npy: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
Load arrays only: np.load doesn't execute embedded Python objects by default (allow_pickle=False; pickle is Python's format for saving whole objects, and loading it can run code), and there's no reason to turn that on without need.
A hash proves the file hasn't changed, not that it was good to begin with. Where the training data came from is a separate question (see the "Security takeaway" in the paper lesson).
9. Summary
All you need is Python 3 and NumPy in a virtual environment; everything runs offline and without a GPU.
The triple loop and the matrix-multiplication operator @ give the same matrix product; the @ operator is faster.
Every paper calculation is a few lines of code with the same numbers: 19/22/43/50, 0.7311, 1.8 and 0.16, 71.64%, 97.73%.
Training is the gradient descent step in a loop; for softmax with cross-entropy the gradient is p−y.
A model is an array of numbers: one changed number changes the answer, so model files get checked with a SHA-256 hash.
Next classes in this faculty (planned). The Computer Science faculty opens when three classes are ready:
"Tokenizer by hand": how text becomes token IDs.
"Training loop and loss curves": learning rate, overfitting, and how to read a loss curve.
All output in this lesson is real: every snippet was run on Nov 17, 2026, with Python 3.13.5 and NumPy 2.5.4. Numbers in sections 2–6 match the paper lesson; section 7 numbers depend on the random number generator.
10. A note
Leonardo da Vinci wrote that practice without knowledge is like a sailor who puts to sea without rudder or compass (notebooks / Treatise on Painting). Build the network with understanding, not only by running a snippet.
np.load default allow_pickle=False; Python pickle security warning: “The pickle module is not secure. Only unpickle data you trust.”: numpy.org · numpy.org · docs.python.org
En Una red neuronal a mano lo hicimos todo sobre papel. Ahora repetimos los mismos cálculos en código, en su propia computadora portátil: sin GPU (unidad de procesamiento gráfico), sin nube, sin descargar modelos. Solo necesita Python 3 y la biblioteca NumPy. Cada fragmento de código es un archivo independiente que puede ejecutar; debajo se muestra la salida real, y los números coinciden con la lección en papel hasta el último dígito. Al final damos un paso más: entrenamos la red desde cero y luego vemos cómo un solo número modificado en el archivo de un modelo cambia la respuesta.
1. Preparación: Python 3 y NumPy en un entorno virtual
Un entorno virtual (venv) es una carpeta independiente con sus propios paquetes (bibliotecas de código ya preparadas) que deja intacto el Python del sistema. El comando activate hace que la terminal actual use ese entorno. Instale NumPy (una biblioteca para cálculos rápidos con matrices de números) una sola vez con pip, el instalador de paquetes de Python; a partir de ahí, todo funciona sin conexión.
Compruébelo con python -c "import numpy; print(numpy.__version__)" (la opción -c ejecuta el programa de una sola línea que va entre comillas). Para esta lección usamos Python 3.13.5 y NumPy 2.5.4. Guarde cada fragmento en un archivo (por ejemplo, s1_matmul.py) y ejecútelo con python s1_matmul.py.
2. Multiplicación de matrices: el triple bucle y el operador @
Repaso: cada celda del resultado es una fila por una columna, con los productos sumados (sección 1 de la lección en papel). El triple bucle de abajo es exactamente ese «triángulo»: i elige la fila, j la columna y k recorre ambas. NumPy hace lo mismo con el operador @ (el operador de multiplicación de matrices de Python: A @ B calcula el producto AB), solo que más rápido. La línea import numpy as np carga NumPy con el nombre corto np, y np.array convierte una lista de listas en un arreglo, la tabla de números de NumPy.
Python
import numpy as np
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
def matmul(A, B):
rows, inner, cols = len(A), len(B), len(B[0])
C = [[0] * cols for _ in range(rows)]
for i in range(rows): # row of A
for j in range(cols): # column of B
for k in range(inner): # walk the "triangle"
C[i][j] += A[i][k] * B[k][j]
return C
print("by hand:", matmul(A, B))
print("numpy:\n", np.array(A) @ np.array(B))
print("BA:\n", np.array(B) @ np.array(A))
El bucle manual y NumPy dan el mismo AB: 19, 22, 43, 50. La última línea confirma BA=AB. En matrices grandes, un bucle de Python escrito a mano es lento, mientras que el operador @ (A @ B) delega el trabajo en una biblioteca de álgebra lineal optimizada. Por eso, en el resto de la lección escribimos los productos de matrices como A @ B.
3. Funciones de activación: ReLU, sigmoide, GELU
Las fórmulas son las mismas que en la sección 2 de la lección en papel. La GELU exacta necesita la función de error (erf), que viene en el módulo estándar math, así que no hay nada que instalar: Φ(x)=21(1+erf(x/2)). En el código, np.maximum(0, x) es la ReLU aplicada de una vez a cada elemento del arreglo, y np.exp es ex para cada elemento.
Python
import math
import numpy as np
def relu(x):
return np.maximum(0, x)
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def gelu(x): # exact form: x * Phi(x), Phi via the error function
return np.array([v * 0.5 * (1 + math.erf(v / math.sqrt(2))) for v in x])
def gelu_tanh(x): # common approximation
return 0.5 * x * (1 + np.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * x**3)))
x = np.array([-2.0, -1.0, 0.0, 1.0, 2.0])
print(" x ReLU sigmoid GELU")
for v, r, s, g in zip(x, relu(x), sigmoid(x), gelu(x)):
print(f"{v:+.0f} {r:4.0f} {s:.4f} {g:+.4f}")
print("max |GELU exact - tanh approx| =", f"{np.max(np.abs(gelu(x) - gelu_tanh(x))):.5f}")
La tabla coincide con la de papel: sigmoide 0.1192, 0.2689, 0.5000, 0.7311, 0.8808; GELU −0.0455, −0.1587, 0, 0.8413, 1.9545. La aproximación con tanh difiere de la forma exacta en 0.00015 como máximo, como dice la lección en papel.
4. Un paso de descenso del gradiente
Modelo y^=w⋅x, pérdida (y^−y)2, x=2, y=4, w=1, η=0.1 (sección 3). Aquí η es la tasa de aprendizaje (lr en el código): cuán grande es el paso que damos; y el gradiente es la pendiente de la pérdida: hacia dónde y con qué inclinación crece.
Python
x, y = 2.0, 4.0 # input and correct answer
w, lr = 1.0, 0.1 # starting weight, learning rate
y_hat = w * x
loss = (y_hat - y) ** 2
grad = 2 * (y_hat - y) * x
w_new = w - lr * grad
loss_new = (w_new * x - y) ** 2
print(f"y_hat={y_hat} loss={loss} grad={grad}")
print(f"w_new={w_new:.1f} y_hat_new={w_new * x:.1f} loss_new={loss_new:.2f}")
Gradiente −8, nuevo peso 1.8, y la pérdida baja de 4 a 0.16: los mismos números que en papel. En la sección 7, este mismo paso se ejecuta en un bucle.
5. El paso hacia adelante 2 → 2 → 1
Toda la red de la sección 4 son cuatro líneas de código: multiplicar, sumar el sesgo (una constante que se añade a cada neurona), ReLU y, después, la capa de salida y la sigmoide. W1 @ x es la matriz por la columna de entrada.
Python
import numpy as np
x = np.array([1.0, 2.0])
W1 = np.array([[0.5, -1.0],
[1.0, 0.5]])
b1 = np.array([0.0, 0.5])
W2 = np.array([1.0, 0.8])
b2 = -1.0
pre = W1 @ x + b1 # hidden layer before activation
h = np.maximum(0, pre) # ReLU
z = W2 @ h + b2 # output logit
y = 1 / (1 + np.exp(-z)) # sigmoid
print("pre-activation:", pre)
print("h (after ReLU):", h)
print(f"z = {z:.1f} y_hat = {y:.4f} ({100 * y:.2f}%)")
Salida
pre-activation: [-1.5 2.5]
h (after ReLU): [0. 2.5]
z = 1.0 y_hat = 0.7311 (73.11%)
La neurona 1 da −1.5 y se apaga, la neurona 2 da 2.5, z=1.0, y la respuesta es 0.7311 (73.11 %), como en papel.
6. Siguiente token: 4 palabras y luego 8 tokens en tres dimensiones
6.1. Cuatro palabras (sección 5). La incrustación de «is» (el vector de números que representa la palabra) es (1,1); al multiplicar por Wout se obtienen los logits (puntuaciones en bruto, una por palabra), y softmax los convierte en probabilidades que suman 1.
Python
import numpy as np
vocab = ["the", "sky", "is", "blue"]
e = np.array([1.0, 1.0]) # embedding of "is" (ID 2)
W_out = np.array([[ 0.2, -0.1],
[ 0.5, 0.0],
[-0.3, 0.1],
[ 1.0, 1.2]])
z = W_out @ e
ez = np.exp(z)
p = ez / ez.sum()
print("logits:", np.round(z, 4))
print("e^z: ", np.round(ez, 4), " sum =", round(ez.sum(), 4))
for t, pi in zip(vocab, p):
print(f" {t:5s} {100 * pi:6.2f}%")
print("prediction:", vocab[int(np.argmax(p))], f" loss = {-np.log(p[3]):.4f}")
Salida
logits: [ 0.1 0.5 -0.2 2.2]
e^z: [1.1052 1.6487 0.8187 9.025 ] sum = 12.5976
the 8.77%
sky 13.09%
is 6.50%
blue 71.64%
prediction: blue loss = 0.3335
Suma de exponenciales 12.5976, «blue» 71.64 %, pérdida 0.3335: coincide.
6.2. Ocho tokens, tres dimensiones (sección 6). Las mismas tablas E y Wout. Un detalle práctico: en softmax restamos el logit más grande antes de exponenciar. Las probabilidades no cambian (el factor se cancela en el numerador y el denominador), pero los logits grandes ya no pueden provocar un desbordamiento (producir un número demasiado grande para que la computadora lo almacene). Así se escribe softmax en el código real.
Python
import numpy as np
vocab = ["the", "sky", "is", "blue", "grass", "green", "sun", "hot"]
ID = {t: i for i, t in enumerate(vocab)}
# Embedding table E (8 x 3): d1 color, d2 sky(+)/ground(-), d3 warm(+)/cool(-)
E = np.array([[0, 0, 0], # the
[0, 2, 0], # sky
[1, 0, 1], # is
[2, 1, -1], # blue
[0, -2, 0], # grass
[2, -1, 0], # green
[0, 2, 2], # sun
[0, 0, 2]], # hot
dtype=float)
# Output matrix W_out (8 x 3): one row per token
neg = [-1, 0, -1]
W_out = np.array([neg, neg, neg, [2, 2, -1], neg, [2, -2, -1], neg, [-2, 0, 3]],
dtype=float)
def cosine(a, b):
return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
def softmax(z):
ez = np.exp(z - z.max()) # subtract the max: same result, no overflow
return ez / ez.sum()
print("cosine similarity:")
for a, b in [("blue", "green"), ("sky", "sun"), ("green", "hot"),
("blue", "hot"), ("sky", "grass")]:
va, vb = E[ID[a]], E[ID[b]]
print(f" {a:5s} . {b:5s} dot={va @ vb:+.0f} cos={cosine(va, vb):+.4f}")
def predict(words, target=None, average=False):
c = E[[ID[w] for w in words]].sum(axis=0)
if average:
c = c / len(words)
p = softmax(W_out @ c)
best = vocab[int(np.argmax(p))]
line = f" {' '.join(words):14s} c={np.round(c, 4)} -> {best} {100 * p.max():.2f}%"
if target:
line += f" loss={-np.log(p[ID[target]]):.4f}"
print(line)
return p
print("next-token prediction (sum of context embeddings):")
p_is = predict(["is"])
print(f" blue/green/hot {100 * p_is[ID['blue']]:.2f}% each, others {100 * p_is[ID['the']]:.2f}% each")
p_sky = predict(["the", "sky", "is"], "blue")
predict(["the", "grass", "is"], "green")
predict(["the", "sun", "is"], "hot")
print(f" wrong target 'green' after 'the sky is': loss={-np.log(p_sky[ID['green']]):.4f}")
print("averaging instead of summing:")
for words in (["the", "sky", "is"], ["the", "grass", "is"], ["the", "sun", "is"]):
predict(words, average=True)
Salida
cosine similarity:
blue . green dot=+3 cos=+0.5477
sky . sun dot=+4 cos=+0.7071
green . hot dot=+0 cos=+0.0000
blue . hot dot=-2 cos=-0.4082
sky . grass dot=-4 cos=-1.0000
next-token prediction (sum of context embeddings):
is c=[1. 0. 1.] -> blue 30.78%
blue/green/hot 30.78% each, others 1.53% each
the sky is c=[1. 2. 1.] -> blue 97.73% loss=0.0229
the grass is c=[ 1. -2. 1.] -> green 97.73% loss=0.0229
the sun is c=[1. 2. 3.] -> hot 98.19% loss=0.0182
wrong target 'green' after 'the sky is': loss=8.0229
averaging instead of summing:
the sky is c=[0.3333 0.6667 0.3333] -> blue 55.01%
the grass is c=[ 0.3333 -0.6667 0.3333] -> green 55.01%
the sun is c=[0.3333 0.6667 1. ] -> hot 70.94%
Todo coincide con la sección 6 en papel:
Cosenos 0.5477, 0.7071, 0, −0.4082, −1.
Con «is» a solas, tres candidatos obtienen 30.78 % cada uno y el resto, 1.53 % cada uno. En caso de empate, argmax (la posición del valor más grande) toma el primero, así que imprime «blue», pero sigue siendo un empate.
Con contexto: «blue» 97.73 %, «green» 97.73 %, «hot» 98.19 %; pérdidas 0.0229, 0.0229, 0.0182; el objetivo erróneo da 8.0229.
El promedio da 55.01 %, 55.01 %, 70.94 %.
7. Un paso más: aprender Wout desde cero
En papel elegimos Wout a mano. Ahora dejemos que la red lo encuentre: partimos de números aleatorios pequeños y repetimos el paso de descenso del gradiente de la sección 4 con las tres oraciones. Las incrustaciones E permanecen fijas.
El gradiente en una línea. Para el contexto c, los logits z=Woutc, las probabilidades p=softmax(z) y la pérdida L=−lnptarget (secciones 5 y 6 en papel), la derivada respecto de los logits es sorprendentemente simple:
Aquí y es todo ceros con un uno en el token correcto (codificación one-hot). En palabras: al token correcto le «faltó» 1−p, así que su fila se atrae hacia c; cada token incorrecto «recibió de más» p, así que su fila se aleja. Se simplifica con tanta elegancia porque el −ln y la exponencial de softmax se cancelan. c⊤ es c escrito como fila, así que (p−y)c⊤ es una tabla con una fila por token, con la misma forma que Wout.
Python
import numpy as np
vocab = ["the", "sky", "is", "blue", "grass", "green", "sun", "hot"]
ID = {t: i for i, t in enumerate(vocab)}
E = np.array([[0, 0, 0], [0, 2, 0], [1, 0, 1], [2, 1, -1],
[0, -2, 0], [2, -1, 0], [0, 2, 2], [0, 0, 2]], dtype=float)
sentences = ["the sky is blue", "the grass is green", "the sun is hot"]
X = np.array([E[[ID[w] for w in s.split()[:3]]].sum(axis=0) for s in sentences]) # 3 x 3 contexts
Y = np.zeros((3, 8))
for row, s in enumerate(sentences):
Y[row, ID[s.split()[3]]] = 1.0 # one-hot targets
def softmax_rows(Z):
EZ = np.exp(Z - Z.max(axis=1, keepdims=True))
return EZ / EZ.sum(axis=1, keepdims=True)
rng = np.random.default_rng(42) # fixed seed: same output every run
W_out = rng.normal(0, 0.1, size=(8, 3)) # random start, no hand-picked numbers
lr, steps = 0.1, 500
for step in range(steps + 1):
P = softmax_rows(X @ W_out.T) # forward pass, 3 x 8
loss = -np.mean(np.log(P[Y == 1])) # mean cross-entropy
if step % 100 == 0:
print(f"step {step:3d} loss {loss:.4f}")
grad = (P - Y).T @ X / len(X) # dL/dW_out = (p - y) c^T, averaged
W_out -= lr * grad # gradient descent step
P = softmax_rows(X @ W_out.T)
for s, p in zip(sentences, P):
ctx, target = " ".join(s.split()[:3]), s.split()[3]
print(f"{ctx:14s} -> {vocab[int(np.argmax(p))]:5s} {100 * p.max():.2f}% (target {target})")
np.save("w_out_trained.npy", W_out)
Salida
step 0 loss 2.0857
step 100 loss 0.1362
step 200 loss 0.0680
step 300 loss 0.0450
step 400 loss 0.0336
step 500 loss 0.0268
the sky is -> blue 95.79% (target blue)
the grass is -> green 98.78% (target green)
the sun is -> hot 97.55% (target hot)
La pérdida baja de 2.0857 (casi como adivinar: ln8=2.0794) a 0.0268 en 500 pasos, y las tres oraciones se predicen correctamente. La matriz aprendida difiere de la hecha a mano, pero cumple la misma función: hay muchas soluciones, y el descenso del gradiente encuentra una de ellas. La semilla del generador (el número inicial del que el generador aleatorio deriva todos sus números) es fija, de modo que cada ejecución imprime los mismos números. En otra versión de NumPy, los números aleatorios iniciales, y con ellos las pérdidas intermedias, pueden diferir ligeramente; el resultado final, tres respuestas correctas, se mantiene.
La última línea, np.save, escribe la matriz aprendida en w_out_trained.npy, el formato binario de NumPy para un solo arreglo; la sección 8 lo utiliza. Pruebe: establezca la tasa de aprendizaje en lr = 1.0 o lr = 0.01 y compare la rapidez con que baja la pérdida. Ese es el tema de una clase futura, «Bucle de entrenamiento y curvas de pérdida».
8. Rincón de seguridad: un modelo es solo un arreglo de números
El archivo de un modelo es un arreglo de pesos. No contiene lógica que pueda leerse como código, así que un solo número alterado pasa inadvertido tanto para quien revisa el código como para el propio programa. Guardemos en un archivo la Wout hecha a mano de la sección 6, cambiemos un número y observemos la respuesta tras «the sky is».
original: blue 97.73% sha256 438549fa74cb0037
tampered: hot 88.03% sha256 a78d2d260e904fe1
hash matches the recorded one? False
Un solo número (fila «hot», columna d2: de 0 a 3) elevó el logit de «hot» de 1 a 7, por encima de «blue» (5). La respuesta pasó de «blue» 97.73 % a «hot» 88.03 %. El programa no se cayó ni mostró ningún error; simplemente respondió de otra manera. Lo único que lo delató fue la huella SHA-256 (Secure Hash Algorithm, de 256 bits). Un hash es una cadena corta calculada a partir de cada byte de un archivo; si cambia siquiera un byte, cambia por completo.
Qué hacer en la práctica.
Registre el hash del archivo de un modelo justo después de entrenarlo o de recibirlo, y guárdelo por separado del archivo.
Compruebe el hash antes de cada carga. El comando sha256sum calcula el hash y, con -c, verifica los archivos frente a una lista guardada. Un ejemplo con el archivo de la sección 7 (Linux; en macOS use shasum -a 256; en Windows PowerShell use Get-FileHash):
Terminal (bash)
sha256sum w_out_trained.npy > w_out_trained.npy.sha256 # record once
sha256sum -c w_out_trained.npy.sha256 # check before use
Salida
w_out_trained.npy: OK
Después de cambiar un peso, la misma comprobación imprime:
Salida
w_out_trained.npy: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match
Cargue solo arreglos: np.load no ejecuta de forma predeterminada los objetos de Python incrustados (allow_pickle=False; pickle es el formato de Python para guardar objetos completos, y cargarlo puede ejecutar código), y no hay motivo para activarlo sin necesidad.
Un hash demuestra que el archivo no ha cambiado, no que fuera bueno desde el principio. El origen de los datos de entrenamiento es otra cuestión (véase la «Conclusión de seguridad» en la lección en papel).
9. Resumen
Solo necesita Python 3 y NumPy en un entorno virtual; todo se ejecuta sin conexión y sin GPU.
El triple bucle y el operador de multiplicación de matrices @ dan el mismo producto matricial; el operador @ es más rápido.
Cada cálculo en papel son unas pocas líneas de código con los mismos números: 19/22/43/50, 0.7311, 1.8 y 0.16, 71.64 %, 97.73 %.
El entrenamiento es el paso de descenso del gradiente dentro de un bucle; para softmax con entropía cruzada, el gradiente es p−y.
Un modelo es un arreglo de números: un solo número modificado cambia la respuesta, por eso los archivos de modelos se verifican con un hash SHA-256.
Próximas clases de esta facultad (previstas). La facultad de Ciencias de la computación abrirá cuando haya tres clases listas:
«Tokenizador a mano»: cómo el texto se convierte en identificadores de token.
«Bucle de entrenamiento y curvas de pérdida»: tasa de aprendizaje, sobreajuste y cómo leer una curva de pérdida.
Toda la salida de esta lección es real: cada fragmento se ejecutó el 17 nov 2026 con Python 3.13.5 y NumPy 2.5.4. Los números de las secciones 2 a 6 coinciden con la lección en papel; los de la sección 7 dependen del generador de números aleatorios.
10. Una nota
Leonardo da Vinci escribió que la práctica sin conocimiento es como un navegante que se hace a la mar sin timón ni brújula (cuadernos / Tratado de la pintura). Construya la red con comprensión, y no solo ejecutando un fragmento de código.
Valor predeterminado allow_pickle=False en np.load; advertencia de seguridad de pickle en Python: «El módulo pickle no es seguro. Deserialice únicamente datos en los que confíe»: numpy.org · numpy.org · docs.python.org
Generador con semilla y advertencia sobre versiones: numpy.org · numpy.org
Los números de la lección provienen de la ejecución de los fragmentos (ejemplos resueltos, no mediciones en vivo).
おさらい:結果の1つのセルは、行と列を掛けて、その積を足したものです(紙のレッスンのセクション1)。下の三重ループは、まさにその「三角形」です。iが行を、jが列を選び、kがそれらに沿って進みます。NumPyは、@演算子(Pythonの行列の掛け算の演算子で、A @ Bは積ABを計算します)で同じことを、より速く行います。import numpy as npの行は、NumPyを短い名前npで読み込み、np.arrayは、リストのリストを、NumPyの数の表である配列に変えます。
Python
import numpy as np
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
def matmul(A, B):
rows, inner, cols = len(A), len(B), len(B[0])
C = [[0] * cols for _ in range(rows)]
for i in range(rows): # row of A
for j in range(cols): # column of B
for k in range(inner): # walk the "triangle"
C[i][j] += A[i][k] * B[k][j]
return C
print("by hand:", matmul(A, B))
print("numpy:\n", np.array(A) @ np.array(B))
print("BA:\n", np.array(B) @ np.array(A))
import numpy as np
vocab = ["the", "sky", "is", "blue", "grass", "green", "sun", "hot"]
ID = {t: i for i, t in enumerate(vocab)}
# Embedding table E (8 x 3): d1 color, d2 sky(+)/ground(-), d3 warm(+)/cool(-)
E = np.array([[0, 0, 0], # the
[0, 2, 0], # sky
[1, 0, 1], # is
[2, 1, -1], # blue
[0, -2, 0], # grass
[2, -1, 0], # green
[0, 2, 2], # sun
[0, 0, 2]], # hot
dtype=float)
# Output matrix W_out (8 x 3): one row per token
neg = [-1, 0, -1]
W_out = np.array([neg, neg, neg, [2, 2, -1], neg, [2, -2, -1], neg, [-2, 0, 3]],
dtype=float)
def cosine(a, b):
return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
def softmax(z):
ez = np.exp(z - z.max()) # subtract the max: same result, no overflow
return ez / ez.sum()
print("cosine similarity:")
for a, b in [("blue", "green"), ("sky", "sun"), ("green", "hot"),
("blue", "hot"), ("sky", "grass")]:
va, vb = E[ID[a]], E[ID[b]]
print(f" {a:5s} . {b:5s} dot={va @ vb:+.0f} cos={cosine(va, vb):+.4f}")
def predict(words, target=None, average=False):
c = E[[ID[w] for w in words]].sum(axis=0)
if average:
c = c / len(words)
p = softmax(W_out @ c)
best = vocab[int(np.argmax(p))]
line = f" {' '.join(words):14s} c={np.round(c, 4)} -> {best} {100 * p.max():.2f}%"
if target:
line += f" loss={-np.log(p[ID[target]]):.4f}"
print(line)
return p
print("next-token prediction (sum of context embeddings):")
p_is = predict(["is"])
print(f" blue/green/hot {100 * p_is[ID['blue']]:.2f}% each, others {100 * p_is[ID['the']]:.2f}% each")
p_sky = predict(["the", "sky", "is"], "blue")
predict(["the", "grass", "is"], "green")
predict(["the", "sun", "is"], "hot")
print(f" wrong target 'green' after 'the sky is': loss={-np.log(p_sky[ID['green']]):.4f}")
print("averaging instead of summing:")
for words in (["the", "sky", "is"], ["the", "grass", "is"], ["the", "sun", "is"]):
predict(words, average=True)
出力
cosine similarity:
blue . green dot=+3 cos=+0.5477
sky . sun dot=+4 cos=+0.7071
green . hot dot=+0 cos=+0.0000
blue . hot dot=-2 cos=-0.4082
sky . grass dot=-4 cos=-1.0000
next-token prediction (sum of context embeddings):
is c=[1. 0. 1.] -> blue 30.78%
blue/green/hot 30.78% each, others 1.53% each
the sky is c=[1. 2. 1.] -> blue 97.73% loss=0.0229
the grass is c=[ 1. -2. 1.] -> green 97.73% loss=0.0229
the sun is c=[1. 2. 3.] -> hot 98.19% loss=0.0182
wrong target 'green' after 'the sky is': loss=8.0229
averaging instead of summing:
the sky is c=[0.3333 0.6667 0.3333] -> blue 55.01%
the grass is c=[ 0.3333 -0.6667 0.3333] -> green 55.01%
the sun is c=[0.3333 0.6667 1. ] -> hot 70.94%
import numpy as np
vocab = ["the", "sky", "is", "blue", "grass", "green", "sun", "hot"]
ID = {t: i for i, t in enumerate(vocab)}
E = np.array([[0, 0, 0], [0, 2, 0], [1, 0, 1], [2, 1, -1],
[0, -2, 0], [2, -1, 0], [0, 2, 2], [0, 0, 2]], dtype=float)
sentences = ["the sky is blue", "the grass is green", "the sun is hot"]
X = np.array([E[[ID[w] for w in s.split()[:3]]].sum(axis=0) for s in sentences]) # 3 x 3 contexts
Y = np.zeros((3, 8))
for row, s in enumerate(sentences):
Y[row, ID[s.split()[3]]] = 1.0 # one-hot targets
def softmax_rows(Z):
EZ = np.exp(Z - Z.max(axis=1, keepdims=True))
return EZ / EZ.sum(axis=1, keepdims=True)
rng = np.random.default_rng(42) # fixed seed: same output every run
W_out = rng.normal(0, 0.1, size=(8, 3)) # random start, no hand-picked numbers
lr, steps = 0.1, 500
for step in range(steps + 1):
P = softmax_rows(X @ W_out.T) # forward pass, 3 x 8
loss = -np.mean(np.log(P[Y == 1])) # mean cross-entropy
if step % 100 == 0:
print(f"step {step:3d} loss {loss:.4f}")
grad = (P - Y).T @ X / len(X) # dL/dW_out = (p - y) c^T, averaged
W_out -= lr * grad # gradient descent step
P = softmax_rows(X @ W_out.T)
for s, p in zip(sentences, P):
ctx, target = " ".join(s.split()[:3]), s.split()[3]
print(f"{ctx:14s} -> {vocab[int(np.argmax(p))]:5s} {100 * p.max():.2f}% (target {target})")
np.save("w_out_trained.npy", W_out)
出力
step 0 loss 2.0857
step 100 loss 0.1362
step 200 loss 0.0680
step 300 loss 0.0450
step 400 loss 0.0336
step 500 loss 0.0268
the sky is -> blue 95.79% (target blue)
the grass is -> green 98.78% (target green)
the sun is -> hot 97.55% (target hot)
読み込むたびに、先にハッシュを確認します。sha256sumコマンドでハッシュを計算でき、-cを付けると、保存したリストとファイルを照合できます。セクション7のファイルを使った例です(Linux。macOSではshasum -a 256、Windows PowerShellではGet-FileHashを使います):
ターミナル(bash)
sha256sum w_out_trained.npy > w_out_trained.npy.sha256 # record once
sha256sum -c w_out_trained.npy.sha256 # check before use
出力
w_out_trained.npy: OK
重みが1つ書き換えられたあとは、同じ確認で、次のように表示されます:
出力
w_out_trained.npy: FAILED
sha256sum: WARNING: 1 computed checksum did NOT match