src/cpu/masked_diffusion.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // ─── CPU masked-diffusion token selection ────────────────────────────────── | ||
| 2 | // | ||
| 3 | // FP32 scalar host implementation of `masked_diffusion_scores` and | ||
| 4 | // `masked_diffusion_commit` — the per-step token selection of a masked- | ||
| 5 | // diffusion language model over a (C codebooks, T frames) grid (the OmniVoice | ||
| 6 | // port in brosoundml). See ops/sampling.h for the full contract and the | ||
| 7 | // pseudocode this follows. | ||
| 8 | // | ||
| 9 | // This is the parity reference for the Brass MIR CUDA kernel | ||
| 10 | // (`build_select_md_mir` in src/kernels/mir_select.cpp), so the arithmetic is | ||
| 11 | // spelled out in the exact order the kernel uses: | ||
| 12 | // * a row's log-sum-exp is max + (float)log(sum), the sum accumulated in | ||
| 13 | // FP64 from FP32 expf terms (order-independent to the last FP32 ulp); | ||
| 14 | // * the guided logit is a + gs * (a - b) with a = c - lse_c, b = u - lse_u, | ||
| 15 | // each operation rounded separately (without FMA contraction); | ||
| 16 | // * the noise comes from detail/hash_rng.h, identical integer arithmetic on | ||
| 17 | // both backends. | ||
| 18 | // The top-k class filter keeps the first k entries in (value desc, index asc) | ||
| 19 | // order: everything above the k-th value, then the lowest-indexed entries | ||
| 20 | // equal to it until k are kept. | ||
| 21 | // | ||
| 22 | // ── ACCUMULATION ──────────────────────────────────────────────────────────── | ||
| 23 | // masked_diffusion_scores — pred, scores and confidence OVERWRITTEN. | ||
| 24 | // masked_diffusion_commit — tokens / unmask_step written only at idx[0..k). | ||
| 25 | |||
| 26 | #include <brotensor/tensor.h> | ||
| 27 | #include <brotensor/detail/hash_rng.h> | ||
| 28 | #include <brotensor/detail/cpu/thread_pool.h> | ||
| 29 | |||
| 30 | #include <algorithm> | ||
| 31 | #include <cmath> | ||
| 32 | #include <cstddef> | ||
| 33 | #include <cstdint> | ||
| 34 | #include <limits> | ||
| 35 | #include <stdexcept> | ||
| 36 | #include <string> | ||
| 37 | #include <vector> | ||
| 38 | |||
| 39 | namespace brotensor::detail::cpu { | ||
| 40 | |||
| 41 | namespace { | ||
| 42 | |||
| 43 | 4 | [[noreturn]] void fail(const char* op, const std::string& reason) { | |
| 44 | 4 | throw std::runtime_error(std::string("brotensor: ") + op + ": " + reason); | |
| 45 | 4 | } | |
| 46 | |||
| 47 | constexpr float kNegInf = -std::numeric_limits<float>::infinity(); | ||
| 48 | |||
| 49 | 323898 | inline float gumbel_from_uniform(float u) { | |
| 50 | 323898 | return -std::log(-std::log(u + 1e-10f) + 1e-10f); | |
| 51 | } | ||
| 52 | |||
| 53 | // max + log(sum exp(x - max)) over a row of n floats; sum in FP64. | ||
| 54 | 22494 | inline float row_lse(const float* x, int n, float& max_out) { | |
| 55 | 22494 | float m = kNegInf; | |
| 56 | 20126387 | for (int i = 0; i < n; ++i) m = (x[i] > m) ? x[i] : m; | |
| 57 | 22494 | double s = 0.0; | |
| 58 | 18271532 | for (int i = 0; i < n; ++i) s += static_cast<double>(std::exp(x[i] - m)); | |
| 59 | 22494 | max_out = m; | |
| 60 | 22494 | return m + static_cast<float>(std::log(s)); | |
| 61 | } | ||
| 62 | |||
| 63 | // (a, ia) precedes (b, ib) in descending-value / ascending-index order. | ||
| 64 | 8924826 | inline bool prefers(float a, int ia, float b, int ib) { | |
| 65 | 8924826 | if (a != b) return a > b; | |
| 66 | 28185 | return ia < ib; | |
| 67 | 8924826 | } | |
| 68 | |||
| 69 | } // namespace | ||
| 70 | |||
| 71 | // ─── masked_diffusion_scores ──────────────────────────────────────────────── | ||
| 72 | |||
| 73 | 15 | void masked_diffusion_scores(const ::brotensor::Tensor& logits, | |
| 74 | const ::brotensor::Tensor& tokens, | ||
| 75 | int T, int C, int V, int mask_id, | ||
| 76 | float guidance_scale, float layer_penalty, | ||
| 77 | float position_temperature, float class_temperature, | ||
| 78 | float class_top_frac, uint64_t seed, | ||
| 79 | ::brotensor::Tensor& pred, ::brotensor::Tensor& scores, | ||
| 80 | ::brotensor::Tensor& confidence) { | ||
| 81 | 15 | const char* op = "masked_diffusion_scores"; | |
| 82 | 18 | if (logits.dtype != Dtype::FP32) fail(op, "logits must be FP32 (CPU backend is FP32-only)"); | |
| 83 | 15 | if (tokens.dtype != Dtype::INT32) fail(op, "tokens must be INT32"); | |
| 84 | 15 | if (T < 1 || C < 1 || V < 1) fail(op, "T, C and V must be >= 1"); | |
| 85 | 15 | if (mask_id < 0 || mask_id >= V) fail(op, "mask_id must be in [0, V)"); | |
| 86 | 14 | const bool guided = guidance_scale != 0.0f; | |
| 87 | 14 | const int R = guided ? 2 * T : T; | |
| 88 | 14 | if (logits.rows != R || logits.cols != C * V) { | |
| 89 | 3 | fail(op, "logits must be (" + std::to_string(R) + ", C*V=" + | |
| 90 | 2 | std::to_string(C * V) + ") for T=" + std::to_string(T) + | |
| 91 | 2 | (guided ? " with" : " without") + " guidance, got (" + | |
| 92 | 2 | std::to_string(logits.rows) + ", " + std::to_string(logits.cols) + ")"); | |
| 93 | } | ||
| 94 | 13 | if (tokens.rows != C || tokens.cols != T) fail(op, "tokens must be (C, T)"); | |
| 95 | |||
| 96 | 12 | const int rows = C * T; | |
| 97 | 12 | if (pred.rows != C || pred.cols != T || pred.dtype != Dtype::INT32) { | |
| 98 | 12 | pred.resize(C, T, Dtype::INT32); | |
| 99 | 12 | } | |
| 100 | 12 | if (scores.rows != C || scores.cols != T || scores.dtype != Dtype::FP32) { | |
| 101 | 12 | scores.resize(C, T, Dtype::FP32); | |
| 102 | 12 | } | |
| 103 | 12 | if (confidence.rows != C || confidence.cols != T || confidence.dtype != Dtype::FP32) { | |
| 104 | 12 | confidence.resize(C, T, Dtype::FP32); | |
| 105 | 12 | } | |
| 106 | |||
| 107 | // Top-k class filter width, fixed per call (ceil(frac * V), clamped). | ||
| 108 | 12 | int k_keep = V; | |
| 109 | 12 | if (class_temperature > 0.0f) { | |
| 110 | 3 | const double kd = std::ceil(static_cast<double>(class_top_frac) * V); | |
| 111 | 3 | k_keep = (kd < 1.0) ? 1 : (kd > V ? V : static_cast<int>(kd)); | |
| 112 | 3 | } | |
| 113 | |||
| 114 | 12 | const float* L = logits.host_f32(); | |
| 115 | 12 | const int32_t* tok = static_cast<const int32_t*>(tokens.host_raw()); | |
| 116 | 12 | int32_t* pr = static_cast<int32_t*>(pred.host_raw_mut()); | |
| 117 | 12 | float* sc = scores.host_f32_mut(); | |
| 118 | 12 | float* cf = confidence.host_f32_mut(); | |
| 119 | 12 | const std::size_t row_stride = static_cast<std::size_t>(C) * V; | |
| 120 | |||
| 121 | 9659 | parallel_for(static_cast<std::size_t>(rows), [&](std::size_t pi) { | |
| 122 | 9647 | const int p = static_cast<int>(pi); | |
| 123 | 9647 | const int c = p / T; | |
| 124 | 9647 | const int t = p - c * T; | |
| 125 | 19294 | const float* cond = L + static_cast<std::size_t>(t) * row_stride + | |
| 126 | 9647 | static_cast<std::size_t>(c) * V; | |
| 127 | |||
| 128 | 9647 | thread_local std::vector<float> lp_buf, sort_buf; | |
| 129 | 9647 | if (static_cast<int>(lp_buf.size()) < V) { | |
| 130 | 4 | lp_buf.resize(V); | |
| 131 | 4 | sort_buf.resize(V); | |
| 132 | 4 | } | |
| 133 | 9647 | float* lp = lp_buf.data(); | |
| 134 | |||
| 135 | // ── log_probs ── | ||
| 136 | 9647 | float dummy = 0.0f; | |
| 137 | 9647 | if (guided) { | |
| 138 | 12868 | const float* unc = L + static_cast<std::size_t>(T + t) * row_stride + | |
| 139 | 6434 | static_cast<std::size_t>(c) * V; | |
| 140 | 6434 | const float lse_c = row_lse(cond, V, dummy); | |
| 141 | 6434 | const float lse_u = row_lse(unc, V, dummy); | |
| 142 | 6335326 | for (int v = 0; v < V; ++v) { | |
| 143 | 6328892 | const float a = cond[v] - lse_c; | |
| 144 | 6328892 | const float b = unc[v] - lse_u; | |
| 145 | 6328892 | lp[v] = a + guidance_scale * (a - b); | |
| 146 | 6328892 | } | |
| 147 | 6434 | const float lse_g = row_lse(lp, V, dummy); | |
| 148 | 6394842 | for (int v = 0; v < V; ++v) lp[v] = lp[v] - lse_g; | |
| 149 | 6434 | } else { | |
| 150 | 3213 | const float lse = row_lse(cond, V, dummy); | |
| 151 | 2959527 | for (int v = 0; v < V; ++v) lp[v] = cond[v] - lse; | |
| 152 | } | ||
| 153 | 9647 | lp[mask_id] = kNegInf; | |
| 154 | |||
| 155 | // ── confidence: max of the UNfiltered log_probs ── | ||
| 156 | 9647 | float conf = kNegInf; | |
| 157 | 9170246 | for (int v = 0; v < V; ++v) conf = (lp[v] > conf) ? lp[v] : conf; | |
| 158 | 9647 | cf[p] = conf; // raw, for every cell — masked or already decided | |
| 159 | |||
| 160 | // ── prediction ── | ||
| 161 | 9647 | int best = 0; | |
| 162 | 9647 | if (class_temperature > 0.0f) { | |
| 163 | // k-th largest value of the row (ties resolved by index below). | ||
| 164 | 3209 | float* srt = sort_buf.data(); | |
| 165 | 3209 | std::copy(lp, lp + V, srt); | |
| 166 | 3209 | std::nth_element(srt, srt + (k_keep - 1), srt + V, | |
| 167 | 7303955 | [](float a, float b) { return a > b; }); | |
| 168 | 3209 | const float thr = srt[k_keep - 1]; | |
| 169 | 3209 | int count_gt = 0; | |
| 170 | 3228647 | for (int v = 0; v < V; ++v) count_gt += (lp[v] > thr) ? 1 : 0; | |
| 171 | 3209 | const int m = k_keep - count_gt; // equal-to-threshold slots | |
| 172 | |||
| 173 | 3209 | const uint64_t base = static_cast<uint64_t>(p) * static_cast<uint64_t>(V); | |
| 174 | 3209 | float best_s = kNegInf; | |
| 175 | 3209 | int seen_eq = 0; | |
| 176 | 3022879 | for (int v = 0; v < V; ++v) { | |
| 177 | 3019670 | bool kept = lp[v] > thr; | |
| 178 | 3019670 | if (!kept && lp[v] == thr) { | |
| 179 | 3216 | kept = seen_eq < m; | |
| 180 | 3216 | ++seen_eq; | |
| 181 | 3216 | } | |
| 182 | 3019670 | float s = kNegInf; | |
| 183 | 3019670 | if (kept) { | |
| 184 | 637610 | const float u = hash_uniform(seed, kHashDomainMaskedDiffusionClass, | |
| 185 | 318805 | base + static_cast<uint64_t>(v)); | |
| 186 | 318805 | s = lp[v] / class_temperature + gumbel_from_uniform(u); | |
| 187 | 318805 | } | |
| 188 | 3019670 | if (prefers(s, v, best_s, best)) { best_s = s; best = v; } | |
| 189 | 3019670 | } | |
| 190 | 3209 | } else { | |
| 191 | 6438 | float best_v = kNegInf; | |
| 192 | 5885253 | for (int v = 0; v < V; ++v) { | |
| 193 | 5878815 | if (prefers(lp[v], v, best_v, best)) { best_v = lp[v]; best = v; } | |
| 194 | 5878815 | } | |
| 195 | } | ||
| 196 | 9647 | pr[p] = best; | |
| 197 | |||
| 198 | // ── score ── | ||
| 199 | 9647 | float s = kNegInf; | |
| 200 | 9647 | if (tok[p] == mask_id) { | |
| 201 | 5805 | s = conf - static_cast<float>(c) * layer_penalty; | |
| 202 | 5805 | if (position_temperature > 0.0f) { | |
| 203 | 7776 | const float u = hash_uniform(seed, kHashDomainMaskedDiffusionPosition, | |
| 204 | 3888 | static_cast<uint64_t>(p)); | |
| 205 | 3888 | s = s / position_temperature + gumbel_from_uniform(u); | |
| 206 | 3888 | } | |
| 207 | 5805 | } | |
| 208 | 9647 | sc[p] = s; | |
| 209 | 9647 | }); | |
| 210 | 15 | } | |
| 211 | |||
| 212 | // ─── masked_diffusion_commit ──────────────────────────────────────────────── | ||
| 213 | |||
| 214 | 7 | void masked_diffusion_commit(const ::brotensor::Tensor& pred, | |
| 215 | const ::brotensor::Tensor& idx, int k, int step, | ||
| 216 | ::brotensor::Tensor& tokens, | ||
| 217 | ::brotensor::Tensor& unmask_step) { | ||
| 218 | 7 | const char* op = "masked_diffusion_commit"; | |
| 219 | 8 | if (pred.dtype != Dtype::INT32) fail(op, "pred must be INT32"); | |
| 220 | 7 | if (idx.dtype != Dtype::INT32) fail(op, "idx must be INT32"); | |
| 221 | 7 | if (tokens.dtype != Dtype::INT32) fail(op, "tokens must be INT32"); | |
| 222 | 7 | if (unmask_step.dtype != Dtype::INT32) fail(op, "unmask_step must be INT32"); | |
| 223 | 14 | if (tokens.rows != pred.rows || tokens.cols != pred.cols || | |
| 224 | 7 | unmask_step.rows != pred.rows || unmask_step.cols != pred.cols) { | |
| 225 | ✗ | fail(op, "pred, tokens and unmask_step must share one (C, T) shape"); | |
| 226 | } | ||
| 227 | 7 | if (k < 0) fail(op, "k must be >= 0"); | |
| 228 | 7 | if (k > idx.size()) fail(op, "idx must hold at least k entries"); | |
| 229 | 6 | if (k == 0) return; | |
| 230 | |||
| 231 | 5 | const int n = pred.size(); | |
| 232 | 5 | const int32_t* pr = static_cast<const int32_t*>(pred.host_raw()); | |
| 233 | 5 | const int32_t* ix = static_cast<const int32_t*>(idx.host_raw()); | |
| 234 | 5 | int32_t* tok = static_cast<int32_t*>(tokens.host_raw_mut()); | |
| 235 | 5 | int32_t* us = static_cast<int32_t*>(unmask_step.host_raw_mut()); | |
| 236 | 461 | for (int i = 0; i < k; ++i) { | |
| 237 | 456 | const int32_t p = ix[i]; | |
| 238 | 456 | if (p < 0 || p >= n) continue; | |
| 239 | 454 | tok[p] = pr[p]; | |
| 240 | 454 | us[p] = step; | |
| 241 | 454 | } | |
| 242 | 7 | } | |
| 243 | |||
| 244 | } // namespace brotensor::detail::cpu | ||
| 245 |