src/cpu/top_k.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | // ─── CPU per-row top-k ────────────────────────────────────────────────────── | ||
| 2 | // | ||
| 3 | // FP32 scalar host implementation. For each row of X(R, C), selects the k | ||
| 4 | // largest values and returns them in descending order in `Vals(R, k)` with | ||
| 5 | // their original column indices in `Idx(R, k)`. Ties are broken by smaller | ||
| 6 | // column index — deterministic and stable across runs. | ||
| 7 | // | ||
| 8 | // Used for: classification heads (top-5), NMS pre-filter (keep top-K box | ||
| 9 | // scores per class), beam-search candidates, retrieval rerankers. Not | ||
| 10 | // differentiable — no backward op. | ||
| 11 | // | ||
| 12 | // Algorithm: partial sort via a max-heap of (value, -index) tuples isn't a | ||
| 13 | // great fit for "tie -> smaller index wins" (we'd want a min-key composite), | ||
| 14 | // so for clarity we use a streaming-replacement strategy: maintain a working | ||
| 15 | // array of (value, index) for the current top-k, scan the row, and replace | ||
| 16 | // the current minimum if a candidate beats it. O(C * k) per row — k is | ||
| 17 | // always small (5, 100, etc.) in real use, so the simpler code wins. | ||
| 18 | // | ||
| 19 | // ── ACCUMULATION ──────────────────────────────────────────────────────────── | ||
| 20 | // top_k_rows — Vals and Idx OVERWRITTEN. | ||
| 21 | |||
| 22 | #include <brotensor/tensor.h> | ||
| 23 | |||
| 24 | #include <algorithm> | ||
| 25 | #include <stdexcept> | ||
| 26 | #include <string> | ||
| 27 | #include <vector> | ||
| 28 | |||
| 29 | namespace brotensor::detail::cpu { | ||
| 30 | |||
| 31 | namespace { | ||
| 32 | |||
| 33 | 2 | [[noreturn]] inline void fail(const char* op, const std::string& reason) { | |
| 34 | 2 | throw std::runtime_error(std::string("brotensor: ") + op + ": " + reason); | |
| 35 | 2 | } | |
| 36 | |||
| 37 | 36 | inline void check_fp32(const ::brotensor::Tensor& t, | |
| 38 | const char* op, const char* name) { | ||
| 39 | 36 | if (t.dtype != Dtype::FP32) { | |
| 40 | ✗ | fail(op, std::string(name) + | |
| 41 | " must be FP32 (CPU backend is FP32-only)"); | ||
| 42 | } | ||
| 43 | 36 | } | |
| 44 | |||
| 45 | // "(a, idx_a) precedes (b, idx_b)" in our descending-value, ascending-index | ||
| 46 | // ordering. Returns true iff a is strictly preferable to b (i.e. should | ||
| 47 | // appear earlier in the output). | ||
| 48 | 4673248 | inline bool prefers(float a, int idx_a, float b, int idx_b) { | |
| 49 | 4673248 | if (a != b) return a > b; | |
| 50 | 326876 | return idx_a < idx_b; | |
| 51 | 4673248 | } | |
| 52 | |||
| 53 | } // namespace | ||
| 54 | |||
| 55 | 36 | void top_k_rows(const ::brotensor::Tensor& X, int k, | |
| 56 | ::brotensor::Tensor& Vals, ::brotensor::Tensor& Idx) { | ||
| 57 | 36 | const char* op = "top_k_rows"; | |
| 58 | 36 | check_fp32(X, op, "X"); | |
| 59 | 36 | const int R = X.rows, C = X.cols; | |
| 60 | 37 | if (k < 1) fail(op, "k must be >= 1"); | |
| 61 | 35 | if (k > C) fail(op, "k must be <= C (per-row length)"); | |
| 62 | |||
| 63 | 34 | if (Vals.rows != R || Vals.cols != k || Vals.dtype != Dtype::FP32) { | |
| 64 | 34 | Vals.resize(R, k, Dtype::FP32); | |
| 65 | 34 | } | |
| 66 | 34 | if (Idx.rows != R || Idx.cols != k || Idx.dtype != Dtype::INT32) { | |
| 67 | 34 | Idx.resize(R, k, Dtype::INT32); | |
| 68 | 34 | } | |
| 69 | 34 | if (R == 0 || k == 0) return; | |
| 70 | |||
| 71 | 34 | const float* Xp = X.host_f32(); | |
| 72 | 34 | float* Vp = Vals.host_f32_mut(); | |
| 73 | 34 | int32_t* Ip = static_cast<int32_t*>(Idx.data); | |
| 74 | |||
| 75 | // Large k (the masked-diffusion host loop asks for k up to the full row | ||
| 76 | // length): the streaming replacement below is O(C * k) per row, so past | ||
| 77 | // a modest k a full sort of the row's indices under the same total order | ||
| 78 | // — O(C log C), independent of k — is the cheaper route. The order is | ||
| 79 | // total (descending value, ascending index), so both paths produce the | ||
| 80 | // identical Vals / Idx; only the cost model differs. | ||
| 81 | 34 | constexpr int kSortThreshold = 64; | |
| 82 | 34 | std::vector<int32_t> order; | |
| 83 | 34 | if (k > kSortThreshold) order.resize(C); | |
| 84 | |||
| 85 | // Per-row working arrays (size k). Keeping them on the stack via VLA | ||
| 86 | // isn't portable on MSVC; allocate on the heap once and reuse. | ||
| 87 | // k is small in practice but C can be huge — so we allocate per row. | ||
| 88 | // The inner top-k is O(k) per candidate scanned. | ||
| 89 | 165 | for (int r = 0; r < R; ++r) { | |
| 90 | 131 | const float* row = Xp + static_cast<long>(r) * C; | |
| 91 | 131 | float* out_v = Vp + static_cast<long>(r) * k; | |
| 92 | 131 | int32_t* out_i = Ip + static_cast<long>(r) * k; | |
| 93 | |||
| 94 | 131 | if (k > kSortThreshold) { | |
| 95 | 375864 | for (int c = 0; c < C; ++c) order[c] = c; | |
| 96 | 32 | std::partial_sort(order.begin(), order.begin() + k, order.end(), | |
| 97 | 2941626 | [row](int32_t a, int32_t b) { | |
| 98 | 2941610 | return prefers(row[a], a, row[b], b); | |
| 99 | }); | ||
| 100 | 110219 | for (int j = 0; j < k; ++j) { | |
| 101 | 110203 | out_i[j] = order[j]; | |
| 102 | 110203 | out_v[j] = row[order[j]]; | |
| 103 | 110203 | } | |
| 104 | 16 | continue; | |
| 105 | } | ||
| 106 | |||
| 107 | // Step 1: seed the working set with the first k elements (verbatim | ||
| 108 | // order — ties get resolved on later replacements). | ||
| 109 | 981 | for (int j = 0; j < k; ++j) { | |
| 110 | 866 | out_v[j] = row[j]; | |
| 111 | 866 | out_i[j] = j; | |
| 112 | 866 | } | |
| 113 | // Track the current weakest entry — anything that beats it gets | ||
| 114 | // swapped in. Scan the working set for the weakest each replace. | ||
| 115 | // (For modest k this is faster + cleaner than a heap.) | ||
| 116 | 115 | int weakest = 0; | |
| 117 | 866 | for (int j = 1; j < k; ++j) { | |
| 118 | 751 | if (prefers(out_v[weakest], out_i[weakest], out_v[j], out_i[j])) { | |
| 119 | 276 | weakest = j; | |
| 120 | 276 | } | |
| 121 | 751 | } | |
| 122 | |||
| 123 | // Step 2: scan the remainder. Replace the weakest if beaten. | ||
| 124 | 1654649 | for (int c = k; c < C; ++c) { | |
| 125 | 1654534 | const float v = row[c]; | |
| 126 | 1654534 | if (prefers(v, c, out_v[weakest], out_i[weakest])) { | |
| 127 | 2520 | out_v[weakest] = v; | |
| 128 | 2520 | out_i[weakest] = c; | |
| 129 | // Re-find the weakest after replacement. | ||
| 130 | 2520 | weakest = 0; | |
| 131 | 73291 | for (int j = 1; j < k; ++j) { | |
| 132 | 141542 | if (prefers(out_v[weakest], out_i[weakest], | |
| 133 | 70771 | out_v[j], out_i[j])) { | |
| 134 | 8082 | weakest = j; | |
| 135 | 8082 | } | |
| 136 | 70771 | } | |
| 137 | 2520 | } | |
| 138 | 1654534 | } | |
| 139 | |||
| 140 | // Step 3: sort the k survivors into descending-value / ascending- | ||
| 141 | // index order (insertion sort — small k). | ||
| 142 | 866 | for (int i = 1; i < k; ++i) { | |
| 143 | 751 | const float v = out_v[i]; | |
| 144 | 751 | const int32_t idx = out_i[i]; | |
| 145 | 751 | int j = i; | |
| 146 | 6470 | while (j > 0 && prefers(v, idx, out_v[j - 1], out_i[j - 1])) { | |
| 147 | 4968 | out_v[j] = out_v[j - 1]; | |
| 148 | 4968 | out_i[j] = out_i[j - 1]; | |
| 149 | 4968 | --j; | |
| 150 | } | ||
| 151 | 751 | out_v[j] = v; | |
| 152 | 751 | out_i[j] = idx; | |
| 153 | 751 | } | |
| 154 | 115 | } | |
| 155 | 36 | } | |
| 156 | |||
| 157 | } // namespace brotensor::detail::cpu | ||
| 158 |