brotensor/
Coverage:
low: ≥ 0%
medium: ≥ 75.0%
high: ≥ 90.0%
Lines:
68 / 88
77.3%
Branches:
33 / 72
45.8%
Functions:
3 / 4
75.0%

src/cpu/rms_norm.cpp
Line Branch Exec Source
1 // ─── CPU RMSNorm ops (CHUNK 2) ─────────────────────────────────────────────
2 //
3 // FP32 scalar host implementations. Ports src/cuda/rms_norm.cu — FP32 path
4 // only. Per-row (one block per row on the GPU).
5 //
6 // rms[b] = sqrt(mean_j x[b, j]^2 + eps)
7 // y[b, j] = x[b, j] * gamma[j] / rms[b]
8 //
9 // Backward (rrms = 1/rms):
10 // sum_xdy = sum_j x_j * dY_j * gamma_j
11 // coeff = (1/D) * rrms^2 * sum_xdy
12 // dX[b,j] = rrms * (gamma_j * dY_j - x_j * coeff)
13 // dGamma_j += sum_b dY[b,j] * x[b,j] * rrms
14 //
15 // ACCUMULATION: dX is OVERWRITTEN (the GPU writes dxrow[j] directly). dGamma
16 // ACCUMULATES (+=) — the GPU atomicAdds across the batch into dGamma, and the
17 // caller is responsible for zeroing dGamma beforehand.
18
19 #include <brotensor/tensor.h>
20 #include <brotensor/detail/cpu/thread_pool.h>
21 #include "cpu_jit.h"
22
23 #include <algorithm>
24 #include <cmath>
25 #include <cstddef>
26 #include <stdexcept>
27 #include <vector>
28
29 namespace brotensor::detail::cpu {
30
31 374 void rms_norm_forward(const ::brotensor::Tensor& X,
32 const ::brotensor::Tensor& gamma,
33 float eps, ::brotensor::Tensor& Y) {
34
1/2
✓ Branch 0 taken 374 times.
✗ Branch 1 not taken.
374 if (gamma.dtype != X.dtype) {
35
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ throw std::runtime_error("rms_norm_forward: gamma.dtype must match X.dtype");
36 }
37 374 const int B = X.rows;
38 374 const int D = X.cols;
39
1/2
✓ Branch 0 taken 374 times.
✗ Branch 1 not taken.
374 if (gamma.size() != D) {
40
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ throw std::runtime_error("rms_norm_forward: gamma must have D elements");
41 }
42
3/4
✓ Branch 0 taken 360 times.
✓ Branch 1 taken 14 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 360 times.
374 if (Y.rows != B || Y.cols != D) Y.resize(B, D);
43
2/4
✓ Branch 0 taken 374 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 374 times.
374 if (B == 0 || D == 0) return;
44 374 const float* Xp = X.host_f32();
45 374 const float* gp = gamma.host_f32();
46 374 float* Yp = Y.host_f32_mut();
47 374 const float eps_safe = std::max(eps, 1e-12f);
48
49
1/2
✓ Branch 0 taken 374 times.
✗ Branch 1 not taken.
374 if (jit::is_jit_available()) {
50 374 jit::rms_norm_forward(Xp, gp, eps_safe, Yp, B, D);
51 374 return;
52 }
53 // Each row b owns Y's row b exclusively (X/gamma are read-only shared
54 // inputs), so this parallelizes across b with no cross-thread writes.
55
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ parallel_for(static_cast<std::size_t>(B), [&](std::size_t bi) {
56 ✗ const int b = static_cast<int>(bi);
57 ✗ const float* xrow = Xp + static_cast<size_t>(b) * D;
58 ✗ float* yrow = Yp + static_cast<size_t>(b) * D;
59 ✗ float sum = 0.0f;
60
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ for (int j = 0; j < D; ++j) {
61 ✗ const float v = xrow[j];
62 ✗ sum += v * v;
63 ✗ }
64 ✗ const float denom = std::max(sum / static_cast<float>(D) + eps_safe, 1e-12f);
65
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ const float rrms = std::isfinite(denom) ? (1.0f / std::sqrt(denom)) : 0.0f;
66
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ for (int j = 0; j < D; ++j) {
67
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ yrow[j] = (rrms > 0.0f) ? (xrow[j] * gp[j] * rrms) : 0.0f;
68 ✗ }
69 ✗ });
70 374 }
71
72 8 void rms_norm_backward(const ::brotensor::Tensor& X,
73 const ::brotensor::Tensor& gamma,
74 const ::brotensor::Tensor& dY, float eps,
75 ::brotensor::Tensor& dX, ::brotensor::Tensor& dGamma) {
76
1/2
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
8 if (gamma.dtype != X.dtype || dY.dtype != X.dtype ||
77 8 dGamma.dtype != X.dtype) {
78
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ throw std::runtime_error("rms_norm_backward: dtypes must match");
79 }
80 8 const int B = X.rows;
81 8 const int D = X.cols;
82
1/2
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
8 if (dY.rows != B || dY.cols != D) {
83
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ throw std::runtime_error("rms_norm_backward: dY shape mismatch");
84 }
85
1/2
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
8 if (gamma.size() != D || dGamma.size() != D) {
86
0/2
✗ Branch 0 not taken.
✗ Branch 1 not taken.
✗ throw std::runtime_error("rms_norm_backward: gamma/dGamma size mismatch");
87 }
88
3/4
✓ Branch 0 taken 1 time.
✓ Branch 1 taken 7 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 1 time.
8 if (dX.rows != B || dX.cols != D) dX.resize(B, D);
89
2/4
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
✗ Branch 2 not taken.
✓ Branch 3 taken 8 times.
8 if (B == 0 || D == 0) return;
90 8 const float* Xp = X.host_f32();
91 8 const float* gp = gamma.host_f32();
92 8 const float* dYp = dY.host_f32();
93 8 float* dXp = dX.host_f32_mut();
94 8 float* dGp = dGamma.host_f32_mut();
95 8 const float inv_D = 1.0f / static_cast<float>(D);
96 8 const float eps_safe = std::max(eps, 1e-12f);
97
98 // dGamma accumulates dGp[j] += ... summed over every row b — a shared
99 // reduction across the batch axis, not disjoint per b. So the dX pass
100 // (fully owned by row b) is parallelized, while rrms per row is cached
101 // (one float per b, disjoint write) so the dGamma pass below can reuse
102 // it without re-deriving it or touching any shared state during the
103 // parallel section. dGamma itself is accumulated in a separate,
104 // single-threaded pass afterwards.
105 8 std::vector<float> rrms_cache(static_cast<std::size_t>(B));
106
107
2/4
✓ Branch 0 taken 8 times.
✗ Branch 1 not taken.
✓ Branch 2 taken 8 times.
✗ Branch 3 not taken.
47 parallel_for(static_cast<std::size_t>(B), [&](std::size_t bi) {
108 39 const int b = static_cast<int>(bi);
109 39 const float* xrow = Xp + static_cast<size_t>(b) * D;
110 39 const float* dyrow = dYp + static_cast<size_t>(b) * D;
111 39 float* dxrow = dXp + static_cast<size_t>(b) * D;
112
113 39 float sum_xx = 0.0f;
114
2/2
✓ Branch 0 taken 1444 times.
✓ Branch 1 taken 39 times.
1483 for (int j = 0; j < D; ++j) {
115 1444 const float v = xrow[j];
116 1444 sum_xx += v * v;
117 1444 }
118 39 const float denom = std::max(sum_xx * inv_D + eps_safe, 1e-12f);
119
1/2
✓ Branch 0 taken 39 times.
✗ Branch 1 not taken.
39 const float rrms = std::isfinite(denom) ? (1.0f / std::sqrt(denom)) : 0.0f;
120 39 rrms_cache[b] = rrms; // disjoint per-b write
121
122 39 float sum_xdy = 0.0f;
123
2/2
✓ Branch 0 taken 1444 times.
✓ Branch 1 taken 39 times.
1483 for (int j = 0; j < D; ++j) {
124 1444 sum_xdy += xrow[j] * dyrow[j] * gp[j];
125 1444 }
126
1/2
✓ Branch 0 taken 39 times.
✗ Branch 1 not taken.
39 const float coeff = std::isfinite(sum_xdy) ? (inv_D * rrms * rrms * sum_xdy) : 0.0f;
127
128
2/2
✓ Branch 0 taken 1444 times.
✓ Branch 1 taken 39 times.
1483 for (int j = 0; j < D; ++j) {
129 1444 const float g = gp[j];
130 1444 const float dy = dyrow[j];
131 1444 const float x = xrow[j];
132
1/2
✓ Branch 0 taken 1444 times.
✗ Branch 1 not taken.
1444 dxrow[j] = (rrms > 0.0f) ? (rrms * (g * dy - x * coeff)) : 0.0f; // overwrite dX
133 1444 }
134 39 });
135
136 // Single-threaded: dGamma reduces across b, so it cannot be split across
137 // threads without a race on dGp[j].
138
2/2
✓ Branch 0 taken 39 times.
✓ Branch 1 taken 8 times.
47 for (int b = 0; b < B; ++b) {
139 39 const float* xrow = Xp + static_cast<size_t>(b) * D;
140 39 const float* dyrow = dYp + static_cast<size_t>(b) * D;
141 39 const float rrms = rrms_cache[b];
142
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 39 times.
39 if (rrms <= 0.0f) continue;
143
2/2
✓ Branch 0 taken 1444 times.
✓ Branch 1 taken 39 times.
1483 for (int j = 0; j < D; ++j) {
144 1444 const float prod = dyrow[j] * xrow[j] * rrms;
145
1/2
✗ Branch 0 not taken.
✓ Branch 1 taken 1444 times.
1444 if (std::isfinite(prod)) dGp[j] += prod; // accumulate dGamma
146 1444 }
147 39 }
148 8 }
149
150 } // namespace brotensor::detail::cpu
151