src/jit/gpu_mir_emit_rownorm.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // Row-norm trace kernel as brass MIR (spirv_emit.h). | ||
| 2 | // | ||
| 3 | // A workgroup holds `rpb` rows of `tpr` threads (plan::row_norm_geometry); | ||
| 4 | // each row's threads walk it in strides of tpr * lanes columns, so every | ||
| 5 | // full access moves 16 bytes. The workgroup index is 2-D when there are more | ||
| 6 | // row groups than one grid dimension takes (65535): group = y * nx + x. | ||
| 7 | // | ||
| 8 | // RMS pass 1 pre chain, sum of squares, pass-one outputs stored | ||
| 9 | // pass 2 x (read back, or the pre chain again), * rstd, gamma, | ||
| 10 | // post chain, stores | ||
| 11 | // Mean pass 1 pre chain, sum, pass-one outputs stored | ||
| 12 | // pass 1b x again, sum of squared deviations from the mean | ||
| 13 | // pass 2 as above with (x - mean) * rstd, gamma, beta | ||
| 14 | // | ||
| 15 | // LayerNorm's variance is the two-pass sum of squared deviations, never | ||
| 16 | // E[x^2] - E[x]^2 (which cancels catastrophically once a row's mean dwarfs | ||
| 17 | // its spread — the rule in CLAUDE.md, the recipe of brass's own fused | ||
| 18 | // LayerNorm kernels). The extra pass re-reads a row the workgroup just | ||
| 19 | // touched, out of cache. | ||
| 20 | // | ||
| 21 | // Reductions: a 32-lane subgroup butterfly, then, when a row spans several | ||
| 22 | // 32-thread groups, one shared-memory round across that row's groups. Every | ||
| 23 | // thread folds the partials itself, so the statistic needs no broadcast. | ||
| 24 | |||
| 25 | #include "gpu_mir_emit_detail.h" | ||
| 26 | #if BRASS_WITH_SPIRV | ||
| 27 | #include "trace_contract.h" | ||
| 28 | #endif | ||
| 29 | |||
| 30 | #include <string> | ||
| 31 | #include <unordered_map> | ||
| 32 | #include <vector> | ||
| 33 | |||
| 34 | namespace brotensor::jit::gpu_mir { | ||
| 35 | |||
| 36 | namespace { | ||
| 37 | |||
| 38 | class RowNormBuilder { | ||
| 39 | public: | ||
| 40 | 176 | RowNormBuilder(brass::Module& mod, const TraceDAG& dag, const plan::RowNormPlan& plan, | |
| 41 | int lanes, const char* name, bool optimize) | ||
| 42 | 44 | : dag_(dag), plan_(plan), ew_(plan.ew), lanes_(lanes), name_(name), | |
| 43 | 88 | mod_(mod), optimize_(optimize) { | |
| 44 | 44 | plan::row_norm_geometry(ew_.cols, ew_.rows, lanes, tpr_, rpb_); | |
| 45 | 44 | warps_ = tpr_ / 32; | |
| 46 | 44 | step_ = tpr_ * lanes; | |
| 47 | 88 | } | |
| 48 | |||
| 49 | 44 | brass::Function* build() { | |
| 50 | 44 | const std::size_t n_out = ew_.outputs.size(); | |
| 51 | 44 | const std::size_t n_in = ew_.inputs.size(); | |
| 52 | 44 | std::vector<Type> params(n_out + n_in, Type::ptr()); | |
| 53 | 44 | Function* fn = mod_.create_function(name_, Type::void_type(), brass::Span<const Type>(params)); | |
| 54 | 44 | KernelBuilder kb(mod_, fn); | |
| 55 | 44 | Ctx c(kb); | |
| 56 | 44 | c_ = &c; | |
| 57 | 44 | Builder& b = c.b; | |
| 58 | 44 | const std::vector<Value*> p = entry_params(c, fn); | |
| 59 | 44 | out_ptr_.assign(p.begin(), p.begin() + static_cast<std::ptrdiff_t>(n_out)); | |
| 60 | 44 | in_ptr_.assign(p.begin() + static_cast<std::ptrdiff_t>(n_out), p.end()); | |
| 61 | |||
| 62 | // Shared partials, one array per reduction so no barrier is needed | ||
| 63 | // between them. | ||
| 64 | 44 | const int nred = (plan_.reduce == plan::RowReduce::Mean) ? 2 : 1; | |
| 65 | 44 | std::vector<Value*> red; | |
| 66 | 44 | if (warps_ > 1) { | |
| 67 | 88 | for (int r = 0; r < nred; ++r) { | |
| 68 | 54 | red.push_back(kb.shared_alloc_f32(static_cast<std::uint32_t>(plan::kRowThreads / 32))); | |
| 69 | 54 | } | |
| 70 | 34 | } | |
| 71 | |||
| 72 | 44 | tid_ = kb.tid_x(); | |
| 73 | 44 | Value* group = b.build_add(b.build_mul(kb.ctaid_y(), kb.nctaid_x()), kb.ctaid_x()); | |
| 74 | 44 | Value* sub = tid_; | |
| 75 | 44 | local_ = c.i32(0); | |
| 76 | 44 | Value* row = group; | |
| 77 | 44 | Value* group_row = group; | |
| 78 | 44 | if (rpb_ > 1) { | |
| 79 | 24 | local_ = b.build_lshr(tid_, c.i32(log2_exact(tpr_))); | |
| 80 | 24 | sub = b.build_and(tid_, c.i32(tpr_ - 1)); | |
| 81 | 24 | group_row = b.build_shl(group, c.i32(log2_exact(rpb_))); | |
| 82 | 24 | row = b.build_add(group_row, local_); | |
| 83 | 24 | } | |
| 84 | // rpb divides the row count, so testing group_row makes this exit | ||
| 85 | // manifestly workgroup-uniform across all subgroup sizes. | ||
| 86 | 88 | kb.if_then(b.build_uge(group_row, c.i32(ew_.rows)), [&] { b.build_ret_void(); }); | |
| 87 | |||
| 88 | 44 | c0_ = lanes_ > 1 ? b.build_shl(sub, c.i32(log2_exact(lanes_))) : sub; | |
| 89 | 44 | row_ = row; | |
| 90 | 44 | rowbase_ = is_pow2(ew_.cols) ? b.build_shl(row, c.i32(log2_exact(ew_.cols))) | |
| 91 | ✗ | : b.build_mul(row, c.i32(ew_.cols)); | |
| 92 | 170 | for (const auto& s : ew_.inputs) { | |
| 93 | 126 | row_bytes(s.dtype); | |
| 94 | 126 | if (s.bcast == BroadcastKind::Col) col_bcast_bytes(s.dtype); | |
| 95 | } | ||
| 96 | 92 | for (const auto& s : ew_.outputs) row_bytes(s.dtype); | |
| 97 | 44 | Value* D = c.i32(ew_.cols); | |
| 98 | 44 | const float inv_d = 1.0f / static_cast<float>(ew_.cols); | |
| 99 | 44 | const float eps_safe = plan_.eps >= 1e-12f ? plan_.eps : 1e-12f; | |
| 100 | |||
| 101 | 44 | Value* mean = nullptr; | |
| 102 | 44 | Value* rstd = nullptr; | |
| 103 | 44 | if (plan_.reduce == plan::RowReduce::Mean) { | |
| 104 | // pass 1: sum | ||
| 105 | 48 | Value* sum = kb.for_range_reduce(c0_, D, c.i32(step_), c.f32(0.0f), [&](Value* col, Value* acc) { | |
| 106 | 24 | Offsets o; | |
| 107 | 24 | const std::vector<Value*> x = pass_one_x(o, col); | |
| 108 | 96 | for (Value* xj : x) acc = b.build_add(acc, xj); | |
| 109 | 24 | return acc; | |
| 110 | 24 | }); | |
| 111 | 24 | mean = b.build_mul(reduce(sum, red.empty() ? nullptr : red[0]), c.f32(inv_d)); | |
| 112 | // pass 1b: squared deviations about that mean | ||
| 113 | 48 | Value* sq = kb.for_range_reduce(c0_, D, c.i32(step_), c.f32(0.0f), [&](Value* col, Value* acc) { | |
| 114 | 24 | Offsets o; | |
| 115 | 96 | for (Value* xj : reload_x(o, col, nullptr)) { | |
| 116 | 72 | Value* d = b.build_sub(xj, mean); | |
| 117 | 72 | acc = b.build_fma_f32(d, d, acc); | |
| 118 | } | ||
| 119 | 24 | return acc; | |
| 120 | 24 | }); | |
| 121 | 24 | Value* var = b.build_mul(reduce(sq, red.empty() ? nullptr : red[1]), c.f32(inv_d)); | |
| 122 | 24 | rstd = kb.rsqrt_approx(b.build_add(var, c.f32(eps_safe))); | |
| 123 | 24 | } else { | |
| 124 | 40 | Value* sq = kb.for_range_reduce(c0_, D, c.i32(step_), c.f32(0.0f), [&](Value* col, Value* acc) { | |
| 125 | 20 | Offsets o; | |
| 126 | 82 | for (Value* xj : pass_one_x(o, col)) acc = b.build_fma_f32(xj, xj, acc); | |
| 127 | 20 | return acc; | |
| 128 | 20 | }); | |
| 129 | 20 | Value* ms = b.build_mul(reduce(sq, red.empty() ? nullptr : red[0]), c.f32(inv_d)); | |
| 130 | 20 | rstd = kb.rsqrt_approx(b.build_add(ms, c.f32(eps_safe))); | |
| 131 | } | ||
| 132 | |||
| 133 | // pass 2: normalise, post chain, store | ||
| 134 | 88 | kb.for_range(c0_, D, c.i32(step_), [&](Value* col) { | |
| 135 | 44 | Offsets o; | |
| 136 | 44 | ValueMap vals; | |
| 137 | 44 | const std::vector<Value*> x = reload_x(o, col, &vals); | |
| 138 | 44 | std::vector<Value*> gam, bet; | |
| 139 | 44 | if (plan_.gamma_input >= 0) { | |
| 140 | 44 | gam = vals.at(ew_.inputs[static_cast<std::size_t>(plan_.gamma_input)].node_id); | |
| 141 | 44 | } | |
| 142 | 44 | if (plan_.beta_input >= 0) { | |
| 143 | 24 | bet = vals.at(ew_.inputs[static_cast<std::size_t>(plan_.beta_input)].node_id); | |
| 144 | 24 | } | |
| 145 | 44 | std::vector<Value*> norm(static_cast<std::size_t>(lanes_)); | |
| 146 | 178 | for (int j = 0; j < lanes_; ++j) { | |
| 147 | 134 | const std::size_t js = static_cast<std::size_t>(j); | |
| 148 | 134 | Value* v = mean ? b.build_mul(b.build_sub(x[js], mean), rstd) : b.build_mul(x[js], rstd); | |
| 149 | 134 | if (!gam.empty()) { | |
| 150 | 134 | v = bet.empty() ? b.build_mul(v, gam[js]) : b.build_fma_f32(v, gam[js], bet[js]); | |
| 151 | 134 | } | |
| 152 | 134 | norm[js] = v; | |
| 153 | 134 | } | |
| 154 | 44 | vals[plan_.norm_node] = std::move(norm); | |
| 155 | 44 | vals = eval_chain(c, dag_, lanes_, std::move(vals), &plan_.post_ids); | |
| 156 | 92 | for (std::size_t m = 0; m < ew_.outputs.size(); ++m) { | |
| 157 | 48 | if (m < plan_.pre_output.size() && plan_.pre_output[m]) continue; // written in pass one | |
| 158 | 44 | const plan::BufferSpec& s = ew_.outputs[m]; | |
| 159 | 88 | store_lanes(c, s.dtype, lanes_, b.build_add(out_ptr_[m], full_off(o, col, s.dtype)), | |
| 160 | 44 | vals.at(s.node_id)); | |
| 161 | 44 | } | |
| 162 | 44 | }); | |
| 163 | 44 | b.build_ret_void(); | |
| 164 | 44 | if (optimize_) { | |
| 165 | #if BRASS_WITH_SPIRV | ||
| 166 | 44 | const brass::verify::GpuKernelContract contract = spirv::build_row_norm_contract(plan_, lanes_); | |
| 167 | 44 | optimize_function(*fn, &contract); | |
| 168 | #else | ||
| 169 | optimize_function(*fn); | ||
| 170 | #endif | ||
| 171 | 44 | } | |
| 172 | 44 | return fn; | |
| 173 | 44 | } | |
| 174 | |||
| 175 | private: | ||
| 176 | // Byte offsets materialised for the column one loop iteration is on. | ||
| 177 | struct Offsets { | ||
| 178 | std::unordered_map<int, Value*> col, full; | ||
| 179 | }; | ||
| 180 | |||
| 181 | 286 | Value* row_bytes(Dtype dt) { | |
| 182 | 286 | const int e = plan::elem_bytes(dt); | |
| 183 | 286 | auto it = rowbyte_.find(e); | |
| 184 | 286 | if (it != rowbyte_.end()) return it->second; | |
| 185 | 44 | Value* v = byte_offset(*c_, rowbase_, e); | |
| 186 | 44 | rowbyte_[e] = v; | |
| 187 | 44 | return v; | |
| 188 | 286 | } | |
| 189 | |||
| 190 | ✗ | Value* col_bcast_bytes(Dtype dt) { | |
| 191 | ✗ | const int e = plan::elem_bytes(dt); | |
| 192 | ✗ | auto it = colbcastbyte_.find(e); | |
| 193 | ✗ | if (it != colbcastbyte_.end()) return it->second; | |
| 194 | ✗ | Value* v = byte_offset(*c_, row_, e); | |
| 195 | ✗ | colbcastbyte_[e] = v; | |
| 196 | ✗ | return v; | |
| 197 | ✗ | } | |
| 198 | |||
| 199 | 180 | Value* col_off(Offsets& o, Value* col, Dtype dt) { | |
| 200 | 180 | const int e = plan::elem_bytes(dt); | |
| 201 | 180 | auto it = o.col.find(e); | |
| 202 | 180 | if (it != o.col.end()) return it->second; | |
| 203 | 112 | Value* v = byte_offset(*c_, col, e); | |
| 204 | 112 | o.col[e] = v; | |
| 205 | 112 | return v; | |
| 206 | 180 | } | |
| 207 | |||
| 208 | 190 | Value* full_off(Offsets& o, Value* col, Dtype dt) { | |
| 209 | 190 | const int e = plan::elem_bytes(dt); | |
| 210 | 190 | auto it = o.full.find(e); | |
| 211 | 190 | if (it != o.full.end()) return it->second; | |
| 212 | 112 | Value* v = c_->b.build_add(row_bytes(dt), col_off(o, col, dt)); | |
| 213 | 112 | o.full[e] = v; | |
| 214 | 112 | return v; | |
| 215 | 190 | } | |
| 216 | |||
| 217 | // Loads the inputs `want` selects at `col`. | ||
| 218 | 108 | ValueMap load_inputs(Offsets& o, Value* col, const std::vector<char>& want) { | |
| 219 | 108 | ValueMap vals; | |
| 220 | 426 | for (std::size_t k = 0; k < ew_.inputs.size(); ++k) { | |
| 221 | 318 | if (!want.empty() && !want[k]) continue; | |
| 222 | 202 | const plan::BufferSpec& s = ew_.inputs[k]; | |
| 223 | 202 | if (s.bcast == BroadcastKind::Scalar) { | |
| 224 | ✗ | Value* v = load_lanes(*c_, s.dtype, 1, in_ptr_[k])[0]; | |
| 225 | ✗ | vals[s.node_id] = std::vector<Value*>(static_cast<std::size_t>(lanes_), v); | |
| 226 | ✗ | continue; | |
| 227 | } | ||
| 228 | 202 | if (s.bcast == BroadcastKind::Col) { | |
| 229 | ✗ | Value* v = load_lanes(*c_, s.dtype, 1, c_->b.build_add(in_ptr_[k], col_bcast_bytes(s.dtype)))[0]; | |
| 230 | ✗ | vals[s.node_id] = std::vector<Value*>(static_cast<std::size_t>(lanes_), v); | |
| 231 | ✗ | continue; | |
| 232 | } | ||
| 233 | 202 | Value* off = s.bcast == BroadcastKind::Row ? col_off(o, col, s.dtype) : full_off(o, col, s.dtype); | |
| 234 | 202 | vals[s.node_id] = load_lanes(*c_, s.dtype, lanes_, c_->b.build_add(in_ptr_[k], off)); | |
| 235 | 202 | } | |
| 236 | 108 | return vals; | |
| 237 | 108 | } | |
| 238 | |||
| 239 | // Pass one: the pre chain at `col`, its outputs stored (final already — | ||
| 240 | // and what lets the later passes read x back instead of replaying it). | ||
| 241 | 44 | std::vector<Value*> pass_one_x(Offsets& o, Value* col) { | |
| 242 | 44 | ValueMap vals = eval_chain(*c_, dag_, lanes_, load_inputs(o, col, plan_.pre_input), &plan_.pre_ids); | |
| 243 | 92 | for (std::size_t m = 0; m < ew_.outputs.size(); ++m) { | |
| 244 | 48 | if (m >= plan_.pre_output.size() || !plan_.pre_output[m]) continue; | |
| 245 | 4 | const plan::BufferSpec& s = ew_.outputs[m]; | |
| 246 | 8 | store_lanes(*c_, s.dtype, lanes_, c_->b.build_add(out_ptr_[m], full_off(o, col, s.dtype)), | |
| 247 | 4 | vals.at(s.node_id)); | |
| 248 | 4 | } | |
| 249 | 44 | return vals.at(plan_.x_node); | |
| 250 | 44 | } | |
| 251 | |||
| 252 | // x at `col` after pass one: read back from the output pass one wrote, | ||
| 253 | // or (no pre output) the pre chain replayed from the inputs. With `vals`, | ||
| 254 | // also loads what pass two needs and leaves it there. | ||
| 255 | 68 | std::vector<Value*> reload_x(Offsets& o, Value* col, ValueMap* vals) { | |
| 256 | 68 | ValueMap local; | |
| 257 | 68 | ValueMap& v = vals ? *vals : local; | |
| 258 | 68 | if (plan_.x_output >= 0) { | |
| 259 | 8 | if (vals) v = load_inputs(o, col, plan_.post_input); | |
| 260 | 8 | const plan::BufferSpec& xs = ew_.outputs[static_cast<std::size_t>(plan_.x_output)]; | |
| 261 | 16 | std::vector<Value*> x = load_lanes( | |
| 262 | 8 | *c_, xs.dtype, lanes_, | |
| 263 | 8 | c_->b.build_add(out_ptr_[static_cast<std::size_t>(plan_.x_output)], full_off(o, col, xs.dtype))); | |
| 264 | 8 | v[plan_.x_node] = x; | |
| 265 | 8 | return x; | |
| 266 | 8 | } | |
| 267 | // Without the reload the plan guarantees pass one stored nothing, so | ||
| 268 | // the inputs are still what pass one read. | ||
| 269 | 60 | v = load_inputs(o, col, vals ? plan_.post_input : plan_.pre_input); | |
| 270 | 60 | v = eval_chain(*c_, dag_, lanes_, std::move(v), &plan_.pre_ids); | |
| 271 | 60 | return v.at(plan_.x_node); | |
| 272 | 68 | } | |
| 273 | |||
| 274 | // The row total of `v` in every thread of the row. | ||
| 275 | 68 | Value* reduce(Value* v, Value* red) { | |
| 276 | 68 | KernelBuilder& kb = c_->kb; | |
| 277 | 68 | Builder& b = c_->b; | |
| 278 | 408 | for (uint32_t m = 16; m >= 1; m >>= 1) v = b.build_add(v, kb.shfl_bfly_f32(v, m)); | |
| 279 | 68 | if (warps_ == 1) return v; | |
| 280 | 54 | Value* lane = b.build_and(tid_, c_->i32(31)); | |
| 281 | 54 | Value* warp = b.build_lshr(tid_, c_->i32(5)); | |
| 282 | 108 | kb.if_then(b.build_eq(lane, c_->i32(0)), [&] { kb.shared_store_f32_indexed(red, warp, v); }); | |
| 283 | 54 | kb.sync(); | |
| 284 | 54 | Value* base = rpb_ == 1 ? c_->i32(0) : b.build_shl(local_, c_->i32(log2_exact(warps_))); | |
| 285 | 54 | Value* total = nullptr; | |
| 286 | 372 | for (int w = 0; w < warps_; ++w) { | |
| 287 | 318 | Value* x = kb.shared_load_f32_indexed(red, b.build_add(base, c_->i32(w))); | |
| 288 | 318 | total = total ? b.build_add(total, x) : x; | |
| 289 | 318 | } | |
| 290 | 54 | return total; | |
| 291 | 68 | } | |
| 292 | |||
| 293 | const TraceDAG& dag_; | ||
| 294 | const plan::RowNormPlan& plan_; | ||
| 295 | const plan::ElementwisePlan& ew_; | ||
| 296 | int lanes_; | ||
| 297 | const char* name_; | ||
| 298 | brass::Module& mod_; | ||
| 299 | bool optimize_ = true; | ||
| 300 | 44 | int tpr_ = 32, rpb_ = 1, warps_ = 1, step_ = 32; | |
| 301 | 44 | Ctx* c_ = nullptr; | |
| 302 | std::vector<Value*> out_ptr_, in_ptr_; | ||
| 303 | 44 | Value* tid_ = nullptr; | |
| 304 | 44 | Value* local_ = nullptr; | |
| 305 | 44 | Value* c0_ = nullptr; | |
| 306 | 44 | Value* row_ = nullptr; | |
| 307 | 44 | Value* rowbase_ = nullptr; | |
| 308 | std::unordered_map<int, Value*> rowbyte_; | ||
| 309 | std::unordered_map<int, Value*> colbcastbyte_; | ||
| 310 | }; | ||
| 311 | |||
| 312 | } // namespace | ||
| 313 | |||
| 314 | 44 | brass::Function* build_row_norm_fn(brass::Module& mod, const TraceDAG& dag, | |
| 315 | const plan::RowNormPlan& plan, int lanes, | ||
| 316 | const char* name, bool optimize) { | ||
| 317 | 44 | return RowNormBuilder(mod, dag, plan, lanes, name, optimize).build(); | |
| 318 | ✗ | } | |
| 319 | |||
| 320 | } // namespace brotensor::jit::gpu_mir | ||
| 321 |