File size: 8,604 Bytes
c39225b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | #include <vector>
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <iostream>
namespace ctc_fast_v3 {
inline float log_add_fast(float a, float b) {
if (a <= -1e20f) return b;
if (b <= -1e20f) return a;
float diff = a - b;
if (diff > 16.0f) return a;
if (diff < -16.0f) return b;
return (diff >= 0.0f) ? (a + std::log1p(std::exp(-diff))) : (b + std::log1p(std::exp(diff)));
}
constexpr int MAX_BEAMS = 32;
constexpr int MAX_CANDIDATES = 1024;
constexpr uint32_t HASH_BUCKETS = 2048;
struct TreeNode {
int32_t parent;
int32_t token;
uint16_t length;
uint64_t hash; // 64-bit rolling hash for O(1) equality check
};
struct Beam {
int32_t node_idx;
float p_b;
float p_nb;
int32_t last_tok;
float score;
};
// Fast bucket hash map for deduplicating beams in O(1)
struct FastBeamMap {
int head[HASH_BUCKETS];
int next[MAX_CANDIDATES];
void clear() {
std::memset(head, -1, sizeof(head));
}
int find(uint64_t h, uint16_t len, const Beam* cands, const TreeNode* pool) const {
uint32_t b = static_cast<uint32_t>(h) & (HASH_BUCKETS - 1);
int idx = head[b];
while (idx >= 0) {
int32_t nid = cands[idx].node_idx;
if (pool[nid].hash == h && pool[nid].length == len) {
return idx;
}
idx = next[idx];
}
return -1;
}
void insert(uint64_t h, int cand_idx) {
uint32_t b = static_cast<uint32_t>(h) & (HASH_BUCKETS - 1);
next[cand_idx] = head[b];
head[b] = cand_idx;
}
};
} // namespace ctc_fast_v3
extern "C" {
/**
* Ultra-Fast O(1) Rolling-Hash CTC Beam Search:
* Eliminates tree traversal via 64-bit rolling hash + fast bucket hash table.
* Zero heap allocations per frame! Target: < 2.5 ms for 375 frames.
*/
int ctc_beam_search_fast_c(
const int32_t* topk_ids, // [T, K]
const float* topk_lprobs, // [T, K]
const float* blank_lprobs, // [T]
uint32_t T,
uint32_t K,
uint32_t beam_size,
int32_t blank_id,
int32_t* out_token_buf, // [max_beams, max_len]
int32_t* out_lens, // [max_beams]
float* out_scores, // [max_beams]
uint32_t max_beams,
uint32_t max_seq_len
) {
using namespace ctc_fast_v3;
uint32_t target_beams = beam_size * 2; // e.g. 16 beams
if (target_beams > MAX_BEAMS) target_beams = MAX_BEAMS;
// Pre-allocated static node pool (zero reallocation)
std::vector<TreeNode> node_pool;
node_pool.reserve(T * target_beams * 2 + 1024);
node_pool.push_back({ -1, blank_id, 0, 0x12345678ULL });
Beam current_beams[MAX_BEAMS];
int num_current = 1;
current_beams[0] = { 0, 0.0f, -1e30f, blank_id, 0.0f };
Beam next_candidates[MAX_CANDIDATES];
int num_candidates = 0;
FastBeamMap beam_map;
for (uint32_t t = 0; t < T; ++t) {
float p_blank = blank_lprobs[t];
const int32_t* t_ids = topk_ids + t * K;
const float* t_lprobs = topk_lprobs + t * K;
beam_map.clear();
num_candidates = 0;
for (int b_idx = 0; b_idx < num_current; ++b_idx) {
const Beam& b = current_beams[b_idx];
float p_tot = log_add_fast(b.p_b, b.p_nb);
uint64_t b_hash = node_pool[b.node_idx].hash;
uint16_t b_len = node_pool[b.node_idx].length;
// 1. Transition to Blank
int found_idx = beam_map.find(b_hash, b_len, next_candidates, node_pool.data());
if (found_idx >= 0) {
next_candidates[found_idx].p_b = log_add_fast(next_candidates[found_idx].p_b, p_tot + p_blank);
} else if (num_candidates < MAX_CANDIDATES) {
int c_idx = num_candidates++;
next_candidates[c_idx] = { b.node_idx, p_tot + p_blank, -1e30f, blank_id, 0.0f };
beam_map.insert(b_hash, c_idx);
}
// 2. Transition to Top-K Non-Blank tokens
for (uint32_t k = 0; k < K; ++k) {
int32_t tok_id = t_ids[k];
if (tok_id == blank_id) continue;
float prob_tok = t_lprobs[k];
if (tok_id == b.last_tok) {
// Case A: Token repeat separated by blank -> extends sequence
uint64_t ext_hash = (b_hash * 1315423911ULL) ^ (static_cast<uint64_t>(tok_id) + 0x9e3779b97f4a7c15ULL);
uint16_t ext_len = b_len + 1;
int ext_idx = beam_map.find(ext_hash, ext_len, next_candidates, node_pool.data());
if (ext_idx >= 0) {
next_candidates[ext_idx].p_nb = log_add_fast(next_candidates[ext_idx].p_nb, b.p_b + prob_tok);
} else if (num_candidates < MAX_CANDIDATES) {
int32_t new_node = static_cast<int32_t>(node_pool.size());
node_pool.push_back({ b.node_idx, tok_id, ext_len, ext_hash });
int c_idx = num_candidates++;
next_candidates[c_idx] = { new_node, -1e30f, b.p_b + prob_tok, tok_id, 0.0f };
beam_map.insert(ext_hash, c_idx);
}
// Case B: Token repeat collapsed -> same sequence
int same_idx = beam_map.find(b_hash, b_len, next_candidates, node_pool.data());
if (same_idx >= 0) {
next_candidates[same_idx].p_nb = log_add_fast(next_candidates[same_idx].p_nb, b.p_nb + prob_tok);
} else if (num_candidates < MAX_CANDIDATES) {
int c_idx = num_candidates++;
next_candidates[c_idx] = { b.node_idx, -1e30f, b.p_nb + prob_tok, tok_id, 0.0f };
beam_map.insert(b_hash, c_idx);
}
} else {
// Different token -> extends sequence
uint64_t new_hash = (b_hash * 1315423911ULL) ^ (static_cast<uint64_t>(tok_id) + 0x9e3779b97f4a7c15ULL);
uint16_t new_len = b_len + 1;
int diff_idx = beam_map.find(new_hash, new_len, next_candidates, node_pool.data());
if (diff_idx >= 0) {
next_candidates[diff_idx].p_nb = log_add_fast(next_candidates[diff_idx].p_nb, p_tot + prob_tok);
} else if (num_candidates < MAX_CANDIDATES) {
int32_t new_node = static_cast<int32_t>(node_pool.size());
node_pool.push_back({ b.node_idx, tok_id, new_len, new_hash });
int c_idx = num_candidates++;
next_candidates[c_idx] = { new_node, -1e30f, p_tot + prob_tok, tok_id, 0.0f };
beam_map.insert(new_hash, c_idx);
}
}
}
}
// Calculate scores
for (int i = 0; i < num_candidates; ++i) {
next_candidates[i].score = log_add_fast(next_candidates[i].p_b, next_candidates[i].p_nb);
}
// Partial sort top `target_beams`
int keep = std::min(num_candidates, static_cast<int>(target_beams));
std::partial_sort(
next_candidates,
next_candidates + keep,
next_candidates + num_candidates,
[](const Beam& a, const Beam& b) { return a.score > b.score; }
);
num_current = keep;
for (int i = 0; i < keep; ++i) {
current_beams[i] = next_candidates[i];
}
}
// Sort final beams descending
std::sort(
current_beams,
current_beams + num_current,
[](const Beam& a, const Beam& b) { return a.score > b.score; }
);
uint32_t num_out = std::min(static_cast<uint32_t>(num_current), max_beams);
std::vector<int32_t> temp_seq;
temp_seq.reserve(max_seq_len);
for (uint32_t i = 0; i < num_out; ++i) {
const auto& b = current_beams[i];
temp_seq.clear();
int32_t curr = b.node_idx;
while (curr > 0) {
temp_seq.push_back(node_pool[curr].token);
curr = node_pool[curr].parent;
}
std::reverse(temp_seq.begin(), temp_seq.end());
uint32_t len = std::min(static_cast<uint32_t>(temp_seq.size()), max_seq_len);
out_lens[i] = len;
out_scores[i] = b.score;
if (len > 0) {
std::memcpy(out_token_buf + i * max_seq_len, temp_seq.data(), len * sizeof(int32_t));
}
}
return num_out;
}
} // extern "C"
|