Files
2026-10-18 20:58:03 +07:00

49 lines
2.1 KiB
Plaintext
Raw Permalink 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.
#version 450
#extension GL_GOOGLE_include_directive : enable
// Softmax + cross-entropy с градиентом
// dlogits = softmax(logits); loss = -log(dlogits[target]); dlogits[target] -= 1
// Ровно то, что делает softmax_ce() в backward.cpp. Одна invokation = строка.
// P0 = (B, V, 0, 0)
#include "common.glsl"
layout(local_size_x = WG) in;
layout(set = 0, binding = 0) readonly buffer bL { float L[]; };
layout(set = 0, binding = 1) readonly buffer bT { int T[]; };
layout(set = 0, binding = 2) buffer bD { float D[]; };
layout(set = 0, binding = 3) buffer bLR { float LR[]; };
void main() {
uint t = gl_GlobalInvocationID.x;
int B = pk.P0.x, V = pk.P0.y;
if (t >= uint(B)) return;
int base = int(t) * V;
float mx = -1e30;
for (int j = 0; j < V; ++j) mx = max(mx, L[base + j]);
// Сумма с компенсацией (Kahan/Neumaier). CPU-эталон считает знаменатель
// softmax в double (cpu_backend.cpp: `double sum = 0.0`), а обычный float-
// аккумулятор по V=3867 слагаемым теряет ~1e-6 — этого хватало, чтобы
// траектории обучения на GPU и CPU разъезжались. Компенсированное
// суммирование даёт точность, близкую к double, без требования Float64
// (которое есть не у всех драйверов).
float sum = 0.0, comp = 0.0;
for (int j = 0; j < V; ++j) {
float e = exp(L[base + j] - mx);
D[base + j] = e;
float ts = sum + e; // НЕ «t»: во внешней области t — номер строки
comp += (abs(sum) >= abs(e)) ? ((sum - ts) + e) : ((e - ts) + sum);
sum = ts;
}
sum += comp;
float inv = 1.0 / max(sum, 1e-30);
for (int j = 0; j < V; ++j) D[base + j] *= inv;
int y = T[t];
float p = (y >= 0 && y < V) ? D[base + y] : 0.0;
LR[t] = -log(max(p, 1e-30));
if (y >= 0 && y < V) D[base + y] -= 1.0;
}