src/cpu/group_norm.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // ─── CPU GroupNorm ops (CHUNK 3) ─────────────────────────────────────────── | ||
| 2 | // | ||
| 3 | // FP32 scalar host implementations. Ports src/cuda/group_norm.cu — FP32 path | ||
| 4 | // only. NCHW activations; one tile per (sample, group). | ||
| 5 | // | ||
| 6 | // A tile spans channels_per_group * spatial elements, where | ||
| 7 | // channels_per_group = C / num_groups and spatial = H * W. | ||
| 8 | // | ||
| 9 | // Forward: | ||
| 10 | // mean = (1/M) Σ x | ||
| 11 | // var = (1/M) Σ x² - mean² (GPU's biased estimator) | ||
| 12 | // rstd = 1 / sqrt(var + eps) | ||
| 13 | // y[c,s] = (x - mean) * rstd * gamma[c] + beta[c] | ||
| 14 | // | ||
| 15 | // Backward (per tile; dx̂ = dY*γ_c, x̂ = (x-mean)*rstd): | ||
| 16 | // sum1 = Σ dx̂ | ||
| 17 | // sum2 = Σ dx̂ · x̂ | ||
| 18 | // dX = rstd * (dx̂ - (sum1 + x̂*sum2) / M) | ||
| 19 | // dGamma_c += Σ_{s in tile,batch} dY · x̂ | ||
| 20 | // dBeta_c += Σ_{s in tile,batch} dY | ||
| 21 | // | ||
| 22 | // ACCUMULATION (matches the GPU kernels): | ||
| 23 | // group_norm_forward — Y OVERWRITTEN. | ||
| 24 | // group_norm_backward — dX OVERWRITTEN; dGamma / dBeta ACCUMULATE (+=). | ||
| 25 | // The GPU atomicAdds into FP32 scratch then folds | ||
| 26 | // into the caller's dGamma/dBeta — caller zeros them. | ||
| 27 | // | ||
| 28 | // FP32 accumulation mirrors the GPU (single-precision sums); a wider double | ||
| 29 | // accumulator would diverge from the GPU and break parity. | ||
| 30 | |||
| 31 | #include <brotensor/tensor.h> | ||
| 32 | #include <brotensor/detail/cpu/thread_pool.h> | ||
| 33 | |||
| 34 | #include <algorithm> | ||
| 35 | #include <cmath> | ||
| 36 | #include <cstddef> | ||
| 37 | #include <stdexcept> | ||
| 38 | #include <vector> | ||
| 39 | |||
| 40 | namespace brotensor::detail::cpu { | ||
| 41 | |||
| 42 | 41 | void group_norm_forward(const ::brotensor::Tensor& X, | |
| 43 | const ::brotensor::Tensor& gamma, | ||
| 44 | const ::brotensor::Tensor& beta, | ||
| 45 | int N, int C, int H, int W, | ||
| 46 | int num_groups, | ||
| 47 | float eps, | ||
| 48 | ::brotensor::Tensor& Y) { | ||
| 49 | 41 | if (gamma.dtype != X.dtype || beta.dtype != X.dtype) { | |
| 50 | ✗ | throw std::runtime_error("group_norm_forward: gamma/beta dtype must match X"); | |
| 51 | } | ||
| 52 | 41 | if (num_groups <= 0 || C % num_groups != 0) { | |
| 53 | ✗ | throw std::runtime_error("group_norm_forward: num_groups must divide C"); | |
| 54 | } | ||
| 55 | 41 | const int spatial = H * W; | |
| 56 | 41 | const int cols = C * spatial; | |
| 57 | 41 | if (gamma.size() != C || beta.size() != C) { | |
| 58 | ✗ | throw std::runtime_error("group_norm_forward: gamma/beta must have C elements"); | |
| 59 | } | ||
| 60 | 41 | if (Y.rows != N || Y.cols != cols || Y.dtype != X.dtype) { | |
| 61 | 41 | Y.resize(N, cols, X.dtype); | |
| 62 | 41 | } | |
| 63 | 41 | if (N == 0 || cols == 0) return; | |
| 64 | |||
| 65 | 41 | const float* Xp = X.host_f32(); | |
| 66 | 41 | const float* gp = gamma.host_f32(); | |
| 67 | 41 | const float* bp = beta.host_f32(); | |
| 68 | 41 | float* Yp = Y.host_f32_mut(); | |
| 69 | |||
| 70 | 41 | const int channels_per_group = C / num_groups; | |
| 71 | 41 | const int tile_size = channels_per_group * spatial; | |
| 72 | 41 | const int sample_stride = C * spatial; | |
| 73 | 41 | const float inv_M = 1.0f / static_cast<float>(tile_size); | |
| 74 | |||
| 75 | // Each sample n owns its own slice of Y exclusively (X/gamma/beta are | ||
| 76 | // read-only shared), so this parallelizes across n with no cross-thread | ||
| 77 | // writes. | ||
| 78 | 98 | parallel_for(static_cast<std::size_t>(N), [&](std::size_t ni) { | |
| 79 | 57 | const int n = static_cast<int>(ni); | |
| 80 | 261 | for (int g = 0; g < num_groups; ++g) { | |
| 81 | 204 | const int chan_base = g * channels_per_group; | |
| 82 | 204 | const float* x_tile = Xp + n * sample_stride + chan_base * spatial; | |
| 83 | 204 | float* y_tile = Yp + n * sample_stride + chan_base * spatial; | |
| 84 | |||
| 85 | // Two passes: mean, then the sum of squared deviations from it. | ||
| 86 | // E[x^2] - E[x]^2 is one pass but cancels catastrophically once a | ||
| 87 | // tile's mean dwarfs its spread — a near-constant channel puts both | ||
| 88 | // terms on the same large value, so their FP32 difference is noise | ||
| 89 | // and can come out negative, making rstd NaN. Deviations are | ||
| 90 | // non-negative by construction, so var cannot go negative. | ||
| 91 | 204 | float sum = 0.0f; | |
| 92 | 51972 | for (int i = 0; i < tile_size; ++i) sum += x_tile[i]; | |
| 93 | 204 | const float mean = sum * inv_M; | |
| 94 | |||
| 95 | 204 | float sumsq = 0.0f; | |
| 96 | 51972 | for (int i = 0; i < tile_size; ++i) { | |
| 97 | 51768 | const float d = x_tile[i] - mean; | |
| 98 | 51768 | sumsq += d * d; | |
| 99 | 51768 | } | |
| 100 | 204 | const float var = sumsq * inv_M; | |
| 101 | 204 | const float eps_safe = std::max(eps, 1e-12f); | |
| 102 | 204 | const float rstd = 1.0f / std::sqrt(std::max(var + eps_safe, 1e-12f)); | |
| 103 | |||
| 104 | 51972 | for (int i = 0; i < tile_size; ++i) { | |
| 105 | 51768 | const int local_c = i / spatial; | |
| 106 | 51768 | const int channel = chan_base + local_c; | |
| 107 | 51768 | const float yn = (x_tile[i] - mean) * rstd; | |
| 108 | 51768 | y_tile[i] = yn * gp[channel] + bp[channel]; // overwrite | |
| 109 | 51768 | } | |
| 110 | 204 | } | |
| 111 | 57 | }); | |
| 112 | 41 | } | |
| 113 | |||
| 114 | 26 | void group_norm_backward(const ::brotensor::Tensor& X, | |
| 115 | const ::brotensor::Tensor& gamma, | ||
| 116 | const ::brotensor::Tensor& dY, | ||
| 117 | int N, int C, int H, int W, | ||
| 118 | int num_groups, | ||
| 119 | float eps, | ||
| 120 | ::brotensor::Tensor& dX, | ||
| 121 | ::brotensor::Tensor& dGamma, | ||
| 122 | ::brotensor::Tensor& dBeta) { | ||
| 123 | 26 | if (gamma.dtype != X.dtype || dY.dtype != X.dtype) { | |
| 124 | ✗ | throw std::runtime_error("group_norm_backward: gamma/dY dtype must match X"); | |
| 125 | } | ||
| 126 | 26 | if (dGamma.dtype != X.dtype || dBeta.dtype != X.dtype) { | |
| 127 | ✗ | throw std::runtime_error("group_norm_backward: dGamma/dBeta dtype must match X"); | |
| 128 | } | ||
| 129 | 26 | if (num_groups <= 0 || C % num_groups != 0) { | |
| 130 | ✗ | throw std::runtime_error("group_norm_backward: num_groups must divide C"); | |
| 131 | } | ||
| 132 | 52 | if (dGamma.rows != C || dGamma.cols != 1 || | |
| 133 | 26 | dBeta.rows != C || dBeta.cols != 1) { | |
| 134 | ✗ | throw std::runtime_error("group_norm_backward: dGamma/dBeta must be (C,1)"); | |
| 135 | } | ||
| 136 | 26 | const int spatial = H * W; | |
| 137 | 26 | const int cols = C * spatial; | |
| 138 | 26 | if (gamma.size() != C) { | |
| 139 | ✗ | throw std::runtime_error("group_norm_backward: gamma must have C elements"); | |
| 140 | } | ||
| 141 | 26 | if (dY.rows != N || dY.cols != cols) { | |
| 142 | ✗ | throw std::runtime_error("group_norm_backward: dY shape mismatch"); | |
| 143 | } | ||
| 144 | 26 | if (dX.rows != N || dX.cols != cols || dX.dtype != X.dtype) { | |
| 145 | 17 | dX.resize(N, cols, X.dtype); | |
| 146 | 17 | } | |
| 147 | 26 | if (N == 0 || cols == 0) return; | |
| 148 | |||
| 149 | 26 | const float* Xp = X.host_f32(); | |
| 150 | 26 | const float* gp = gamma.host_f32(); | |
| 151 | 26 | const float* dYp = dY.host_f32(); | |
| 152 | 26 | float* dXp = dX.host_f32_mut(); | |
| 153 | 26 | float* dGp = dGamma.host_f32_mut(); | |
| 154 | 26 | float* dBp = dBeta.host_f32_mut(); | |
| 155 | |||
| 156 | 26 | const int channels_per_group = C / num_groups; | |
| 157 | 26 | const int tile_size = channels_per_group * spatial; | |
| 158 | 26 | const int sample_stride = C * spatial; | |
| 159 | 26 | const float inv_M = 1.0f / static_cast<float>(tile_size); | |
| 160 | |||
| 161 | // dGamma_c / dBeta_c accumulate over EVERY n (a fixed channel appears in | ||
| 162 | // exactly one group but in all N samples' tiles), so a naive | ||
| 163 | // parallel-for over n would race on dGp[channel]/dBp[channel] — that's a | ||
| 164 | // shared reduction across the batch axis, not disjoint per n. | ||
| 165 | // | ||
| 166 | // Fix: each n instead writes its per-channel partial dg/db into row n of | ||
| 167 | // a (N, C) scratch buffer (disjoint per n — every channel is touched by | ||
| 168 | // exactly one group/local_c per n, so each element of the row is | ||
| 169 | // written exactly once, no init needed). A final single-threaded pass | ||
| 170 | // sums those partials down into dGp/dBp. Pass 1/2/3 (stats, partial | ||
| 171 | // dg/db + x̂ caching, dX write) are otherwise fully independent per n and | ||
| 172 | // run inside the parallel_for; x̂'s scratch buffer is declared LOCAL to | ||
| 173 | // the lambda (one per n, sized tile_size) instead of shared across n, so | ||
| 174 | // concurrent n's never touch the same buffer. | ||
| 175 | 26 | std::vector<float> dg_partial(static_cast<std::size_t>(N) * C); | |
| 176 | 26 | std::vector<float> db_partial(static_cast<std::size_t>(N) * C); | |
| 177 | |||
| 178 | 60 | parallel_for(static_cast<std::size_t>(N), [&](std::size_t ni) { | |
| 179 | 34 | const int n = static_cast<int>(ni); | |
| 180 | 34 | float* dg_row = dg_partial.data() + static_cast<std::size_t>(n) * C; | |
| 181 | 34 | float* db_row = db_partial.data() + static_cast<std::size_t>(n) * C; | |
| 182 | // Local per-n scratch for x̂ — safe even though this lambda runs on | ||
| 183 | // different threads, since each invocation gets its own stack/heap- | ||
| 184 | // local buffer. | ||
| 185 | 34 | std::vector<float> xhat_buf(static_cast<std::size_t>(tile_size)); | |
| 186 | |||
| 187 | 160 | for (int g = 0; g < num_groups; ++g) { | |
| 188 | 126 | const int chan_base = g * channels_per_group; | |
| 189 | 126 | const float* x_tile = Xp + n * sample_stride + chan_base * spatial; | |
| 190 | 126 | const float* dy_tile = dYp + n * sample_stride + chan_base * spatial; | |
| 191 | 126 | float* dx_tile = dXp + n * sample_stride + chan_base * spatial; | |
| 192 | |||
| 193 | // Pass 1: mean, var, rstd over the tile. Variance from squared | ||
| 194 | // deviations, for the cancellation reason spelled out in | ||
| 195 | // group_norm_forward above. | ||
| 196 | 126 | float sum = 0.0f; | |
| 197 | 11943 | for (int i = 0; i < tile_size; ++i) sum += x_tile[i]; | |
| 198 | 126 | const float mean = sum * inv_M; | |
| 199 | |||
| 200 | 126 | float sumsq = 0.0f; | |
| 201 | 11830 | for (int i = 0; i < tile_size; ++i) { | |
| 202 | 11704 | const float d = x_tile[i] - mean; | |
| 203 | 11704 | sumsq += d * d; | |
| 204 | 11704 | } | |
| 205 | 126 | const float var = sumsq * inv_M; | |
| 206 | 126 | const float eps_safe = std::max(eps, 1e-12f); | |
| 207 | 126 | const float rstd = 1.0f / std::sqrt(std::max(var + eps_safe, 1e-12f)); | |
| 208 | |||
| 209 | // Pass 2: sum1 = Σ dx̂, sum2 = Σ dx̂·x̂; stash this n's per-channel | ||
| 210 | // dg/db into the partial buffers; cache x̂ into xhat_buf for | ||
| 211 | // reuse in pass 3. Nested (channel, spatial) loops keep | ||
| 212 | // local_c/channel loop-invariant per channel instead of | ||
| 213 | // deriving it via division per element. | ||
| 214 | 126 | float sum1 = 0.0f, sum2 = 0.0f; | |
| 215 | 521 | for (int local_c = 0; local_c < channels_per_group; ++local_c) { | |
| 216 | 395 | const int channel = chan_base + local_c; | |
| 217 | 395 | const float gv = gp[channel]; | |
| 218 | 395 | const int base = local_c * spatial; | |
| 219 | 395 | float dg = 0.0f, db = 0.0f; | |
| 220 | 11866 | for (int s = 0; s < spatial; ++s) { | |
| 221 | 11471 | const int i = base + s; | |
| 222 | 11471 | const float dyv = dy_tile[i]; | |
| 223 | 11471 | const float xh = (x_tile[i] - mean) * rstd; | |
| 224 | 11471 | xhat_buf[i] = xh; | |
| 225 | 11471 | const float dxh = dyv * gv; | |
| 226 | 11471 | sum1 += dxh; | |
| 227 | 11471 | sum2 += dxh * xh; | |
| 228 | 11471 | dg += dyv * xh; | |
| 229 | 11471 | db += dyv; | |
| 230 | 11471 | } | |
| 231 | 395 | dg_row[channel] = dg; // disjoint per-n write | |
| 232 | 395 | db_row[channel] = db; // disjoint per-n write | |
| 233 | 395 | } | |
| 234 | |||
| 235 | // Pass 3: dX = rstd * (dx̂ - (sum1 + x̂*sum2) / M). | ||
| 236 | 521 | for (int local_c = 0; local_c < channels_per_group; ++local_c) { | |
| 237 | 395 | const int channel = chan_base + local_c; | |
| 238 | 395 | const float gv = gp[channel]; | |
| 239 | 395 | const int base = local_c * spatial; | |
| 240 | 11853 | for (int s = 0; s < spatial; ++s) { | |
| 241 | 11458 | const int i = base + s; | |
| 242 | 11458 | const float dyv = dy_tile[i]; | |
| 243 | 11458 | const float xh = xhat_buf[i]; | |
| 244 | 11458 | const float dxh = dyv * gv; | |
| 245 | 11458 | dx_tile[i] = rstd * (dxh - (sum1 + xh * sum2) * inv_M); // overwrite | |
| 246 | 11458 | } | |
| 247 | 395 | } | |
| 248 | 126 | } | |
| 249 | 34 | }); | |
| 250 | |||
| 251 | // Single-threaded: sum the per-n partials down into dGamma/dBeta. | ||
| 252 | 294 | for (int c = 0; c < C; ++c) { | |
| 253 | 268 | float dg = 0.0f, db = 0.0f; | |
| 254 | 664 | for (int n = 0; n < N; ++n) { | |
| 255 | 396 | dg += dg_partial[static_cast<std::size_t>(n) * C + c]; | |
| 256 | 396 | db += db_partial[static_cast<std::size_t>(n) * C + c]; | |
| 257 | 396 | } | |
| 258 | 268 | dGp[c] += dg; // accumulate | |
| 259 | 268 | dBp[c] += db; // accumulate | |
| 260 | 268 | } | |
| 261 | 26 | } | |
| 262 | |||
| 263 | } // namespace brotensor::detail::cpu | ||
| 264 |