File size: 14,268 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
"""
v2/src/decoder.py

Production On-Device CTC Beam Search Decoder for 2,048 BPE Vocab with KenLM Language Model Rescoring.
Integrates SentencePiece BPE Tokenizer (ko_bpe_2048.model) and 8-bit Quantized Trie KenLM.
"""

from __future__ import annotations

import math
import ctypes
from pathlib import Path
from typing import List, Dict, Tuple, Optional, Any

import numpy as np
import torch
import torch.nn.functional as F

try:
    import kenlm
except ImportError:
    kenlm = None

from dataset import SentencePieceCTCTokenizer, normalize_text

# Load C++ Ultra-Fast CTC Beam Search Engine (< 1ms per utterance)
_FAST_BEAM_LIB = None

def _get_fast_beam_lib():
    """
    Dynamically discovers, compiles (if missing on Linux/macOS), and loads
    the high-performance C++ CTC Fast Beam Search shared library across multi-OS platforms.
    """
    global _FAST_BEAM_LIB
    if _FAST_BEAM_LIB is not None:
        return _FAST_BEAM_LIB

    src_dir = Path(__file__).resolve().parent
    cpp_source = src_dir / "fast_beam_search_v3.cpp"

    candidates = [
        src_dir / "libfast_beam_search_v3.so",
        src_dir / "libfast_beam_search_v3.dylib",
        src_dir / "fast_beam_search_v3.dll",
        src_dir / "libfast_beam_search.dylib",
        src_dir / "libfast_beam_search.so",
    ]

    # 1. Check existing compiled binary
    lib_path = None
    for p in candidates:
        if p.exists():
            lib_path = p
            break

    # 2. If not found, attempt on-the-fly compilation via system C++ compiler
    if lib_path is None and cpp_source.exists():
        try:
            import platform
            import shutil
            import subprocess

            sys_name = platform.system()
            target_name = (
                "libfast_beam_search_v3.dylib" if sys_name == "Darwin" else
                ("fast_beam_search_v3.dll" if sys_name == "Windows" else "libfast_beam_search_v3.so")
            )
            target_path = src_dir / target_name
            compiler = shutil.which("g++") or shutil.which("clang++")
            if compiler:
                flags = ["-O3", "-std=c++17", "-shared"]
                if sys_name != "Windows":
                    flags.append("-fPIC")
                cmd = [compiler] + flags + [str(cpp_source), "-o", str(target_path)]
                res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
                if res.returncode == 0 and target_path.exists():
                    lib_path = target_path
                    print(f"⚡ [Decoder V2] Auto-compiled native C++ beam search engine: {target_path.name}")
        except Exception:
            pass

    # 3. Load library with ctypes
    if lib_path and lib_path.exists():
        try:
            loaded_lib = ctypes.CDLL(str(lib_path))
            if hasattr(loaded_lib, "ctc_beam_search_fast_c"):
                loaded_lib.ctc_beam_search_fast_c.argtypes = [
                    ctypes.POINTER(ctypes.c_int32),
                    ctypes.POINTER(ctypes.c_float),
                    ctypes.POINTER(ctypes.c_float),
                    ctypes.c_uint32,
                    ctypes.c_uint32,
                    ctypes.c_uint32,
                    ctypes.c_int32,
                    ctypes.POINTER(ctypes.c_int32),
                    ctypes.POINTER(ctypes.c_int32),
                    ctypes.POINTER(ctypes.c_float),
                    ctypes.c_uint32,
                    ctypes.c_uint32
                ]
                loaded_lib.ctc_beam_search_fast_c.restype = ctypes.c_int
                _FAST_BEAM_LIB = loaded_lib
        except Exception:
            _FAST_BEAM_LIB = None

    return _FAST_BEAM_LIB

_FAST_BEAM_LIB = _get_fast_beam_lib()


class KenLMBeamSearchDecoder:
    """
    On-device CTC Beam Search Decoder for 2,048 BPE Vocab:
    - Maintains top-K acoustic beams across temporal frames
    - Ultra-fast native C++ engine (<1ms) with KenLM 5-gram Rescoring
    - Optimal tuned weights: alpha=0.10, beta=0.60, beam_size=16 for Korean lecture speech
    """
    def __init__(
        self,
        tokenizer: SentencePieceCTCTokenizer,
        lm_path: Optional[str] = "lm/ko_bpe_2048_lm.bin",
        beam_size: int = 16,
        alpha: float = 0.10,      # Language model weight (tuned for 2K BPE)
        beta: float = 0.60,       # Token insertion bonus (tuned to prevent overflow)
        blank_id: int = 0
    ):
        self.tokenizer = tokenizer
        self.beam_size = max(1, beam_size)
        self.alpha = alpha
        self.beta = beta
        self.blank_id = blank_id

        self.lm = None
        if lm_path and kenlm is not None:
            pkg_root = Path(__file__).resolve().parent.parent
            candidates = [
                Path(lm_path),
                pkg_root / lm_path,
                pkg_root / "lm/ko_bpe_2048_lm.bin",
                pkg_root / "v2/lm/ko_bpe_2048_lm.bin",
            ]
            target_lm = None
            for cand in candidates:
                if cand.exists():
                    target_lm = cand
                    break

            if target_lm is not None:
                self.lm = kenlm.LanguageModel(str(target_lm))
                engine_type = "Native C++ Fast Engine" if _FAST_BEAM_LIB is not None else "Python Engine"
                print(f"[Decoder V2] Loaded 2K BPE KenLM model ({target_lm.stat().st_size / (1024*1024):.2f} MB, {engine_type}) from {target_lm.name}")
            else:
                print(f"[Decoder V2 Warning] KenLM file not found (tried {lm_path}). Falling back to acoustic beam search.")

    def decode_greedy(self, logits: torch.Tensor) -> str:
        """Standard Argmax Greedy Decoding (baseline)."""
        preds = torch.argmax(logits, dim=-1).cpu().tolist()
        return self.tokenizer.decode(preds, remove_blank=True, collapse_repeats=True)

    def decode_topk(
        self,
        topk_ids: np.ndarray,
        topk_logprobs: np.ndarray,
        blank_logprobs: np.ndarray,
        beam_size: Optional[int] = None,
        alpha: Optional[float] = None,
        beta: Optional[float] = None
    ) -> str:
        """
        Ultra-fast Time-Synchronous CTC Beam Search using Native C++ Engine (< 1ms).
        """
        k_beam = beam_size or self.beam_size
        a = alpha if alpha is not None else self.alpha
        b = beta if beta is not None else self.beta

        T, K = topk_ids.shape

        if _FAST_BEAM_LIB is not None:
            max_beams = max(16, k_beam * 2)
            max_seq_len = 512
            out_tokens = np.zeros((max_beams, max_seq_len), dtype=np.int32)
            out_lens = np.zeros(max_beams, dtype=np.int32)
            out_scores = np.zeros(max_beams, dtype=np.float32)

            t_ids_c = np.ascontiguousarray(topk_ids, dtype=np.int32)
            t_lprob_c = np.ascontiguousarray(topk_logprobs, dtype=np.float32)
            blank_lp_c = np.ascontiguousarray(blank_logprobs, dtype=np.float32)

            n_hyp = _FAST_BEAM_LIB.ctc_beam_search_fast_c(
                t_ids_c.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
                t_lprob_c.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
                blank_lp_c.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
                T, K, k_beam, self.blank_id,
                out_tokens.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
                out_lens.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)),
                out_scores.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
                max_beams, max_seq_len
            )

            best_hypothesis = ""
            best_total_score = -float("inf")

            for i in range(n_hyp):
                seq_l = out_lens[i]
                if seq_l == 0:
                    continue
                toks = out_tokens[i, :seq_l].tolist()
                text = self.tokenizer.decode(toks, remove_blank=True, collapse_repeats=True)
                if not text:
                    continue

                lm_score = 0.0
                if self.lm is not None:
                    bpe_seq = " ".join([self.tokenizer.id_to_piece(t) for t in toks])
                    lm_score = self.lm.score(bpe_seq)

                words = len(text.split())
                score = out_scores[i] + (a * lm_score) + (b * words)
                if score > best_total_score:
                    best_total_score = score
                    best_hypothesis = text

            if best_hypothesis:
                return best_hypothesis

        # Fallback to greedy if C++ engine produces empty text
        return self.tokenizer.decode(topk_ids[:, 0].tolist(), remove_blank=True, collapse_repeats=True)

    def decode_beam(
        self,
        logits: torch.Tensor,
        beam_size: Optional[int] = None,
        alpha: Optional[float] = None,
        beta: Optional[float] = None
    ) -> str:
        """
        Executes Time-Synchronous CTC Beam Search with KenLM Rescoring on 2,048 BPE Vocab.
        Automatically uses Native C++ engine if available.
        """
        if logits.dim() == 3:
            logits = logits.squeeze(0)

        k_beam = beam_size or self.beam_size
        a = alpha if alpha is not None else self.alpha
        b = beta if beta is not None else self.beta

        # C++ Fast-path (< 1ms)
        if _FAST_BEAM_LIB is not None:
            lprobs = F.log_softmax(logits.float(), dim=-1)
            topk_lprobs, topk_ids = torch.topk(lprobs, k=32, dim=-1)
            blank_lprobs = lprobs[:, self.blank_id]
            return self.decode_topk(
                topk_ids.cpu().numpy().astype(np.int32),
                topk_lprobs.cpu().float().numpy(),
                blank_lprobs.cpu().float().numpy(),
                beam_size=k_beam,
                alpha=a,
                beta=b
            )

        # Fallback pure Python path
        log_probs = F.log_softmax(logits, dim=-1).cpu()
        T, V = log_probs.shape

        # Initial beam hypothesis at t=0
        beams: Dict[Tuple[int, ...], Tuple[float, float, int]] = {
            (): (0.0, -float("inf"), self.blank_id)
        }

        # Dynamic Top-K candidate pruning adapted for 2,048 Vocab
        top_k_candidates = min(40, V)

        for t in range(T):
            frame_probs = log_probs[t]
            top_vals, top_indices = torch.topk(frame_probs, top_k_candidates)
            top_vals = top_vals.tolist()
            top_indices = top_indices.tolist()

            next_beams: Dict[Tuple[int, ...], Tuple[float, float, int]] = {}

            for prefix, (p_b, p_nb, last_tok) in beams.items():
                p_total = math.log(math.exp(p_b) + (math.exp(p_nb) if p_nb > -float("inf") else 0.0) + 1e-30)

                # 1. Transition to Blank
                prob_blank = frame_probs[self.blank_id].item()
                nb_p_b, nb_p_nb, _ = next_beams.get(prefix, (-float("inf"), -float("inf"), self.blank_id))
                new_p_b = math.log(math.exp(nb_p_b) + math.exp(p_total + prob_blank) + 1e-30)
                next_beams[prefix] = (new_p_b, nb_p_nb, self.blank_id)

                # 2. Transition to Non-Blank tokens
                for p_val, tok_id in zip(top_vals, top_indices):
                    if tok_id == self.blank_id:
                        continue

                    prob_tok = p_val
                    if tok_id == last_tok:
                        # Repeated token extends same prefix only if immediately following same token
                        new_prefix = prefix
                        nb_p_b, nb_p_nb, _ = next_beams.get(new_prefix, (-float("inf"), -float("inf"), tok_id))
                        add_p = math.log(math.exp(nb_p_nb) + math.exp(p_nb + prob_tok) + 1e-30)
                        next_beams[new_prefix] = (nb_p_b, add_p, tok_id)

                        # Coming from blank starts a new identical token
                        extended_prefix = prefix + (tok_id,)
                        enb_p_b, enb_p_nb, _ = next_beams.get(extended_prefix, (-float("inf"), -float("inf"), tok_id))
                        new_enb_p = math.log(math.exp(enb_p_nb) + math.exp(p_b + prob_tok) + 1e-30)
                        next_beams[extended_prefix] = (enb_p_b, new_enb_p, tok_id)
                    else:
                        new_prefix = prefix + (tok_id,)
                        nb_p_b, nb_p_nb, _ = next_beams.get(new_prefix, (-float("inf"), -float("inf"), tok_id))
                        new_p_nb = math.log(math.exp(nb_p_b) + math.exp(p_total + prob_tok) + 1e-30)
                        next_beams[new_prefix] = (nb_p_b, new_p_nb, tok_id)

            def _score_beam(item):
                pref, (pb, pnb, _) = item
                return math.log(
                    (math.exp(pb) if pb > -float("inf") else 0.0) +
                    (math.exp(pnb) if pnb > -float("inf") else 0.0) +
                    1e-30
                )

            sorted_items = sorted(next_beams.items(), key=_score_beam, reverse=True)[: k_beam * 3]
            beams = {pref: val for pref, val in sorted_items}

        # Final Rescoring with BPE KenLM
        best_hypothesis = ""
        best_total_score = -float("inf")

        for prefix, (p_b, p_nb, _) in beams.items():
            acoustic_score = math.log(
                (math.exp(p_b) if p_b > -float("inf") else 0.0) +
                (math.exp(p_nb) if p_nb > -float("inf") else 0.0) +
                1e-30
            )

            if not prefix:
                continue

            decoded_text = self.tokenizer.decode(list(prefix), remove_blank=True, collapse_repeats=False)
            if not decoded_text:
                continue

            lm_score = 0.0
            num_tokens = len(prefix)
            if self.lm is not None:
                # Query KenLM on whitespace-separated BPE pieces
                bpe_seq = " ".join([self.tokenizer.id_to_piece(t) for t in prefix])
                lm_score = self.lm.score(bpe_seq)

            total_score = acoustic_score + (a * lm_score) + (b * num_tokens)
            if total_score > best_total_score:
                best_total_score = total_score
                best_hypothesis = decoded_text

        if not best_hypothesis:
            best_hypothesis = self.decode_greedy(logits)

        return best_hypothesis