Files
Xenith/xenith/core/backward.cpp
T
2026-10-29 20:48:09 +07:00

207 lines
9.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "train.h"
#include <cmath>
#include <cstring>
#include <algorithm>
namespace xt {
static float softmax_ce(const float* logits, int V, int target, float* dlogits) {
float mx = -1e30f;
for (int j = 0; j < V; ++j) mx = std::max(mx, logits[j]);
float sum = 0.0f;
for (int j = 0; j < V; ++j) { float e = std::exp(logits[j] - mx); dlogits[j] = e; sum += e; }
const float inv = 1.0f / sum;
for (int j = 0; j < V; ++j) dlogits[j] *= inv;
float loss = -std::log(std::max(dlogits[target], 1e-30f));
dlogits[target] -= 1.0f;
return loss;
}
float backward(Params& p, const ForwardCache& fc,
const int* x, const int* y, int n_pairs,
const uint8_t* mask, float label_smoothing, bool zero_grads) {
const Config& c = p.cfg;
const int d = c.n_embd, H = c.n_head, hd = c.head_dim(), f = c.ffn();
const int V = c.vocab_out();
const int B = n_pairs;
const int S = (fc.seq_len > 0) ? fc.seq_len : B;
const int n_seq = (S > 0) ? (B / S) : 1;
const float scale = 1.0f / std::sqrt((float)hd);
// Градиенты могли не выделяться (ленивая загрузка только для генерации).
p.ensure_grads();
// zero_grads == false — режим градиентного накопления: градиенты
// предыдущих микро-батчей должны сохраниться.
if (zero_grads) p.zero_grad();
Tensor dlogits(B, V);
Tensor loss_row(B, 1);
double loss_sum = 0;
int n_active = 0;
// Считаем softmax+CE сразу по всему батчу одним вызовом бэкенда:
// на GPU это один dispatch по строкам, на CPU — тот же параллельный цикл.
backend()->softmax_ce(fc.logits, y, B, V, dlogits, loss_row);
// --- label smoothing (опционально) ---
// Цель: q_y = 1-α+α/V, q_j = α/V. После softmax_ce в dlogits лежит
// p_j (и p_y - 1 в строке цели). Коррекция: dl_j -= α/V (все j),
// dl_y += α. Loss: (1-α)·CE_y + (α/V)·Σ_j(-log p_j).
const float ls = std::max(0.0f, std::min(label_smoothing, 0.5f));
// Хост-модификации dlogits (сглаживание/маска) требуют свежей host-копии:
// на GPU-бэкенде вычитываем её лениво — только когда действительно правим.
const bool host_touch = (ls > 0.0f) || (mask != nullptr);
if (host_touch) backend()->materialize(dlogits);
// loss_row нужен на хосте ВСЕГДА (сумма loss) — это крошечный буфер B float'ов.
backend()->materialize(loss_row);
if (ls > 0.0f) {
const float av = ls / (float)V;
for (int t = 0; t < B; ++t) {
if (mask && !mask[t]) continue;
float* dl = dlogits.row(t);
const int yt = y[t];
double sum_nlp = 0.0;
for (int j = 0; j < V; ++j) {
const float pj = (j == yt) ? (dl[j] + 1.0f) : dl[j];
sum_nlp += -std::log(std::max(pj, 1e-30f));
}
loss_row.at(t) = (1.0f - ls) * loss_row.at(t) + av * (float)sum_nlp;
for (int j = 0; j < V; ++j) dl[j] -= av;
if (yt >= 0 && yt < V) dl[yt] += ls;
}
backend()->host_written(loss_row);
}
for (int t = 0; t < B; ++t) {
// mask[t] == 0 → позиция t НЕ учится предсказывать y[t].
// Обнуление строки dlogits обязательно: иначе градиент потечёт и по
// замаскированным позициям (softmax_ce уже записал туда p - onehot).
if (mask && !mask[t]) {
std::memset(dlogits.row(t), 0, (size_t)V * sizeof(float));
continue;
}
loss_sum += loss_row.at(t);
++n_active;
}
if (host_touch) backend()->host_written(dlogits);
if (n_active == 0) return 0.0f; // весь батч замаскирован — шага не будет
// Нормируем на число АКТИВНЫХ позиций, а не на B: иначе эффективный lr
// плавает в зависимости от того, сколько в батче пользовательских токенов.
// Раньше здесь был host-цикл `for (auto& t : dlogits.d) t *= dl;` — он
// заставлял вычитывать dlogits (B×V float — самый большой тензор шага) на
// хост КАЖДЫЙ шаг. Теперь масштабирование делает бэкенд: на GPU — ядро
// elementwise (данные не покидают видеокарту), на CPU — тот же цикл.
const float dl = 1.0f / (float)n_active;
backend()->scale(dlogits, dl);
Tensor dxf(B, d);
if (p.tied()) {
gemm_nn(dlogits, p.wte, dxf);
gemm_tn(dlogits, fc.xf, p.gwte, true);
} else {
gemm_nn(dlogits, p.lm_head, dxf);
gemm_tn(dlogits, fc.xf, p.glm_head, true);
}
Tensor dx;
rmsnorm_backward(fc.x, p.rms_final, fc.inv_rms, dxf, dx, p.grms_final);
Tensor tmp, dxb, dx2b, dha, dh1, dh3, dq, dk, dv, dattout;
for (int L = c.n_layer - 1; L >= 0; --L) {
const LayerCache& lc = fc.layers[L];
// ССЫЛКА, не копия: dx на GPU-бэкенде device-resident, а пословная
// копия `const Tensor dres = dx;` снимала бы УСТАРЕВШИЙ host-буфер
// (нули) и весь FFN-блок градиентов считался бы из нулей. Порядок
// операций ниже гарантирует: dres используется ТОЛЬКО до первого
// add_into(dx, g), поэтому ссылка семантически равна прежнему снимку.
const Tensor& dres = dx;
gemm_tn(lc.ha, dres, p.g2[L], true); // dW2
gemm_nt(dres, p.w2[L], dha); // dha = dres @ w2^T
dh1.resize(B, f);
dh3.resize(B, f);
backend()->swiglu_backward(lc.h1, lc.h3, dha, dh1, dh3);
gemm_tn(lc.x2b, dh1, p.g1[L], true); // dW1
gemm_tn(lc.x2b, dh3, p.g3[L], true); // dW3
dx2b.resize(B, d);
gemm_nt(dh1, p.w1[L], dx2b);
gemm_nt(dh3, p.w3[L], tmp);
backend()->add_into(dx2b, tmp);
{
Tensor g;
rmsnorm_backward(lc.x2, p.rms_ffn[L], lc.inv_rms2, dx2b, g, p.grms_ffn[L]);
backend()->add_into(dx, g);
}
gemm_tn(lc.attout, dx, p.go[L], true);
dattout.resize(B, d);
gemm_nt(dx, p.wo[L], dattout);
// dq/dk/dv: три прохода на GPU (dpdot+ds+dq, dk из ds, dv) или один
// параллельный проход CpuBackend. dq/dk возвращаются НЕ повёрнутыми
// обратно RoPE — поворот ниже.
backend()->attention_backward(lc.q, lc.k, lc.v, lc.att, dattout,
n_seq, S, H, hd, scale, dq, dk, dv);
// --- RoPE backward: обратный поворот dq/dk ---
backend()->rope_backward(dq, dk, n_seq, S, H, hd,
fc.rope_cos.data(), fc.rope_sin.data());
gemm_tn(lc.xb, dq, p.gq[L], true);
gemm_tn(lc.xb, dk, p.gk[L], true);
gemm_tn(lc.xb, dv, p.gv[L], true);
dxb.resize(B, d);
gemm_nt(dq, p.wq[L], dxb);
gemm_nt(dk, p.wk[L], tmp);
backend()->add_into(dxb, tmp);
gemm_nt(dv, p.wv[L], tmp);
backend()->add_into(dxb, tmp);
{
Tensor g;
rmsnorm_backward(lc.x, p.rms_attn[L], lc.inv_rms, dxb, g, p.grms_attn[L]);
backend()->add_into(dx, g);
}
}
// Градиент эмбеддингов: gwte[x[t]] += dx[t].
// VkBackend выполняет это на CPU (детерминированно, без гонок атомиков).
backend()->scatter_add_rows(p.gwte, x, B, dx);
return (float)(loss_sum / (double)n_active);
}
float softmax_eval(const Params& p, const ForwardCache& fc,
const int* x, const int* y, int n_pairs, Tensor& per_token_loss,
const uint8_t* mask) {
(void)x;
const int V = p.cfg.vocab_out();
// Валидация читает логиты на хосте — на GPU-бэкенде вычитываем их сюда.
backend()->materialize(const_cast<Tensor&>(fc.logits));
Tensor dl(n_pairs, V);
per_token_loss.resize(n_pairs, 1);
double sum = 0;
int n_active = 0;
for (int t = 0; t < n_pairs; ++t) {
if (mask && !mask[t]) { per_token_loss.at(t) = 0.0f; continue; }
const float l = softmax_ce(fc.logits.row(t), V, y[t], dl.row(t));
per_token_loss.at(t) = l;
sum += l;
++n_active;
}
if (n_active == 0) return 0.0f;
return (float)(sum / (double)n_active);
}
}