Notesoop-STT-Ko-v2 / src /fast_beam_search_v3.cpp
yclee12345's picture
Initial release of Notesoop-STT-Ko-v2 (Private)
c39225b verified
Raw History Blame Contribute Delete
8.6 kB
#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"