Skip to content

Open-source speech recognition toolkit for training, inference, streaming ASR, VAD, punctuation, speaker diarization pipelines, and OpenAI-compatible/MCP serving.

Dev new (#1065)

Yabin Li702ec03ad89d
diff --git a/README_zh.md b/README_zh.md
index f58d243e3..051a4d274 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -44,15 +44,80 @@ FunASR希望在语音识别的学术研究和工业应用之间架起一座桥
## 安装教程
FunASR安装教程请阅读([Installation](https://alibaba-damo-academy.github.io/FunASR/en/installation/installation.html))
-<a name="服务部署"></a>
-## 服务部署
-FunASR支持预训练或者进一步微调的模型进行服务部署。目前中文离线文件转写服务一键部署的CPU版本已经发布,详细信息参阅([一键部署文档](funasr/runtime/docs/SDK_tutorial_zh.md)。更多服务部署详细信息可以参阅([服务部署文档](funasr/runtime/readme_cn.md))。
+## 模型仓库
+
+FunASR开源了大量在工业数据上预训练模型,您可以在[模型许可协议](./MODEL_LICENSE)下自由使用、复制、修改和分享FunASR模型,下面列举代表性的模型,更多模型请参考[模型仓库]()。
+
+(注:[🤗]()表示Huggingface模型仓库链接,[⭐]()表示ModelScope模型仓库链接)
+
+
+| 模型名字 | 任务详情 | 训练数据 | 参数量 |
+|:------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------:|:------------:|:----:|
+| paraformer-zh ([🤗]() [⭐](https://www.modelscope.cn/models/damo/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch/summary) ) | 语音识别,带时间戳输出,非实时 | 60000小时,中文 | 220M |
+| paraformer-zh-spk ([🤗]() [⭐](https://modelscope.cn/models/damo/speech_paraformer-large-vad-punc-spk_asr_nat-zh-cn/summary) ) | 分角色语音识别,带时间戳输出,非实时 | 60000小时,中文 | 220M |
+| paraformer-zh-online ([🤗]() [⭐](https://modelscope.cn/models/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-online/summary) ) | 语音识别,实时 | 60000小时,中文 | 220M |
+| paraformer-en ([🤗]() [⭐](https://www.modelscope.cn/models/damo/speech_paraformer-large-vad-punc_asr_nat-en-16k-common-vocab10020/summary) ) | 分角色语音识别,带时间戳输出,非实时 | 50000小时,英文 | 220M |
+| paraformer-en-spk ([🤗]() [⭐]() ) | 语音识别,非实时 | 50000小时,英文 | 220M |
+| conformer-en ([🤗]() [⭐](https://modelscope.cn/models/damo/speech_conformer_asr-en-16k-vocab4199-pytorch/summary) ) | 语音识别,非实时 | 50000小时,英文 | 220M |
+| ct-punc ([🤗]() [⭐](https://modelscope.cn/models/damo/punc_ct-transformer_cn-en-common-vocab471067-large/summary) ) | 标点恢复,非实时 | 100M,中文与英文 | 1.1G |
+| fsmn-vad ([🤗]() [⭐](https://modelscope.cn/models/damo/speech_fsmn_vad_zh-cn-16k-common-pytorch/summary) ) | 语音端点检测,实时 | 5000小时,中文与英文 | 0.4M |
+| fa-zh ([🤗]() [⭐](https://modelscope.cn/models/damo/speech_timestamp_prediction-v1-16k-offline/summary) ) | 字级别时间戳预测 | 50000小时,中文 | 38M |
+
<a name="快速开始"></a>
## 快速开始
-快速使用教程([新人文档](https://alibaba-damo-academy.github.io/FunASR/en/funasr/quick_start_zh.html))
+FunASR支持数万小时工业数据训练的模型的推理和微调,详细信息可以参阅([modelscope_egs](https://alibaba-damo-academy.github.io/FunASR/en/modelscope_pipeline/quick_start.html));也支持学术标准数据集模型的训练和微调,详细信息可以参阅([egs](https://alibaba-damo-academy.github.io/FunASR/en/academic_recipe/asr_recipe.html))。
+
+下面为快速上手教程,测试音频([中文](https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/test_audio/vad_example.wav),[英文]())
+### 非实时语音识别
+```python
+from funasr import infer
+
+p = infer(model="paraformer-zh", vad_model="fsmn-vad", punc_model="ct-punc", model_hub="ms")
+
+res = p("asr_example_zh.wav", batch_size_token=5000)
+print(res)
+```
+注:`model_hub`:表示模型仓库,`ms`为选择modelscope下载,`hf`为选择huggingface下载。
+
+### 实时语音识别
+```python
+from funasr import infer
+
+p = infer(model="paraformer-zh-streaming", model_hub="ms")
+
+chunk_size = [0, 10, 5] #[0, 10, 5] 600ms, [0, 8, 4] 480ms
+param_dict = {"cache": dict(), "is_final": False, "chunk_size": chunk_size, "encoder_chunk_look_back": 4, "decoder_chunk_look_back": 1}
+
+import torchaudio
+speech = torchaudio.load("asr_example_zh.wav")[0][0]
+speech_length = speech.shape[0]
+
+stride_size = chunk_size[1] * 960
+sample_offset = 0
+for sample_offset in range(0, speech_length, min(stride_size, speech_length - sample_offset)):
+ param_dict["is_final"] = True if sample_offset + stride_size >= speech_length - 1 else False
+ input = speech[sample_offset: sample_offset + stride_size]
+ rec_result = p(input=input, param_dict=param_dict)
+ print(rec_result)
+```
+注:`chunk_size`为流式延时配置,`[0,10,5]`表示上屏实时出字粒度为`10*60=600ms`,未来信息为`5*60=300ms`。每次推理输入为`600ms`(采样点数为`16000*0.6=960`),输出为对应文字,最后一个语音片段输入需要设置`is_final=True`来强制输出最后一个字。
+
+更多详细用法([新人文档](https://alibaba-damo-academy.github.io/FunASR/en/funasr/quick_start_zh.html))
+
+
+<a name="服务部署"></a>
+## 服务部署
+FunASR支持预训练或者进一步微调的模型进行服务部署。目前支持以下几种服务部署:
+
+- 中文离线文件转写服务(CPU版本),已完成
+- 中文流式语音识别服务(CPU版本),已完成
+- 英文离线文件转写服务(CPU版本),已完成
+- 中文离线文件转写服务(GPU版本),进行中
+- 更多支持中
+
+详细信息可以参阅([服务部署文档](funasr/runtime/readme_cn.md))。
-FunASR支持数万小时工业数据训练的模型的推理和微调,详细信息可以参阅([modelscope_egs](https://alibaba-damo-academy.github.io/FunASR/en/modelscope_pipeline/quick_start.html));也支持学术标准数据集模型的训练和微调,详细信息可以参阅([egs](https://alibaba-damo-academy.github.io/FunASR/en/academic_recipe/asr_recipe.html))。 模型包含语音识别(ASR)、语音活动检测(VAD)、标点恢复、语言模型、说话人验证、说话人分离和多人对话语音识别等,详细模型列表可以参阅[模型仓库](https://github.com/alibaba-damo-academy/FunASR/blob/main/docs/model_zoo/modelscope_models.md):
<a name="社区交流"></a>
## 联系我们
diff --git a/funasr/__init__.py b/funasr/__init__.py
index f297bc3e6..1f31505ac 100644
--- a/funasr/__init__.py
+++ b/funasr/__init__.py
@@ -1,8 +1,132 @@
"""Initialize funasr package."""
import os
+from pathlib import Path
+import torch
+import numpy as np
dirname = os.path.dirname(__file__)
version_file = os.path.join(dirname, "version.txt")
with open(version_file, "r") as f:
__version__ = f.read().strip()
+
+
+def prepare_model(
+ model: str = None,
+ # mode: str = None,
+ vad_model: str = None,
+ punc_model: str = None,
+ model_hub: str = "ms",
+ cache_dir: str = None,
+ **kwargs,
+):
+ if not Path(model).exists():
+ if model_hub == "ms" or model_hub == "modelscope":
+ try:
+ from modelscope.hub.snapshot_download import snapshot_download as download_tool
+ model = name_maps_ms[model] if model is not None else None
+ vad_model = name_maps_ms[vad_model] if vad_model is not None else None
+ punc_model = name_maps_ms[punc_model] if punc_model is not None else None
+ except:
+ raise "You are exporting model from modelscope, please install modelscope and try it again. To install modelscope, you could:\n" \
+ "\npip3 install -U modelscope\n" \
+ "For the users in China, you could install with the command:\n" \
+ "\npip3 install -U modelscope -i https://mirror.sjtu.edu.cn/pypi/web/simple"
+ elif model_hub == "hf" or model_hub == "huggingface":
+ download_tool = 0
+ else:
+ raise "model_hub must be on of ms or hf, but get {}".format(model_hub)
+ try:
+ model = download_tool(model, cache_dir=cache_dir, revision=kwargs.get("revision", None))
+ print("model have been downloaded to: {}".format(model))
+ except:
+ raise "model_dir must be model_name in modelscope or local path downloaded from modelscope, but is {}".format(
+ model)
+
+ if vad_model is not None and not Path(vad_model).exists():
+ vad_model = download_tool(vad_model, cache_dir=cache_dir)
+ print("model have been downloaded to: {}".format(vad_model))
+ if punc_model is not None and not Path(punc_model).exists():
+ punc_model = download_tool(punc_model, cache_dir=cache_dir)
+ print("model have been downloaded to: {}".format(punc_model))
+
+ # asr
+ kwargs.update({"cmvn_file": None if model is None else os.path.join(model, "am.mvn"),
+ "asr_model_file": None if model is None else os.path.join(model, "model.pb"),
+ "asr_train_config": None if model is None else os.path.join(model, "config.yaml"),
+ })
+ mode = kwargs.get("mode", None)
+ if mode is None:
+ import json
+ json_file = os.path.join(model, 'configuration.json')
+ with open(json_file, 'r') as f:
+ config_data = json.load(f)
+ if config_data['task'] == "punctuation":
+ mode = config_data['model']['punc_model_config']['mode']
+ else:
+ mode = config_data['model']['model_config']['mode']
+ if vad_model is not None and "vad" not in mode:
+ mode = "paraformer_vad"
+ kwargs["mode"] = mode
+ # vad
+ kwargs.update({"vad_cmvn_file": None if vad_model is None else os.path.join(vad_model, "vad.mvn"),
+ "vad_model_file": None if vad_model is None else os.path.join(vad_model, "vad.pb"),
+ "vad_infer_config": None if vad_model is None else os.path.join(vad_model, "vad.yaml"),
+ })
+ # punc
+ kwargs.update({
+ "punc_model_file": None if punc_model is None else os.path.join(punc_model, "punc.pb"),
+ "punc_infer_config": None if punc_model is None else os.path.join(punc_model, "punc.yaml"),
+ })
+
+
+ return model, vad_model, punc_model, kwargs
+
+name_maps_ms = {
+ "paraformer-zh": "damo/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch",
+ "paraformer-zh-spk": "damo/speech_paraformer-large-vad-punc-spk_asr_nat-zh-cn",
+ "paraformer-en": "damo/speech_paraformer-large-vad-punc_asr_nat-en-16k-common-vocab10020",
+ "paraformer-en-spk": "damo/speech_paraformer-large-vad-punc_asr_nat-en-16k-common-vocab10020",
+ "paraformer-zh-streaming": "damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-online",
+ "fsmn-vad": "damo/speech_fsmn_vad_zh-cn-16k-common-pytorch",
+ "ct-punc": "damo/punc_ct-transformer_cn-en-common-vocab471067-large",
+ "fa-zh": "damo/speech_timestamp_prediction-v1-16k-offline",
+}
+
+def infer(task_name: str = "asr",
+ model: str = None,
+ # mode: str = None,
+ vad_model: str = None,
+ punc_model: str = None,
+ model_hub: str = "ms",
+ cache_dir: str = None,
+ **kwargs,
+ ):
+
+ model, vad_model, punc_model, kwargs = prepare_model(model, vad_model, punc_model, model_hub, cache_dir, **kwargs)
+ if task_name == "asr":
+ from funasr.bin.asr_inference_launch import inference_launch
+
+ inference_pipeline = inference_launch(**kwargs)
+ elif task_name == "":
+ pipeline = 1
+ elif task_name == "":
+ pipeline = 2
+ elif task_name == "":
+ pipeline = 2
+
+ def _infer_fn(input, **kwargs):
+ data_type = kwargs.get('data_type', 'sound')
+ data_path_and_name_and_type = [input, 'speech', data_type]
+ raw_inputs = None
+ if isinstance(input, torch.Tensor):
+ input = input.numpy()
+ if isinstance(input, np.ndarray):
+ data_path_and_name_and_type = None
+ raw_inputs = input
+
+
+
+ return inference_pipeline(data_path_and_name_and_type, raw_inputs=raw_inputs, **kwargs)
+
+ return _infer_fn
\ No newline at end of file
diff --git a/funasr/bin/asr_inference_launch.py b/funasr/bin/asr_inference_launch.py
index 04ddd925a..e93d74037 100644
--- a/funasr/bin/asr_inference_launch.py
+++ b/funasr/bin/asr_inference_launch.py
@@ -462,18 +462,18 @@ def inference_paraformer(
def inference_paraformer_vad_punc(
- maxlenratio: float,
- minlenratio: float,
- batch_size: int,
- beam_size: int,
- ngpu: int,
- ctc_weight: float,
- lm_weight: float,
- penalty: float,
- log_level: Union[int, str],
+ maxlenratio: float=0.0,
+ minlenratio: float=0.0,
+ batch_size: int=1,
+ beam_size: int=1,
+ ngpu: int=1,
+ ctc_weight: float=0.0,
+ lm_weight: float=0.0,
+ penalty: float=0.0,
+ log_level: Union[int, str]=logging.ERROR,
# data_path_and_name_and_type,
- asr_train_config: Optional[str],
- asr_model_file: Optional[str],
+ asr_train_config: Optional[str]=None,
+ asr_model_file: Optional[str]=None,
cmvn_file: Optional[str] = None,
lm_train_config: Optional[str] = None,
lm_file: Optional[str] = None,
@@ -487,7 +487,7 @@ def inference_paraformer_vad_punc(
seed: int = 0,
ngram_weight: float = 0.9,
nbest: int = 1,
- num_workers: int = 1,
+ num_workers: int = 0,
vad_infer_config: Optional[str] = None,
vad_model_file: Optional[str] = None,
vad_cmvn_file: Optional[str] = None,
@@ -1098,18 +1098,18 @@ def inference_paraformer_vad_speaker(
def inference_paraformer_online(
- maxlenratio: float,
- minlenratio: float,
- batch_size: int,
- beam_size: int,
- ngpu: int,
- ctc_weight: float,
- lm_weight: float,
- penalty: float,
- log_level: Union[int, str],
+ maxlenratio: float=0.0,
+ minlenratio: float=0.0,
+ batch_size: int=1,
+ beam_size: int=1,
+ ngpu: int=1,
+ ctc_weight: float=0.0,
+ lm_weight: float=0.0,
+ penalty: float=0.0,
+ log_level: Union[int, str]=logging.ERROR,
# data_path_and_name_and_type,
- asr_train_config: Optional[str],
- asr_model_file: Optional[str],
+ asr_train_config: Optional[str]=None,
+ asr_model_file: Optional[str]=None,
cmvn_file: Optional[str] = None,
lm_train_config: Optional[str] = None,
lm_file: Optional[str] = None,
diff --git a/funasr/runtime/onnxruntime/src/util.cpp b/funasr/runtime/onnxruntime/src/util.cpp
deleted file mode 100644
index 70059ca21..000000000
--- a/funasr/runtime/onnxruntime/src/util.cpp
+++ /dev/null
@@ -1,231 +0,0 @@
-
-#include "precomp.h"
-
-namespace funasr {
-float *LoadParams(const char *filename)
-{
-
- FILE *fp;
- fp = fopen(filename, "rb");
- fseek(fp, 0, SEEK_END);
- uint32_t nFileLen = ftell(fp);
- fseek(fp, 0, SEEK_SET);
-
- float *params_addr = (float *)AlignedMalloc(32, nFileLen);
- int n = fread(params_addr, 1, nFileLen, fp);
- fclose(fp);
-
- return params_addr;
-}
-
-int ValAlign(int val, int align)
-{
- float tmp = ceil((float)val / (float)align) * (float)align;
- return (int)tmp;
-}
-
-void DispParams(float *din, int size)
-{
- int i;
- for (i = 0; i < size; i++) {
- printf("%f ", din[i]);
- }
- printf("\n");
-}
-void SaveDataFile(const char *filename, void *data, uint32_t len)
-{
- FILE *fp;
- fp = fopen(filename, "wb+");
- fwrite(data, 1, len, fp);
- fclose(fp);
-}
-
-void BasicNorm(Tensor<float> *&din, float norm)
-{
-
- int Tmax = din->size[2];
-
- int i, j;
- for (i = 0; i < Tmax; i++) {
- float sum = 0;
- for (j = 0; j < 512; j++) {
- int ii = i * 512 + j;
- sum += din->buff[ii] * din->buff[ii];
- }
- float mean = sqrt(sum / 512 + norm);
- for (j = 0; j < 512; j++) {
- int ii = i * 512 + j;
- din->buff[ii] = din->buff[ii] / mean;
- }
- }
-}
-
-void FindMax(float *din, int len, float &max_val, int &max_idx)
-{
- int i;
- max_val = -INFINITY;
- max_idx = -1;
- for (i = 0; i < len; i++) {
- if (din[i] > max_val) {
- max_val = din[i];
- max_idx = i;
- }
- }
-}
-
-string PathAppend(const string &p1, const string &p2)
-{
-
- char sep = '/';
- string tmp = p1;
-
-#ifdef _WIN32
- sep = '\\';
-#endif
-
- if (p1[p1.length()-1] != sep) { // Need to add a
- tmp += sep; // path separator
- return (tmp + p2);
- } else
- return (p1 + p2);
-}
-
-void Relu(Tensor<float> *din)
-{
- int i;
- for (i = 0; i < din->buff_size; i++) {
- float val = din->buff[i];
- din->buff[i] = val < 0 ? 0 : val;
- }
-}
-
-void Swish(Tensor<float> *din)
-{
- int i;
- for (i = 0; i < din->buff_size; i++) {
- float val = din->buff[i];
- din->buff[i] = val / (1 + exp(-val));
- }
-}
-
-void Sigmoid(Tensor<float> *din)
-{
- int i;
- for (i = 0; i < din->buff_size; i++) {
- float val = din->buff[i];
- din->buff[i] = 1 / (1 + exp(-val));
- }
-}
-
-void DoubleSwish(Tensor<float> *din)
-{
- int i;
- for (i = 0; i < din->buff_size; i++) {
- float val = din->buff[i];
- din->buff[i] = val / (1 + exp(-val + 1));
- }
-}
-
-void Softmax(float *din, int mask, int len)
-{
- float *tmp = (float *)malloc(mask * sizeof(float));
- int i;
- float sum = 0;
- float max = -INFINITY;
-
- for (i = 0; i < mask; i++) {
- max = max < din[i] ? din[i] : max;
- }
-
- for (i = 0; i < mask; i++) {
- tmp[i] = exp(din[i] - max);
- sum += tmp[i];
- }
- for (i = 0; i < mask; i++) {
- din[i] = tmp[i] / sum;
- }
- free(tmp);
- for (i = mask; i < len; i++) {
- din[i] = 0;
- }
-}
-
-void LogSoftmax(float *din, int len)
-{
- float *tmp = (float *)malloc(len * sizeof(float));
- int i;
- float sum = 0;
- for (i = 0; i < len; i++) {
- tmp[i] = exp(din[i]);
- sum += tmp[i];
- }
- for (i = 0; i < len; i++) {
- din[i] = log(tmp[i] / sum);
- }
- free(tmp);
-}
-
-void Glu(Tensor<float> *din, Tensor<float> *dout)
-{
- int mm = din->buff_size / 1024;
- int i, j;
- for (i = 0; i < mm; i++) {
- for (j = 0; j < 512; j++) {
- int in_off = i * 1024 + j;
- int out_off = i * 512 + j;
- float a = din->buff[in_off];
- float b = din->buff[in_off + 512];
- dout->buff[out_off] = a / (1 + exp(-b));
- }
- }
-}
-
-bool is_target_file(const std::string& filename, const std::string target) {
- std::size_t pos = filename.find_last_of(".");
- if (pos == std::string::npos) {
- return false;
- }
- std::string extension = filename.substr(pos + 1);
- return (extension == target);
-}
-
-void KeepChineseCharacterAndSplit(const std::string &input_str,
- std::vector<std::string> &chinese_characters) {
- chinese_characters.resize(0);
- std::vector<U16CHAR_T> u16_buf;
- u16_buf.resize(std::max(u16_buf.size(), input_str.size() + 1));
- U16CHAR_T* pu16 = u16_buf.data();
- U8CHAR_T * pu8 = (U8CHAR_T*)input_str.data();
- size_t ilen = input_str.size();
- size_t len = EncodeConverter::Utf8ToUtf16(pu8, ilen, pu16, ilen + 1);
- for (size_t i = 0; i < len; i++) {
- if (EncodeConverter::IsChineseCharacter(pu16[i])) {
- U8CHAR_T u8buf[4];
- size_t n = EncodeConverter::Utf16ToUtf8(pu16 + i, u8buf);
- u8buf[n] = '\0';
- chinese_characters.push_back((const char*)u8buf);
- }
- }
-}
-
-std::vector<std::string> split(const std::string &s, char delim) {
- std::vector<std::string> elems;
- std::stringstream ss(s);
- std::string item;
- while(std::getline(ss, item, delim)) {
- elems.push_back(item);
- }
- return elems;
-}
-
-template<typename T>
-void PrintMat(const std::vector<std::vector<T>> &mat, const std::string &name) {
- std::cout << name << ":" << std::endl;
- for (auto item : mat) {
- for (auto item_ : item) {
- std::cout << item_ << " ";
- }
- std::cout << std::endl;
- }
-}
-} // namespace funasr
diff --git a/funasr/runtime/onnxruntime/src/util.h b/funasr/runtime/onnxruntime/src/util.h
deleted file mode 100644
index df9abd1e0..000000000
--- a/funasr/runtime/onnxruntime/src/util.h
+++ /dev/null
@@ -1,38 +0,0 @@
-#ifndef UTIL_H
-#define UTIL_H
-
-using namespace std;
-
-namespace funasr {
-extern float *LoadParams(const char *filename);
-
-extern void SaveDataFile(const char *filename, void *data, uint32_t len);
-extern void Relu(Tensor<float> *din);
-extern void Swish(Tensor<float> *din);
-extern void Sigmoid(Tensor<float> *din);
-extern void DoubleSwish(Tensor<float> *din);
-
-extern void Softmax(float *din, int mask, int len);
-
-extern void LogSoftmax(float *din, int len);
-extern int ValAlign(int val, int align);
-extern void DispParams(float *din, int size);
-
-extern void BasicNorm(Tensor<float> *&din, float norm);
-
-extern void FindMax(float *din, int len, float &max_val, int &max_idx);
-
-extern void Glu(Tensor<float> *din, Tensor<float> *dout);
-
-string PathAppend(const string &p1, const string &p2);
-bool is_target_file(const std::string& filename, const std::string target);
-
-void KeepChineseCharacterAndSplit(const std::string &input_str,
- std::vector<std::string> &chinese_characters);
-
-std::vector<std::string> split(const std::string &s, char delim);
-
-template<typename T>
-void PrintMat(const std::vector<std::vector<T>> &mat, const std::string &name);
-} // namespace funasr
-#endif
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/CMakeLists.txt b/funasr/runtime/onnxruntime/third_party/openfst/src/lib/CMakeLists.txt
deleted file mode 100644
index c004aee10..000000000
--- a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/CMakeLists.txt
+++ /dev/null
@@ -1,26 +0,0 @@
-FILE(GLOB HEADER_FILES ../include/fst/*.h)
-
-
-add_library(fst
- compat.cc
- flags.cc
- fst-types.cc
- fst.cc
- mapped-file.cc
- properties.cc
- symbol-table.cc
- symbol-table-ops.cc
- util.cc
- weight.cc
- ${HEADER_FILES}
-)
-set_target_properties(fst PROPERTIES
- SOVERSION "${SOVERSION}"
-)
-
-
-
-install(TARGETS fst
- LIBRARY DESTINATION lib
- ARCHIVE DESTINATION lib
- RUNTIME DESTINATION lib)
diff --git a/funasr/runtime/python/grpc/.gitignore b/funasr/runtime/python/grpc/.gitignore
deleted file mode 100644
index eeb8a6ec4..000000000
--- a/funasr/runtime/python/grpc/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-**/__pycache__
diff --git a/funasr/runtime/websocket/hotwords.txt b/funasr/runtime/websocket/hotwords.txt
deleted file mode 100644
index 6179cbc6a..000000000
--- a/funasr/runtime/websocket/hotwords.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-阿里巴巴
-通义实验室
diff --git a/funasr/text/cleaner.py b/funasr/text/cleaner.py
index 632267296..1044f504f 100644
--- a/funasr/text/cleaner.py
+++ b/funasr/text/cleaner.py
@@ -1,7 +1,7 @@
from typing import Collection
from jaconv import jaconv
-import tacotron_cleaner.cleaners
+# import tacotron_cleaner.cleaners
try:
from vietnamese_cleaner import vietnamese_cleaners
@@ -31,7 +31,8 @@ class TextCleaner:
def __call__(self, text: str) -> str:
for t in self.cleaner_types:
if t == "tacotron":
- text = tacotron_cleaner.cleaners.custom_english_cleaners(text)
+ # text = tacotron_cleaner.cleaners.custom_english_cleaners(text)
+ pass
elif t == "jaconv":
text = jaconv.normalize(text)
elif t == "vietnamese":
diff --git a/funasr/runtime/__init__.py b/runtime/__init__.py
similarity index 100%
rename from funasr/runtime/__init__.py
rename to runtime/__init__.py
diff --git a/funasr/runtime/android/AndroidClient/app/build.gradle b/runtime/android/AndroidClient/app/build.gradle
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/build.gradle
rename to runtime/android/AndroidClient/app/build.gradle
diff --git a/funasr/runtime/android/AndroidClient/app/proguard-rules.pro b/runtime/android/AndroidClient/app/proguard-rules.pro
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/proguard-rules.pro
rename to runtime/android/AndroidClient/app/proguard-rules.pro
diff --git a/funasr/runtime/android/AndroidClient/app/src/androidTest/java/com/yeyupiaoling/androidclient/ExampleInstrumentedTest.kt b/runtime/android/AndroidClient/app/src/androidTest/java/com/yeyupiaoling/androidclient/ExampleInstrumentedTest.kt
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/androidTest/java/com/yeyupiaoling/androidclient/ExampleInstrumentedTest.kt
rename to runtime/android/AndroidClient/app/src/androidTest/java/com/yeyupiaoling/androidclient/ExampleInstrumentedTest.kt
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/AndroidManifest.xml b/runtime/android/AndroidClient/app/src/main/AndroidManifest.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/AndroidManifest.xml
rename to runtime/android/AndroidClient/app/src/main/AndroidManifest.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/AudioView.java b/runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/AudioView.java
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/AudioView.java
rename to runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/AudioView.java
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/MainActivity.java b/runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/MainActivity.java
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/MainActivity.java
rename to runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/MainActivity.java
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/SSLSocketClient.java b/runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/SSLSocketClient.java
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/SSLSocketClient.java
rename to runtime/android/AndroidClient/app/src/main/java/com/yeyupiaoling/androidclient/SSLSocketClient.java
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/drawable/edittext_border.xml b/runtime/android/AndroidClient/app/src/main/res/drawable/edittext_border.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/drawable/edittext_border.xml
rename to runtime/android/AndroidClient/app/src/main/res/drawable/edittext_border.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/drawable/ic_launcher_background.xml b/runtime/android/AndroidClient/app/src/main/res/drawable/ic_launcher_background.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/drawable/ic_launcher_background.xml
rename to runtime/android/AndroidClient/app/src/main/res/drawable/ic_launcher_background.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/drawable/ic_launcher_foreground.xml b/runtime/android/AndroidClient/app/src/main/res/drawable/ic_launcher_foreground.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/drawable/ic_launcher_foreground.xml
rename to runtime/android/AndroidClient/app/src/main/res/drawable/ic_launcher_foreground.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/drawable/logo.png b/runtime/android/AndroidClient/app/src/main/res/drawable/logo.png
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/drawable/logo.png
rename to runtime/android/AndroidClient/app/src/main/res/drawable/logo.png
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/layout/activity_main.xml b/runtime/android/AndroidClient/app/src/main/res/layout/activity_main.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/layout/activity_main.xml
rename to runtime/android/AndroidClient/app/src/main/res/layout/activity_main.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/layout/dialog_input_hotwords.xml b/runtime/android/AndroidClient/app/src/main/res/layout/dialog_input_hotwords.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/layout/dialog_input_hotwords.xml
rename to runtime/android/AndroidClient/app/src/main/res/layout/dialog_input_hotwords.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/layout/dialog_input_uri.xml b/runtime/android/AndroidClient/app/src/main/res/layout/dialog_input_uri.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/layout/dialog_input_uri.xml
rename to runtime/android/AndroidClient/app/src/main/res/layout/dialog_input_uri.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/menu/menu.xml b/runtime/android/AndroidClient/app/src/main/res/menu/menu.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/menu/menu.xml
rename to runtime/android/AndroidClient/app/src/main/res/menu/menu.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/runtime/android/AndroidClient/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/runtime/android/AndroidClient/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/runtime/android/AndroidClient/app/src/main/res/mipmap-hdpi/ic_launcher.webp
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-hdpi/ic_launcher.webp
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-hdpi/ic_launcher.webp
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/runtime/android/AndroidClient/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/runtime/android/AndroidClient/app/src/main/res/mipmap-mdpi/ic_launcher.webp
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-mdpi/ic_launcher.webp
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-mdpi/ic_launcher.webp
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/runtime/android/AndroidClient/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/runtime/android/AndroidClient/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/runtime/android/AndroidClient/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/runtime/android/AndroidClient/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/runtime/android/AndroidClient/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/runtime/android/AndroidClient/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/runtime/android/AndroidClient/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
rename to runtime/android/AndroidClient/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/values/colors.xml b/runtime/android/AndroidClient/app/src/main/res/values/colors.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/values/colors.xml
rename to runtime/android/AndroidClient/app/src/main/res/values/colors.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/values/strings.xml b/runtime/android/AndroidClient/app/src/main/res/values/strings.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/values/strings.xml
rename to runtime/android/AndroidClient/app/src/main/res/values/strings.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/values/themes.xml b/runtime/android/AndroidClient/app/src/main/res/values/themes.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/values/themes.xml
rename to runtime/android/AndroidClient/app/src/main/res/values/themes.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/xml/backup_rules.xml b/runtime/android/AndroidClient/app/src/main/res/xml/backup_rules.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/xml/backup_rules.xml
rename to runtime/android/AndroidClient/app/src/main/res/xml/backup_rules.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/main/res/xml/data_extraction_rules.xml b/runtime/android/AndroidClient/app/src/main/res/xml/data_extraction_rules.xml
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/main/res/xml/data_extraction_rules.xml
rename to runtime/android/AndroidClient/app/src/main/res/xml/data_extraction_rules.xml
diff --git a/funasr/runtime/android/AndroidClient/app/src/test/java/com/yeyupiaoling/androidclient/ExampleUnitTest.kt b/runtime/android/AndroidClient/app/src/test/java/com/yeyupiaoling/androidclient/ExampleUnitTest.kt
similarity index 100%
rename from funasr/runtime/android/AndroidClient/app/src/test/java/com/yeyupiaoling/androidclient/ExampleUnitTest.kt
rename to runtime/android/AndroidClient/app/src/test/java/com/yeyupiaoling/androidclient/ExampleUnitTest.kt
diff --git a/funasr/runtime/android/AndroidClient/build.gradle b/runtime/android/AndroidClient/build.gradle
similarity index 100%
rename from funasr/runtime/android/AndroidClient/build.gradle
rename to runtime/android/AndroidClient/build.gradle
diff --git a/funasr/runtime/android/AndroidClient/gradle.properties b/runtime/android/AndroidClient/gradle.properties
similarity index 100%
rename from funasr/runtime/android/AndroidClient/gradle.properties
rename to runtime/android/AndroidClient/gradle.properties
diff --git a/funasr/runtime/android/AndroidClient/gradle/wrapper/gradle-wrapper.jar b/runtime/android/AndroidClient/gradle/wrapper/gradle-wrapper.jar
similarity index 100%
rename from funasr/runtime/android/AndroidClient/gradle/wrapper/gradle-wrapper.jar
rename to runtime/android/AndroidClient/gradle/wrapper/gradle-wrapper.jar
diff --git a/funasr/runtime/android/AndroidClient/gradle/wrapper/gradle-wrapper.properties b/runtime/android/AndroidClient/gradle/wrapper/gradle-wrapper.properties
similarity index 100%
rename from funasr/runtime/android/AndroidClient/gradle/wrapper/gradle-wrapper.properties
rename to runtime/android/AndroidClient/gradle/wrapper/gradle-wrapper.properties
diff --git a/funasr/runtime/android/AndroidClient/gradlew b/runtime/android/AndroidClient/gradlew
similarity index 100%
rename from funasr/runtime/android/AndroidClient/gradlew
rename to runtime/android/AndroidClient/gradlew
diff --git a/funasr/runtime/android/AndroidClient/gradlew.bat b/runtime/android/AndroidClient/gradlew.bat
similarity index 100%
rename from funasr/runtime/android/AndroidClient/gradlew.bat
rename to runtime/android/AndroidClient/gradlew.bat
diff --git a/funasr/runtime/android/AndroidClient/settings.gradle b/runtime/android/AndroidClient/settings.gradle
similarity index 100%
rename from funasr/runtime/android/AndroidClient/settings.gradle
rename to runtime/android/AndroidClient/settings.gradle
diff --git a/funasr/runtime/android/images/QRcode.png b/runtime/android/images/QRcode.png
similarity index 100%
rename from funasr/runtime/android/images/QRcode.png
rename to runtime/android/images/QRcode.png
diff --git a/funasr/runtime/android/images/image1.png b/runtime/android/images/image1.png
similarity index 100%
rename from funasr/runtime/android/images/image1.png
rename to runtime/android/images/image1.png
diff --git a/funasr/runtime/android/images/image2.png b/runtime/android/images/image2.png
similarity index 100%
rename from funasr/runtime/android/images/image2.png
rename to runtime/android/images/image2.png
diff --git a/funasr/runtime/android/images/image3.png b/runtime/android/images/image3.png
similarity index 100%
rename from funasr/runtime/android/images/image3.png
rename to runtime/android/images/image3.png
diff --git a/funasr/runtime/android/readme.md b/runtime/android/readme.md
similarity index 100%
rename from funasr/runtime/android/readme.md
rename to runtime/android/readme.md
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp.Examples/AliFsmnVadSharp.Examples.csproj b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp.Examples/AliFsmnVadSharp.Examples.csproj
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp.Examples/AliFsmnVadSharp.Examples.csproj
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp.Examples/AliFsmnVadSharp.Examples.csproj
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp.Examples/Program.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp.Examples/Program.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp.Examples/Program.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp.Examples/Program.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp.sln b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp.sln
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp.sln
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp.sln
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/AliFsmnVad.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/AliFsmnVad.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/AliFsmnVad.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/AliFsmnVad.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/AliFsmnVadSharp.csproj b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/AliFsmnVadSharp.csproj
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/AliFsmnVadSharp.csproj
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/AliFsmnVadSharp.csproj
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/DLL/KaldiNativeFbank.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/DLL/KaldiNativeFbank.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/DLL/KaldiNativeFbank.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/DLL/KaldiNativeFbank.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/DLL/KnfOnlineFbank.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/DLL/KnfOnlineFbank.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/DLL/KnfOnlineFbank.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/DLL/KnfOnlineFbank.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/E2EVadModel.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/E2EVadModel.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/E2EVadModel.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/E2EVadModel.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Lib/kaldi-native-fbank-dll.dll b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Lib/kaldi-native-fbank-dll.dll
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Lib/kaldi-native-fbank-dll.dll
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Lib/kaldi-native-fbank-dll.dll
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/CmvnEntity.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/CmvnEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/CmvnEntity.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/CmvnEntity.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/E2EVadFrameProbEntity.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/E2EVadFrameProbEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/E2EVadFrameProbEntity.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/E2EVadFrameProbEntity.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/E2EVadSpeechBufWithDoaEntity.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/E2EVadSpeechBufWithDoaEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/E2EVadSpeechBufWithDoaEntity.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/E2EVadSpeechBufWithDoaEntity.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/EncoderConfEntity.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/EncoderConfEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/EncoderConfEntity.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/EncoderConfEntity.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/FrontendConfEntity.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/FrontendConfEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/FrontendConfEntity.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/FrontendConfEntity.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/SegmentEntity.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/SegmentEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/SegmentEntity.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/SegmentEntity.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadInputEntity.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadInputEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadInputEntity.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadInputEntity.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadOutputEntity.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadOutputEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadOutputEntity.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadOutputEntity.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadPostConfEntity.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadPostConfEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadPostConfEntity.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadPostConfEntity.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadYamlEntity.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadYamlEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadYamlEntity.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Model/VadYamlEntity.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Struct/FbankData.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Struct/FbankData.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Struct/FbankData.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Struct/FbankData.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Utils/YamlHelper.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Utils/YamlHelper.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Utils/YamlHelper.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/Utils/YamlHelper.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/WavFrontend.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/WavFrontend.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/WavFrontend.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/WavFrontend.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/WindowDetector.cs b/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/WindowDetector.cs
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/AliFsmnVadSharp/WindowDetector.cs
rename to runtime/csharp/AliFsmnVad/AliFsmnVadSharp/WindowDetector.cs
diff --git a/funasr/runtime/csharp/AliFsmnVad/README.md b/runtime/csharp/AliFsmnVad/README.md
similarity index 100%
rename from funasr/runtime/csharp/AliFsmnVad/README.md
rename to runtime/csharp/AliFsmnVad/README.md
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/App.xaml b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/App.xaml
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/App.xaml
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/App.xaml
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/App.xaml.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/App.xaml.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/App.xaml.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/App.xaml.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/AppShell.xaml b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/AppShell.xaml
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/AppShell.xaml
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/AppShell.xaml
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/AppShell.xaml.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/AppShell.xaml.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/AppShell.xaml.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/AppShell.xaml.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MainPage.xaml b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MainPage.xaml
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MainPage.xaml
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MainPage.xaml
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MainPage.xaml.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MainPage.xaml.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MainPage.xaml.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MainPage.xaml.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiApp1.csproj b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiApp1.csproj
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiApp1.csproj
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiApp1.csproj
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiApp1.csproj.user b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiApp1.csproj.user
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiApp1.csproj.user
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiApp1.csproj.user
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiProgram.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiProgram.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiProgram.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MauiProgram.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MySplashPage.xaml b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MySplashPage.xaml
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MySplashPage.xaml
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MySplashPage.xaml
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MySplashPage.xaml.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MySplashPage.xaml.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MySplashPage.xaml.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/MySplashPage.xaml.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/AndroidManifest.xml b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/AndroidManifest.xml
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/AndroidManifest.xml
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/AndroidManifest.xml
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/MainActivity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/MainActivity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/MainActivity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/MainActivity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/MainApplication.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/MainApplication.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/MainApplication.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/MainApplication.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/Resources/values/colors.xml b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/Resources/values/colors.xml
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/Resources/values/colors.xml
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Android/Resources/values/colors.xml
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/AppDelegate.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/AppDelegate.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/AppDelegate.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/AppDelegate.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/Info.plist b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/Info.plist
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/Info.plist
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/Info.plist
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/Program.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/Program.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/Program.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/MacCatalyst/Program.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Tizen/Main.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Tizen/Main.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Tizen/Main.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Tizen/Main.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Tizen/tizen-manifest.xml b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Tizen/tizen-manifest.xml
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Tizen/tizen-manifest.xml
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Tizen/tizen-manifest.xml
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/App.xaml b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/App.xaml
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/App.xaml
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/App.xaml
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/App.xaml.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/App.xaml.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/App.xaml.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/App.xaml.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/Package.appxmanifest b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/Package.appxmanifest
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/Package.appxmanifest
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/Package.appxmanifest
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/app.manifest b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/app.manifest
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/app.manifest
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/Windows/app.manifest
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/AppDelegate.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/AppDelegate.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/AppDelegate.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/AppDelegate.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/Info.plist b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/Info.plist
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/Info.plist
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/Info.plist
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/Program.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/Program.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/Program.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Platforms/iOS/Program.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Properties/launchSettings.json b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Properties/launchSettings.json
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Properties/launchSettings.json
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Properties/launchSettings.json
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/RecognitionForFiles.xaml b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/RecognitionForFiles.xaml
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/RecognitionForFiles.xaml
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/RecognitionForFiles.xaml
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/RecognitionForFiles.xaml.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/RecognitionForFiles.xaml.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/RecognitionForFiles.xaml.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/RecognitionForFiles.xaml.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/AppIcon/appicon.svg b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/AppIcon/appicon.svg
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/AppIcon/appicon.svg
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/AppIcon/appicon.svg
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/AppIcon/appiconfg.svg b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/AppIcon/appiconfg.svg
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/AppIcon/appiconfg.svg
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/AppIcon/appiconfg.svg
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Fonts/OpenSans-Regular.ttf b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Fonts/OpenSans-Regular.ttf
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Fonts/OpenSans-Regular.ttf
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Fonts/OpenSans-Regular.ttf
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Fonts/OpenSans-Semibold.ttf b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Fonts/OpenSans-Semibold.ttf
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Fonts/OpenSans-Semibold.ttf
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Fonts/OpenSans-Semibold.ttf
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Images/dotnet_bot.svg b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Images/dotnet_bot.svg
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Images/dotnet_bot.svg
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Images/dotnet_bot.svg
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Raw/AboutAssets.txt b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Raw/AboutAssets.txt
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Raw/AboutAssets.txt
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Raw/AboutAssets.txt
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Splash/splash.svg b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Splash/splash.svg
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Splash/splash.svg
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Splash/splash.svg
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Styles/Colors.xaml b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Styles/Colors.xaml
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Styles/Colors.xaml
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Styles/Colors.xaml
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Styles/Styles.xaml b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Styles/Styles.xaml
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Styles/Styles.xaml
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Resources/Styles/Styles.xaml
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Utils/DownloadHelper.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Utils/DownloadHelper.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Utils/DownloadHelper.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Utils/DownloadHelper.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Utils/SysConf.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Utils/SysConf.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Utils/SysConf.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples.MauiApp/Utils/SysConf.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples/AliParaformerAsr.Examples.csproj b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples/AliParaformerAsr.Examples.csproj
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples/AliParaformerAsr.Examples.csproj
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples/AliParaformerAsr.Examples.csproj
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples/Program.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples/Program.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples/Program.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.Examples/Program.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.sln b/runtime/csharp/AliParaformerAsr/AliParaformerAsr.sln
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr.sln
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr.sln
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/AliParaformerAsr.csproj b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/AliParaformerAsr.csproj
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/AliParaformerAsr.csproj
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/AliParaformerAsr.csproj
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/CmvnEntity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/CmvnEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/CmvnEntity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/CmvnEntity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/DecoderConfEntity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/DecoderConfEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/DecoderConfEntity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/DecoderConfEntity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/EncoderConfEntity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/EncoderConfEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/EncoderConfEntity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/EncoderConfEntity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/FrontendConfEntity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/FrontendConfEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/FrontendConfEntity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/FrontendConfEntity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/ModelConfEntity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/ModelConfEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/ModelConfEntity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/ModelConfEntity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineInputEntity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineInputEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineInputEntity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineInputEntity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineOutputEntity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineOutputEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineOutputEntity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineOutputEntity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineYamlEntity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineYamlEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineYamlEntity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/OfflineYamlEntity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PostEncoderConfEntity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PostEncoderConfEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PostEncoderConfEntity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PostEncoderConfEntity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PreEncoderConfEntity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PreEncoderConfEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PreEncoderConfEntity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PreEncoderConfEntity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PredictorConfEntity.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PredictorConfEntity.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PredictorConfEntity.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Model/PredictorConfEntity.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/OfflineRecognizer.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/OfflineRecognizer.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/OfflineRecognizer.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/OfflineRecognizer.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Utils/YamlHelper.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Utils/YamlHelper.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/Utils/YamlHelper.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/Utils/YamlHelper.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/WavFrontend.cs b/runtime/csharp/AliParaformerAsr/AliParaformerAsr/WavFrontend.cs
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/AliParaformerAsr/WavFrontend.cs
rename to runtime/csharp/AliParaformerAsr/AliParaformerAsr/WavFrontend.cs
diff --git a/funasr/runtime/csharp/AliParaformerAsr/README.md b/runtime/csharp/AliParaformerAsr/README.md
similarity index 100%
rename from funasr/runtime/csharp/AliParaformerAsr/README.md
rename to runtime/csharp/AliParaformerAsr/README.md
diff --git a/funasr/runtime/csharp/ws-client/FunASRClient_CShape.sln b/runtime/csharp/ws-client/FunASRClient_CShape.sln
similarity index 100%
rename from funasr/runtime/csharp/ws-client/FunASRClient_CShape.sln
rename to runtime/csharp/ws-client/FunASRClient_CShape.sln
diff --git a/funasr/runtime/csharp/ws-client/FunASRClient_CShape.suo b/runtime/csharp/ws-client/FunASRClient_CShape.suo
similarity index 100%
rename from funasr/runtime/csharp/ws-client/FunASRClient_CShape.suo
rename to runtime/csharp/ws-client/FunASRClient_CShape.suo
diff --git a/funasr/runtime/csharp/ws-client/FunASRWSClient_Offline/FunASRWSClient_Offline.csproj b/runtime/csharp/ws-client/FunASRWSClient_Offline/FunASRWSClient_Offline.csproj
similarity index 100%
rename from funasr/runtime/csharp/ws-client/FunASRWSClient_Offline/FunASRWSClient_Offline.csproj
rename to runtime/csharp/ws-client/FunASRWSClient_Offline/FunASRWSClient_Offline.csproj
diff --git a/funasr/runtime/csharp/ws-client/FunASRWSClient_Offline/Program.cs b/runtime/csharp/ws-client/FunASRWSClient_Offline/Program.cs
similarity index 100%
rename from funasr/runtime/csharp/ws-client/FunASRWSClient_Offline/Program.cs
rename to runtime/csharp/ws-client/FunASRWSClient_Offline/Program.cs
diff --git a/funasr/runtime/csharp/ws-client/FunASRWSClient_Offline/README.md b/runtime/csharp/ws-client/FunASRWSClient_Offline/README.md
similarity index 100%
rename from funasr/runtime/csharp/ws-client/FunASRWSClient_Offline/README.md
rename to runtime/csharp/ws-client/FunASRWSClient_Offline/README.md
diff --git a/funasr/runtime/csharp/ws-client/FunASRWSClient_Offline/WebScoketClient.cs b/runtime/csharp/ws-client/FunASRWSClient_Offline/WebScoketClient.cs
similarity index 100%
rename from funasr/runtime/csharp/ws-client/FunASRWSClient_Offline/WebScoketClient.cs
rename to runtime/csharp/ws-client/FunASRWSClient_Offline/WebScoketClient.cs
diff --git a/funasr/runtime/csharp/ws-client/FunASRWSClient_Online/FunASRWSClient_Online.csproj b/runtime/csharp/ws-client/FunASRWSClient_Online/FunASRWSClient_Online.csproj
similarity index 100%
rename from funasr/runtime/csharp/ws-client/FunASRWSClient_Online/FunASRWSClient_Online.csproj
rename to runtime/csharp/ws-client/FunASRWSClient_Online/FunASRWSClient_Online.csproj
diff --git a/funasr/runtime/csharp/ws-client/FunASRWSClient_Online/Program.cs b/runtime/csharp/ws-client/FunASRWSClient_Online/Program.cs
similarity index 100%
rename from funasr/runtime/csharp/ws-client/FunASRWSClient_Online/Program.cs
rename to runtime/csharp/ws-client/FunASRWSClient_Online/Program.cs
diff --git a/funasr/runtime/csharp/ws-client/FunASRWSClient_Online/README.md b/runtime/csharp/ws-client/FunASRWSClient_Online/README.md
similarity index 100%
rename from funasr/runtime/csharp/ws-client/FunASRWSClient_Online/README.md
rename to runtime/csharp/ws-client/FunASRWSClient_Online/README.md
diff --git a/funasr/runtime/csharp/ws-client/FunASRWSClient_Online/WaveCollect.cs b/runtime/csharp/ws-client/FunASRWSClient_Online/WaveCollect.cs
similarity index 100%
rename from funasr/runtime/csharp/ws-client/FunASRWSClient_Online/WaveCollect.cs
rename to runtime/csharp/ws-client/FunASRWSClient_Online/WaveCollect.cs
diff --git a/funasr/runtime/csharp/ws-client/FunASRWSClient_Online/WebScoketClient.cs b/runtime/csharp/ws-client/FunASRWSClient_Online/WebScoketClient.cs
similarity index 100%
rename from funasr/runtime/csharp/ws-client/FunASRWSClient_Online/WebScoketClient.cs
rename to runtime/csharp/ws-client/FunASRWSClient_Online/WebScoketClient.cs
diff --git a/funasr/runtime/csharp/ws-client/confg/config.ini b/runtime/csharp/ws-client/confg/config.ini
similarity index 100%
rename from funasr/runtime/csharp/ws-client/confg/config.ini
rename to runtime/csharp/ws-client/confg/config.ini
diff --git a/funasr/runtime/csharp/ws-client/confg/hotword.txt b/runtime/csharp/ws-client/confg/hotword.txt
similarity index 100%
rename from funasr/runtime/csharp/ws-client/confg/hotword.txt
rename to runtime/csharp/ws-client/confg/hotword.txt
diff --git a/funasr/runtime/csharp/ws-client/confg/tmp.wav b/runtime/csharp/ws-client/confg/tmp.wav
similarity index 100%
rename from funasr/runtime/csharp/ws-client/confg/tmp.wav
rename to runtime/csharp/ws-client/confg/tmp.wav
diff --git a/funasr/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-en.sh b/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-en.sh
similarity index 99%
rename from funasr/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-en.sh
rename to runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-en.sh
index 47f47ebb6..893ab70a5 100644
--- a/funasr/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-en.sh
+++ b/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-en.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
-scriptVersion="0.0.1"
-scriptDate="20231010"
+scriptVersion="0.0.2"
+scriptDate="20231030"
# Set color
@@ -27,7 +27,7 @@ SUDO_CMD="sudo"
DEFAULT_DOCKER_OFFLINE_CPU_EN_LISTS_OSS="https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/docker_lists/docker_offline_cpu_en_lists"
-DEFAULT_DOCKER_OFFLINE_CPU_EN_LISTS_GIT="https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/funasr/runtime/docs/docker_offline_cpu_en_lists"
+DEFAULT_DOCKER_OFFLINE_CPU_EN_LISTS_GIT="https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/runtime/docs/docker_offline_cpu_en_lists"
DEFAULT_DOCKER_IMAGE_LISTS=$DEFAULT_DOCKER_OFFLINE_CPU_EN_LISTS_OSS
DEFAULT_FUNASR_DOCKER_URL="registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr"
DEFAULT_FUNASR_RUNTIME_RESOURCES="funasr-runtime-resources"
@@ -42,7 +42,7 @@ DEFAULT_FUNASR_WORKSPACE_DIR="/workspace/models"
DEFAULT_DOCKER_PORT="10095"
DEFAULT_PROGRESS_FILENAME="progress.txt"
DEFAULT_SERVER_EXEC_NAME="funasr-wss-server"
-DEFAULT_DOCKER_EXEC_DIR="/workspace/FunASR/funasr/runtime/websocket/build/bin"
+DEFAULT_DOCKER_EXEC_DIR="/workspace/FunASR/runtime/websocket/build/bin"
DEFAULT_DOCKER_EXEC_PATH=${DEFAULT_DOCKER_EXEC_DIR}/${DEFAULT_SERVER_EXEC_NAME}
DEFAULT_SAMPLES_NAME="funasr_samples"
DEFAULT_SAMPLES_DIR="samples"
@@ -683,7 +683,7 @@ paramsFromDefault(){
if [ ! -z "$punc_id" ]; then
PARAMS_PUNC_ID=$punc_id
fi
- docker_exec_path=`sed '/^PARAMS_DOCKER_EXEC_PATH=/!d;s/.*=//' ${DEFAULT_FUNASR_CONFIG_FILE}`
+ # docker_exec_path=`sed '/^PARAMS_DOCKER_EXEC_PATH=/!d;s/.*=//' ${DEFAULT_FUNASR_CONFIG_FILE}`
if [ ! -z "$docker_exec_path" ]; then
PARAMS_DOCKER_EXEC_PATH=$docker_exec_path
fi
@@ -939,7 +939,7 @@ dockerRun(){
run_cmd="${SUDO_CMD} docker run"
port_map=" -p ${PARAMS_HOST_PORT}:${PARAMS_DOCKER_PORT}"
env_params=" --privileged=true"
- dir_map_params=" -v ${DEFAULT_FUNASR_CONFIG_DIR}:/workspace/.config -v ${PARAMS_FUNASR_LOCAL_MODELS_DIR}:${PARAMS_DOWNLOAD_MODEL_DIR}"
+ dir_map_params=" -v ${DEFAULT_FUNASR_CONFIG_DIR}:/workspace/.config -v ${PARAMS_FUNASR_LOCAL_MODELS_DIR}:${PARAMS_DOWNLOAD_MODEL_DIR} -v ${PARAMS_FUNASR_LOCAL_WORKSPACE}:/workspace/resources"
serverConfigGeneration
env_params=" ${env_params} --env DAEMON_SERVER_CONFIG=${daemon_server_config}"
@@ -1060,8 +1060,8 @@ serverConfigGeneration(){
crt_path="\"--certfile\":\"\""
key_path="\"--keyfile\":\"\""
else
- crt_path="\"--certfile\":\"/workspace/FunASR/funasr/runtime/ssl_key/server.crt\""
- key_path="\"--keyfile\":\"/workspace/FunASR/funasr/runtime/ssl_key/server.key\""
+ crt_path="\"--certfile\":\"/workspace/FunASR/runtime/ssl_key/server.crt\""
+ key_path="\"--keyfile\":\"/workspace/FunASR/runtime/ssl_key/server.key\""
fi
exec_params="\"exec\":\"${PARAMS_DOCKER_EXEC_PATH}\""
diff --git a/funasr/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-zh.sh b/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-zh.sh
similarity index 93%
rename from funasr/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-zh.sh
rename to runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-zh.sh
index 5738d6edd..ecb21af3d 100644
--- a/funasr/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-zh.sh
+++ b/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-zh.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
-scriptVersion="0.0.7"
-scriptDate="20230818"
+scriptVersion="0.0.8"
+scriptDate="20231030"
# Set color
@@ -27,7 +27,7 @@ SUDO_CMD="sudo"
DEFAULT_DOCKER_OFFLINE_CPU_ZH_LISTS_OSS="https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/docker_lists/docker_offline_cpu_zh_lists"
-DEFAULT_DOCKER_OFFLINE_CPU_ZH_LISTS_GIT="https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/funasr/runtime/docs/docker_offline_cpu_zh_lists"
+DEFAULT_DOCKER_OFFLINE_CPU_ZH_LISTS_GIT="https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/runtime/docs/docker_offline_cpu_zh_lists"
DEFAULT_DOCKER_IMAGE_LISTS=$DEFAULT_DOCKER_OFFLINE_CPU_ZH_LISTS_OSS
DEFAULT_FUNASR_DOCKER_URL="registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr"
DEFAULT_FUNASR_RUNTIME_RESOURCES="funasr-runtime-resources"
@@ -42,7 +42,7 @@ DEFAULT_FUNASR_WORKSPACE_DIR="/workspace/models"
DEFAULT_DOCKER_PORT="10095"
DEFAULT_PROGRESS_FILENAME="progress.txt"
DEFAULT_SERVER_EXEC_NAME="funasr-wss-server"
-DEFAULT_DOCKER_EXEC_DIR="/workspace/FunASR/funasr/runtime/websocket/build/bin"
+DEFAULT_DOCKER_EXEC_DIR="/workspace/FunASR/runtime/websocket/build/bin"
DEFAULT_DOCKER_EXEC_PATH=${DEFAULT_DOCKER_EXEC_DIR}/${DEFAULT_SERVER_EXEC_NAME}
DEFAULT_SAMPLES_NAME="funasr_samples"
DEFAULT_SAMPLES_DIR="samples"
@@ -56,6 +56,7 @@ DOCKER_IMAGES=()
ASR_MODELS=()
VAD_MODELS=()
PUNC_MODELS=()
+LM_MODELS=()
# Handles the download progress bar
asr_percent_int=0
@@ -420,6 +421,10 @@ readDockerInfoFromUrl(){
if [ ! -z "$docker_info_cur_val" ]; then
PUNC_MODELS[${#PUNC_MODELS[*]}]=$docker_info_cur_val
fi
+ elif [ "$docker_info_cur_key" = "DEFAULT_LM_MODEL:" ]; then
+ if [ ! -z "$docker_info_cur_val" ]; then
+ LM_MODELS[${#LM_MODELS[*]}]=$docker_info_cur_val
+ fi
fi
done
echo -e " $DONE"
@@ -497,6 +502,7 @@ selectModels(){
selectAsrModels
selectVadModels
selectPuncModels
+ selectLMModels
echo
}
@@ -534,6 +540,17 @@ selectPuncModels(){
echo
}
+selectLMModels(){
+ echo -e " ${YELLOW}Please choose the LM model.${PLAIN}"
+ menuSelection ${LM_MODELS[*]}
+ result=$?
+ index=`expr ${result} - 1`
+
+ PARAMS_LM_ID=${LM_MODELS[${index}]}
+ echo -e " ${UNDERLINE}You have chosen the LM model:${PLAIN} ${GREEN}${PARAMS_LM_ID}${PLAIN}"
+ echo
+}
+
# Configure FunASR server host port setting.
setupHostPort(){
echo -e "${UNDERLINE}${BOLD}[3/6]${PLAIN}"
@@ -600,6 +617,14 @@ complementParameters(){
PARAMS_LOCAL_PUNC_DIR=$(dirname "${PARAMS_LOCAL_PUNC_PATH}")
fi
+ # parameters about LM model
+ if [ ! -z "$PARAMS_LM_ID" ]; then
+ PARAMS_DOCKER_LM_PATH=${PARAMS_DOWNLOAD_MODEL_DIR}/${PARAMS_LM_ID}
+ PARAMS_DOCKER_LM_DIR=$(dirname "${PARAMS_DOCKER_LM_PATH}")
+ PARAMS_LOCAL_LM_PATH=${PARAMS_FUNASR_LOCAL_MODELS_DIR}/${PARAMS_LM_ID}
+ PARAMS_LOCAL_LM_DIR=$(dirname "${PARAMS_LOCAL_LM_PATH}")
+ fi
+
# parameters about thread_num
params_decoder_thread_num=`sed '/^PARAMS_DECODER_THREAD_NUM=/!d;s/.*=//' ${DEFAULT_FUNASR_CONFIG_FILE}`
if [ -z "$params_decoder_thread_num" ]; then
@@ -683,7 +708,19 @@ paramsFromDefault(){
if [ ! -z "$punc_id" ]; then
PARAMS_PUNC_ID=$punc_id
fi
- docker_exec_path=`sed '/^PARAMS_DOCKER_EXEC_PATH=/!d;s/.*=//' ${DEFAULT_FUNASR_CONFIG_FILE}`
+ local_lm_path=`sed '/^PARAMS_LOCAL_LM_PATH=/!d;s/.*=//' ${DEFAULT_FUNASR_CONFIG_FILE}`
+ if [ ! -z "$local_lm_path" ]; then
+ PARAMS_LOCAL_LM_PATH=$local_lm_path
+ fi
+ docker_lm_path=`sed '/^PARAMS_DOCKER_LM_PATH=/!d;s/.*=//' ${DEFAULT_FUNASR_CONFIG_FILE}`
+ if [ ! -z "$docker_lm_path" ]; then
+ PARAMS_DOCKER_LM_PATH=$docker_lm_path
+ fi
+ lm_id=`sed '/^PARAMS_LM_ID=/!d;s/.*=//' ${DEFAULT_FUNASR_CONFIG_FILE}`
+ if [ ! -z "$lm_id" ]; then
+ PARAMS_LM_ID=$lm_id
+ fi
+ # docker_exec_path=`sed '/^PARAMS_DOCKER_EXEC_PATH=/!d;s/.*=//' ${DEFAULT_FUNASR_CONFIG_FILE}`
if [ ! -z "$docker_exec_path" ]; then
PARAMS_DOCKER_EXEC_PATH=$docker_exec_path
fi
@@ -742,6 +779,12 @@ saveParams(){
echo "PARAMS_DOCKER_PUNC_DIR=${PARAMS_DOCKER_PUNC_DIR}" >> $DEFAULT_FUNASR_CONFIG_FILE
echo "PARAMS_PUNC_ID=${PARAMS_PUNC_ID}" >> $DEFAULT_FUNASR_CONFIG_FILE
+ echo "PARAMS_LOCAL_LM_PATH=${PARAMS_LOCAL_LM_PATH}" >> $DEFAULT_FUNASR_CONFIG_FILE
+ echo "PARAMS_LOCAL_LM_DIR=${PARAMS_LOCAL_LM_DIR}" >> $DEFAULT_FUNASR_CONFIG_FILE
+ echo "PARAMS_DOCKER_LM_PATH=${PARAMS_DOCKER_LM_PATH}" >> $DEFAULT_FUNASR_CONFIG_FILE
+ echo "PARAMS_DOCKER_LM_DIR=${PARAMS_DOCKER_LM_DIR}" >> $DEFAULT_FUNASR_CONFIG_FILE
+ echo "PARAMS_LM_ID=${PARAMS_LM_ID}" >> $DEFAULT_FUNASR_CONFIG_FILE
+
echo "PARAMS_LOCAL_VAD_PATH=${PARAMS_LOCAL_VAD_PATH}" >> $DEFAULT_FUNASR_CONFIG_FILE
echo "PARAMS_LOCAL_VAD_DIR=${PARAMS_LOCAL_VAD_DIR}" >> $DEFAULT_FUNASR_CONFIG_FILE
echo "PARAMS_DOCKER_VAD_PATH=${PARAMS_DOCKER_VAD_PATH}" >> $DEFAULT_FUNASR_CONFIG_FILE
@@ -801,6 +844,15 @@ showAllParams(){
echo -e " The path to the local PUNC model directory for the load : ${GREEN}${PARAMS_LOCAL_PUNC_PATH}${PLAIN}"
fi
echo -e " The PUNC model directory corresponds to the directory in Docker: ${GREEN}${PARAMS_DOCKER_PUNC_PATH}${PLAIN}"
+
+ if [ ! -z "$PARAMS_LM_ID" ]; then
+ echo -e " The LM model_id used : ${GREEN}${PARAMS_LM_ID}${PLAIN}"
+ fi
+ if [ ! -z "$PARAMS_LOCAL_LM_PATH" ]; then
+ echo -e " The path to the local LM model directory for the load : ${GREEN}${PARAMS_LOCAL_LM_PATH}${PLAIN}"
+ fi
+ echo -e " The LM model directory corresponds to the directory in Docker: ${GREEN}${PARAMS_DOCKER_LM_PATH}${PLAIN}"
+
echo
echo -e " The path in the docker of the FunASR service executor : ${GREEN}${PARAMS_DOCKER_EXEC_PATH}${PLAIN}"
@@ -939,7 +991,7 @@ dockerRun(){
run_cmd="${SUDO_CMD} docker run"
port_map=" -p ${PARAMS_HOST_PORT}:${PARAMS_DOCKER_PORT}"
env_params=" --privileged=true"
- dir_map_params=" -v ${DEFAULT_FUNASR_CONFIG_DIR}:/workspace/.config -v ${PARAMS_FUNASR_LOCAL_MODELS_DIR}:${PARAMS_DOWNLOAD_MODEL_DIR}"
+ dir_map_params=" -v ${DEFAULT_FUNASR_CONFIG_DIR}:/workspace/.config -v ${PARAMS_FUNASR_LOCAL_MODELS_DIR}:${PARAMS_DOWNLOAD_MODEL_DIR} -v ${PARAMS_FUNASR_LOCAL_WORKSPACE}:/workspace/resources"
serverConfigGeneration
env_params=" ${env_params} --env DAEMON_SERVER_CONFIG=${daemon_server_config}"
@@ -1046,8 +1098,16 @@ serverConfigGeneration(){
fi
punc_params="\"--punc-dir\":\"${PARAMS_DOCKER_PUNC_PATH}\""
fi
+ if [ ! -z "$PARAMS_LM_ID" ]; then
+ lm_params="\"--lm-dir\":\"${PARAMS_LM_ID}\""
+ else
+ if [ ! -z "$PARAMS_LOCAL_LM_PATH" ]; then
+ dir_map_params="${dir_map_params} -v ${PARAMS_LOCAL_VAD_PATH}:${PARAMS_DOCKER_VAD_PATH}"
+ fi
+ lm_params="\"--lm-dir\":\"${PARAMS_DOCKER_LM_PATH}\""
+ fi
download_params="\"--download-model-dir\":\"${PARAMS_DOWNLOAD_MODEL_DIR}\""
- model_params="${asr_params},${vad_params},${punc_params},${download_params}"
+ model_params="${asr_params},${vad_params},${punc_params},${lm_params},${download_params}"
# params about thread_num
decoder_params="\"--decoder-thread-num\":\"${PARAMS_DECODER_THREAD_NUM}\""
@@ -1060,8 +1120,8 @@ serverConfigGeneration(){
crt_path="\"--certfile\":\"\""
key_path="\"--keyfile\":\"\""
else
- crt_path="\"--certfile\":\"/workspace/FunASR/funasr/runtime/ssl_key/server.crt\""
- key_path="\"--keyfile\":\"/workspace/FunASR/funasr/runtime/ssl_key/server.key\""
+ crt_path="\"--certfile\":\"/workspace/FunASR/runtime/ssl_key/server.crt\""
+ key_path="\"--keyfile\":\"/workspace/FunASR/runtime/ssl_key/server.key\""
fi
exec_params="\"exec\":\"${PARAMS_DOCKER_EXEC_PATH}\""
@@ -1285,6 +1345,21 @@ modelChange(){
PARAMS_DOCKER_PUNC_PATH=${PARAMS_DOCKER_PUNC_DIR}/${model_name}
fi
fi
+ result=$(echo ${model_type} | grep "\-\-lm_model")
+ if [ "$result" != "" ]; then
+ if [ $local_flag -eq 0 ]; then
+ PARAMS_LM_ID=$model_id
+ PARAMS_DOCKER_LM_PATH=${PARAMS_DOWNLOAD_MODEL_DIR}/${PARAMS_LM_ID}
+ PARAMS_DOCKER_LM_DIR=$(dirname "${PARAMS_DOCKER_LM_PATH}")
+ PARAMS_LOCAL_LM_PATH=${PARAMS_FUNASR_LOCAL_MODELS_DIR}/${PARAMS_LM_ID}
+ PARAMS_LOCAL_LM_DIR=$(dirname "${PARAMS_LOCAL_LM_PATH}")
+ else
+ model_name=$(basename "${PARAMS_LOCAL_LM_PATH}")
+ PARAMS_LOCAL_LM_DIR=$(dirname "${PARAMS_LOCAL_LM_PATH}")
+ PARAMS_DOCKER_LM_DIR=$PARAMS_DOWNLOAD_MODEL_DIR
+ PARAMS_DOCKER_LM_PATH=${PARAMS_DOCKER_LM_DIR}/${model_name}
+ fi
+ fi
}
threadNumChange() {
@@ -1437,7 +1512,7 @@ displayHelp(){
echo -e " ${BOLD}-r, restart, --restart${PLAIN} Restart FunASR docker."
echo -e " ${BOLD}-u, update , --update${PLAIN} Update parameters that has already been set."
echo -e " update [--workspace] <workspace in local>"
- echo -e " update [--asr_model | --vad_model | --punc_model] <model_id or local model path>"
+ echo -e " update [--asr_model | --vad_model | --punc_model | --lm_model] <model_id or local model path>"
echo -e " update [--host_port | --docker_port] <port number>"
echo -e " update [--decode_thread_num | io_thread_num] <the number of threads>"
echo -e " update [--ssl] <0: close SSL; 1: open SSL, default:1>"
@@ -1519,6 +1594,17 @@ PARAMS_DOCKER_PUNC_PATH=""
# The punc model ID in ModelScope
PARAMS_PUNC_ID="damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx"
+# The dir stored lm model in local
+PARAMS_LOCAL_LM_DIR=""
+# The path of lm model in local
+PARAMS_LOCAL_LM_PATH=""
+# The dir stored lm model in docker
+PARAMS_DOCKER_LM_DIR=""
+# The path of lm model in docker
+PARAMS_DOCKER_LM_PATH=""
+# The lm model ID in ModelScope
+PARAMS_LM_ID="damo/speech_ngram_lm_zh-cn-ai-wesp-fst"
+
# The dir stored vad model in local
PARAMS_LOCAL_VAD_DIR=""
# The path of vad model in local
@@ -1668,7 +1754,7 @@ case "$1" in
if [ $# -eq 3 ]; then
type=$2
val=$3
- if [ "$type" = "--asr_model" ] || [ "$type" = "--vad_model" ] || [ "$type" = "--punc_model" ]; then
+ if [ "$type" = "--asr_model" ] || [ "$type" = "--vad_model" ] || [ "$type" = "--punc_model" ] || [ "$type" = "--lm_model" ]; then
modelChange $type $val
elif [ "$type" = "--decode_thread_num" ] || [ "$type" = "--io_thread_num" ]; then
threadNumChange $type $val
diff --git a/funasr/runtime/deploy_tools/funasr-runtime-deploy-online-cpu-zh.sh b/runtime/deploy_tools/funasr-runtime-deploy-online-cpu-zh.sh
similarity index 99%
rename from funasr/runtime/deploy_tools/funasr-runtime-deploy-online-cpu-zh.sh
rename to runtime/deploy_tools/funasr-runtime-deploy-online-cpu-zh.sh
index 423b2a095..a1e999979 100644
--- a/funasr/runtime/deploy_tools/funasr-runtime-deploy-online-cpu-zh.sh
+++ b/runtime/deploy_tools/funasr-runtime-deploy-online-cpu-zh.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
-scriptVersion="0.0.2"
-scriptDate="20230914"
+scriptVersion="0.0.3"
+scriptDate="20231030"
# Set color
@@ -27,7 +27,7 @@ SUDO_CMD="sudo"
DEFAULT_DOCKER_ONLINE_CPU_ZH_LISTS_OSS="https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/docker_lists/docker_online_cpu_zh_lists"
-DEFAULT_DOCKER_ONLINE_CPU_ZH_LISTS_GIT="https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/funasr/runtime/docs/docker_online_cpu_zh_lists"
+DEFAULT_DOCKER_ONLINE_CPU_ZH_LISTS_GIT="https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/runtime/docs/docker_online_cpu_zh_lists"
DEFAULT_DOCKER_IMAGE_LISTS=$DEFAULT_DOCKER_ONLINE_CPU_ZH_LISTS_OSS
DEFAULT_FUNASR_DOCKER_URL="registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr"
DEFAULT_FUNASR_RUNTIME_RESOURCES="funasr-runtime-resources"
@@ -42,7 +42,7 @@ DEFAULT_FUNASR_WORKSPACE_DIR="/workspace/models"
DEFAULT_DOCKER_PORT="10095"
DEFAULT_PROGRESS_FILENAME="progress.txt"
DEFAULT_SERVER_EXEC_NAME="funasr-wss-server-2pass"
-DEFAULT_DOCKER_EXEC_DIR="/workspace/FunASR/funasr/runtime/websocket/build/bin"
+DEFAULT_DOCKER_EXEC_DIR="/workspace/FunASR/runtime/websocket/build/bin"
DEFAULT_DOCKER_EXEC_PATH=${DEFAULT_DOCKER_EXEC_DIR}/${DEFAULT_SERVER_EXEC_NAME}
DEFAULT_SAMPLES_NAME="funasr_samples"
DEFAULT_SAMPLES_DIR="samples"
@@ -683,7 +683,7 @@ paramsFromDefault(){
if [ ! -z "$punc_id" ]; then
PARAMS_PUNC_ID=$punc_id
fi
- docker_exec_path=`sed '/^PARAMS_DOCKER_EXEC_PATH=/!d;s/.*=//' ${DEFAULT_FUNASR_CONFIG_FILE}`
+ # docker_exec_path=`sed '/^PARAMS_DOCKER_EXEC_PATH=/!d;s/.*=//' ${DEFAULT_FUNASR_CONFIG_FILE}`
if [ ! -z "$docker_exec_path" ]; then
PARAMS_DOCKER_EXEC_PATH=$docker_exec_path
fi
@@ -939,7 +939,7 @@ dockerRun(){
run_cmd="${SUDO_CMD} docker run"
port_map=" -p ${PARAMS_HOST_PORT}:${PARAMS_DOCKER_PORT}"
env_params=" --privileged=true"
- dir_map_params=" -v ${DEFAULT_FUNASR_CONFIG_DIR}:/workspace/.config -v ${PARAMS_FUNASR_LOCAL_MODELS_DIR}:${PARAMS_DOWNLOAD_MODEL_DIR}"
+ dir_map_params=" -v ${DEFAULT_FUNASR_CONFIG_DIR}:/workspace/.config -v ${PARAMS_FUNASR_LOCAL_MODELS_DIR}:${PARAMS_DOWNLOAD_MODEL_DIR} -v ${PARAMS_FUNASR_LOCAL_WORKSPACE}:/workspace/resources"
serverConfigGeneration
env_params=" ${env_params} --env DAEMON_SERVER_CONFIG=${daemon_server_config}"
@@ -1060,8 +1060,8 @@ serverConfigGeneration(){
crt_path="\"--certfile\":\"\""
key_path="\"--keyfile\":\"\""
else
- crt_path="\"--certfile\":\"/workspace/FunASR/funasr/runtime/ssl_key/server.crt\""
- key_path="\"--keyfile\":\"/workspace/FunASR/funasr/runtime/ssl_key/server.key\""
+ crt_path="\"--certfile\":\"/workspace/FunASR/runtime/ssl_key/server.crt\""
+ key_path="\"--keyfile\":\"/workspace/FunASR/runtime/ssl_key/server.key\""
fi
exec_params="\"exec\":\"${PARAMS_DOCKER_EXEC_PATH}\""
diff --git a/runtime/deploy_tools/install_docker.sh b/runtime/deploy_tools/install_docker.sh
new file mode 100644
index 000000000..964765a87
--- /dev/null
+++ b/runtime/deploy_tools/install_docker.sh
@@ -0,0 +1,82 @@
+
+# Set color
+RED="\033[31;1m"
+GREEN="\033[32;1m"
+YELLOW="\033[33;1m"
+BLUE="\033[34;1m"
+CYAN="\033[36;1m"
+PLAIN="\033[0m"
+
+# Info messages
+DONE="${GREEN}[DONE]${PLAIN}"
+ERROR="${RED}[ERROR]${PLAIN}"
+WARNING="${YELLOW}[WARNING]${PLAIN}"
+
+# Font Format
+BOLD="\033[1m"
+UNDERLINE="\033[4m"
+
+# Current folder
+CUR_DIR=`pwd`
+SUDO_CMD="sudo"
+
+# OS
+OSID=$(grep ^ID= /etc/os-release | cut -d= -f2)
+OSVER=$(lsb_release -cs)
+OSNUM=$(grep -oE "[0-9.]+" /etc/issue)
+DOCKERINFO=$(${SUDO_CMD} docker info | wc -l)
+DOCKERINFOLEN=`expr ${DOCKERINFO} + 0`
+
+
+if [ $DOCKERINFOLEN -gt 30 ]; then
+ echo -e " ${YELLOW}Docker has installed.${PLAIN}"
+else
+ lowercase_osid=$(echo ${OSID} | tr '[A-Z]' '[a-z]')
+ echo -e " ${YELLOW}Start install docker for ${lowercase_osid} ${PLAIN}"
+ DOCKER_INSTALL_CMD="curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun"
+ DOCKER_INSTALL_RUN_CMD=""
+
+ case "$lowercase_osid" in
+ ubuntu)
+ DOCKER_INSTALL_CMD="curl -fsSL https://test.docker.com -o test-docker.sh"
+ DOCKER_INSTALL_RUN_CMD="${SUDO_CMD} sh test-docker.sh"
+ ;;
+ centos)
+ DOCKER_INSTALL_CMD="curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun"
+ ;;
+ debian)
+ DOCKER_INSTALL_CMD="curl -fsSL https://get.docker.com -o get-docker.sh"
+ DOCKER_INSTALL_RUN_CMD="${SUDO_CMD} sh get-docker.sh"
+ ;;
+ \"alios\")
+ DOCKER_INSTALL_CMD="curl -fsSL https://get.docker.com -o get-docker.sh"
+ DOCKER_INSTALL_RUN_CMD="${SUDO_CMD} sh get-docker.sh"
+ ;;
+ \"alinux\")
+ DOCKER_INSTALL_CMD="${SUDO_CMD} yum -y install dnf"
+ DOCKER_INSTALL_RUN_CMD="${SUDO_CMD} dnf -y install docker"
+ ;;
+ *)
+ echo -e " ${RED}$lowercase_osid is not supported.${PLAIN}"
+ ;;
+ esac
+
+ echo -e " Get docker installer: ${GREEN}${DOCKER_INSTALL_CMD}${PLAIN}"
+ echo -e " Get docker run: ${GREEN}${DOCKER_INSTALL_RUN_CMD}${PLAIN}"
+
+ $DOCKER_INSTALL_CMD
+ if [ ! -z "$DOCKER_INSTALL_RUN_CMD" ]; then
+ $DOCKER_INSTALL_RUN_CMD
+ fi
+ $SUDO_CMD systemctl start docker
+
+ DOCKERINFO=$(${SUDO_CMD} docker info | wc -l)
+ DOCKERINFOLEN=`expr ${DOCKERINFO} + 0`
+ if [ $DOCKERINFOLEN -gt 30 ]; then
+ echo -e " ${GREEN}Docker install success, start docker server.${PLAIN}"
+ $SUDO_CMD systemctl start docker
+ else
+ echo -e " ${RED}Docker install failed!${PLAIN}"
+ exit 1
+ fi
+fi
\ No newline at end of file
diff --git a/funasr/runtime/docs/SDK_advanced_guide_offline.md b/runtime/docs/SDK_advanced_guide_offline.md
similarity index 90%
rename from funasr/runtime/docs/SDK_advanced_guide_offline.md
rename to runtime/docs/SDK_advanced_guide_offline.md
index 43a69cd83..091036543 100644
--- a/funasr/runtime/docs/SDK_advanced_guide_offline.md
+++ b/runtime/docs/SDK_advanced_guide_offline.md
@@ -36,9 +36,9 @@ sudo systemctl start docker
Use the following command to pull and launch the Docker image for the FunASR runtime-SDK:
```shell
-sudo docker pull registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-cpu-0.2.2
+sudo docker pull registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-cpu-0.3.0
-sudo docker run -p 10095:10095 -it --privileged=true -v /root:/workspace/models registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-cpu-0.2.2
+sudo docker run -p 10095:10095 -it --privileged=true -v /root:/workspace/models registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-cpu-0.3.0
```
Introduction to command parameters:
@@ -58,10 +58,11 @@ nohup bash run_server.sh \
--vad-dir damo/speech_fsmn_vad_zh-cn-16k-common-onnx \
--model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-onnx \
--punc-dir damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx \
+ --lm-dir damo/speech_ngram_lm_zh-cn-ai-wesp-fst \
--itn-dir thuduj12/fst_itn_zh > log.out 2>&1 &
# If you want to close ssl,please add:--certfile 0
-# If you want to deploy the timestamp or hotword model, please set --model-dir to the corresponding model:
+# If you want to deploy the timestamp or nn hotword model, please set --model-dir to the corresponding model:
# speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-onnx(timestamp)
# damo/speech_paraformer-large-contextual_asr_nat-zh-cn-16k-common-vocab8404-onnx(hotword)
@@ -72,13 +73,14 @@ nohup bash run_server.sh \
The funasr-wss-server supports downloading models from Modelscope. You can set the model download address (--download-model-dir, default is /workspace/models) and the model ID (--model-dir, --vad-dir, --punc-dir). Here is an example:
```shell
-cd /workspace/FunASR/funasr/runtime
+cd /workspace/FunASR/runtime
nohup bash run_server.sh \
--download-model-dir /workspace/models \
--model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-onnx \
--vad-dir damo/speech_fsmn_vad_zh-cn-16k-common-onnx \
--punc-dir damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx \
--itn-dir thuduj12/fst_itn_zh \
+ --lm-dir damo/speech_ngram_lm_zh-cn-ai-wesp-fst \
--decoder-thread-num 32 \
--io-thread-num 8 \
--port 10095 \
@@ -103,7 +105,7 @@ Introduction to run_server.sh parameters:
--io-thread-num: Number of IO threads that the server starts. Default is 1.
--certfile <string>: SSL certificate file. Default is ../../../ssl_key/server.crt. If you want to close ssl,set 0
--keyfile <string>: SSL key file. Default is ../../../ssl_key/server.key.
---hotword Hotword file path, one line for each hot word, if the client provides hot words, then combined with the hot words provided by the client. Default is ../../hotwords.txt
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20), if the client provides hot words, then combined with the hot words provided by the client.
```
### Shutting Down the FunASR Service
@@ -132,7 +134,8 @@ After executing the above command, the real-time speech transcription service wi
[FSMN-VAD](https://www.modelscope.cn/models/damo/speech_fsmn_vad_zh-cn-16k-common-onnx/summary),
[Paraformer-lagre](https://www.modelscope.cn/models/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-onnx/summary),
[CT-Transformer](https://www.modelscope.cn/models/damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx/summary),
-[FST-ITN](https://www.modelscope.cn/models/thuduj12/fst_itn_zh/summary)
+[FST-ITN](https://www.modelscope.cn/models/thuduj12/fst_itn_zh/summary),
+[Ngram lm](https://www.modelscope.cn/models/damo/speech_ngram_lm_zh-cn-ai-wesp-fst/summary)
If you wish to deploy your fine-tuned model (e.g., 10epoch.pb), you need to manually rename the model to model.pb and replace the original model.pb in ModelScope. Then, specify the path as `model_dir`.
@@ -156,7 +159,7 @@ Introduction to command parameters:
--output_dir: the path to the recognition result output.
--ssl: whether to use SSL encryption. The default is to use SSL.
--mode: offline mode.
---hotword: If am is hotword model, setting hotword: *.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20)
--use_itn: whether to use itn, the default value is 1 for enabling and 0 for disabling.
```
@@ -172,7 +175,7 @@ Introduction to command parameters:
--port: the port number of the server listener.
--wav-path: the audio input. Input can be a path to a wav file or a wav.scp file (a Kaldi-formatted wav list in which each line includes a wav_id followed by a tab and a wav_path).
--is-ssl: whether to use SSL encryption. The default is to use SSL.
---hotword: If am is hotword model, setting hotword: *.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20)
--use-itn: whether to use itn, the default value is 1 for enabling and 0 for disabling.
```
@@ -186,11 +189,11 @@ The code for FunASR-runtime is open source. If the server and client cannot full
### C++ client
-https://github.com/alibaba-damo-academy/FunASR/tree/main/funasr/runtime/websocket
+https://github.com/alibaba-damo-academy/FunASR/tree/main/runtime/websocket
### Python client
-https://github.com/alibaba-damo-academy/FunASR/tree/main/funasr/runtime/python/websocket
+https://github.com/alibaba-damo-academy/FunASR/tree/main/runtime/python/websocket
### C++ server
@@ -203,7 +206,7 @@ FUNASR_RESULT result=FsmnVadInfer(vad_hanlde, wav_file.c_str(), NULL, 16000);
// Where: vad_hanlde is the return value of FunOfflineInit, wav_file is the path to the audio file, and sampling_rate is the sampling rate (default 16k).
```
-See the usage example for details [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp)
+See the usage example for details [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp)
#### ASR
```text
@@ -214,7 +217,7 @@ FUNASR_RESULT result=FunOfflineInfer(asr_hanlde, wav_file.c_str(), RASR_NONE, NU
// Where: asr_hanlde is the return value of FunOfflineInit, wav_file is the path to the audio file, and sampling_rate is the sampling rate (default 16k).
```
-See the usage example for details, [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline.cpp)
+See the usage example for details, [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline.cpp)
#### PUNC
```text
@@ -224,4 +227,4 @@ FUNASR_HANDLE punc_hanlde=CTTransformerInit(model_path, thread_num);
FUNASR_RESULT result=CTTransformerInfer(punc_hanlde, txt_str.c_str(), RASR_NONE, NULL);
// Where: punc_hanlde is the return value of CTTransformerInit, txt_str is the text
```
-See the usage example for details, [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp)
+See the usage example for details, [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp)
diff --git a/funasr/runtime/docs/SDK_advanced_guide_offline_en.md b/runtime/docs/SDK_advanced_guide_offline_en.md
similarity index 92%
rename from funasr/runtime/docs/SDK_advanced_guide_offline_en.md
rename to runtime/docs/SDK_advanced_guide_offline_en.md
index b829e67c7..e4650382e 100644
--- a/funasr/runtime/docs/SDK_advanced_guide_offline_en.md
+++ b/runtime/docs/SDK_advanced_guide_offline_en.md
@@ -36,9 +36,9 @@ sudo systemctl start docker
Use the following command to pull and launch the Docker image for the FunASR runtime-SDK:
```shell
-sudo docker pull registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-en-cpu-0.1.0
+sudo docker pull registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-en-cpu-0.1.1
-sudo docker run -p 10095:10095 -it --privileged=true -v /root:/workspace/models registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-en-cpu-0.1.0
+sudo docker run -p 10095:10095 -it --privileged=true -v /root:/workspace/models registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-en-cpu-0.1.1
```
Introduction to command parameters:
@@ -69,7 +69,7 @@ nohup bash run_server.sh \
The funasr-wss-server supports downloading models from Modelscope. You can set the model download address (--download-model-dir, default is /workspace/models) and the model ID (--model-dir, --vad-dir, --punc-dir). Here is an example:
```shell
-cd /workspace/FunASR/funasr/runtime
+cd /workspace/FunASR/runtime
nohup bash run_server.sh \
--download-model-dir /workspace/models \
--model-dir damo/speech_paraformer-large_asr_nat-en-16k-common-vocab10020-onnx \
@@ -147,7 +147,7 @@ Introduction to command parameters:
--output_dir: the path to the recognition result output.
--ssl: whether to use SSL encryption. The default is to use SSL.
--mode: offline mode.
---hotword: If am is hotword model, setting hotword: *.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20)
--use_itn: whether to use itn, the default value is 1 for enabling and 0 for disabling.
```
@@ -163,7 +163,7 @@ Introduction to command parameters:
--port: the port number of the server listener.
--wav-path: the audio input. Input can be a path to a wav file or a wav.scp file (a Kaldi-formatted wav list in which each line includes a wav_id followed by a tab and a wav_path).
--is-ssl: whether to use SSL encryption. The default is to use SSL.
---hotword: If am is hotword model, setting hotword: *.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20)
--use-itn: whether to use itn, the default value is 1 for enabling and 0 for disabling.
```
@@ -177,11 +177,11 @@ The code for FunASR-runtime is open source. If the server and client cannot full
### C++ client
-https://github.com/alibaba-damo-academy/FunASR/tree/main/funasr/runtime/websocket
+https://github.com/alibaba-damo-academy/FunASR/tree/main/runtime/websocket
### Python client
-https://github.com/alibaba-damo-academy/FunASR/tree/main/funasr/runtime/python/websocket
+https://github.com/alibaba-damo-academy/FunASR/tree/main/runtime/python/websocket
### C++ server
@@ -194,7 +194,7 @@ FUNASR_RESULT result=FsmnVadInfer(vad_hanlde, wav_file.c_str(), NULL, 16000);
// Where: vad_hanlde is the return value of FunOfflineInit, wav_file is the path to the audio file, and sampling_rate is the sampling rate (default 16k).
```
-See the usage example for details [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp)
+See the usage example for details [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp)
#### ASR
```text
@@ -205,7 +205,7 @@ FUNASR_RESULT result=FunOfflineInfer(asr_hanlde, wav_file.c_str(), RASR_NONE, NU
// Where: asr_hanlde is the return value of FunOfflineInit, wav_file is the path to the audio file, and sampling_rate is the sampling rate (default 16k).
```
-See the usage example for details, [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline.cpp)
+See the usage example for details, [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline.cpp)
#### PUNC
```text
@@ -215,4 +215,4 @@ FUNASR_HANDLE punc_hanlde=CTTransformerInit(model_path, thread_num);
FUNASR_RESULT result=CTTransformerInfer(punc_hanlde, txt_str.c_str(), RASR_NONE, NULL);
// Where: punc_hanlde is the return value of CTTransformerInit, txt_str is the text
```
-See the usage example for details, [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp)
+See the usage example for details, [docs](https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp)
diff --git a/funasr/runtime/docs/SDK_advanced_guide_offline_en_zh.md b/runtime/docs/SDK_advanced_guide_offline_en_zh.md
similarity index 91%
rename from funasr/runtime/docs/SDK_advanced_guide_offline_en_zh.md
rename to runtime/docs/SDK_advanced_guide_offline_en_zh.md
index 48c67c9a5..3bd2b7723 100644
--- a/funasr/runtime/docs/SDK_advanced_guide_offline_en_zh.md
+++ b/runtime/docs/SDK_advanced_guide_offline_en_zh.md
@@ -13,21 +13,30 @@ FunASR提供可一键本地或者云端服务器部署的英文离线文件转
详细性能测试报告([点击此处](./benchmark_onnx_cpp.md))
-云服务厂商,针对新用户,有3个月免费试用活动,申请教程([点击此处](https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/docs/aliyun_server_tutorial.md))
+云服务厂商,针对新用户,有3个月免费试用活动,申请教程([点击此处](https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/docs/aliyun_server_tutorial.md))
## 快速上手
+
+### docker安装
+如果您已安装docker,忽略本步骤!!
+通过下述命令在服务器上安装docker:
+```shell
+curl -O https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/shell/install_docker.sh;
+sudo bash install_docker.sh
+```
+
### 镜像启动
通过下述命令拉取并启动FunASR runtime-SDK的docker镜像:
```shell
sudo docker pull \
- registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-en-cpu-0.1.0
+ registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-en-cpu-0.1.1
mkdir -p ./funasr-runtime-resources/models
sudo docker run -p 10095:10095 -it --privileged=true \
-v $PWD/funasr-runtime-resources/models:/workspace/models \
- registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-en-cpu-0.1.0
+ registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-en-cpu-0.1.1
```
如果您没有安装docker,可参考[Docker安装](#Docker安装)
@@ -35,7 +44,7 @@ sudo docker run -p 10095:10095 -it --privileged=true \
docker启动之后,启动 funasr-wss-server服务程序:
```shell
-cd FunASR/funasr/runtime
+cd FunASR/runtime
nohup bash run_server.sh \
--download-model-dir /workspace/models \
--vad-dir damo/speech_fsmn_vad_zh-cn-16k-common-onnx \
@@ -112,7 +121,7 @@ python3 funasr_wss_client.py --host "127.0.0.1" --port 10095 --mode offline \
--audio_in 需要进行转写的音频文件,支持文件路径,文件列表wav.scp
--thread_num 设置并发发送线程数,默认为1
--ssl 设置是否开启ssl证书校验,默认1开启,设置为0关闭
---hotword 如果模型为热词模型,可以设置热词: *.txt(每行一个热词) 或者空格分隔的热词字符串(阿里巴巴 达摩院)
+--hotword 热词文件,每行一个热词,格式(热词 权重):阿里巴巴 20
--use_itn 设置是否使用itn,默认1开启,设置为0关闭
```
@@ -129,7 +138,7 @@ python3 funasr_wss_client.py --host "127.0.0.1" --port 10095 --mode offline \
需要改为部署机器ip
--port 10095 部署端口号
--wav-path 需要进行转写的音频文件,支持文件路径
---hotword 如果模型为热词模型,可以设置热词: *.txt(每行一个热词) 或者空格分隔的热词字符串 (阿里巴巴 达摩院)
+--hotword 热词文件,每行一个热词,格式(热词 权重):阿里巴巴 20
--use-itn 设置是否使用itn,默认1开启,设置为0关闭
```
@@ -152,7 +161,7 @@ FunasrWsClient --host localhost --port 10095 --audio_in ./asr_example.wav --mode
### 启动FunASR服务
```shell
-cd /workspace/FunASR/funasr/runtime
+cd /workspace/FunASR/runtime
nohup bash run_server.sh \
--download-model-dir /workspace/models \
--model-dir damo/speech_paraformer-large_asr_nat-en-16k-common-vocab10020-onnx \
@@ -217,11 +226,11 @@ kill -9 PID
FunASR-runtime的代码已开源,如果服务端和客户端不能很好的满足您的需求,您可以根据自己的需求进行进一步的开发:
### c++ 客户端:
-https://github.com/alibaba-damo-academy/FunASR/tree/main/funasr/runtime/websocket
+https://github.com/alibaba-damo-academy/FunASR/tree/main/runtime/websocket
### python 客户端:
-https://github.com/alibaba-damo-academy/FunASR/tree/main/funasr/runtime/python/websocket
+https://github.com/alibaba-damo-academy/FunASR/tree/main/runtime/python/websocket
### 自定义客户端:
@@ -241,7 +250,7 @@ FUNASR_RESULT result=FsmnVadInfer(vad_hanlde, wav_file.c_str(), NULL, 16000);
// 其中:vad_hanlde为FunOfflineInit返回值,wav_file为音频路径,sampling_rate为采样率(默认16k)
```
-使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp
+使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp
#### ASR
```text
@@ -252,7 +261,7 @@ FUNASR_RESULT result=FunOfflineInfer(asr_hanlde, wav_file.c_str(), RASR_NONE, NU
// 其中:asr_hanlde为FunOfflineInit返回值,wav_file为音频路径,sampling_rate为采样率(默认16k)
```
-使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline.cpp
+使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline.cpp
#### PUNC
```text
@@ -262,4 +271,4 @@ FUNASR_HANDLE punc_hanlde=CTTransformerInit(model_path, thread_num);
FUNASR_RESULT result=CTTransformerInfer(punc_hanlde, txt_str.c_str(), RASR_NONE, NULL);
// 其中:punc_hanlde为CTTransformerInit返回值,txt_str为文本
```
-使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp
+使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp
diff --git a/funasr/runtime/docs/SDK_advanced_guide_offline_zh.md b/runtime/docs/SDK_advanced_guide_offline_zh.md
similarity index 87%
rename from funasr/runtime/docs/SDK_advanced_guide_offline_zh.md
rename to runtime/docs/SDK_advanced_guide_offline_zh.md
index ee6550108..8655efc1c 100644
--- a/funasr/runtime/docs/SDK_advanced_guide_offline_zh.md
+++ b/runtime/docs/SDK_advanced_guide_offline_zh.md
@@ -13,21 +13,30 @@ FunASR提供可一键本地或者云端服务器部署的中文离线文件转
详细性能测试报告([点击此处](./benchmark_onnx_cpp.md))
-云服务厂商,针对新用户,有3个月免费试用活动,申请教程([点击此处](https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/docs/aliyun_server_tutorial.md))
+云服务厂商,针对新用户,有3个月免费试用活动,申请教程([点击此处](https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/docs/aliyun_server_tutorial.md))
## 快速上手
+
+### docker安装
+如果您已安装docker,忽略本步骤!!
+通过下述命令在服务器上安装docker:
+```shell
+curl -O https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/shell/install_docker.sh;
+sudo bash install_docker.sh
+```
+
### 镜像启动
通过下述命令拉取并启动FunASR runtime-SDK的docker镜像:
```shell
sudo docker pull \
- registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-cpu-0.2.2
+ registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-cpu-0.3.0
mkdir -p ./funasr-runtime-resources/models
sudo docker run -p 10095:10095 -it --privileged=true \
-v $PWD/funasr-runtime-resources/models:/workspace/models \
- registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-cpu-0.2.2
+ registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-cpu-0.3.0
```
如果您没有安装docker,可参考[Docker安装](#Docker安装)
@@ -35,16 +44,17 @@ sudo docker run -p 10095:10095 -it --privileged=true \
docker启动之后,启动 funasr-wss-server服务程序:
```shell
-cd FunASR/funasr/runtime
+cd FunASR/runtime
nohup bash run_server.sh \
--download-model-dir /workspace/models \
--vad-dir damo/speech_fsmn_vad_zh-cn-16k-common-onnx \
--model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-onnx \
--punc-dir damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx \
+ --lm-dir damo/speech_ngram_lm_zh-cn-ai-wesp-fst \
--itn-dir thuduj12/fst_itn_zh > log.out 2>&1 &
# 如果您想关闭ssl,增加参数:--certfile 0
-# 如果您想使用时间戳或者热词模型进行部署,请设置--model-dir为对应模型:
+# 如果您想使用时间戳或者nn热词模型进行部署,请设置--model-dir为对应模型:
# damo/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-onnx(时间戳)
# 或者 damo/speech_paraformer-large-contextual_asr_nat-zh-cn-16k-common-vocab8404-onnx(热词)
@@ -116,7 +126,7 @@ python3 funasr_wss_client.py --host "127.0.0.1" --port 10095 --mode offline \
--audio_in 需要进行转写的音频文件,支持文件路径,文件列表wav.scp
--thread_num 设置并发发送线程数,默认为1
--ssl 设置是否开启ssl证书校验,默认1开启,设置为0关闭
---hotword 如果模型为热词模型,可以设置热词: *.txt(每行一个热词) 或者空格分隔的热词字符串(阿里巴巴 达摩院)
+--hotword 热词文件,每行一个热词,格式(热词 权重):阿里巴巴 20
--use_itn 设置是否使用itn,默认1开启,设置为0关闭
```
@@ -133,7 +143,7 @@ python3 funasr_wss_client.py --host "127.0.0.1" --port 10095 --mode offline \
需要改为部署机器ip
--port 10095 部署端口号
--wav-path 需要进行转写的音频文件,支持文件路径
---hotword 如果模型为热词模型,可以设置热词: *.txt(每行一个热词) 或者空格分隔的热词字符串 (阿里巴巴 达摩院)
+--hotword 热词文件,每行一个热词,格式(热词 权重):阿里巴巴 20
--use-itn 设置是否使用itn,默认1开启,设置为0关闭
```
@@ -154,7 +164,7 @@ FunasrWsClient --host localhost --port 10095 --audio_in ./asr_example.wav --mode
### 启动FunASR服务
```shell
-cd /workspace/FunASR/funasr/runtime
+cd /workspace/FunASR/runtime
nohup bash run_server.sh \
--download-model-dir /workspace/models \
--model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-onnx \
@@ -166,7 +176,7 @@ nohup bash run_server.sh \
--port 10095 \
--certfile ../../../ssl_key/server.crt \
--keyfile ../../../ssl_key/server.key \
- --hotword ../../hotwords.txt > log.out 2>&1 &
+ --hotword ../../hotwords.txt > log.out 2>&1 &
```
**run_server.sh命令参数介绍**
```text
@@ -177,13 +187,14 @@ nohup bash run_server.sh \
--vad-quant True为量化VAD模型,False为非量化VAD模型,默认是True
--punc-dir modelscope model ID
--punc-quant True为量化PUNC模型,False为非量化PUNC模型,默认是True
+--lm-dir modelscope model ID
--itn-dir modelscope model ID
--port 服务端监听的端口号,默认为 10095
--decoder-thread-num 服务端启动的推理线程数,默认为 8
--io-thread-num 服务端启动的IO线程数,默认为 1
--certfile ssl的证书文件,默认为:../../../ssl_key/server.crt,如果需要关闭ssl,参数设置为0
--keyfile ssl的密钥文件,默认为:../../../ssl_key/server.key
---hotword 热词文件路径,每一个热词一行,如果客户端提供热词,则与客户端提供的热词合并一起使用。默认为:../../hotwords.txt
+--hotword 热词文件路径,每行一个热词,格式:热词 权重(例如:阿里巴巴 20),如果客户端提供热词,则与客户端提供的热词合并一起使用。
```
### 关闭FunASR服务
@@ -212,7 +223,8 @@ kill -9 PID
[FSMN-VAD模型](https://www.modelscope.cn/models/damo/speech_fsmn_vad_zh-cn-16k-common-onnx/summary),
[Paraformer-lagre模型](https://www.modelscope.cn/models/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-onnx/summary),
[CT-Transformer标点预测模型](https://www.modelscope.cn/models/damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx/summary),
-[基于FST的中文ITN](https://www.modelscope.cn/models/thuduj12/fst_itn_zh/summary)
+[基于FST的中文ITN](https://www.modelscope.cn/models/thuduj12/fst_itn_zh/summary),
+[Ngram中文语言模型](https://www.modelscope.cn/models/damo/speech_ngram_lm_zh-cn-ai-wesp-fst/summary)
如果,您希望部署您finetune后的模型(例如10epoch.pb),需要手动将模型重命名为model.pb,并将原modelscope中模型model.pb替换掉,将路径指定为`model_dir`即可。
@@ -222,11 +234,11 @@ kill -9 PID
FunASR-runtime的代码已开源,如果服务端和客户端不能很好的满足您的需求,您可以根据自己的需求进行进一步的开发:
### c++ 客户端:
-https://github.com/alibaba-damo-academy/FunASR/tree/main/funasr/runtime/websocket
+https://github.com/alibaba-damo-academy/FunASR/tree/main/runtime/websocket
### python 客户端:
-https://github.com/alibaba-damo-academy/FunASR/tree/main/funasr/runtime/python/websocket
+https://github.com/alibaba-damo-academy/FunASR/tree/main/runtime/python/websocket
### 自定义客户端:
@@ -246,7 +258,7 @@ FUNASR_RESULT result=FsmnVadInfer(vad_hanlde, wav_file.c_str(), NULL, 16000);
// 其中:vad_hanlde为FunOfflineInit返回值,wav_file为音频路径,sampling_rate为采样率(默认16k)
```
-使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp
+使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp
#### ASR
```text
@@ -257,7 +269,7 @@ FUNASR_RESULT result=FunOfflineInfer(asr_hanlde, wav_file.c_str(), RASR_NONE, NU
// 其中:asr_hanlde为FunOfflineInit返回值,wav_file为音频路径,sampling_rate为采样率(默认16k)
```
-使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline.cpp
+使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline.cpp
#### PUNC
```text
@@ -267,4 +279,4 @@ FUNASR_HANDLE punc_hanlde=CTTransformerInit(model_path, thread_num);
FUNASR_RESULT result=CTTransformerInfer(punc_hanlde, txt_str.c_str(), RASR_NONE, NULL);
// 其中:punc_hanlde为CTTransformerInit返回值,txt_str为文本
```
-使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp
+使用示例详见:https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp
diff --git a/funasr/runtime/docs/SDK_advanced_guide_online.md b/runtime/docs/SDK_advanced_guide_online.md
similarity index 95%
rename from funasr/runtime/docs/SDK_advanced_guide_online.md
rename to runtime/docs/SDK_advanced_guide_online.md
index e7910b969..3a26db55a 100644
--- a/funasr/runtime/docs/SDK_advanced_guide_online.md
+++ b/runtime/docs/SDK_advanced_guide_online.md
@@ -18,7 +18,7 @@ If you do not have Docker installed, please refer to [Docker Installation](https
After Docker is launched, start the funasr-wss-server-2pass service program:
```shell
-cd FunASR/funasr/runtime
+cd FunASR/runtime
nohup bash run_server_2pass.sh \
--download-model-dir /workspace/models \
--vad-dir damo/speech_fsmn_vad_zh-cn-16k-common-onnx \
@@ -61,7 +61,7 @@ For more detailed usage, please click on the links above. For more client versio
Use the flollowing script to start the server :
```shell
-cd /workspace/FunASR/funasr/runtime
+cd /workspace/FunASR/runtime
nohup bash run_server_2pass.sh \
--model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-onnx \
--online-model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-online-onnx \
@@ -76,7 +76,7 @@ nohup bash run_server_2pass.sh \
--hotword ../../hotwords.txt > log.out 2>&1 &
# If you want to close ssl,please add:--certfile 0
-# If you want to deploy the timestamp or hotword model, please set --model-dir to the corresponding model:
+# If you want to deploy the timestamp or nn hotword model, please set --model-dir to the corresponding model:
# speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-onnx(timestamp)
# damo/speech_paraformer-large-contextual_asr_nat-zh-cn-16k-common-vocab8404-onnx(hotword)
@@ -98,7 +98,7 @@ nohup bash run_server_2pass.sh \
--io-thread-num: Number of IO threads that the server starts. Default is 1.
--certfile <string>: SSL certificate file. Default is ../../../ssl_key/server.crt. If you want to close ssl,set 0
--keyfile <string>: SSL key file. Default is ../../../ssl_key/server.key.
---hotword Hotword file path, one line for each hot word, if the client provides hot words, then combined with the hot words provided by the client. Default is ../../hotwords.txt
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20), if the client provides hot words, then combined with the hot words provided by the client.
```
### Shutting Down the FunASR Service
diff --git a/funasr/runtime/docs/SDK_advanced_guide_online_zh.md b/runtime/docs/SDK_advanced_guide_online_zh.md
similarity index 93%
rename from funasr/runtime/docs/SDK_advanced_guide_online_zh.md
rename to runtime/docs/SDK_advanced_guide_online_zh.md
index 5fdcdb862..ce9165552 100644
--- a/funasr/runtime/docs/SDK_advanced_guide_online_zh.md
+++ b/runtime/docs/SDK_advanced_guide_online_zh.md
@@ -6,6 +6,15 @@ FunASR提供可便捷本地或者云端服务器部署的实时语音听写服
本文档为FunASR实时转写服务开发指南。如果您想快速体验实时语音听写服务,可参考[快速上手](#快速上手)。
## 快速上手
+
+### docker安装
+如果您已安装docker,忽略本步骤!!
+通过下述命令在服务器上安装docker:
+```shell
+curl -O https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/shell/install_docker.sh;
+sudo bash install_docker.sh
+```
+
### 镜像启动
通过下述命令拉取并启动FunASR软件包的docker镜像:
@@ -24,7 +33,7 @@ sudo docker run -p 10095:10095 -it --privileged=true \
docker启动之后,启动 funasr-wss-server-2pass服务程序:
```shell
-cd FunASR/funasr/runtime
+cd FunASR/runtime
nohup bash run_server_2pass.sh \
--download-model-dir /workspace/models \
--vad-dir damo/speech_fsmn_vad_zh-cn-16k-common-onnx \
@@ -69,7 +78,7 @@ python3 wss_client_asr.py --host "127.0.0.1" --port 10095 --mode 2pass
### 启动FunASR服务
```shell
-cd /workspace/FunASR/funasr/runtime
+cd /workspace/FunASR/runtime
nohup bash run_server_2pass.sh \
--model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-onnx \
--online-model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-online-onnx \
@@ -99,7 +108,7 @@ nohup bash run_server_2pass.sh \
--io-thread-num 服务端启动的IO线程数,默认为 1
--certfile ssl的证书文件,默认为:../../../ssl_key/server.crt,如果需要关闭ssl,参数设置为0
--keyfile ssl的密钥文件,默认为:../../../ssl_key/server.key
---hotword 热词文件路径,每一个热词一行,如果客户端提供热词,则与客户端提供的热词合并一起使用。默认为:../../hotwords.txt
+--hotword 热词文件路径,每行一个热词,格式:热词 权重(例如:阿里巴巴 20),如果客户端提供热词,则与客户端提供的热词合并一起使用。
```
### 关闭FunASR服务
diff --git a/funasr/runtime/docs/SDK_tutorial.md b/runtime/docs/SDK_tutorial.md
similarity index 95%
rename from funasr/runtime/docs/SDK_tutorial.md
rename to runtime/docs/SDK_tutorial.md
index c2579c05f..4421d8214 100644
--- a/funasr/runtime/docs/SDK_tutorial.md
+++ b/runtime/docs/SDK_tutorial.md
@@ -27,16 +27,16 @@ Cloud service providers offer a 3-month free trial for new users. Application tu
Download the deployment tool `funasr-runtime-deploy-offline-cpu-zh.sh`
```shell
-curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/funasr/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-zh.sh;
+curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-zh.sh;
# If there is a network problem, users in mainland China can use the following command:
# curl -O https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/shell/funasr-runtime-deploy-offline-cpu-zh.sh;
```
Execute the deployment tool and press the Enter key at the prompt to complete the installation and deployment of the server. Currently, the convenient deployment tool only supports Linux environments. For other environments, please refer to the development guide ([docs](./SDK_advanced_guide_offline.md)).
```shell
-sudo bash funasr-runtime-deploy-offline-cpu-zh.sh install --workspace /root/funasr-runtime-resources
+sudo bash funasr-runtime-deploy-offline-cpu-zh.sh install --workspace ./funasr-runtime-resources
```
-Note: If you need to deploy the timestamp model or hotword model, select the corresponding model in step 2 of the installation and deployment process, where 1 is the paraformer-large model, 2 is the paraformer-large timestamp model, and 3 is the paraformer-large hotword model.
+Note: If you need to deploy the timestamp model or hotword model, select the corresponding model in step 2 of the installation and deployment process, where 1 is the paraformer-large model, 2 is the paraformer-large timestamp model, and 3 is the paraformer-large hotword model;The server loads the hotword file from: ./funasr-runtime-resources/hotowrds.txt (one hotword per line, formatted as word weight: 阿里巴巴 20).
### Client Testing and Usage
@@ -73,7 +73,7 @@ Command parameter instructions:
--audio_in is the audio file that needs to be transcribed, supporting file paths and file list wav.scp
--thread_num sets the number of concurrent sending threads, default is 1
--ssl sets whether to enable SSL certificate verification, default is 1 to enable, and 0 to disable
---hotword If am is hotword model, setting hotword: *.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20)
--use_itn: whether to use itn, the default value is 1 for enabling and 0 for disabling.
```
@@ -91,7 +91,7 @@ Command parameter description:
--wav-path specifies the audio file to be transcribed, and supports file paths.
--thread_num sets the number of concurrent send threads, with a default value of 1.
--ssl sets whether to enable SSL certificate verification, with a default value of 1 for enabling and 0 for disabling.
---hotword If am is hotword model, setting hotword: *.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20)
--use-itn: whether to use itn, the default value is 1 for enabling and 0 for disabling.
```
diff --git a/funasr/runtime/docs/SDK_tutorial_en.md b/runtime/docs/SDK_tutorial_en.md
similarity index 96%
rename from funasr/runtime/docs/SDK_tutorial_en.md
rename to runtime/docs/SDK_tutorial_en.md
index be4733282..09dcf4642 100644
--- a/funasr/runtime/docs/SDK_tutorial_en.md
+++ b/runtime/docs/SDK_tutorial_en.md
@@ -27,7 +27,7 @@ Cloud service providers offer a 3-month free trial for new users. Application tu
Download the deployment tool `funasr-runtime-deploy-offline-cpu-en.sh`
```shell
-curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/funasr/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-en.sh;
+curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-en.sh;
# If there is a network problem, users in mainland China can use the following command:
# curl -O https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/shell/funasr-runtime-deploy-offline-cpu-en.sh;
```
@@ -72,7 +72,7 @@ Command parameter instructions:
--audio_in is the audio file that needs to be transcribed, supporting file paths and file list wav.scp
--thread_num sets the number of concurrent sending threads, default is 1
--ssl sets whether to enable SSL certificate verification, default is 1 to enable, and 0 to disable
---hotword If am is hotword model, setting hotword: *.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20)
--use_itn: whether to use itn, the default value is 1 for enabling and 0 for disabling.
```
@@ -90,7 +90,7 @@ Command parameter description:
--wav-path specifies the audio file to be transcribed, and supports file paths.
--thread_num sets the number of concurrent send threads, with a default value of 1.
--ssl sets whether to enable SSL certificate verification, with a default value of 1 for enabling and 0 for disabling.
---hotword If am is hotword model, setting hotword: *.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20)
--use-itn: whether to use itn, the default value is 1 for enabling and 0 for disabling.
```
diff --git a/funasr/runtime/docs/SDK_tutorial_en_zh.md b/runtime/docs/SDK_tutorial_en_zh.md
similarity index 94%
rename from funasr/runtime/docs/SDK_tutorial_en_zh.md
rename to runtime/docs/SDK_tutorial_en_zh.md
index 015036a74..9e66dd177 100644
--- a/funasr/runtime/docs/SDK_tutorial_en_zh.md
+++ b/runtime/docs/SDK_tutorial_en_zh.md
@@ -17,7 +17,7 @@ FunASR提供可便捷本地或者云端服务器部署的离线文件转写服
详细性能测试报告([点击此处](./benchmark_onnx_cpp.md))
-云服务厂商,针对新用户,有3个月免费试用活动,申请教程([点击此处](https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/docs/aliyun_server_tutorial.md))
+云服务厂商,针对新用户,有3个月免费试用活动,申请教程([点击此处](https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/docs/aliyun_server_tutorial.md))
## 快速上手
@@ -28,7 +28,7 @@ FunASR提供可便捷本地或者云端服务器部署的离线文件转写服
下载部署工具`funasr-runtime-deploy-offline-cpu-en.sh`
```shell
-curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/funasr/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-en.sh;
+curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-en.sh;
# 如遇到网络问题,中国大陆用户,可以使用下面的命令:
# curl -O https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/shell/funasr-runtime-deploy-offline-cpu-en.sh;
```
@@ -75,7 +75,7 @@ python3 funasr_wss_client.py --host "127.0.0.1" --port 10095 --mode offline --au
--audio_in 需要进行转写的音频文件,支持文件路径,文件列表wav.scp
--thread_num 设置并发发送线程数,默认为1
--ssl 设置是否开启ssl证书校验,默认1开启,设置为0关闭
---hotword 如果模型为热词模型,可以设置热词: *.txt(每行一个热词) 或者空格分隔的热词字符串 (阿里巴巴 达摩院)
+--hotword 热词文件,每行一个热词,格式(热词 权重):阿里巴巴 20
--use_itn 设置是否使用itn,默认1开启,设置为0关闭
```
@@ -94,7 +94,7 @@ python3 funasr_wss_client.py --host "127.0.0.1" --port 10095 --mode offline --au
--wav-path 需要进行转写的音频文件,支持文件路径
--thread_num 设置并发发送线程数,默认为1
--ssl 设置是否开启ssl证书校验,默认1开启,设置为0关闭
---hotword 如果模型为热词模型,可以设置热词: *.txt(每行一个热词) 或者空格分隔的热词字符串 (阿里巴巴 达摩院)
+--hotword 热词文件,每行一个热词,格式(热词 权重):阿里巴巴 20
--use-itn 设置是否使用itn,默认1开启,设置为0关闭
```
diff --git a/funasr/runtime/docs/SDK_tutorial_online.md b/runtime/docs/SDK_tutorial_online.md
similarity index 96%
rename from funasr/runtime/docs/SDK_tutorial_online.md
rename to runtime/docs/SDK_tutorial_online.md
index d7a429b12..a38502d3c 100644
--- a/funasr/runtime/docs/SDK_tutorial_online.md
+++ b/runtime/docs/SDK_tutorial_online.md
@@ -24,7 +24,7 @@ Cloud service providers offer a 3-month free trial for new users. Application tu
Download the deployment tool `funasr-runtime-deploy-online-cpu-zh.sh`
```shell
-curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/funasr/runtime/deploy_tools/funasr-runtime-deploy-online-cpu-zh.sh;
+curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/runtime/deploy_tools/funasr-runtime-deploy-online-cpu-zh.sh;
# If there is a network problem, users in mainland China can use the following command:
# curl -O https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/shell/funasr-runtime-deploy-online-cpu-zh.sh;
```
@@ -33,7 +33,7 @@ Execute the deployment tool and press the Enter key at the prompt to complete th
```shell
sudo bash funasr-runtime-deploy-online-cpu-zh.sh install --workspace ./funasr-runtime-resources
```
-Note: If you need to deploy the timestamp model or hotword model, select the corresponding model in step 2 of the installation and deployment process, where 1 is the paraformer-large model, 2 is the paraformer-large timestamp model, and 3 is the paraformer-large hotword model.
+Note: If you need to deploy the timestamp model or hotword model, select the corresponding model in step 2 of the installation and deployment process, where 1 is the paraformer-large model, 2 is the paraformer-large timestamp model, and 3 is the paraformer-large hotword model;The server loads the hotword file from: ./funasr-runtime-resources/hotowrds.txt (one hotword per line, formatted as word weight: 阿里巴巴 20).
### Client Testing and Usage
@@ -71,7 +71,7 @@ Command parameter instructions:
--audio_in is the audio file that needs to be transcribed, supporting file paths and file list wav.scp
--thread_num sets the number of concurrent sending threads, default is 1
--ssl sets whether to enable SSL certificate verification, default is 1 to enable, and 0 to disable
---hotword: If am is hotword model, setting hotword: *.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20)
--use_itn: whether to use itn, the default value is 1 for enabling and 0 for disabling.
```
@@ -91,7 +91,7 @@ Command parameter description:
--wav-path specifies the audio file to be transcribed, and supports file paths.
--threa-num sets the number of concurrent send threads, with a default value of 1.
--is-ssl sets whether to enable SSL certificate verification, with a default value of 1 for enabling and 0 for disabling.
---hotword: If am is hotword model, setting hotword: *.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)
+--hotword: Hotword file path, one line for each hotword(e.g.:阿里巴巴 20)
--use-itn: whether to use itn, the default value is 1 for enabling and 0 for disabling.
```
diff --git a/funasr/runtime/docs/SDK_tutorial_online_zh.md b/runtime/docs/SDK_tutorial_online_zh.md
similarity index 94%
rename from funasr/runtime/docs/SDK_tutorial_online_zh.md
rename to runtime/docs/SDK_tutorial_online_zh.md
index f0d447a88..21a5aa68f 100644
--- a/funasr/runtime/docs/SDK_tutorial_online_zh.md
+++ b/runtime/docs/SDK_tutorial_online_zh.md
@@ -14,7 +14,7 @@ FunASR集成了达摩院语音实验室在Modelscope社区开源的语音端点
详细性能测试报告([点击此处](./benchmark_onnx_cpp.md))
-云服务厂商,针对新用户,有3个月免费试用活动,申请教程([点击此处](https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/docs/aliyun_server_tutorial.md))
+云服务厂商,针对新用户,有3个月免费试用活动,申请教程([点击此处](https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/docs/aliyun_server_tutorial.md))
## 快速上手
@@ -25,7 +25,7 @@ FunASR集成了达摩院语音实验室在Modelscope社区开源的语音端点
下载部署工具`funasr-runtime-deploy-online-cpu-zh.sh`
```shell
-curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/funasr/runtime/deploy_tools/funasr-runtime-deploy-online-cpu-zh.sh;
+curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/runtime/deploy_tools/funasr-runtime-deploy-online-cpu-zh.sh;
# 如遇到网络问题,中国大陆用户,可以使用下面的命令:
# curl -O https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/shell/funasr-runtime-deploy-online-cpu-zh.sh;
```
@@ -34,7 +34,7 @@ curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/funas
```shell
sudo bash funasr-runtime-deploy-online-cpu-zh.sh install --workspace ./funasr-runtime-resources
```
-**注:如果需要部署时间戳模型或者热词模型,在安装部署步骤2时选择对应模型,其中1为paraformer-large模型,2为paraformer-large 时间戳模型,3为paraformer-large 热词模型**
+**注:如果需要部署时间戳模型或者热词模型,在安装部署步骤2时选择对应模型,其中1为paraformer-large模型,2为paraformer-large 时间戳模型,3为paraformer-large nn热词模型;服务端加载热词文件地址为:./funasr-runtime-resources/hotowrds.txt(每行一个热词,格式为 热词 权重:阿里巴巴 20)**
### 客户端测试与使用
@@ -76,7 +76,7 @@ python3 funasr_wss_client.py --host "127.0.0.1" --port 10095 --mode 2pass
--audio_in 需要进行转写的音频文件,支持文件路径,文件列表wav.scp
--thread_num 设置并发发送线程数,默认为1
--ssl 设置是否开启ssl证书校验,默认1开启,设置为0关闭+
---hotword 如果模型为热词模型,可以设置热词: *.txt(每行一个热词) 或者空格分隔的热词字符串 (阿里巴巴 达摩院)
+--hotword 热词文件,每行一个热词,格式(热词 权重):阿里巴巴 20
--use_itn 设置是否使用itn,默认1开启,设置为0关闭
```
@@ -99,7 +99,7 @@ python3 funasr_wss_client.py --host "127.0.0.1" --port 10095 --mode 2pass
--wav-path 需要进行转写的音频文件,支持文件路径
--thread-num 设置并发发送线程数,默认为1
--is-ssl 设置是否开启ssl证书校验,默认1开启,设置为0关闭
---hotword 如果模型为热词模型,可以设置热词: *.txt(每行一个热词) 或者空格分隔的热词字符串 (阿里巴巴 达摩院)
+--hotword 热词文件,每行一个热词,格式(热词 权重):阿里巴巴 20
--use-itn 设置是否使用itn,默认1开启,设置为0关闭
```
diff --git a/funasr/runtime/docs/SDK_tutorial_zh.md b/runtime/docs/SDK_tutorial_zh.md
similarity index 94%
rename from funasr/runtime/docs/SDK_tutorial_zh.md
rename to runtime/docs/SDK_tutorial_zh.md
index 2c0895723..e2572cdf5 100644
--- a/funasr/runtime/docs/SDK_tutorial_zh.md
+++ b/runtime/docs/SDK_tutorial_zh.md
@@ -17,7 +17,7 @@ FunASR提供可便捷本地或者云端服务器部署的离线文件转写服
详细性能测试报告([点击此处](./benchmark_onnx_cpp.md))
-云服务厂商,针对新用户,有3个月免费试用活动,申请教程([点击此处](https://github.com/alibaba-damo-academy/FunASR/blob/main/funasr/runtime/docs/aliyun_server_tutorial.md))
+云服务厂商,针对新用户,有3个月免费试用活动,申请教程([点击此处](https://github.com/alibaba-damo-academy/FunASR/blob/main/runtime/docs/aliyun_server_tutorial.md))
## 快速上手
@@ -28,7 +28,7 @@ FunASR提供可便捷本地或者云端服务器部署的离线文件转写服
下载部署工具`funasr-runtime-deploy-offline-cpu-zh.sh`
```shell
-curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/funasr/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-zh.sh;
+curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/runtime/deploy_tools/funasr-runtime-deploy-offline-cpu-zh.sh;
# 如遇到网络问题,中国大陆用户,可以使用下面的命令:
# curl -O https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/shell/funasr-runtime-deploy-offline-cpu-zh.sh;
```
@@ -37,7 +37,8 @@ curl -O https://raw.githubusercontent.com/alibaba-damo-academy/FunASR/main/funas
```shell
sudo bash funasr-runtime-deploy-offline-cpu-zh.sh install --workspace ./funasr-runtime-resources
```
-**注:如果需要部署时间戳模型或者热词模型,在安装部署步骤2时选择对应模型,其中1为paraformer-large模型,2为paraformer-large 时间戳模型,3为paraformer-large 热词模型**
+**注:如果需要部署时间戳模型或者热词模型,在安装部署步骤2时选择对应模型,其中1为paraformer-large模型,2为paraformer-large 时间戳模型,3为paraformer-large nn热词模型;服务端加载热词文件地址为:./funasr-runtime-resources/hotowrds.txt(每行一个热词,格式为 热词 权重:阿里巴巴 20)**
+
### 客户端测试与使用
@@ -76,7 +77,7 @@ python3 funasr_wss_client.py --host "127.0.0.1" --port 10095 --mode offline --au
--audio_in 需要进行转写的音频文件,支持文件路径,文件列表wav.scp
--thread_num 设置并发发送线程数,默认为1
--ssl 设置是否开启ssl证书校验,默认1开启,设置为0关闭
---hotword 如果模型为热词模型,可以设置热词: *.txt(每行一个热词) 或者空格分隔的热词字符串 (阿里巴巴 达摩院)
+--hotword 热词文件,每行一个热词,格式(热词 权重):阿里巴巴 20
--use_itn 设置是否使用itn,默认1开启,设置为0关闭
```
@@ -95,7 +96,7 @@ python3 funasr_wss_client.py --host "127.0.0.1" --port 10095 --mode offline --au
--wav-path 需要进行转写的音频文件,支持文件路径
--thread_num 设置并发发送线程数,默认为1
--ssl 设置是否开启ssl证书校验,默认1开启,设置为0关闭
---hotword 如果模型为热词模型,可以设置热词: *.txt(每行一个热词) 或者空格分隔的热词字符串 (阿里巴巴 达摩院)
+--hotword 热词文件,每行一个热词,格式(热词 权重):阿里巴巴 20
--use-itn 设置是否使用itn,默认1开启,设置为0关闭
```
diff --git a/funasr/runtime/docs/aliyun_server_tutorial.md b/runtime/docs/aliyun_server_tutorial.md
similarity index 100%
rename from funasr/runtime/docs/aliyun_server_tutorial.md
rename to runtime/docs/aliyun_server_tutorial.md
diff --git a/funasr/runtime/docs/benchmark_libtorch.md b/runtime/docs/benchmark_libtorch.md
similarity index 100%
rename from funasr/runtime/docs/benchmark_libtorch.md
rename to runtime/docs/benchmark_libtorch.md
diff --git a/funasr/runtime/docs/benchmark_onnx.md b/runtime/docs/benchmark_onnx.md
similarity index 100%
rename from funasr/runtime/docs/benchmark_onnx.md
rename to runtime/docs/benchmark_onnx.md
diff --git a/funasr/runtime/docs/benchmark_onnx_cpp.md b/runtime/docs/benchmark_onnx_cpp.md
similarity index 62%
rename from funasr/runtime/docs/benchmark_onnx_cpp.md
rename to runtime/docs/benchmark_onnx_cpp.md
index 20811af43..87162ac7f 100644
--- a/funasr/runtime/docs/benchmark_onnx_cpp.md
+++ b/runtime/docs/benchmark_onnx_cpp.md
@@ -46,7 +46,7 @@ make
## [Paraformer-large](https://www.modelscope.cn/models/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch/summary)
```shell
./funasr-onnx-offline-rtf \
- --model-dir ./asrmodel/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch \
+ --model-dir ./damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch \
--quantize true \
--wav-path ./aishell1_test.scp \
--thread-num 32
@@ -100,14 +100,14 @@ CER after int8-quant: 1.95%
| 96 (onnx fp32) | 115s | 0.003183 | 314 |
| 96 (onnx int8) | 80s | 0.002222 | 450 |
-## [FSMN-VAD](https://www.modelscope.cn/models/damo/speech_fsmn_vad_zh-cn-16k-common-pytorch/summary) + [Paraformer-large](https://www.modelscope.cn/models/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch/summary) + [CT-Transformer](https://www.modelscope.cn/models/damo/punc_ct-transformer_zh-cn-common-vocab272727-pytorch/summary)
+## [FSMN-VAD](https://www.modelscope.cn/models/damo/speech_fsmn_vad_zh-cn-16k-common-onnx/summary) + [Paraformer-large](https://www.modelscope.cn/models/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch/summary) + [CT-Transformer](https://www.modelscope.cn/models/damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx/summary)
```shell
./funasr-onnx-offline-rtf \
- --model-dir ./asrmodel/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch \
+ --model-dir ./damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch \
--quantize true \
- --vad-dir ./asrmodel/speech_fsmn_vad_zh-cn-16k-common-pytorch \
- --punc-dir ./asrmodel/punc_ct-transformer_zh-cn-common-vocab272727-pytorch \
+ --vad-dir ./damo/speech_fsmn_vad_zh-cn-16k-common-onnx \
+ --punc-dir ./damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx \
--wav-path ./aishell1_test.scp \
--thread-num 32
@@ -150,14 +150,82 @@ Node: '--quantize false' means fp32, otherwise it will be int8
| 96 (onnx fp32) | 117s | 0.003257 | 307 |
| 96 (onnx int8) | 81s | 0.002258 | 442 |
-## [FSMN-VAD](https://www.modelscope.cn/models/damo/speech_fsmn_vad_zh-cn-16k-common-pytorch/summary) + [Paraformer-en](https://www.modelscope.cn/models/damo/speech_paraformer-large_asr_nat-en-16k-common-vocab10020-onnx/summary) + [CT-Transformer](https://www.modelscope.cn/models/damo/punc_ct-transformer_zh-cn-common-vocab272727-pytorch/summary)
+
+
+## [FSMN-VAD](https://www.modelscope.cn/models/damo/speech_fsmn_vad_zh-cn-16k-common-onnx/summary) + [Paraformer-large](https://www.modelscope.cn/models/damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch/summary) +[Ngram](https://www.modelscope.cn/models/damo/speech_ngram_lm_zh-cn-ai-wesp-fst/summary) + [CT-Transformer](https://www.modelscope.cn/models/damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx/summary)
+
+```shell
+./funasr-onnx-offline-rtf \
+ --model-dir ./damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch \
+ --quantize true \
+ --vad-dir ./damo/speech_fsmn_vad_zh-cn-16k-common-onnx \
+ --punc-dir ./damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx \
+ --lm-dir ./damo/speech_ngram_lm_zh-cn-ai-wesp-fst \
+ --wav-path ./aishell1_test.scp \
+ --thread-num 32
+
+Node: '--quantize false' means fp32, otherwise it will be int8
+```
+
+ ### Intel(R) Xeon(R) Platinum 8369B CPU @ 2.90GHz 16core-32processor with avx512_vnni
+
+| concurrent-tasks | processing time(s) | RTF | Speedup Rate |
+|------------------|:------------------:|:------:|:------------:|
+| 1 (onnx fp32) | 2506s | 0.0694 | 14 |
+| 1 (onnx int8) | 1448s | 0.0401 | 25 |
+| 8 (onnx fp32) | 326s | 0.0090 | 110 |
+| 8 (onnx int8) | 184s | 0.0051 | 195 |
+| 16 (onnx fp32) | 178s | 0.0049 | 202 |
+| 16 (onnx int8) | 99s | 0.0027 | 361 |
+| 32 (onnx fp32) | 152s | 0.0042 | 236 |
+| 32 (onnx int8) | 85s | 0.0023 | 422 |
+| 64 (onnx fp32) | 157s | 0.0043 | 228 |
+| 64 (onnx int8) | 89s | 0.0024 | 403 |
+| 96 (onnx fp32) | 158s | 0.0044 | 227 |
+| 96 (onnx int8) | 91s | 0.0025 | 396 |
+
+
+```shell
+# using hotwords
+./funasr-onnx-offline-rtf \
+ --model-dir ./damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch \
+ --quantize true \
+ --vad-dir ./damo/speech_fsmn_vad_zh-cn-16k-common-onnx \
+ --punc-dir ./damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx \
+ --lm-dir ./damo/speech_ngram_lm_zh-cn-ai-wesp-fst \
+ --hotword hotwords_dev_600.txt \
+ --wav-path ./aishell1_test.scp \
+ --thread-num 32
+
+Node: '--quantize false' means fp32, otherwise it will be int8
+```
+
+ ### Intel(R) Xeon(R) Platinum 8369B CPU @ 2.90GHz 16core-32processor with avx512_vnni
+
+| concurrent-tasks | processing time(s) | RTF | Speedup Rate |
+|------------------|:------------------:|:------:|:------------:|
+| 1 (onnx fp32) | 3172s | 0.0878 | 11 |
+| 1 (onnx int8) | 2140s | 0.0592 | 16 |
+| 8 (onnx fp32) | 412s | 0.0114 | 87 |
+| 8 (onnx int8) | 268s | 0.0074 | 134 |
+| 16 (onnx fp32) | 218s | 0.0060 | 165 |
+| 16 (onnx int8) | 140s | 0.0038 | 257 |
+| 32 (onnx fp32) | 183s | 0.0050 | 196 |
+| 32 (onnx int8) | 116s | 0.0032 | 310 |
+| 64 (onnx fp32) | 188s | 0.0052 | 192 |
+| 64 (onnx int8) | 120s | 0.0033 | 299 |
+| 96 (onnx fp32) | 191s | 0.0052 | 188 |
+| 96 (onnx int8) | 122s | 0.0033 | 294 |
+
+
+## [FSMN-VAD](https://www.modelscope.cn/models/damo/speech_fsmn_vad_zh-cn-16k-common-onnx/summary) + [Paraformer-en](https://www.modelscope.cn/models/damo/speech_paraformer-large_asr_nat-en-16k-common-vocab10020-onnx/summary) + [CT-Transformer](https://www.modelscope.cn/models/damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx/summary)
```shell
./funasr-onnx-offline-rtf \
- --model-dir ./asrmodel/speech_paraformer-large_asr_nat-en-16k-common-vocab10020-onnx \
+ --model-dir ./damo/speech_paraformer-large_asr_nat-en-16k-common-vocab10020-onnx \
--quantize true \
- --vad-dir ./asrmodel/speech_fsmn_vad_zh-cn-16k-common-pytorch \
- --punc-dir ./asrmodel/punc_ct-transformer_zh-cn-common-vocab272727-pytorch \
+ --vad-dir ./damo/speech_fsmn_vad_zh-cn-16k-common-onnx \
+ --punc-dir ./damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx \
--wav-path ./librispeech_test_clean.scp \
--thread-num 32
diff --git a/funasr/runtime/docs/docker_offline_cpu_en_lists b/runtime/docs/docker_offline_cpu_en_lists
similarity index 87%
rename from funasr/runtime/docs/docker_offline_cpu_en_lists
rename to runtime/docs/docker_offline_cpu_en_lists
index e826c74b9..fb3192f2a 100644
--- a/funasr/runtime/docs/docker_offline_cpu_en_lists
+++ b/runtime/docs/docker_offline_cpu_en_lists
@@ -1,5 +1,5 @@
DOCKER:
- funasr-runtime-sdk-en-cpu-0.1.0
+ funasr-runtime-sdk-en-cpu-0.1.1
DEFAULT_ASR_MODEL:
damo/speech_paraformer-large_asr_nat-en-16k-common-vocab10020-onnx
DEFAULT_VAD_MODEL:
diff --git a/funasr/runtime/docs/docker_offline_cpu_zh_lists b/runtime/docs/docker_offline_cpu_zh_lists
similarity index 82%
rename from funasr/runtime/docs/docker_offline_cpu_zh_lists
rename to runtime/docs/docker_offline_cpu_zh_lists
index df6eddbea..4651784f9 100644
--- a/funasr/runtime/docs/docker_offline_cpu_zh_lists
+++ b/runtime/docs/docker_offline_cpu_zh_lists
@@ -1,7 +1,7 @@
DOCKER:
+ funasr-runtime-sdk-cpu-0.3.0
funasr-runtime-sdk-cpu-0.2.2
funasr-runtime-sdk-cpu-0.2.1
- funasr-runtime-sdk-cpu-0.2.0
DEFAULT_ASR_MODEL:
damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-onnx
damo/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-onnx
@@ -10,3 +10,6 @@ DEFAULT_VAD_MODEL:
damo/speech_fsmn_vad_zh-cn-16k-common-onnx
DEFAULT_PUNC_MODEL:
damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx
+DEFAULT_LM_MODEL:
+ damo/speech_ngram_lm_zh-cn-ai-wesp-fst
+ NONE
diff --git a/funasr/runtime/docs/docker_online_cpu_zh_lists b/runtime/docs/docker_online_cpu_zh_lists
similarity index 93%
rename from funasr/runtime/docs/docker_online_cpu_zh_lists
rename to runtime/docs/docker_online_cpu_zh_lists
index 46bd196be..903d2b470 100644
--- a/funasr/runtime/docs/docker_online_cpu_zh_lists
+++ b/runtime/docs/docker_online_cpu_zh_lists
@@ -1,7 +1,7 @@
DOCKER:
+ funasr-runtime-sdk-online-cpu-0.1.4
funasr-runtime-sdk-online-cpu-0.1.3
funasr-runtime-sdk-online-cpu-0.1.2
- funasr-runtime-sdk-online-cpu-0.1.1
DEFAULT_ASR_MODEL:
damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-onnx
damo/speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-onnx
diff --git a/funasr/runtime/docs/images/2pass.jpg b/runtime/docs/images/2pass.jpg
similarity index 100%
rename from funasr/runtime/docs/images/2pass.jpg
rename to runtime/docs/images/2pass.jpg
diff --git a/funasr/runtime/docs/images/aliyun1.png b/runtime/docs/images/aliyun1.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun1.png
rename to runtime/docs/images/aliyun1.png
diff --git a/funasr/runtime/docs/images/aliyun10.png b/runtime/docs/images/aliyun10.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun10.png
rename to runtime/docs/images/aliyun10.png
diff --git a/funasr/runtime/docs/images/aliyun11.png b/runtime/docs/images/aliyun11.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun11.png
rename to runtime/docs/images/aliyun11.png
diff --git a/funasr/runtime/docs/images/aliyun12.png b/runtime/docs/images/aliyun12.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun12.png
rename to runtime/docs/images/aliyun12.png
diff --git a/funasr/runtime/docs/images/aliyun2.png b/runtime/docs/images/aliyun2.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun2.png
rename to runtime/docs/images/aliyun2.png
diff --git a/funasr/runtime/docs/images/aliyun3.png b/runtime/docs/images/aliyun3.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun3.png
rename to runtime/docs/images/aliyun3.png
diff --git a/funasr/runtime/docs/images/aliyun4.png b/runtime/docs/images/aliyun4.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun4.png
rename to runtime/docs/images/aliyun4.png
diff --git a/funasr/runtime/docs/images/aliyun5.png b/runtime/docs/images/aliyun5.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun5.png
rename to runtime/docs/images/aliyun5.png
diff --git a/funasr/runtime/docs/images/aliyun6.png b/runtime/docs/images/aliyun6.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun6.png
rename to runtime/docs/images/aliyun6.png
diff --git a/funasr/runtime/docs/images/aliyun7.png b/runtime/docs/images/aliyun7.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun7.png
rename to runtime/docs/images/aliyun7.png
diff --git a/funasr/runtime/docs/images/aliyun8.png b/runtime/docs/images/aliyun8.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun8.png
rename to runtime/docs/images/aliyun8.png
diff --git a/funasr/runtime/docs/images/aliyun9.png b/runtime/docs/images/aliyun9.png
similarity index 100%
rename from funasr/runtime/docs/images/aliyun9.png
rename to runtime/docs/images/aliyun9.png
diff --git a/funasr/runtime/docs/images/html.png b/runtime/docs/images/html.png
similarity index 100%
rename from funasr/runtime/docs/images/html.png
rename to runtime/docs/images/html.png
diff --git a/runtime/docs/lm_train_tutorial.md b/runtime/docs/lm_train_tutorial.md
new file mode 100644
index 000000000..e0b427b93
--- /dev/null
+++ b/runtime/docs/lm_train_tutorial.md
@@ -0,0 +1,40 @@
+# 如何训练LM
+
+训练脚本详见([点击此处](../tools/train_compile_ngram.sh))
+
+## 数据准备
+```shell
+# 下载: 示例训练语料text、lexicon 和 am建模单元units.txt
+wget https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/requirements/lm.tar.gz
+tar -zxvf lm.tar.gz
+```
+
+## 训练arpa
+```shell
+# make sure that srilm is installed
+# the format of the text should be:
+# BAC009S0002W0122 而 对 楼市 成交 抑制 作用 最 大 的 限 购
+# BAC009S0002W0123 也 成为 地方 政府 的 眼中 钉
+
+bash fst/train_lms.sh
+```
+
+## 生成lexicon
+```shell
+python3 fst/generate_lexicon.py lm/corpus.dict lm/lexicon.txt lm/lexicon.out
+```
+
+## 编译TLG.fst
+```shell
+# Compile the lexicon and token FSTs
+fst/compile_dict_token.sh lm lm/tmp lm/lang
+
+# Compile the language-model FST and the final decoding graph TLG.fst
+fst/make_decode_graph.sh lm lm/lang || exit 1;
+
+# Collect resource files required for decoding
+fst/collect_resource_file.sh lm lm/resource
+
+#编译后的模型资源位于 lm/resource
+```
+
diff --git a/funasr/runtime/docs/websocket_protocol.md b/runtime/docs/websocket_protocol.md
similarity index 87%
rename from funasr/runtime/docs/websocket_protocol.md
rename to runtime/docs/websocket_protocol.md
index cc4052fb3..f03b6881e 100644
--- a/funasr/runtime/docs/websocket_protocol.md
+++ b/runtime/docs/websocket_protocol.md
@@ -10,7 +10,7 @@ Configuration parameters and meta information are in JSON format, while audio da
#### Initial Communication
The message (which needs to be serialized in JSON) is:
```text
-{"mode": "offline", "wav_name": "wav_name","wav_format":"pcm","is_speaking": True,"wav_format":"pcm","hotwords":"阿里巴巴 达摩院 阿里云","itn":true}
+{"mode": "offline", "wav_name": "wav_name", "wav_format":"pcm", "is_speaking": True, "wav_format":"pcm", "hotwords":"{"阿里巴巴":20,"通义实验室":30}", "itn":True}
```
Parameter explanation:
```text
@@ -19,7 +19,7 @@ Parameter explanation:
`wav_format`: the audio and video file extension, such as pcm, mp3, mp4, etc.
`is_speaking`: False indicates the end of a sentence, such as a VAD segmentation point or the end of a WAV file
`audio_fs`: when the input audio is in PCM format, the audio sampling rate parameter needs to be added
-`hotwords`:If AM is the hotword model, hotword data needs to be sent to the server in string format, with " " used as a separator between hotwords. For example:"阿里巴巴 达摩院 阿里云"
+`hotwords`:If using the hotword, you need to send the hotword data (string) to the server. For example:"{"阿里巴巴":20,"通义实验室":30}"
`itn`: whether to use itn, the default value is true for enabling and false for disabling.
```
@@ -59,7 +59,7 @@ Configuration parameters and meta information are in JSON format, while audio da
#### Initial Communication
The message (which needs to be serialized in JSON) is:
```text
-{"mode": "2pass", "wav_name": "wav_name", "is_speaking": True, "wav_format":"pcm", "chunk_size":[5,10,5],"hotwords":"阿里巴巴 达摩院 阿里云","itn":true}
+{"mode": "2pass", "wav_name": "wav_name", "is_speaking": True, "wav_format":"pcm", "chunk_size":[5,10,5],"hotwords":"{"阿里巴巴":20,"通义实验室":30}","itn":true}
```
Parameter explanation:
```text
@@ -69,7 +69,7 @@ Parameter explanation:
`is_speaking`: False indicates the end of a sentence, such as a VAD segmentation point or the end of a WAV file
`chunk_size`: indicates the latency configuration of the streaming model, `[5,10,5]` indicates that the current audio is 600ms long, with a 300ms look-ahead and look-back time.
`audio_fs`: when the input audio is in PCM format, the audio sampling rate parameter needs to be added
-`hotwords`:If AM is the hotword model, hotword data needs to be sent to the server in string format, with " " used as a separator between hotwords. For example:"阿里巴巴 达摩院 阿里云"
+`hotwords`:If using the hotword, you need to send the hotword data (string) to the server. For example:"{"阿里巴巴":20,"通义实验室":30}"
`itn`: whether to use itn, the default value is true for enabling and false for disabling.
```
#### Sending Audio Data
diff --git a/funasr/runtime/docs/websocket_protocol_zh.md b/runtime/docs/websocket_protocol_zh.md
similarity index 85%
rename from funasr/runtime/docs/websocket_protocol_zh.md
rename to runtime/docs/websocket_protocol_zh.md
index 8d5888e80..cfba8f202 100644
--- a/funasr/runtime/docs/websocket_protocol_zh.md
+++ b/runtime/docs/websocket_protocol_zh.md
@@ -10,7 +10,7 @@
#### 首次通信
message为(需要用json序列化):
```text
-{"mode": "offline", "wav_name": "wav_name","wav_format":"pcm","is_speaking": True,"hotwords":"阿里巴巴 达摩院 阿里云","itn":True}
+{"mode": "offline", "wav_name": "wav_name", "wav_format":"pcm", "is_speaking": True, "hotwords":"{"阿里巴巴":20,"通义实验室":30}", "itn":True}
```
参数介绍:
```text
@@ -19,9 +19,10 @@ message为(需要用json序列化):
`wav_format`:表示音视频文件后缀名,可选pcm、mp3、mp4等
`is_speaking`:False 表示断句尾点,例如,vad切割点,或者一条wav结束
`audio_fs`:当输入音频为pcm数据时,需要加上音频采样率参数
-`hotwords`:如果AM为热词模型,需要向服务端发送热词数据,格式为字符串,热词之间用" "分隔,例如 "阿里巴巴 达摩院 阿里云"
+`hotwords`:如果使用热词,需要向服务端发送热词数据(字符串),格式为 "{"阿里巴巴":20,"通义实验室":30}"
`itn`: 设置是否使用itn,默认True
```
+注:热词权重仅在fst热词服务下生效。
#### 发送音频数据
pcm直接将音频数据,其他格式音频数据,连同头部信息与音视频bytes数据发送,支持多种采样率与音视频格式
@@ -59,7 +60,7 @@ message为(采用json序列化)
#### 首次通信
message为(需要用json序列化):
```text
-{"mode": "2pass", "wav_name": "wav_name", "is_speaking": True, "wav_format":"pcm", "chunk_size":[5,10,5], "hotwords":"阿里巴巴 达摩院 阿里云","itn":True}
+{"mode": "2pass", "wav_name": "wav_name", "is_speaking": True, "wav_format":"pcm", "chunk_size":[5,10,5], "hotwords":"{"阿里巴巴":20,"通义实验室":30}","itn":True}
```
参数介绍:
```text
@@ -69,9 +70,11 @@ message为(需要用json序列化):
`is_speaking`:表示断句尾点,例如,vad切割点,或者一条wav结束
`chunk_size`:表示流式模型latency配置,`[5,10,5]`,表示当前音频为600ms,并且回看300ms,又看300ms。
`audio_fs`:当输入音频为pcm数据是,需要加上音频采样率参数
-`hotwords`:如果AM为热词模型,需要向服务端发送热词数据,格式为字符串,热词之间用" "分隔,例如 "阿里巴巴 达摩院 阿里云"
+`hotwords`:如果使用热词,需要向服务端发送热词数据(字符串),格式为 "{"阿里巴巴":20,"通义实验室":30}"
`itn`: 设置是否使用itn,默认True
```
+注:热词权重仅在fst热词服务下生效。
+
#### 发送音频数据
直接将音频数据,移除头部信息后的bytes数据发送,支持音频采样率为8000(`message`中需要指定`audio_fs`为8000),16000
#### 发送结束标志
diff --git a/funasr/runtime/grpc/CMakeLists.txt b/runtime/grpc/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/grpc/CMakeLists.txt
rename to runtime/grpc/CMakeLists.txt
diff --git a/funasr/runtime/grpc/Readme.md b/runtime/grpc/Readme.md
similarity index 100%
rename from funasr/runtime/grpc/Readme.md
rename to runtime/grpc/Readme.md
diff --git a/funasr/runtime/grpc/build.sh b/runtime/grpc/build.sh
similarity index 100%
rename from funasr/runtime/grpc/build.sh
rename to runtime/grpc/build.sh
diff --git a/funasr/runtime/grpc/common.cmake b/runtime/grpc/common.cmake
similarity index 100%
rename from funasr/runtime/grpc/common.cmake
rename to runtime/grpc/common.cmake
diff --git a/funasr/runtime/grpc/paraformer-server.cc b/runtime/grpc/paraformer-server.cc
similarity index 100%
rename from funasr/runtime/grpc/paraformer-server.cc
rename to runtime/grpc/paraformer-server.cc
diff --git a/funasr/runtime/grpc/paraformer-server.h b/runtime/grpc/paraformer-server.h
similarity index 100%
rename from funasr/runtime/grpc/paraformer-server.h
rename to runtime/grpc/paraformer-server.h
diff --git a/funasr/runtime/grpc/run_server.sh b/runtime/grpc/run_server.sh
similarity index 100%
rename from funasr/runtime/grpc/run_server.sh
rename to runtime/grpc/run_server.sh
diff --git a/funasr/runtime/html5/h5Server.py b/runtime/html5/h5Server.py
similarity index 100%
rename from funasr/runtime/html5/h5Server.py
rename to runtime/html5/h5Server.py
diff --git a/funasr/runtime/html5/readme.md b/runtime/html5/readme.md
similarity index 100%
rename from funasr/runtime/html5/readme.md
rename to runtime/html5/readme.md
diff --git a/funasr/runtime/html5/readme_zh.md b/runtime/html5/readme_zh.md
similarity index 100%
rename from funasr/runtime/html5/readme_zh.md
rename to runtime/html5/readme_zh.md
diff --git a/funasr/runtime/html5/ssl_key b/runtime/html5/ssl_key
similarity index 100%
rename from funasr/runtime/html5/ssl_key
rename to runtime/html5/ssl_key
diff --git a/funasr/runtime/html5/static/index.html b/runtime/html5/static/index.html
similarity index 88%
rename from funasr/runtime/html5/static/index.html
rename to runtime/html5/static/index.html
index 27be9080a..3aeda038d 100644
--- a/funasr/runtime/html5/static/index.html
+++ b/runtime/html5/static/index.html
@@ -51,13 +51,15 @@
</div>
<br>
-
- 热词设置(空格隔开,如"阿里巴巴 达摩院 阿里云"):
- <br>
-
- <input type="text" id="varHot" style=" width: 100%;height:100%" />
- <br>
-
+ <div style="border:2px solid #ccc;">
+ 热词设置(一行一个关键字,空格隔开权重,如"阿里巴巴 20"):
+ <br>
+
+
+ <textarea rows="3" id="varHot" style=" width: 100%;height:100%" >阿里巴巴 20</textarea>
+ <br>
+
+ </div>
语音识别结果显示:
<br>
diff --git a/funasr/runtime/html5/static/main.js b/runtime/html5/static/main.js
similarity index 91%
rename from funasr/runtime/html5/static/main.js
rename to runtime/html5/static/main.js
index 38811cd41..52a8d96d8 100644
--- a/funasr/runtime/html5/static/main.js
+++ b/runtime/html5/static/main.js
@@ -255,15 +255,35 @@ function on_recoder_mode_change()
}
}
+
+
function getHotwords(){
- var obj = document.getElementById("varHot");
+
+ var obj = document.getElementById("varHot");
+
+ if(typeof(obj) == 'undefined' || obj==null || obj.value.length<=0){
+ return "";
+ }
+ let val = obj.value.toString();
- if(typeof(obj) == 'undefined' || obj==null || obj.value.length<=0){
- return "";
- }
- let val = obj.value.toString();
- console.log("hotwords="+val);
- return val;
+ console.log("hotwords="+val);
+ let items = val.split(/[(\r\n)\r\n]+/); //split by \r\n
+ var jsonresult = {};
+ const regexNum = /^[0-9]*$/; // test number
+ for (item of items) {
+
+ let result = item.split(" ");
+ if(result.length>=2 && regexNum.test(result[result.length-1]))
+ {
+ var wordstr="";
+ for(var i=0;i<result.length-1;i++)
+ wordstr=wordstr+result[i]+" ";
+
+ jsonresult[wordstr.trim()]=result[result.length-1];
+ }
+ }
+ console.log("jsonresult="+JSON.stringify(jsonresult));
+ return jsonresult;
}
function getAsrMode(){
diff --git a/funasr/runtime/html5/static/pcm.js b/runtime/html5/static/pcm.js
similarity index 100%
rename from funasr/runtime/html5/static/pcm.js
rename to runtime/html5/static/pcm.js
diff --git a/funasr/runtime/html5/static/recorder-core.js b/runtime/html5/static/recorder-core.js
similarity index 100%
rename from funasr/runtime/html5/static/recorder-core.js
rename to runtime/html5/static/recorder-core.js
diff --git a/funasr/runtime/html5/static/wav.js b/runtime/html5/static/wav.js
similarity index 100%
rename from funasr/runtime/html5/static/wav.js
rename to runtime/html5/static/wav.js
diff --git a/funasr/runtime/html5/static/wsconnecter.js b/runtime/html5/static/wsconnecter.js
similarity index 95%
rename from funasr/runtime/html5/static/wsconnecter.js
rename to runtime/html5/static/wsconnecter.js
index ee0bcca92..b9a786de5 100644
--- a/funasr/runtime/html5/static/wsconnecter.js
+++ b/runtime/html5/static/wsconnecter.js
@@ -83,6 +83,7 @@ function WebSocketConnectMethod( config ) { //定义socket连接方法类
request.audio_fs=file_sample_rate;
}
}
+
var hotwords=getHotwords();
if(hotwords.length>0)
{
diff --git a/funasr/runtime/ios/Readme.md b/runtime/ios/Readme.md
similarity index 100%
rename from funasr/runtime/ios/Readme.md
rename to runtime/ios/Readme.md
diff --git a/funasr/runtime/ios/paraformer_online/Podfile b/runtime/ios/paraformer_online/Podfile
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/Podfile
rename to runtime/ios/paraformer_online/Podfile
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.pbxproj b/runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.pbxproj
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.pbxproj
rename to runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.pbxproj
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.xcworkspace/contents.xcworkspacedata
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.xcworkspace/contents.xcworkspacedata
rename to runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.xcworkspace/contents.xcworkspacedata
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.xcworkspace/xcuserdata/qiuwei.xcuserdatad/UserInterfaceState.xcuserstate b/runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.xcworkspace/xcuserdata/qiuwei.xcuserdatad/UserInterfaceState.xcuserstate
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.xcworkspace/xcuserdata/qiuwei.xcuserdatad/UserInterfaceState.xcuserstate
rename to runtime/ios/paraformer_online/paraformer_online.xcodeproj/project.xcworkspace/xcuserdata/qiuwei.xcuserdatad/UserInterfaceState.xcuserstate
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online.xcodeproj/xcuserdata/qiuwei.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/runtime/ios/paraformer_online/paraformer_online.xcodeproj/xcuserdata/qiuwei.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online.xcodeproj/xcuserdata/qiuwei.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist
rename to runtime/ios/paraformer_online/paraformer_online.xcodeproj/xcuserdata/qiuwei.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online.xcodeproj/xcuserdata/qiuwei.xcuserdatad/xcschemes/xcschememanagement.plist b/runtime/ios/paraformer_online/paraformer_online.xcodeproj/xcuserdata/qiuwei.xcuserdatad/xcschemes/xcschememanagement.plist
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online.xcodeproj/xcuserdata/qiuwei.xcuserdatad/xcschemes/xcschememanagement.plist
rename to runtime/ios/paraformer_online/paraformer_online.xcodeproj/xcuserdata/qiuwei.xcuserdatad/xcschemes/xcschememanagement.plist
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/AppDelegate.h b/runtime/ios/paraformer_online/paraformer_online/AppDelegate.h
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/AppDelegate.h
rename to runtime/ios/paraformer_online/paraformer_online/AppDelegate.h
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/AppDelegate.m b/runtime/ios/paraformer_online/paraformer_online/AppDelegate.m
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/AppDelegate.m
rename to runtime/ios/paraformer_online/paraformer_online/AppDelegate.m
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/AccentColor.colorset/Contents.json b/runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/AccentColor.colorset/Contents.json
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/AccentColor.colorset/Contents.json
rename to runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/AccentColor.colorset/Contents.json
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/AppIcon.appiconset/Contents.json b/runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/AppIcon.appiconset/Contents.json
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/AppIcon.appiconset/Contents.json
rename to runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/AppIcon.appiconset/Contents.json
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/Contents.json b/runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/Contents.json
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/Contents.json
rename to runtime/ios/paraformer_online/paraformer_online/Assets.xcassets/Contents.json
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/AudioCapture.h b/runtime/ios/paraformer_online/paraformer_online/AudioCapture.h
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/AudioCapture.h
rename to runtime/ios/paraformer_online/paraformer_online/AudioCapture.h
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/AudioCapture.mm b/runtime/ios/paraformer_online/paraformer_online/AudioCapture.mm
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/AudioCapture.mm
rename to runtime/ios/paraformer_online/paraformer_online/AudioCapture.mm
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/AudioRecorder.h b/runtime/ios/paraformer_online/paraformer_online/AudioRecorder.h
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/AudioRecorder.h
rename to runtime/ios/paraformer_online/paraformer_online/AudioRecorder.h
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/AudioRecorder.m b/runtime/ios/paraformer_online/paraformer_online/AudioRecorder.m
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/AudioRecorder.m
rename to runtime/ios/paraformer_online/paraformer_online/AudioRecorder.m
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/Base.lproj/LaunchScreen.storyboard b/runtime/ios/paraformer_online/paraformer_online/Base.lproj/LaunchScreen.storyboard
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/Base.lproj/LaunchScreen.storyboard
rename to runtime/ios/paraformer_online/paraformer_online/Base.lproj/LaunchScreen.storyboard
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/Base.lproj/Main.storyboard b/runtime/ios/paraformer_online/paraformer_online/Base.lproj/Main.storyboard
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/Base.lproj/Main.storyboard
rename to runtime/ios/paraformer_online/paraformer_online/Base.lproj/Main.storyboard
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/Info.plist b/runtime/ios/paraformer_online/paraformer_online/Info.plist
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/Info.plist
rename to runtime/ios/paraformer_online/paraformer_online/Info.plist
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/SceneDelegate.h b/runtime/ios/paraformer_online/paraformer_online/SceneDelegate.h
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/SceneDelegate.h
rename to runtime/ios/paraformer_online/paraformer_online/SceneDelegate.h
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/SceneDelegate.m b/runtime/ios/paraformer_online/paraformer_online/SceneDelegate.m
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/SceneDelegate.m
rename to runtime/ios/paraformer_online/paraformer_online/SceneDelegate.m
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/ViewController.h b/runtime/ios/paraformer_online/paraformer_online/ViewController.h
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/ViewController.h
rename to runtime/ios/paraformer_online/paraformer_online/ViewController.h
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/ViewController.mm b/runtime/ios/paraformer_online/paraformer_online/ViewController.mm
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/ViewController.mm
rename to runtime/ios/paraformer_online/paraformer_online/ViewController.mm
diff --git a/funasr/runtime/ios/paraformer_online/paraformer_online/main.m b/runtime/ios/paraformer_online/paraformer_online/main.m
similarity index 100%
rename from funasr/runtime/ios/paraformer_online/paraformer_online/main.m
rename to runtime/ios/paraformer_online/paraformer_online/main.m
diff --git a/funasr/runtime/java/FunasrWsClient.java b/runtime/java/FunasrWsClient.java
similarity index 90%
rename from funasr/runtime/java/FunasrWsClient.java
rename to runtime/java/FunasrWsClient.java
index 74a8695e3..2037c9a8a 100644
--- a/funasr/runtime/java/FunasrWsClient.java
+++ b/runtime/java/FunasrWsClient.java
@@ -27,7 +27,8 @@ import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
/** This example demonstrates how to connect to websocket server. */
public class FunasrWsClient extends WebSocketClient {
@@ -79,10 +80,34 @@ public class FunasrWsClient extends WebSocketClient {
obj.put("chunk_size", array);
obj.put("chunk_interval", new Integer(chunkInterval));
obj.put("wav_name", wavName);
+
if(FunasrWsClient.hotwords.trim().length()>0)
{
- obj.put("hotwords", FunasrWsClient.hotwords.trim());
+ String regex = "\\d+";
+ JSONObject jsonitems = new JSONObject();
+ String[] items=FunasrWsClient.hotwords.trim().split(" ");
+ Pattern pattern = Pattern.compile(regex);
+ String tmpWords="";
+ for(int i=0;i<items.length;i++)
+ {
+
+ Matcher matcher = pattern.matcher(items[i]);
+
+ if (matcher.matches()) {
+
+ jsonitems.put(tmpWords.trim(), items[i].trim());
+ tmpWords="";
+ continue;
+ }
+ tmpWords=tmpWords+items[i]+" ";
+
+ }
+
+
+
+ obj.put("hotwords", jsonitems.toString());
}
+
if(suffix.equals("wav")){
suffix="pcm";
}
@@ -231,6 +256,7 @@ public class FunasrWsClient extends WebSocketClient {
static int chunkInterval = 10;
static int sendChunkSize = 1920;
static String hotwords="";
+ static String fsthotwords="";
String wavName = "javatest";
@@ -281,7 +307,7 @@ public class FunasrWsClient extends WebSocketClient {
.required(false);
parser
.addArgument("--hotwords")
- .help("hotwords, splited by space")
+ .help("hotwords, splited by space, hello 30 nihao 40")
.setDefault("")
.type(String.class)
.required(false);
diff --git a/funasr/runtime/java/Makefile b/runtime/java/Makefile
similarity index 100%
rename from funasr/runtime/java/Makefile
rename to runtime/java/Makefile
diff --git a/funasr/runtime/java/readme.md b/runtime/java/readme.md
similarity index 100%
rename from funasr/runtime/java/readme.md
rename to runtime/java/readme.md
diff --git a/funasr/runtime/onnxruntime/CMakeLists.txt b/runtime/onnxruntime/CMakeLists.txt
similarity index 93%
rename from funasr/runtime/onnxruntime/CMakeLists.txt
rename to runtime/onnxruntime/CMakeLists.txt
index 64d1c8250..2f193b022 100644
--- a/funasr/runtime/onnxruntime/CMakeLists.txt
+++ b/runtime/onnxruntime/CMakeLists.txt
@@ -29,11 +29,12 @@ ELSE()
link_directories(${ONNXRUNTIME_DIR}/lib)
link_directories(${FFMPEG_DIR}/lib)
endif()
-
+include_directories(${CMAKE_SOURCE_DIR}/src)
include_directories(${PROJECT_SOURCE_DIR}/third_party/kaldi-native-fbank)
include_directories(${PROJECT_SOURCE_DIR}/third_party/yaml-cpp/include)
include_directories(${PROJECT_SOURCE_DIR}/third_party/jieba/include)
include_directories(${PROJECT_SOURCE_DIR}/third_party/jieba/include/limonp/include)
+include_directories(${PROJECT_SOURCE_DIR}/third_party/kaldi)
if(ENABLE_GLOG)
include_directories(${PROJECT_SOURCE_DIR}/third_party/glog/src)
@@ -58,5 +59,6 @@ endif()
add_subdirectory(third_party/yaml-cpp)
add_subdirectory(third_party/kaldi-native-fbank/kaldi-native-fbank/csrc)
+add_subdirectory(third_party/kaldi)
add_subdirectory(src)
add_subdirectory(bin)
diff --git a/funasr/runtime/onnxruntime/CMakeSettings.json b/runtime/onnxruntime/CMakeSettings.json
similarity index 100%
rename from funasr/runtime/onnxruntime/CMakeSettings.json
rename to runtime/onnxruntime/CMakeSettings.json
diff --git a/funasr/runtime/onnxruntime/bin/CMakeLists.txt b/runtime/onnxruntime/bin/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/bin/CMakeLists.txt
rename to runtime/onnxruntime/bin/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/bin/funasr-onnx-2pass-rtf.cpp b/runtime/onnxruntime/bin/funasr-onnx-2pass-rtf.cpp
similarity index 94%
rename from funasr/runtime/onnxruntime/bin/funasr-onnx-2pass-rtf.cpp
rename to runtime/onnxruntime/bin/funasr-onnx-2pass-rtf.cpp
index 3a00e7322..5bf8f18ae 100644
--- a/funasr/runtime/onnxruntime/bin/funasr-onnx-2pass-rtf.cpp
+++ b/runtime/onnxruntime/bin/funasr-onnx-2pass-rtf.cpp
@@ -17,6 +17,7 @@
#include <mutex>
#include <thread>
#include <glog/logging.h>
+#include "util.h"
#include "funasrruntime.h"
#include "tclap/CmdLine.h"
#include "com-define.h"
@@ -42,16 +43,15 @@ void GetValue(TCLAP::ValueArg<std::string>& value_arg, string key, std::map<std:
LOG(INFO)<< key << " : " << value_arg.getValue();
}
-
void runReg(FUNASR_HANDLE tpass_handle, std::vector<int> chunk_size, vector<string> wav_list, vector<string> wav_ids,
- float* total_length, long* total_time, int core_id, ASR_TYPE asr_mode_, string hotwords) {
+ float* total_length, long* total_time, int core_id, ASR_TYPE asr_mode_, string nn_hotwords_) {
struct timeval start, end;
long seconds = 0;
float n_total_length = 0.0f;
long n_total_time = 0;
- std::vector<std::vector<float>> hotwords_embedding = CompileHotwordEmbedding(tpass_handle, hotwords, ASR_TWO_PASS);
+ std::vector<std::vector<float>> hotwords_embedding = CompileHotwordEmbedding(tpass_handle, nn_hotwords_, ASR_TWO_PASS);
// init online features
FUNASR_HANDLE tpass_online_handle=FunTpassOnlineInit(tpass_handle, chunk_size);
@@ -220,7 +220,7 @@ int main(int argc, char** argv)
TCLAP::ValueArg<std::int32_t> onnx_thread("", "model-thread-num", "onnxruntime SetIntraOpNumThreads", false, 1, "int32_t");
TCLAP::ValueArg<std::int32_t> thread_num_("", THREAD_NUM, "multi-thread num for rtf", false, 1, "int32_t");
TCLAP::ValueArg<std::string> wav_path("", WAV_PATH, "the input could be: wav_path, e.g.: asr_example.wav; pcm_path, e.g.: asr_example.pcm; wav.scp, kaldi style wav list (wav_id \t wav_path)", true, "", "string");
- TCLAP::ValueArg<std::string> hotword("", HOTWORD, "*.txt(one hotword perline) or hotwords seperate by | (could be: 阿里巴巴 达摩院)", false, "", "string");
+ TCLAP::ValueArg<std::string> hotword("", HOTWORD, "the hotword file, one hotword perline, Format: Hotword Weight (could be: 阿里巴巴 20)", false, "", "string");
cmd.add(offline_model_dir);
cmd.add(online_model_dir);
@@ -276,25 +276,12 @@ int main(int argc, char** argv)
long modle_init_micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
LOG(INFO) << "Model initialization takes " << (double)modle_init_micros / 1000000 << " s";
- // read hotwords
- std::string hotword_ = hotword.getValue();
- std::string hotwords_;
-
- if(is_target_file(hotword_, "txt")){
- ifstream in(hotword_);
- if (!in.is_open()) {
- LOG(ERROR) << "Failed to open file: " << model_path.at(HOTWORD) ;
- return 0;
- }
- string line;
- while(getline(in, line))
- {
- hotwords_ +=line+HOTWORD_SEP;
- }
- in.close();
- }else{
- hotwords_ = hotword_;
- }
+ // hotword file
+ unordered_map<string, int> hws_map;
+ std::string nn_hotwords_ = "";
+ std::string hotword_path = model_path.at(HOTWORD);
+ LOG(INFO) << "hotword path: " << hotword_path;
+ funasr::ExtractHws(hotword_path, hws_map, nn_hotwords_);
// read wav_path
vector<string> wav_list;
@@ -332,7 +319,7 @@ int main(int argc, char** argv)
int rtf_threds = thread_num_.getValue();
for (int i = 0; i < rtf_threds; i++)
{
- threads.emplace_back(thread(runReg, tpass_hanlde, chunk_size, wav_list, wav_ids, &total_length, &total_time, i, (ASR_TYPE)asr_mode_, hotwords_));
+ threads.emplace_back(thread(runReg, tpass_hanlde, chunk_size, wav_list, wav_ids, &total_length, &total_time, i, (ASR_TYPE)asr_mode_, nn_hotwords_));
}
for (auto& thread : threads)
diff --git a/funasr/runtime/onnxruntime/bin/funasr-onnx-2pass.cpp b/runtime/onnxruntime/bin/funasr-onnx-2pass.cpp
similarity index 93%
rename from funasr/runtime/onnxruntime/bin/funasr-onnx-2pass.cpp
rename to runtime/onnxruntime/bin/funasr-onnx-2pass.cpp
index 59fceb786..d0154999d 100644
--- a/funasr/runtime/onnxruntime/bin/funasr-onnx-2pass.cpp
+++ b/runtime/onnxruntime/bin/funasr-onnx-2pass.cpp
@@ -14,6 +14,7 @@
#include <sstream>
#include <map>
#include <glog/logging.h>
+#include "util.h"
#include "funasrruntime.h"
#include "tclap/CmdLine.h"
#include "com-define.h"
@@ -54,7 +55,7 @@ int main(int argc, char** argv)
TCLAP::ValueArg<std::int32_t> onnx_thread("", "model-thread-num", "onnxruntime SetIntraOpNumThreads", false, 1, "int32_t");
TCLAP::ValueArg<std::string> wav_path("", WAV_PATH, "the input could be: wav_path, e.g.: asr_example.wav; pcm_path, e.g.: asr_example.pcm; wav.scp, kaldi style wav list (wav_id \t wav_path)", true, "", "string");
- TCLAP::ValueArg<std::string> hotword("", HOTWORD, "*.txt(one hotword perline) or hotwords seperate by | (could be: 阿里巴巴 达摩院)", false, "", "string");
+ TCLAP::ValueArg<std::string> hotword("", HOTWORD, "the hotword file, one hotword perline, Format: Hotword Weight (could be: 阿里巴巴 20)", false, "", "string");
cmd.add(offline_model_dir);
cmd.add(online_model_dir);
@@ -109,25 +110,12 @@ int main(int argc, char** argv)
long modle_init_micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
LOG(INFO) << "Model initialization takes " << (double)modle_init_micros / 1000000 << " s";
- // read hotwords
- std::string hotword_ = hotword.getValue();
- std::string hotwords_="";
-
- if(is_target_file(hotword_, "txt")){
- ifstream in(hotword_);
- if (!in.is_open()) {
- LOG(ERROR) << "Failed to open file: " << model_path.at(HOTWORD) ;
- return 0;
- }
- string line;
- while(getline(in, line))
- {
- hotwords_ +=line+HOTWORD_SEP;
- }
- in.close();
- }else{
- hotwords_ = hotword_;
- }
+ // hotword file
+ unordered_map<string, int> hws_map;
+ std::string nn_hotwords_ = "";
+ std::string hotword_path = model_path.at(HOTWORD);
+ LOG(INFO) << "hotword path: " << hotword_path;
+ funasr::ExtractHws(hotword_path, hws_map, nn_hotwords_);
// read wav_path
vector<string> wav_list;
@@ -156,7 +144,7 @@ int main(int argc, char** argv)
wav_ids.emplace_back(default_id);
}
- std::vector<std::vector<float>> hotwords_embedding = CompileHotwordEmbedding(tpass_handle, hotwords_, ASR_TWO_PASS);
+ std::vector<std::vector<float>> hotwords_embedding = CompileHotwordEmbedding(tpass_handle, nn_hotwords_, ASR_TWO_PASS);
// init online features
std::vector<int> chunk_size = {5,10,5};
FUNASR_HANDLE tpass_online_handle=FunTpassOnlineInit(tpass_handle, chunk_size);
diff --git a/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp b/runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp
rename to runtime/onnxruntime/bin/funasr-onnx-offline-punc.cpp
diff --git a/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-rtf.cpp b/runtime/onnxruntime/bin/funasr-onnx-offline-rtf.cpp
similarity index 75%
rename from funasr/runtime/onnxruntime/bin/funasr-onnx-offline-rtf.cpp
rename to runtime/onnxruntime/bin/funasr-onnx-offline-rtf.cpp
index c5092774f..41cd03834 100644
--- a/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-rtf.cpp
+++ b/runtime/onnxruntime/bin/funasr-onnx-offline-rtf.cpp
@@ -22,25 +22,40 @@
#include <mutex>
#include <thread>
#include <map>
-
+#include <unordered_map>
+#include "util.h"
using namespace std;
std::atomic<int> wav_index(0);
std::mutex mtx;
void runReg(FUNASR_HANDLE asr_handle, vector<string> wav_list, vector<string> wav_ids,
- float* total_length, long* total_time, int core_id, string hotwords) {
+ float* total_length, long* total_time, int core_id, float glob_beam = 3.0f, float lat_beam = 3.0f, float am_sc = 10.0f,
+ int fst_inc_wts = 20, string hotword_path = "") {
struct timeval start, end;
long seconds = 0;
float n_total_length = 0.0f;
long n_total_time = 0;
- std::vector<std::vector<float>> hotwords_embedding = CompileHotwordEmbedding(asr_handle, hotwords);
+
+ // init wfst decoder
+ FUNASR_DEC_HANDLE decoder_handle = FunASRWfstDecoderInit(asr_handle, ASR_OFFLINE, glob_beam, lat_beam, am_sc);
+
+ // process fst hotwords list
+ unordered_map<string, int> hws_map;
+ string nn_hotwords_ = "";
+ funasr::ExtractHws(hotword_path, hws_map, nn_hotwords_);
+
+ // load hotwords list and build graph
+ FunWfstDecoderLoadHwsRes(decoder_handle, fst_inc_wts, hws_map);
+
+ std::vector<std::vector<float>> hotwords_embedding = CompileHotwordEmbedding(asr_handle, nn_hotwords_);
// warm up
for (size_t i = 0; i < 1; i++)
{
- FUNASR_RESULT result=FunOfflineInfer(asr_handle, wav_list[0].c_str(), RASR_NONE, NULL, hotwords_embedding, 16000);
+ FunOfflineReset(asr_handle, decoder_handle);
+ FUNASR_RESULT result=FunOfflineInfer(asr_handle, wav_list[0].c_str(), RASR_NONE, NULL, hotwords_embedding, 16000, false, decoder_handle);
if(result){
FunASRFreeResult(result);
}
@@ -54,7 +69,7 @@ void runReg(FUNASR_HANDLE asr_handle, vector<string> wav_list, vector<string> wa
}
gettimeofday(&start, NULL);
- FUNASR_RESULT result=FunOfflineInfer(asr_handle, wav_list[i].c_str(), RASR_NONE, NULL, hotwords_embedding, 16000);
+ FUNASR_RESULT result=FunOfflineInfer(asr_handle, wav_list[i].c_str(), RASR_NONE, NULL, hotwords_embedding, 16000, false, decoder_handle);
gettimeofday(&end, NULL);
seconds = (end.tv_sec - start.tv_sec);
@@ -82,6 +97,8 @@ void runReg(FUNASR_HANDLE asr_handle, vector<string> wav_list, vector<string> wa
*total_time = n_total_time;
}
}
+ FunWfstDecoderUnloadHwsRes(decoder_handle);
+ FunASRWfstDecoderUninit(decoder_handle);
}
bool is_target_file(const std::string& filename, const std::string target) {
@@ -113,11 +130,16 @@ int main(int argc, char *argv[])
TCLAP::ValueArg<std::string> vad_quant("", VAD_QUANT, "true (Default), load the model of model.onnx in vad_dir. If set true, load the model of model_quant.onnx in vad_dir", false, "true", "string");
TCLAP::ValueArg<std::string> punc_dir("", PUNC_DIR, "the punc model path, which contains model.onnx, punc.yaml", false, "", "string");
TCLAP::ValueArg<std::string> punc_quant("", PUNC_QUANT, "true (Default), load the model of model.onnx in punc_dir. If set true, load the model of model_quant.onnx in punc_dir", false, "true", "string");
+ TCLAP::ValueArg<std::string> lm_dir("", LM_DIR, "the lm model path, which contains compiled models: TLG.fst, config.yaml ", false, "", "string");
+ TCLAP::ValueArg<float> global_beam("", GLOB_BEAM, "the decoding beam for beam searching ", false, 3.0, "float");
+ TCLAP::ValueArg<float> lattice_beam("", LAT_BEAM, "the lattice generation beam for beam searching ", false, 3.0, "float");
+ TCLAP::ValueArg<float> am_scale("", AM_SCALE, "the acoustic scale for beam searching ", false, 10.0, "float");
+ TCLAP::ValueArg<std::int32_t> fst_inc_wts("", FST_INC_WTS, "the fst hotwords incremental bias", false, 20, "int32_t");
TCLAP::ValueArg<std::string> itn_dir("", ITN_DIR, "the itn model(fst) path, which contains zh_itn_tagger.fst and zh_itn_verbalizer.fst", false, "", "string");
TCLAP::ValueArg<std::string> wav_path("", WAV_PATH, "the input could be: wav_path, e.g.: asr_example.wav; pcm_path, e.g.: asr_example.pcm; wav.scp, kaldi style wav list (wav_id \t wav_path)", true, "", "string");
TCLAP::ValueArg<std::int32_t> thread_num("", THREAD_NUM, "multi-thread num for rtf", true, 0, "int32_t");
- TCLAP::ValueArg<std::string> hotword("", HOTWORD, "*.txt(one hotword perline) or hotwords seperate by | (could be: 阿里巴巴 达摩院)", false, "", "string");
+ TCLAP::ValueArg<std::string> hotword("", HOTWORD, "the hotword file, one hotword perline, Format: Hotword Weight (could be: 阿里巴巴 20)", false, "", "string");
cmd.add(model_dir);
cmd.add(quantize);
@@ -126,9 +148,14 @@ int main(int argc, char *argv[])
cmd.add(punc_dir);
cmd.add(punc_quant);
cmd.add(itn_dir);
+ cmd.add(lm_dir);
+ cmd.add(global_beam);
+ cmd.add(lattice_beam);
+ cmd.add(am_scale);
+ cmd.add(hotword);
+ cmd.add(fst_inc_wts);
cmd.add(wav_path);
cmd.add(thread_num);
- cmd.add(hotword);
cmd.parse(argc, argv);
std::map<std::string, std::string> model_path;
@@ -139,6 +166,8 @@ int main(int argc, char *argv[])
GetValue(punc_dir, PUNC_DIR, model_path);
GetValue(punc_quant, PUNC_QUANT, model_path);
GetValue(itn_dir, ITN_DIR, model_path);
+ GetValue(lm_dir, LM_DIR, model_path);
+ GetValue(hotword, HOTWORD, model_path);
GetValue(wav_path, WAV_PATH, model_path);
struct timeval start, end;
@@ -156,26 +185,6 @@ int main(int argc, char *argv[])
long modle_init_micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
LOG(INFO) << "Model initialization takes " << (double)modle_init_micros / 1000000 << " s";
- // read hotwords
- std::string hotword_ = hotword.getValue();
- std::string hotwords_;
-
- if(is_target_file(hotword_, "txt")){
- ifstream in(hotword_);
- if (!in.is_open()) {
- LOG(ERROR) << "Failed to open file: " << model_path.at(HOTWORD) ;
- return 0;
- }
- string line;
- while(getline(in, line))
- {
- hotwords_ +=line+HOTWORD_SEP;
- }
- in.close();
- }else{
- hotwords_ = hotword_;
- }
-
// read wav_path
vector<string> wav_list;
vector<string> wav_ids;
@@ -212,9 +221,20 @@ int main(int argc, char *argv[])
std::vector<std::thread> threads;
int rtf_threds = thread_num.getValue();
+ std::string hotword_path = hotword.getValue();
+ int value_bias = 20;
+ value_bias = fst_inc_wts.getValue();
+ float glob_beam = 3.0f;
+ float lat_beam = 3.0f;
+ float am_sc = 10.0f;
+ if (lm_dir.isSet()) {
+ glob_beam = global_beam.getValue();
+ lat_beam = lattice_beam.getValue();
+ am_sc = am_scale.getValue();
+ }
for (int i = 0; i < rtf_threds; i++)
{
- threads.emplace_back(thread(runReg, asr_handle, wav_list, wav_ids, &total_length, &total_time, i, hotwords_));
+ threads.emplace_back(thread(runReg, asr_handle, wav_list, wav_ids, &total_length, &total_time, i, glob_beam, lat_beam, am_sc, value_bias, hotword_path));
}
for (auto& thread : threads)
diff --git a/funasr/runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp b/runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp
rename to runtime/onnxruntime/bin/funasr-onnx-offline-vad.cpp
diff --git a/funasr/runtime/onnxruntime/bin/funasr-onnx-offline.cpp b/runtime/onnxruntime/bin/funasr-onnx-offline.cpp
similarity index 71%
rename from funasr/runtime/onnxruntime/bin/funasr-onnx-offline.cpp
rename to runtime/onnxruntime/bin/funasr-onnx-offline.cpp
index 8b0f9b593..67a267d0d 100644
--- a/funasr/runtime/onnxruntime/bin/funasr-onnx-offline.cpp
+++ b/runtime/onnxruntime/bin/funasr-onnx-offline.cpp
@@ -17,7 +17,8 @@
#include "funasrruntime.h"
#include "tclap/CmdLine.h"
#include "com-define.h"
-
+#include <unordered_map>
+#include "util.h"
using namespace std;
bool is_target_file(const std::string& filename, const std::string target) {
@@ -49,10 +50,14 @@ int main(int argc, char** argv)
TCLAP::ValueArg<std::string> vad_quant("", VAD_QUANT, "true (Default), load the model of model.onnx in vad_dir. If set true, load the model of model_quant.onnx in vad_dir", false, "true", "string");
TCLAP::ValueArg<std::string> punc_dir("", PUNC_DIR, "the punc model path, which contains model.onnx, punc.yaml", false, "", "string");
TCLAP::ValueArg<std::string> punc_quant("", PUNC_QUANT, "true (Default), load the model of model.onnx in punc_dir. If set true, load the model of model_quant.onnx in punc_dir", false, "true", "string");
+ TCLAP::ValueArg<std::string> lm_dir("", LM_DIR, "the lm model path, which contains compiled models: TLG.fst, config.yaml ", false, "", "string");
+ TCLAP::ValueArg<float> global_beam("", GLOB_BEAM, "the decoding beam for beam searching ", false, 3.0, "float");
+ TCLAP::ValueArg<float> lattice_beam("", LAT_BEAM, "the lattice generation beam for beam searching ", false, 3.0, "float");
+ TCLAP::ValueArg<float> am_scale("", AM_SCALE, "the acoustic scale for beam searching ", false, 10.0, "float");
+ TCLAP::ValueArg<std::int32_t> fst_inc_wts("", FST_INC_WTS, "the fst hotwords incremental bias", false, 20, "int32_t");
TCLAP::ValueArg<std::string> itn_dir("", ITN_DIR, "the itn model(fst) path, which contains zh_itn_tagger.fst and zh_itn_verbalizer.fst", false, "", "string");
-
- TCLAP::ValueArg<std::string> wav_path("", WAV_PATH, "the input could be: wav_path, e.g.: asr_example.wav; pcm_path, e.g.: asr_example.pcm; wav.scp, kaldi style wav list (wav_id \t wav_path)", true, "", "string");
- TCLAP::ValueArg<std::string> hotword("", HOTWORD, "*.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)", false, "", "string");
+ TCLAP::ValueArg<std::string> wav_path("", WAV_PATH, "the input could be: wav_path, e.g.: asr_example.wav; pcm_path, e.g.: asr_example.pcm; wav.scp, kaldi style wav list (wav_id \t wav_path)", true, "", "string");
+ TCLAP::ValueArg<std::string> hotword("", HOTWORD, "the hotword file, one hotword perline, Format: Hotword Weight (could be: 阿里巴巴 20)", false, "", "string");
cmd.add(model_dir);
cmd.add(quantize);
@@ -61,6 +66,11 @@ int main(int argc, char** argv)
cmd.add(punc_dir);
cmd.add(punc_quant);
cmd.add(itn_dir);
+ cmd.add(lm_dir);
+ cmd.add(global_beam);
+ cmd.add(lattice_beam);
+ cmd.add(am_scale);
+ cmd.add(fst_inc_wts);
cmd.add(wav_path);
cmd.add(hotword);
cmd.parse(argc, argv);
@@ -73,6 +83,7 @@ int main(int argc, char** argv)
GetValue(punc_dir, PUNC_DIR, model_path);
GetValue(punc_quant, PUNC_QUANT, model_path);
GetValue(itn_dir, ITN_DIR, model_path);
+ GetValue(lm_dir, LM_DIR, model_path);
GetValue(wav_path, WAV_PATH, model_path);
struct timeval start, end;
@@ -85,32 +96,29 @@ int main(int argc, char** argv)
LOG(ERROR) << "FunASR init failed";
exit(-1);
}
+ float glob_beam = 3.0f;
+ float lat_beam = 3.0f;
+ float am_sc = 10.0f;
+ if (lm_dir.isSet()) {
+ glob_beam = global_beam.getValue();
+ lat_beam = lattice_beam.getValue();
+ am_sc = am_scale.getValue();
+ }
+ // init wfst decoder
+ FUNASR_DEC_HANDLE decoder_handle = FunASRWfstDecoderInit(asr_hanlde, ASR_OFFLINE, glob_beam, lat_beam, am_sc);
+
+ // hotword file
+ unordered_map<string, int> hws_map;
+ std::string nn_hotwords_ = "";
+ std::string hotword_path = hotword.getValue();
+ LOG(INFO) << "hotword path: " << hotword_path;
+ funasr::ExtractHws(hotword_path, hws_map, nn_hotwords_);
gettimeofday(&end, NULL);
long seconds = (end.tv_sec - start.tv_sec);
long modle_init_micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
LOG(INFO) << "Model initialization takes " << (double)modle_init_micros / 1000000 << " s";
- // read hotwords
- std::string hotword_ = hotword.getValue();
- std::string hotwords_;
-
- if(is_target_file(hotword_, "txt")){
- ifstream in(hotword_);
- if (!in.is_open()) {
- LOG(ERROR) << "Failed to open file: " << model_path.at(HOTWORD) ;
- return 0;
- }
- string line;
- while(getline(in, line))
- {
- hotwords_ +=line+HOTWORD_SEP;
- }
- in.close();
- }else{
- hotwords_ = hotword_;
- }
-
// read wav_path
vector<string> wav_list;
vector<string> wav_ids;
@@ -140,12 +148,16 @@ int main(int argc, char** argv)
float snippet_time = 0.0f;
long taking_micros = 0;
- std::vector<std::vector<float>> hotwords_embedding = CompileHotwordEmbedding(asr_hanlde, hotwords_);
+
+ // load hotwords list and build graph
+ FunWfstDecoderLoadHwsRes(decoder_handle, fst_inc_wts.getValue(), hws_map);
+
+ std::vector<std::vector<float>> hotwords_embedding = CompileHotwordEmbedding(asr_hanlde, nn_hotwords_);
for (int i = 0; i < wav_list.size(); i++) {
auto& wav_file = wav_list[i];
auto& wav_id = wav_ids[i];
gettimeofday(&start, NULL);
- FUNASR_RESULT result=FunOfflineInfer(asr_hanlde, wav_file.c_str(), RASR_NONE, NULL, hotwords_embedding, 16000);
+ FUNASR_RESULT result=FunOfflineInfer(asr_hanlde, wav_file.c_str(), RASR_NONE, NULL, hotwords_embedding, 16000, false, decoder_handle);
gettimeofday(&end, NULL);
seconds = (end.tv_sec - start.tv_sec);
taking_micros += ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
@@ -166,10 +178,12 @@ int main(int argc, char** argv)
LOG(ERROR) << ("No return data!\n");
}
}
-
+ FunWfstDecoderUnloadHwsRes(decoder_handle);
LOG(INFO) << "Audio length: " << (double)snippet_time << " s";
LOG(INFO) << "Model inference takes: " << (double)taking_micros / 1000000 <<" s";
LOG(INFO) << "Model inference RTF: " << (double)taking_micros/ (snippet_time*1000000);
+
+ FunASRWfstDecoderUninit(decoder_handle);
FunOfflineUninit(asr_hanlde);
return 0;
}
diff --git a/funasr/runtime/onnxruntime/bin/funasr-onnx-online-asr.cpp b/runtime/onnxruntime/bin/funasr-onnx-online-asr.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/bin/funasr-onnx-online-asr.cpp
rename to runtime/onnxruntime/bin/funasr-onnx-online-asr.cpp
diff --git a/funasr/runtime/onnxruntime/bin/funasr-onnx-online-punc.cpp b/runtime/onnxruntime/bin/funasr-onnx-online-punc.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/bin/funasr-onnx-online-punc.cpp
rename to runtime/onnxruntime/bin/funasr-onnx-online-punc.cpp
diff --git a/funasr/runtime/onnxruntime/bin/funasr-onnx-online-rtf.cpp b/runtime/onnxruntime/bin/funasr-onnx-online-rtf.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/bin/funasr-onnx-online-rtf.cpp
rename to runtime/onnxruntime/bin/funasr-onnx-online-rtf.cpp
diff --git a/funasr/runtime/onnxruntime/bin/funasr-onnx-online-vad.cpp b/runtime/onnxruntime/bin/funasr-onnx-online-vad.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/bin/funasr-onnx-online-vad.cpp
rename to runtime/onnxruntime/bin/funasr-onnx-online-vad.cpp
diff --git a/funasr/runtime/onnxruntime/include/audio.h b/runtime/onnxruntime/include/audio.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/audio.h
rename to runtime/onnxruntime/include/audio.h
diff --git a/funasr/runtime/onnxruntime/include/com-define.h b/runtime/onnxruntime/include/com-define.h
similarity index 89%
rename from funasr/runtime/onnxruntime/include/com-define.h
rename to runtime/onnxruntime/include/com-define.h
index 0ecb9c2b6..57908e6f2 100644
--- a/funasr/runtime/onnxruntime/include/com-define.h
+++ b/runtime/onnxruntime/include/com-define.h
@@ -15,6 +15,12 @@ namespace funasr {
#define MODEL_DIR "model-dir"
#define OFFLINE_MODEL_DIR "model-dir"
#define ONLINE_MODEL_DIR "online-model-dir"
+#define LM_DIR "lm-dir"
+#define GLOB_BEAM "global-beam"
+#define LAT_BEAM "lattice-beam"
+#define AM_SCALE "am-scale"
+// #define FST_HOTWORD "fst-hotword"
+#define FST_INC_WTS "fst-inc-wts"
#define VAD_DIR "vad-dir"
#define PUNC_DIR "punc-dir"
#define QUANTIZE "quantize"
@@ -46,9 +52,11 @@ namespace funasr {
#define VAD_CONFIG_NAME "vad.yaml"
#define AM_CMVN_NAME "am.mvn"
#define AM_CONFIG_NAME "config.yaml"
+#define LM_CONFIG_NAME "config.yaml"
#define PUNC_CONFIG_NAME "punc.yaml"
#define MODEL_SEG_DICT "seg_dict"
#define HOTWORD "hotword"
+// #define NN_HOTWORD "nn-hotword"
#define ITN_DIR "itn-dir"
#define ITN_TAGGER_NAME "zh_itn_tagger.fst"
@@ -59,6 +67,8 @@ namespace funasr {
#define DECODER_NAME "decoder.onnx"
#define QUANT_DECODER_NAME "decoder_quant.onnx"
+#define LM_FST_RES "TLG.fst"
+
// vad
#ifndef VAD_SILENCE_DURATION
#define VAD_SILENCE_DURATION 800
diff --git a/funasr/runtime/onnxruntime/include/funasrruntime.h b/runtime/onnxruntime/include/funasrruntime.h
similarity index 86%
rename from funasr/runtime/onnxruntime/include/funasrruntime.h
rename to runtime/onnxruntime/include/funasrruntime.h
index 3b5ae8f0d..3b52f38d0 100644
--- a/funasr/runtime/onnxruntime/include/funasrruntime.h
+++ b/runtime/onnxruntime/include/funasrruntime.h
@@ -1,7 +1,7 @@
#pragma once
#include <map>
#include <vector>
-
+#include <unordered_map>
#ifdef WIN32
#ifdef _FUNASR_API_EXPORT
#define _FUNASRAPI __declspec(dllexport)
@@ -21,6 +21,7 @@
typedef void* FUNASR_HANDLE;
typedef void* FUNASR_RESULT;
+typedef void* FUNASR_DEC_HANDLE;
typedef unsigned char FUNASR_BOOL;
#define FUNASR_TRUE 1
@@ -58,6 +59,8 @@ typedef void (* QM_CALLBACK)(int cur_step, int n_total); // n_total: total steps
// ASR
_FUNASRAPI FUNASR_HANDLE FunASRInit(std::map<std::string, std::string>& model_path, int thread_num, ASR_TYPE type=ASR_OFFLINE);
_FUNASRAPI FUNASR_HANDLE FunASROnlineInit(FUNASR_HANDLE asr_handle, std::vector<int> chunk_size={5,10,5});
+_FUNASRAPI void FunASRReset(FUNASR_HANDLE handle, FUNASR_DEC_HANDLE dec_handle=nullptr);
+
// buffer
_FUNASRAPI FUNASR_RESULT FunASRInferBuffer(FUNASR_HANDLE handle, const char* sz_buf, int n_len, FUNASR_MODE mode, QM_CALLBACK fn_callback, bool input_finished=true, int sampling_rate=16000, std::string wav_format="pcm");
// file, support wav & pcm
@@ -93,14 +96,15 @@ _FUNASRAPI void CTTransformerUninit(FUNASR_HANDLE handle);
//OfflineStream
_FUNASRAPI FUNASR_HANDLE FunOfflineInit(std::map<std::string, std::string>& model_path, int thread_num);
+_FUNASRAPI void FunOfflineReset(FUNASR_HANDLE handle, FUNASR_DEC_HANDLE dec_handle=nullptr);
// buffer
_FUNASRAPI FUNASR_RESULT FunOfflineInferBuffer(FUNASR_HANDLE handle, const char* sz_buf, int n_len,
FUNASR_MODE mode, QM_CALLBACK fn_callback, const std::vector<std::vector<float>> &hw_emb,
- int sampling_rate=16000, std::string wav_format="pcm", bool itn=true);
+ int sampling_rate=16000, std::string wav_format="pcm", bool itn=true, FUNASR_DEC_HANDLE dec_handle=nullptr);
// file, support wav & pcm
_FUNASRAPI FUNASR_RESULT FunOfflineInfer(FUNASR_HANDLE handle, const char* sz_filename, FUNASR_MODE mode,
QM_CALLBACK fn_callback, const std::vector<std::vector<float>> &hw_emb,
- int sampling_rate=16000, bool itn=true);
+ int sampling_rate=16000, bool itn=true, FUNASR_DEC_HANDLE dec_handle=nullptr);
#if !defined(__APPLE__)
_FUNASRAPI const std::vector<std::vector<float>> CompileHotwordEmbedding(FUNASR_HANDLE handle, std::string &hotwords, ASR_TYPE mode=ASR_OFFLINE);
#endif
@@ -118,4 +122,9 @@ _FUNASRAPI FUNASR_RESULT FunTpassInferBuffer(FUNASR_HANDLE handle, FUNASR_HANDLE
_FUNASRAPI void FunTpassUninit(FUNASR_HANDLE handle);
_FUNASRAPI void FunTpassOnlineUninit(FUNASR_HANDLE handle);
+// wfst decoder
+_FUNASRAPI FUNASR_DEC_HANDLE FunASRWfstDecoderInit(FUNASR_HANDLE handle, int asr_type, float glob_beam, float lat_beam, float am_scale);
+_FUNASRAPI void FunASRWfstDecoderUninit(FUNASR_DEC_HANDLE handle);
+_FUNASRAPI void FunWfstDecoderLoadHwsRes(FUNASR_DEC_HANDLE handle, int inc_bias, std::unordered_map<std::string, int> &hws_map);
+_FUNASRAPI void FunWfstDecoderUnloadHwsRes(FUNASR_DEC_HANDLE handle);
diff --git a/funasr/runtime/onnxruntime/include/itn-model.h b/runtime/onnxruntime/include/itn-model.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/itn-model.h
rename to runtime/onnxruntime/include/itn-model.h
diff --git a/funasr/runtime/onnxruntime/include/model.h b/runtime/onnxruntime/include/model.h
similarity index 81%
rename from funasr/runtime/onnxruntime/include/model.h
rename to runtime/onnxruntime/include/model.h
index 7f1e0acb3..356fca330 100644
--- a/funasr/runtime/onnxruntime/include/model.h
+++ b/runtime/onnxruntime/include/model.h
@@ -9,11 +9,15 @@ namespace funasr {
class Model {
public:
virtual ~Model(){};
+ virtual void StartUtterance() = 0;
+ virtual void EndUtterance() = 0;
virtual void Reset() = 0;
virtual void InitAsr(const std::string &am_model, const std::string &am_cmvn, const std::string &am_config, int thread_num){};
virtual void InitAsr(const std::string &en_model, const std::string &de_model, const std::string &am_cmvn, const std::string &am_config, int thread_num){};
virtual void InitAsr(const std::string &am_model, const std::string &en_model, const std::string &de_model, const std::string &am_cmvn, const std::string &am_config, int thread_num){};
- virtual std::string Forward(float *din, int len, bool input_finished, const std::vector<std::vector<float>> &hw_emb={{0.0}}){return "";};
+ virtual void InitLm(const std::string &lm_file, const std::string &lm_config){};
+ virtual void InitFstDecoder(){};
+ virtual std::string Forward(float *din, int len, bool input_finished, const std::vector<std::vector<float>> &hw_emb={{0.0}}, void* wfst_decoder=nullptr){return "";};
virtual std::string Rescoring() = 0;
virtual void InitHwCompiler(const std::string &hw_model, int thread_num){};
virtual void InitSegDict(const std::string &seg_dict_model){};
diff --git a/funasr/runtime/onnxruntime/include/offline-stream.h b/runtime/onnxruntime/include/offline-stream.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/offline-stream.h
rename to runtime/onnxruntime/include/offline-stream.h
diff --git a/funasr/runtime/onnxruntime/include/punc-model.h b/runtime/onnxruntime/include/punc-model.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/punc-model.h
rename to runtime/onnxruntime/include/punc-model.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/Arg.h b/runtime/onnxruntime/include/tclap/Arg.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/Arg.h
rename to runtime/onnxruntime/include/tclap/Arg.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/ArgException.h b/runtime/onnxruntime/include/tclap/ArgException.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/ArgException.h
rename to runtime/onnxruntime/include/tclap/ArgException.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/ArgTraits.h b/runtime/onnxruntime/include/tclap/ArgTraits.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/ArgTraits.h
rename to runtime/onnxruntime/include/tclap/ArgTraits.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/CmdLine.h b/runtime/onnxruntime/include/tclap/CmdLine.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/CmdLine.h
rename to runtime/onnxruntime/include/tclap/CmdLine.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/CmdLineInterface.h b/runtime/onnxruntime/include/tclap/CmdLineInterface.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/CmdLineInterface.h
rename to runtime/onnxruntime/include/tclap/CmdLineInterface.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/CmdLineOutput.h b/runtime/onnxruntime/include/tclap/CmdLineOutput.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/CmdLineOutput.h
rename to runtime/onnxruntime/include/tclap/CmdLineOutput.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/Constraint.h b/runtime/onnxruntime/include/tclap/Constraint.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/Constraint.h
rename to runtime/onnxruntime/include/tclap/Constraint.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/DocBookOutput.h b/runtime/onnxruntime/include/tclap/DocBookOutput.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/DocBookOutput.h
rename to runtime/onnxruntime/include/tclap/DocBookOutput.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/HelpVisitor.h b/runtime/onnxruntime/include/tclap/HelpVisitor.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/HelpVisitor.h
rename to runtime/onnxruntime/include/tclap/HelpVisitor.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/IgnoreRestVisitor.h b/runtime/onnxruntime/include/tclap/IgnoreRestVisitor.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/IgnoreRestVisitor.h
rename to runtime/onnxruntime/include/tclap/IgnoreRestVisitor.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/MultiArg.h b/runtime/onnxruntime/include/tclap/MultiArg.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/MultiArg.h
rename to runtime/onnxruntime/include/tclap/MultiArg.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/MultiSwitchArg.h b/runtime/onnxruntime/include/tclap/MultiSwitchArg.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/MultiSwitchArg.h
rename to runtime/onnxruntime/include/tclap/MultiSwitchArg.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/OptionalUnlabeledTracker.h b/runtime/onnxruntime/include/tclap/OptionalUnlabeledTracker.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/OptionalUnlabeledTracker.h
rename to runtime/onnxruntime/include/tclap/OptionalUnlabeledTracker.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/StandardTraits.h b/runtime/onnxruntime/include/tclap/StandardTraits.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/StandardTraits.h
rename to runtime/onnxruntime/include/tclap/StandardTraits.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/StdOutput.h b/runtime/onnxruntime/include/tclap/StdOutput.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/StdOutput.h
rename to runtime/onnxruntime/include/tclap/StdOutput.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/SwitchArg.h b/runtime/onnxruntime/include/tclap/SwitchArg.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/SwitchArg.h
rename to runtime/onnxruntime/include/tclap/SwitchArg.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/UnlabeledMultiArg.h b/runtime/onnxruntime/include/tclap/UnlabeledMultiArg.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/UnlabeledMultiArg.h
rename to runtime/onnxruntime/include/tclap/UnlabeledMultiArg.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/UnlabeledValueArg.h b/runtime/onnxruntime/include/tclap/UnlabeledValueArg.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/UnlabeledValueArg.h
rename to runtime/onnxruntime/include/tclap/UnlabeledValueArg.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/ValueArg.h b/runtime/onnxruntime/include/tclap/ValueArg.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/ValueArg.h
rename to runtime/onnxruntime/include/tclap/ValueArg.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/ValuesConstraint.h b/runtime/onnxruntime/include/tclap/ValuesConstraint.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/ValuesConstraint.h
rename to runtime/onnxruntime/include/tclap/ValuesConstraint.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/VersionVisitor.h b/runtime/onnxruntime/include/tclap/VersionVisitor.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/VersionVisitor.h
rename to runtime/onnxruntime/include/tclap/VersionVisitor.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/Visitor.h b/runtime/onnxruntime/include/tclap/Visitor.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/Visitor.h
rename to runtime/onnxruntime/include/tclap/Visitor.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/XorHandler.h b/runtime/onnxruntime/include/tclap/XorHandler.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/XorHandler.h
rename to runtime/onnxruntime/include/tclap/XorHandler.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/ZshCompletionOutput.h b/runtime/onnxruntime/include/tclap/ZshCompletionOutput.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/ZshCompletionOutput.h
rename to runtime/onnxruntime/include/tclap/ZshCompletionOutput.h
diff --git a/funasr/runtime/onnxruntime/include/tclap/sstream.h b/runtime/onnxruntime/include/tclap/sstream.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tclap/sstream.h
rename to runtime/onnxruntime/include/tclap/sstream.h
diff --git a/funasr/runtime/onnxruntime/include/tpass-online-stream.h b/runtime/onnxruntime/include/tpass-online-stream.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tpass-online-stream.h
rename to runtime/onnxruntime/include/tpass-online-stream.h
diff --git a/funasr/runtime/onnxruntime/include/tpass-stream.h b/runtime/onnxruntime/include/tpass-stream.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/tpass-stream.h
rename to runtime/onnxruntime/include/tpass-stream.h
diff --git a/funasr/runtime/onnxruntime/include/vad-model.h b/runtime/onnxruntime/include/vad-model.h
similarity index 100%
rename from funasr/runtime/onnxruntime/include/vad-model.h
rename to runtime/onnxruntime/include/vad-model.h
diff --git a/funasr/runtime/onnxruntime/readme.md b/runtime/onnxruntime/readme.md
similarity index 91%
rename from funasr/runtime/onnxruntime/readme.md
rename to runtime/onnxruntime/readme.md
index 6735a7c45..d63010fb6 100644
--- a/funasr/runtime/onnxruntime/readme.md
+++ b/runtime/onnxruntime/readme.md
@@ -1,4 +1,4 @@
-# Please ref to [websocket service](https://github.com/alibaba-damo-academy/FunASR/tree/main/funasr/runtime/websocket)
+# Please ref to [websocket service](https://github.com/alibaba-damo-academy/FunASR/tree/main/runtime/websocket)
# If you want to compile the file yourself, you can follow the steps below.
## Building for Linux/Unix
@@ -27,7 +27,7 @@ apt-get install libssl-dev #ubuntu
### Build runtime
```shell
-git clone https://github.com/alibaba-damo-academy/FunASR.git && cd FunASR/funasr/runtime/onnxruntime
+git clone https://github.com/alibaba-damo-academy/FunASR.git && cd FunASR/runtime/onnxruntime
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=release .. -DONNXRUNTIME_DIR=/path/to/onnxruntime-linux-x64-1.14.0 -DFFMPEG_DIR=/path/to/ffmpeg-N-111383-g20b8688092-linux64-gpl-shared
make -j 4
diff --git a/funasr/runtime/onnxruntime/src/CMakeLists.txt b/runtime/onnxruntime/src/CMakeLists.txt
similarity index 76%
rename from funasr/runtime/onnxruntime/src/CMakeLists.txt
rename to runtime/onnxruntime/src/CMakeLists.txt
index 4e8ac8ad2..042be49d5 100644
--- a/funasr/runtime/onnxruntime/src/CMakeLists.txt
+++ b/runtime/onnxruntime/src/CMakeLists.txt
@@ -7,7 +7,7 @@ message("files: "${files})
add_library(funasr SHARED ${files})
if(WIN32)
- set(EXTRA_LIBS pthread yaml-cpp csrc fst glog gflags)
+ set(EXTRA_LIBS pthread yaml-cpp csrc kaldi-decoder fst glog gflags)
if(CMAKE_CL_64)
target_link_directories(funasr PUBLIC ${CMAKE_SOURCE_DIR}/win/lib/x64)
else()
@@ -17,11 +17,12 @@ if(WIN32)
target_compile_definitions(funasr PUBLIC -D_FUNASR_API_EXPORT)
else()
- set(EXTRA_LIBS pthread yaml-cpp csrc fst glog gflags avutil avcodec avformat swresample)
+ set(EXTRA_LIBS pthread yaml-cpp csrc kaldi-decoder fst glog gflags avutil avcodec avformat swresample)
include_directories(${ONNXRUNTIME_DIR}/include)
include_directories(${FFMPEG_DIR}/include)
endif()
#message("CXX_FLAGS "${CMAKE_CXX_FLAGS})
include_directories(${CMAKE_SOURCE_DIR}/include)
+include_directories(${CMAKE_SOURCE_DIR}/third_party)
target_link_libraries(funasr PUBLIC onnxruntime ${EXTRA_LIBS})
diff --git a/funasr/runtime/onnxruntime/src/alignedmem.cpp b/runtime/onnxruntime/src/alignedmem.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/alignedmem.cpp
rename to runtime/onnxruntime/src/alignedmem.cpp
diff --git a/funasr/runtime/onnxruntime/src/alignedmem.h b/runtime/onnxruntime/src/alignedmem.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/alignedmem.h
rename to runtime/onnxruntime/src/alignedmem.h
diff --git a/funasr/runtime/onnxruntime/src/audio.cpp b/runtime/onnxruntime/src/audio.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/audio.cpp
rename to runtime/onnxruntime/src/audio.cpp
diff --git a/runtime/onnxruntime/src/bias-lm.cpp b/runtime/onnxruntime/src/bias-lm.cpp
new file mode 100644
index 000000000..5be87f82b
--- /dev/null
+++ b/runtime/onnxruntime/src/bias-lm.cpp
@@ -0,0 +1,178 @@
+#include "bias-lm.h"
+
+namespace funasr {
+void print(std::queue<StateId> &q) {
+ std::queue<StateId> data = q;
+ while (!data.empty())
+ {
+ cout << data.front() << " ";
+ data.pop();
+ }
+ cout << endl;
+}
+
+void BiasLm::LoadCfgFromYaml(const char* filename, BiasLmOption &opt) {
+ YAML::Node config;
+ try {
+ config = YAML::LoadFile(filename);
+ } catch(exception const &e) {
+ LOG(INFO) << "Error loading file, yaml file error or not exist.";
+ exit(-1);
+ }
+ try {
+ YAML::Node bias_lm_conf = config["bias_lm_conf"];
+ opt_.incre_bias_ = bias_lm_conf["increment_weight"].as<float>();
+ } catch(exception const &e) {
+ }
+}
+
+void BiasLm::BuildGraph(std::vector<std::vector<int>> &split_id_vec,
+ std::vector<float> &custom_weight) {
+ if (split_id_vec.empty()) {
+ LOG(INFO) << "Skip building biaslm graph, hotword not exits.";
+ return ;
+ }
+ assert(split_id_vec.size() == custom_weight.size());
+ // Build prefix tree
+ std::unique_ptr<fst::StdVectorFst> prefix_tree(new fst::StdVectorFst());
+ StateId start_state = prefix_tree->AddState();
+ prefix_tree->SetStart(start_state);
+ int id = 0;
+ for (auto& x : split_id_vec) {
+ StateId state = start_state;
+ StateId next_state = state;
+ float w = custom_weight[id++];
+ std::vector<int> split_id = x;
+ for (int j = 0; j < split_id.size(); j++) {
+ next_state = prefix_tree->AddState();
+ if (j == split_id.size() - 1) {
+ prefix_tree->SetFinal(next_state, w);
+ }
+ prefix_tree->AddArc(state, Arc(split_id[j], split_id[j], opt_.incre_bias_, next_state));
+ state = next_state;
+ }
+ }
+ graph_ = std::unique_ptr<fst::StdVectorFst>(new fst::StdVectorFst());
+ fst::Determinize(*prefix_tree, graph_.get());
+
+ int num_node = graph_->NumStates();
+ node_list_.resize(num_node);
+ for (auto& x : split_id_vec) {
+ StateId cur_state = 0;
+ StateId next_state = 0;
+ std::vector<int> split_id = x;
+ for (int j = 0; j < split_id.size(); j++) {
+ Matcher matcher(*graph_, fst::MATCH_INPUT);
+ matcher.SetState(cur_state);
+ if (matcher.Find(split_id[j])) {
+ next_state = matcher.Value().nextstate;
+ if (graph_->Final(next_state) != Weight::Zero()) {
+ node_list_[next_state].is_final_ = true;
+ }
+ node_list_[next_state].score_ = opt_.incre_bias_ * (j + 1);
+ cur_state = next_state;
+ }
+ }
+ }
+
+ // Build Aho-Corasick Automata
+ std::queue<StateId> q;
+ Matcher matcher(*graph_, fst::MATCH_INPUT);
+ // Back off state of all child nodes of the root node points to the root node
+ for (ArcIterator aiter(*graph_, start_state); !aiter.Done(); aiter.Next()) {
+ const Arc& arc = aiter.Value();
+ node_list_[arc.nextstate].back_off_ = start_state;
+ float back_off_score = (node_list_[arc.nextstate].is_final_ ? 0 :
+ node_list_[start_state].score_ - node_list_[arc.nextstate].score_);
+ graph_->AddArc(arc.nextstate, Arc(0, 0, back_off_score, start_state));
+ q.push(arc.nextstate);
+ }
+ while (!q.empty()) {
+ StateId state_id = q.front();
+ q.pop();
+ for (ArcIterator aiter(*graph_, state_id); !aiter.Done(); aiter.Next()) {
+ const Arc& arc = aiter.Value();
+ StateId next_state = arc.nextstate;
+ StateId temp_state = node_list_[state_id].back_off_;
+ if (next_state == start_state || next_state == temp_state) {
+ continue;
+ }
+ while (true) {
+ matcher.SetState(temp_state);
+ if (matcher.Find(arc.ilabel)) {
+ node_list_[next_state].back_off_ = matcher.Value().nextstate;
+ break;
+ } else if (temp_state == start_state) {
+ node_list_[next_state].back_off_ = start_state;
+ break;
+ }
+ temp_state = node_list_[temp_state].back_off_;
+ }
+ float back_off_score = (node_list_[next_state].is_final_ ? 0 :
+ node_list_[node_list_[next_state].back_off_].score_ -
+ node_list_[next_state].score_);
+ graph_->AddArc(next_state, Arc(0, 0, back_off_score,
+ node_list_[next_state].back_off_));
+ q.push(next_state);
+ }
+ }
+ fst::ArcSort(graph_.get(), fst::StdILabelCompare());
+ //graph_->Write("graph.final.fst");
+}
+
+float BiasLm::BiasLmScore(const StateId &his_state, const Label &lab, Label &new_state) {
+ if (lab < 1 || lab > phn_set_.Size() || !graph_) { return VALUE_ZERO; }
+ StateId cur_state = his_state;
+ StateId next_state;
+ float score = VALUE_ZERO;
+ Matcher matcher(*graph_, fst::MATCH_INPUT);
+ while (true) {
+ StateId prev_state = cur_state;
+ matcher.SetState(cur_state);
+ if (matcher.Find(lab)) {
+ next_state = matcher.Value().nextstate;
+ score += matcher.Value().weight.Value();
+ if (node_list_[next_state].is_final_) {
+ score = score + graph_->Final(next_state).Value();
+ }
+ cur_state = next_state;
+ break;
+ } else {
+ ArcIterator aiter(*graph_, cur_state);
+ const Arc& arc = aiter.Value();
+ if (arc.ilabel == 0) {
+ score += arc.weight.Value();
+ next_state = arc.nextstate;
+ cur_state = next_state;
+ }
+ if (prev_state == ROOT_NODE && cur_state == ROOT_NODE) {
+ break;
+ }
+ }
+ }
+ new_state = cur_state;
+ return score;
+}
+
+void BiasLm::VocabIdToPhnIdVector(int vocab_id, std::vector<int> &phn_ids) {
+ bool is_oov = false;
+ phn_ids.clear();
+ std::string word = vocab_.Id2String(vocab_id);
+ std::vector<std::string> phn_vec;
+ Utf8ToCharset(word, phn_vec);
+ for (auto& phn : phn_vec) {
+ if (!phn_set_.Find(phn)) {
+ is_oov = true;
+ break;
+ } else {
+ phn_ids.push_back(phn_set_.String2Id(phn));
+ }
+ }
+ if (is_oov) { phn_ids.clear(); }
+}
+
+std::string BiasLm::GetPhoneLabel(int phone_id) {
+ if (phone_id < 0 || phone_id >= phn_set_.Size()) { return ""; }
+ return phn_set_.Id2String(phone_id);
+}
+}
diff --git a/runtime/onnxruntime/src/bias-lm.h b/runtime/onnxruntime/src/bias-lm.h
new file mode 100644
index 000000000..7254d493b
--- /dev/null
+++ b/runtime/onnxruntime/src/bias-lm.h
@@ -0,0 +1,137 @@
+#ifndef BIAS_LM_
+#define BIAS_LM_
+#include <assert.h>
+#include "util.h"
+#include "fst/fstlib.h"
+#include "phone-set.h"
+#include "vocab.h"
+#include "util/text-utils.h"
+#include <yaml-cpp/yaml.h>
+// node type
+#define ROOT_NODE 0
+#define VALUE_ZERO 0.0f
+
+namespace funasr {
+typedef fst::StdArc Arc;
+typedef typename Arc::StateId StateId;
+typedef typename Arc::Weight Weight;
+typedef typename Arc::Label Label;
+typedef typename fst::SortedMatcher<fst::StdVectorFst> Matcher;
+typedef typename fst::ArcIterator<fst::StdVectorFst> ArcIterator;
+
+class Node {
+ public:
+ Node() : score_(0.0f), is_final_(false), back_off_(-1) {}
+ float score_;
+ bool is_final_;
+ StateId back_off_;
+};
+
+class BiasLmOption {
+ public:
+ BiasLmOption() : incre_bias_(20.0f), scale_(1.0f) {}
+ float incre_bias_;
+ float scale_;
+};
+
+class BiasLm {
+ public:
+ BiasLm(const string &hws_file, const string &cfg_file,
+ const PhoneSet& phn_set, const Vocab& vocab) :
+ phn_set_(phn_set), vocab_(vocab) {
+ std::string line;
+ std::ifstream ifs_hws(hws_file.c_str());
+ std::vector<float> custom_weight;
+ std::vector<std::vector<int>> split_id_vec;
+
+ struct timeval start, end;
+ gettimeofday(&start, NULL);
+
+ LoadCfgFromYaml(cfg_file.c_str(), opt_);
+ while (getline(ifs_hws, line)) {
+ Trim(&line);
+ if (line.empty()) {
+ continue;
+ }
+ float score = 1.0f;
+ bool is_oov = false;
+ std::vector<std::string> text;
+ std::vector<std::string> split_str;
+ std::vector<int> split_id;
+ SplitStringToVector(line, "\t", true, &text);
+ if (text.size() > 1) {
+ score = std::stof(text[1]);
+ }
+ Utf8ToCharset(text[0], split_str);
+ for (auto &str : split_str) {
+ split_id.push_back(phn_set_.String2Id(str));
+ if (!phn_set_.Find(str)) {
+ is_oov = true;
+ break;
+ }
+ }
+ if (!is_oov) {
+ split_id_vec.push_back(split_id);
+ custom_weight.push_back(score);
+ }
+ }
+ BuildGraph(split_id_vec, custom_weight);
+ ifs_hws.close();
+
+ gettimeofday(&end, NULL);
+ long seconds = (end.tv_sec - start.tv_sec);
+ long modle_init_micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
+ LOG(INFO) << "Build bias lm takes " << (double)modle_init_micros / 1000000 << " s";
+ }
+
+ BiasLm(unordered_map<string, int> &hws_map, int inc_bias,
+ const PhoneSet& phn_set, const Vocab& vocab) :
+ phn_set_(phn_set), vocab_(vocab) {
+ std::vector<float> custom_weight;
+ std::vector<std::vector<int>> split_id_vec;
+
+ struct timeval start, end;
+ gettimeofday(&start, NULL);
+ opt_.incre_bias_ = inc_bias;
+ for (const pair<string, int>& kv : hws_map) {
+ float score = 1.0f;
+ bool is_oov = false;
+ std::vector<std::string> text;
+ std::vector<std::string> split_str;
+ std::vector<int> split_id;
+ score = kv.second;
+ Utf8ToCharset(kv.first, split_str);
+ for (auto &str : split_str) {
+ split_id.push_back(phn_set_.String2Id(str));
+ if (!phn_set_.Find(str)) {
+ is_oov = true;
+ break;
+ }
+ }
+ if (!is_oov) {
+ split_id_vec.push_back(split_id);
+ custom_weight.push_back(score);
+ }
+ }
+ BuildGraph(split_id_vec, custom_weight);
+
+ gettimeofday(&end, NULL);
+ long seconds = (end.tv_sec - start.tv_sec);
+ long modle_init_micros = ((seconds * 1000000) + end.tv_usec) - (start.tv_usec);
+ LOG(INFO) << "Build bias lm takes " << (double)modle_init_micros / 1000000 << " s";
+ }
+
+ void BuildGraph(std::vector<std::vector<int>> &vec, std::vector<float> &wts);
+ float BiasLmScore(const StateId &cur_state, const Label &lab, Label &new_state);
+ void VocabIdToPhnIdVector(int vocab_id, std::vector<int> &phn_ids);
+ void LoadCfgFromYaml(const char* filename, BiasLmOption &opt);
+ std::string GetPhoneLabel(int phone_id);
+ private:
+ const PhoneSet& phn_set_;
+ const Vocab& vocab_;
+ std::unique_ptr<fst::StdVectorFst> graph_ = nullptr;
+ std::vector<Node> node_list_;
+ BiasLmOption opt_;
+};
+} // namespace funasr
+#endif // BIAS_LM_
diff --git a/funasr/runtime/onnxruntime/src/common-struct.h b/runtime/onnxruntime/src/common-struct.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/common-struct.h
rename to runtime/onnxruntime/src/common-struct.h
diff --git a/funasr/runtime/onnxruntime/src/commonfunc.h b/runtime/onnxruntime/src/commonfunc.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/commonfunc.h
rename to runtime/onnxruntime/src/commonfunc.h
diff --git a/funasr/runtime/onnxruntime/src/ct-transformer-online.cpp b/runtime/onnxruntime/src/ct-transformer-online.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/ct-transformer-online.cpp
rename to runtime/onnxruntime/src/ct-transformer-online.cpp
diff --git a/funasr/runtime/onnxruntime/src/ct-transformer-online.h b/runtime/onnxruntime/src/ct-transformer-online.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/ct-transformer-online.h
rename to runtime/onnxruntime/src/ct-transformer-online.h
diff --git a/funasr/runtime/onnxruntime/src/ct-transformer.cpp b/runtime/onnxruntime/src/ct-transformer.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/ct-transformer.cpp
rename to runtime/onnxruntime/src/ct-transformer.cpp
diff --git a/funasr/runtime/onnxruntime/src/ct-transformer.h b/runtime/onnxruntime/src/ct-transformer.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/ct-transformer.h
rename to runtime/onnxruntime/src/ct-transformer.h
diff --git a/funasr/runtime/onnxruntime/src/e2e-vad.h b/runtime/onnxruntime/src/e2e-vad.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/e2e-vad.h
rename to runtime/onnxruntime/src/e2e-vad.h
diff --git a/funasr/runtime/onnxruntime/src/encode_converter.cpp b/runtime/onnxruntime/src/encode_converter.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/encode_converter.cpp
rename to runtime/onnxruntime/src/encode_converter.cpp
diff --git a/funasr/runtime/onnxruntime/src/encode_converter.h b/runtime/onnxruntime/src/encode_converter.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/encode_converter.h
rename to runtime/onnxruntime/src/encode_converter.h
diff --git a/funasr/runtime/onnxruntime/src/fsmn-vad-online.cpp b/runtime/onnxruntime/src/fsmn-vad-online.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/fsmn-vad-online.cpp
rename to runtime/onnxruntime/src/fsmn-vad-online.cpp
diff --git a/funasr/runtime/onnxruntime/src/fsmn-vad-online.h b/runtime/onnxruntime/src/fsmn-vad-online.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/fsmn-vad-online.h
rename to runtime/onnxruntime/src/fsmn-vad-online.h
diff --git a/funasr/runtime/onnxruntime/src/fsmn-vad.cpp b/runtime/onnxruntime/src/fsmn-vad.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/fsmn-vad.cpp
rename to runtime/onnxruntime/src/fsmn-vad.cpp
diff --git a/funasr/runtime/onnxruntime/src/fsmn-vad.h b/runtime/onnxruntime/src/fsmn-vad.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/fsmn-vad.h
rename to runtime/onnxruntime/src/fsmn-vad.h
diff --git a/funasr/runtime/onnxruntime/src/funasrruntime.cpp b/runtime/onnxruntime/src/funasrruntime.cpp
similarity index 89%
rename from funasr/runtime/onnxruntime/src/funasrruntime.cpp
rename to runtime/onnxruntime/src/funasrruntime.cpp
index 91ef18893..f16851f1a 100644
--- a/funasr/runtime/onnxruntime/src/funasrruntime.cpp
+++ b/runtime/onnxruntime/src/funasrruntime.cpp
@@ -216,7 +216,7 @@
// APIs for Offline-stream Infer
_FUNASRAPI FUNASR_RESULT FunOfflineInferBuffer(FUNASR_HANDLE handle, const char* sz_buf, int n_len,
FUNASR_MODE mode, QM_CALLBACK fn_callback, const std::vector<std::vector<float>> &hw_emb,
- int sampling_rate, std::string wav_format, bool itn)
+ int sampling_rate, std::string wav_format, bool itn, FUNASR_DEC_HANDLE dec_handle)
{
funasr::OfflineStream* offline_stream = (funasr::OfflineStream*)handle;
if (!offline_stream)
@@ -256,7 +256,12 @@
std::string cur_stamp = "[";
std::string lang = (offline_stream->asr_handle)->GetLang();
while (audio.Fetch(buff, len, flag, start_time) > 0) {
- string msg = (offline_stream->asr_handle)->Forward(buff, len, true, hw_emb);
+ // dec reset
+ funasr::WfstDecoder* wfst_decoder = (funasr::WfstDecoder*)dec_handle;
+ if (wfst_decoder){
+ wfst_decoder->StartUtterance();
+ }
+ string msg = (offline_stream->asr_handle)->Forward(buff, len, true, hw_emb, dec_handle);
std::vector<std::string> msg_vec = funasr::split(msg, '|');
if(msg_vec.size()==0){
continue;
@@ -297,7 +302,7 @@
}
_FUNASRAPI FUNASR_RESULT FunOfflineInfer(FUNASR_HANDLE handle, const char* sz_filename, FUNASR_MODE mode, QM_CALLBACK fn_callback,
- const std::vector<std::vector<float>> &hw_emb, int sampling_rate, bool itn)
+ const std::vector<std::vector<float>> &hw_emb, int sampling_rate, bool itn, FUNASR_DEC_HANDLE dec_handle)
{
funasr::OfflineStream* offline_stream = (funasr::OfflineStream*)handle;
if (!offline_stream)
@@ -340,7 +345,12 @@
std::string cur_stamp = "[";
std::string lang = (offline_stream->asr_handle)->GetLang();
while (audio.Fetch(buff, len, flag, start_time) > 0) {
- string msg = (offline_stream->asr_handle)->Forward(buff, len, true, hw_emb);
+ // dec reset
+ funasr::WfstDecoder* wfst_decoder = (funasr::WfstDecoder*)dec_handle;
+ if (wfst_decoder){
+ wfst_decoder->StartUtterance();
+ }
+ string msg = (offline_stream->asr_handle)->Forward(buff, len, true, hw_emb, dec_handle);
std::vector<std::string> msg_vec = funasr::split(msg, '|');
if(msg_vec.size()==0){
continue;
@@ -630,6 +640,25 @@
}
}
+ // APIs for decoder status reset
+ _FUNASRAPI void FunASRReset(FUNASR_HANDLE handle, FUNASR_DEC_HANDLE dec_handle)
+ {
+ funasr::Model* recog_obj = (funasr::Model*)handle;
+ recog_obj->StartUtterance();
+ funasr::WfstDecoder* wfst_decoder = (funasr::WfstDecoder*)dec_handle;
+ if (wfst_decoder)
+ wfst_decoder->StartUtterance();
+ }
+
+ _FUNASRAPI void FunOfflineReset(FUNASR_HANDLE handle, FUNASR_DEC_HANDLE dec_handle)
+ {
+ funasr::OfflineStream* recog_obj = (funasr::OfflineStream*)handle;
+ recog_obj->asr_handle->StartUtterance();
+ funasr::WfstDecoder* wfst_decoder = (funasr::WfstDecoder*)dec_handle;
+ if (wfst_decoder)
+ wfst_decoder->StartUtterance();
+ }
+
// APIs for Uninit
_FUNASRAPI void FunASRUninit(FUNASR_HANDLE handle)
{
@@ -691,4 +720,38 @@
delete tpass_online_stream;
}
+ _FUNASRAPI FUNASR_DEC_HANDLE FunASRWfstDecoderInit(FUNASR_HANDLE handle, int asr_type, float glob_beam, float lat_beam, float am_scale)
+ {
+ funasr::WfstDecoder* mm = nullptr;
+ if (asr_type == ASR_OFFLINE) {
+ funasr::OfflineStream* offline_stream = (funasr::OfflineStream*)handle;
+ funasr::Paraformer* paraformer = (funasr::Paraformer*)offline_stream->asr_handle.get();
+ if (paraformer->lm_)
+ mm = new funasr::WfstDecoder(paraformer->lm_.get(),
+ paraformer->GetPhoneSet(), paraformer->GetVocab(), glob_beam, lat_beam, am_scale);
+ }
+ return mm;
+ }
+
+ _FUNASRAPI void FunASRWfstDecoderUninit(FUNASR_DEC_HANDLE handle)
+ {
+ funasr::WfstDecoder* wfst_decoder = (funasr::WfstDecoder*)handle;
+ if (!wfst_decoder)
+ return;
+ delete wfst_decoder;
+ }
+ _FUNASRAPI void FunWfstDecoderLoadHwsRes(FUNASR_DEC_HANDLE handle, int inc_bias, unordered_map<string, int> &hws_map)
+ {
+ funasr::WfstDecoder* wfst_decoder = (funasr::WfstDecoder*)handle;
+ if (!wfst_decoder)
+ return;
+ wfst_decoder->LoadHwsRes(inc_bias, hws_map);
+ }
+ _FUNASRAPI void FunWfstDecoderUnloadHwsRes(FUNASR_DEC_HANDLE handle)
+ {
+ funasr::WfstDecoder* wfst_decoder = (funasr::WfstDecoder*)handle;
+ if (!wfst_decoder)
+ return;
+ wfst_decoder->UnloadHwsRes();
+ }
diff --git a/funasr/runtime/onnxruntime/src/itn-processor.cpp b/runtime/onnxruntime/src/itn-processor.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/itn-processor.cpp
rename to runtime/onnxruntime/src/itn-processor.cpp
diff --git a/funasr/runtime/onnxruntime/src/itn-processor.h b/runtime/onnxruntime/src/itn-processor.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/itn-processor.h
rename to runtime/onnxruntime/src/itn-processor.h
diff --git a/funasr/runtime/onnxruntime/src/itn-token-parser.cpp b/runtime/onnxruntime/src/itn-token-parser.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/itn-token-parser.cpp
rename to runtime/onnxruntime/src/itn-token-parser.cpp
diff --git a/funasr/runtime/onnxruntime/src/itn-token-parser.h b/runtime/onnxruntime/src/itn-token-parser.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/itn-token-parser.h
rename to runtime/onnxruntime/src/itn-token-parser.h
diff --git a/funasr/runtime/onnxruntime/src/model.cpp b/runtime/onnxruntime/src/model.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/model.cpp
rename to runtime/onnxruntime/src/model.cpp
diff --git a/funasr/runtime/onnxruntime/src/offline-stream.cpp b/runtime/onnxruntime/src/offline-stream.cpp
similarity index 92%
rename from funasr/runtime/onnxruntime/src/offline-stream.cpp
rename to runtime/onnxruntime/src/offline-stream.cpp
index caea72e7f..2709ca6b2 100644
--- a/funasr/runtime/onnxruntime/src/offline-stream.cpp
+++ b/runtime/onnxruntime/src/offline-stream.cpp
@@ -61,6 +61,13 @@ OfflineStream::OfflineStream(std::map<std::string, std::string>& model_path, int
asr_handle->InitAsr(am_model_path, am_cmvn_path, am_config_path, thread_num);
}
+ // Lm resource
+ if (model_path.find(LM_DIR) != model_path.end() && model_path.at(LM_DIR) != "") {
+ string fst_path, lm_config_path, hws_path;
+ fst_path = PathAppend(model_path.at(LM_DIR), LM_FST_RES);
+ lm_config_path = PathAppend(model_path.at(LM_DIR), LM_CONFIG_NAME);
+ asr_handle->InitLm(fst_path, lm_config_path);
+ }
// PUNC model
if(model_path.find(PUNC_DIR) != model_path.end()){
diff --git a/funasr/runtime/onnxruntime/src/paraformer-online.cpp b/runtime/onnxruntime/src/paraformer-online.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/paraformer-online.cpp
rename to runtime/onnxruntime/src/paraformer-online.cpp
diff --git a/funasr/runtime/onnxruntime/src/paraformer-online.h b/runtime/onnxruntime/src/paraformer-online.h
similarity index 97%
rename from funasr/runtime/onnxruntime/src/paraformer-online.h
rename to runtime/onnxruntime/src/paraformer-online.h
index 86ee36382..932785c56 100644
--- a/funasr/runtime/onnxruntime/src/paraformer-online.h
+++ b/runtime/onnxruntime/src/paraformer-online.h
@@ -39,6 +39,14 @@ namespace funasr {
vector<const char*> &de_szOutputNames,
vector<float> &means_list,
vector<float> &vars_list);
+
+ void StartUtterance()
+ {
+ }
+
+ void EndUtterance()
+ {
+ }
Paraformer* para_handle_ = nullptr;
// from para_handle_
diff --git a/funasr/runtime/onnxruntime/src/paraformer.cpp b/runtime/onnxruntime/src/paraformer.cpp
similarity index 72%
rename from funasr/runtime/onnxruntime/src/paraformer.cpp
rename to runtime/onnxruntime/src/paraformer.cpp
index 5bbaeef4c..b6babfefe 100644
--- a/funasr/runtime/onnxruntime/src/paraformer.cpp
+++ b/runtime/onnxruntime/src/paraformer.cpp
@@ -66,6 +66,7 @@ void Paraformer::InitAsr(const std::string &am_model, const std::string &am_cmvn
m_szOutputNames.push_back(item.c_str());
vocab = new Vocab(am_config.c_str());
LoadConfigFromYaml(am_config.c_str());
+ phone_set_ = new PhoneSet(am_config.c_str());
LoadCmvn(am_cmvn.c_str());
}
@@ -143,6 +144,7 @@ void Paraformer::InitAsr(const std::string &en_model, const std::string &de_mode
de_szOutputNames_.push_back(item.c_str());
vocab = new Vocab(am_config.c_str());
+ phone_set_ = new PhoneSet(am_config.c_str());
LoadCmvn(am_cmvn.c_str());
}
@@ -184,6 +186,20 @@ void Paraformer::InitAsr(const std::string &am_model, const std::string &en_mode
m_szOutputNames.push_back(item.c_str());
}
+void Paraformer::InitLm(const std::string &lm_file,
+ const std::string &lm_cfg_file) {
+ try {
+ lm_ = std::shared_ptr<fst::Fst<fst::StdArc>>(
+ fst::Fst<fst::StdArc>::Read(lm_file));
+ if (vocab) { delete vocab; }
+ vocab = new Vocab(lm_cfg_file.c_str());
+ LOG(INFO) << "Successfully load lm file " << lm_file;
+ } catch (std::exception const &e) {
+ LOG(ERROR) << "Error when load lm file: " << e.what();
+ exit(0);
+ }
+}
+
void Paraformer::LoadConfigFromYaml(const char* filename){
YAML::Node config;
@@ -286,6 +302,14 @@ Paraformer::~Paraformer()
delete seg_dict;
}
+void Paraformer::StartUtterance()
+{
+}
+
+void Paraformer::EndUtterance()
+{
+}
+
void Paraformer::Reset()
{
}
@@ -377,229 +401,15 @@ string Paraformer::GreedySearch(float * in, int n_len, int64_t token_nums, bool
}
}
-string Paraformer::PostProcess(std::vector<string> &raw_char, std::vector<std::vector<float>> &timestamp_list){
- std::vector<std::vector<float>> timestamp_merge;
- int i;
- list<string> words;
- int is_pre_english = false;
- int pre_english_len = 0;
- int is_combining = false;
- string combine = "";
-
- float begin=-1;
- for (i=0; i<raw_char.size(); i++){
- string word = raw_char[i];
- // step1 space character skips
- if (word == "<s>" || word == "</s>" || word == "<unk>")
- continue;
- // step2 combie phoneme to full word
- {
- int sub_word = !(word.find("@@") == string::npos);
- // process word start and middle part
- if (sub_word) {
- combine += word.erase(word.length() - 2);
- if(!is_combining){
- begin = timestamp_list[i][0];
- }
- is_combining = true;
- continue;
- }
- // process word end part
- else if (is_combining) {
- combine += word;
- is_combining = false;
- word = combine;
- combine = "";
- }
- }
-
- // step3 process english word deal with space , turn abbreviation to upper case
- {
- // input word is chinese, not need process
- if (vocab->IsChinese(word)) {
- words.push_back(word);
- timestamp_merge.emplace_back(timestamp_list[i]);
- is_pre_english = false;
- }
- // input word is english word
- else {
- // pre word is chinese
- if (!is_pre_english) {
- // word[0] = word[0] - 32;
- words.push_back(word);
- begin = (begin==-1)?timestamp_list[i][0]:begin;
- std::vector<float> vec = {begin, timestamp_list[i][1]};
- timestamp_merge.emplace_back(vec);
- begin = -1;
- pre_english_len = word.size();
- }
- // pre word is english word
- else {
- // single letter turn to upper case
- // if (word.size() == 1) {
- // word[0] = word[0] - 32;
- // }
-
- if (pre_english_len > 1) {
- words.push_back(" ");
- words.push_back(word);
- begin = (begin==-1)?timestamp_list[i][0]:begin;
- std::vector<float> vec = {begin, timestamp_list[i][1]};
- timestamp_merge.emplace_back(vec);
- begin = -1;
- pre_english_len = word.size();
- }
- else {
- // if (word.size() > 1) {
- // words.push_back(" ");
- // }
- words.push_back(" ");
- words.push_back(word);
- begin = (begin==-1)?timestamp_list[i][0]:begin;
- std::vector<float> vec = {begin, timestamp_list[i][1]};
- timestamp_merge.emplace_back(vec);
- begin = -1;
- pre_english_len = word.size();
- }
- }
- is_pre_english = true;
- }
- }
- }
- string stamp_str="";
- for (i=0; i<timestamp_merge.size(); i++) {
- stamp_str += std::to_string(timestamp_merge[i][0]);
- stamp_str += ", ";
- stamp_str += std::to_string(timestamp_merge[i][1]);
- if(i!=timestamp_merge.size()-1){
- stamp_str += ",";
- }
- }
-
- stringstream ss;
- for (auto it = words.begin(); it != words.end(); it++) {
- ss << *it;
- }
-
- return ss.str()+" | "+stamp_str;
+string Paraformer::BeamSearch(WfstDecoder* &wfst_decoder, float *in, int len, int64_t token_nums)
+{
+ return wfst_decoder->Search(in, len, token_nums);
}
-void Paraformer::TimestampOnnx(std::vector<float>& us_alphas,
- std::vector<float> us_cif_peak,
- std::vector<string>& char_list,
- std::string &res_str,
- std::vector<std::vector<float>> &timestamp_vec,
- float begin_time,
- float total_offset){
- if (char_list.empty()) {
- return ;
- }
-
- const float START_END_THRESHOLD = 5.0;
- const float MAX_TOKEN_DURATION = 30.0;
- const float TIME_RATE = 10.0 * 6 / 1000 / 3;
- // 3 times upsampled, cif_peak is flattened into a 1D array
- std::vector<float> cif_peak = us_cif_peak;
- int num_frames = cif_peak.size();
- if (char_list.back() == "</s>") {
- char_list.pop_back();
- }
- if (char_list.empty()) {
- return ;
- }
- vector<vector<float>> timestamp_list;
- vector<string> new_char_list;
- vector<float> fire_place;
- // for bicif model trained with large data, cif2 actually fires when a character starts
- // so treat the frames between two peaks as the duration of the former token
- for (int i = 0; i < num_frames; i++) {
- if (cif_peak[i] > 1.0 - 1e-4) {
- fire_place.push_back(i + total_offset);
- }
- }
- int num_peak = fire_place.size();
- if(num_peak != (int)char_list.size() + 1){
- float sum = std::accumulate(us_alphas.begin(), us_alphas.end(), 0.0f);
- float scale = sum/((int)char_list.size() + 1);
- if(scale == 0){
- return;
- }
- cif_peak.clear();
- sum = 0.0;
- for(auto &alpha:us_alphas){
- alpha = alpha/scale;
- sum += alpha;
- cif_peak.emplace_back(sum);
- if(sum>=1.0 - 1e-4){
- sum -=(1.0 - 1e-4);
- }
- }
-
- fire_place.clear();
- for (int i = 0; i < num_frames; i++) {
- if (cif_peak[i] > 1.0 - 1e-4) {
- fire_place.push_back(i + total_offset);
- }
- }
- }
-
- num_peak = fire_place.size();
- if(fire_place.size() == 0){
- return;
- }
-
- // begin silence
- if (fire_place[0] > START_END_THRESHOLD) {
- new_char_list.push_back("<sil>");
- timestamp_list.push_back({0.0, fire_place[0] * TIME_RATE});
- }
-
- // tokens timestamp
- for (int i = 0; i < num_peak - 1; i++) {
- new_char_list.push_back(char_list[i]);
- if (i == num_peak - 2 || MAX_TOKEN_DURATION < 0 || fire_place[i + 1] - fire_place[i] < MAX_TOKEN_DURATION) {
- timestamp_list.push_back({fire_place[i] * TIME_RATE, fire_place[i + 1] * TIME_RATE});
- } else {
- // cut the duration to token and sil of the 0-weight frames last long
- float _split = fire_place[i] + MAX_TOKEN_DURATION;
- timestamp_list.push_back({fire_place[i] * TIME_RATE, _split * TIME_RATE});
- timestamp_list.push_back({_split * TIME_RATE, fire_place[i + 1] * TIME_RATE});
- new_char_list.push_back("<sil>");
- }
- }
-
- // tail token and end silence
- if(timestamp_list.size()==0){
- LOG(ERROR)<<"timestamp_list's size is 0!";
- return;
- }
- if (num_frames - fire_place.back() > START_END_THRESHOLD) {
- float _end = (num_frames + fire_place.back()) / 2.0;
- timestamp_list.back()[1] = _end * TIME_RATE;
- timestamp_list.push_back({_end * TIME_RATE, num_frames * TIME_RATE});
- new_char_list.push_back("<sil>");
- } else {
- timestamp_list.back()[1] = num_frames * TIME_RATE;
- }
-
- if (begin_time) { // add offset time in model with vad
- for (auto& timestamp : timestamp_list) {
- timestamp[0] += begin_time / 1000.0;
- timestamp[1] += begin_time / 1000.0;
- }
- }
-
- assert(new_char_list.size() == timestamp_list.size());
-
- for (int i = 0; i < (int)new_char_list.size(); i++) {
- res_str += new_char_list[i] + " " + to_string(timestamp_list[i][0]) + " " + to_string(timestamp_list[i][1]) + ";";
- }
-
- for (int i = 0; i < (int)new_char_list.size(); i++) {
- if(new_char_list[i] != "<sil>"){
- timestamp_vec.push_back(timestamp_list[i]);
- }
- }
+string Paraformer::FinalizeDecode(WfstDecoder* &wfst_decoder,
+ bool is_stamp, std::vector<float> us_alphas, std::vector<float> us_cif_peak)
+{
+ return wfst_decoder->FinalizeDecode(is_stamp, us_alphas, us_cif_peak);
}
vector<float> Paraformer::ApplyLfr(const std::vector<float> &in)
@@ -641,9 +451,9 @@ vector<float> Paraformer::ApplyLfr(const std::vector<float> &in)
}
}
-string Paraformer::Forward(float* din, int len, bool input_finished, const std::vector<std::vector<float>> &hw_emb)
+string Paraformer::Forward(float* din, int len, bool input_finished, const std::vector<std::vector<float>> &hw_emb, void* decoder_handle)
{
-
+ WfstDecoder* wfst_decoder = (WfstDecoder*)decoder_handle;
int32_t in_feat_dim = fbank_opts_.mel_opts.num_bins;
std::vector<float> wav_feats = FbankKaldi(MODEL_SAMPLE_RATE, din, len);
wav_feats = ApplyLfr(wav_feats);
@@ -725,9 +535,23 @@ string Paraformer::Forward(float* din, int len, bool input_finished, const std::
for (int i = 0; i < us_peaks_shape[1]; i++) {
us_peaks[i] = us_peaks_data[i];
}
- result = GreedySearch(floatData, *encoder_out_lens, outputShape[2], true, us_alphas, us_peaks);
+ if (lm_ == nullptr) {
+ result = GreedySearch(floatData, *encoder_out_lens, outputShape[2], true, us_alphas, us_peaks);
+ } else {
+ result = BeamSearch(wfst_decoder, floatData, *encoder_out_lens, outputShape[2]);
+ if (input_finished) {
+ result = FinalizeDecode(wfst_decoder, true, us_alphas, us_peaks);
+ }
+ }
}else{
- result = GreedySearch(floatData, *encoder_out_lens, outputShape[2]);
+ if (lm_ == nullptr) {
+ result = GreedySearch(floatData, *encoder_out_lens, outputShape[2]);
+ } else {
+ result = BeamSearch(wfst_decoder, floatData, *encoder_out_lens, outputShape[2]);
+ if (input_finished) {
+ result = FinalizeDecode(wfst_decoder);
+ }
+ }
}
}
catch (std::exception const &e)
@@ -773,11 +597,19 @@ std::vector<std::vector<float>> Paraformer::CompileHotwordEmbedding(std::string
}
std::vector<int32_t> hw_vector(max_hotword_len, 0);
int vector_len = std::min(max_hotword_len, (int)chars.size());
- for (int i=0; i<chars.size(); i++) {
- std::cout << chars[i] << " ";
- hw_vector[i] = vocab->GetIdByToken(chars[i]);
+ int chs_oov = false;
+ for (int i=0; i<vector_len; i++) {
+ hw_vector[i] = phone_set_->String2Id(chars[i]);
+ if(hw_vector[i] == -1){
+ chs_oov = true;
+ break;
+ }
+ }
+ if(chs_oov){
+ LOG(INFO) << "OOV: " << hotword;
+ continue;
}
- std::cout << std::endl;
+ LOG(INFO) << hotword;
lengths.push_back(vector_len);
real_hw_size += 1;
hotword_matrix.insert(hotword_matrix.end(), hw_vector.begin(), hw_vector.end());
@@ -834,6 +666,16 @@ std::vector<std::vector<float>> Paraformer::CompileHotwordEmbedding(std::string
return result;
}
+Vocab* Paraformer::GetVocab()
+{
+ return vocab;
+}
+
+PhoneSet* Paraformer::GetPhoneSet()
+{
+ return phone_set_;
+}
+
string Paraformer::Rescoring()
{
LOG(ERROR)<<"Not Imp!!!!!!";
diff --git a/funasr/runtime/onnxruntime/src/paraformer.h b/runtime/onnxruntime/src/paraformer.h
similarity index 79%
rename from funasr/runtime/onnxruntime/src/paraformer.h
rename to runtime/onnxruntime/src/paraformer.h
index 455078e1b..58de34532 100644
--- a/funasr/runtime/onnxruntime/src/paraformer.h
+++ b/runtime/onnxruntime/src/paraformer.h
@@ -5,6 +5,10 @@
#pragma once
#include "precomp.h"
+#include "fst/fstlib.h"
+#include "fst/symbol-table.h"
+#include "bias-lm.h"
+#include "phone-set.h"
namespace funasr {
@@ -17,6 +21,7 @@ namespace funasr {
private:
Vocab* vocab = nullptr;
SegDict* seg_dict = nullptr;
+ PhoneSet* phone_set_ = nullptr;
//const float scale = 22.6274169979695;
const float scale = 1.0;
@@ -47,15 +52,22 @@ namespace funasr {
std::vector<std::vector<float>> CompileHotwordEmbedding(std::string &hotwords);
void Reset();
vector<float> FbankKaldi(float sample_rate, const float* waves, int len);
- string Forward(float* din, int len, bool input_finished=true, const std::vector<std::vector<float>> &hw_emb={{0.0}});
- string GreedySearch( float* in, int n_len, int64_t token_nums, bool is_stamp=false, std::vector<float> us_alphas={0}, std::vector<float> us_cif_peak={0});
- void TimestampOnnx(std::vector<float> &us_alphas, vector<float> us_cif_peak, vector<string>& char_list, std::string &res_str,
- vector<vector<float>> &timestamp_list, float begin_time = 0.0, float total_offset = -1.5);
- string PostProcess(std::vector<string> &raw_char, std::vector<std::vector<float>> &timestamp_list);
+ string Forward(float* din, int len, bool input_finished=true, const std::vector<std::vector<float>> &hw_emb={{0.0}}, void* wfst_decoder=nullptr);
+ string GreedySearch( float* in, int n_len, int64_t token_nums,
+ bool is_stamp=false, std::vector<float> us_alphas={0}, std::vector<float> us_cif_peak={0});
string Rescoring();
string GetLang(){return language;};
-
+
+ void StartUtterance();
+ void EndUtterance();
+ void InitLm(const std::string &lm_file, const std::string &lm_cfg_file);
+ string BeamSearch(WfstDecoder* &wfst_decoder, float* in, int n_len, int64_t token_nums);
+ string FinalizeDecode(WfstDecoder* &wfst_decoder,
+ bool is_stamp=false, std::vector<float> us_alphas={0}, std::vector<float> us_cif_peak={0});
+ Vocab* GetVocab();
+ PhoneSet* GetPhoneSet();
+
knf::FbankOptions fbank_opts_;
vector<float> means_list_;
vector<float> vars_list_;
@@ -82,7 +94,10 @@ namespace funasr {
vector<string> de_strInputNames, de_strOutputNames;
vector<const char*> de_szInputNames_;
vector<const char*> de_szOutputNames_;
-
+
+ // lm
+ std::shared_ptr<fst::Fst<fst::StdArc>> lm_ = nullptr;
+
string window_type = "hamming";
int frame_length = 25;
int frame_shift = 10;
diff --git a/runtime/onnxruntime/src/phone-set.cpp b/runtime/onnxruntime/src/phone-set.cpp
new file mode 100644
index 000000000..167fa010a
--- /dev/null
+++ b/runtime/onnxruntime/src/phone-set.cpp
@@ -0,0 +1,76 @@
+#include "phone-set.h"
+#include <yaml-cpp/yaml.h>
+#include <glog/logging.h>
+
+#include <fstream>
+#include <iostream>
+#include <list>
+#include <sstream>
+#include <string>
+
+using namespace std;
+
+namespace funasr {
+PhoneSet::PhoneSet(const char *filename) {
+ ifstream in(filename);
+ LoadPhoneSetFromYaml(filename);
+}
+PhoneSet::~PhoneSet()
+{
+}
+
+void PhoneSet::LoadPhoneSetFromYaml(const char* filename) {
+ YAML::Node config;
+ try{
+ config = YAML::LoadFile(filename);
+ }catch(exception const &e){
+ LOG(INFO) << "Error loading file, yaml file error or not exist.";
+ exit(-1);
+ }
+ YAML::Node myList = config["token_list"];
+ int id = 0;
+ for (YAML::const_iterator it = myList.begin(); it != myList.end(); ++it, id++) {
+ phone_.push_back(it->as<string>());
+ phn2Id_.emplace(it->as<string>(), id);
+ }
+}
+
+int PhoneSet::Size() const {
+ return phone_.size();
+}
+
+int PhoneSet::String2Id(string phn_str) const {
+ if (phn2Id_.count(phn_str)) {
+ return phn2Id_.at(phn_str);
+ } else {
+ //LOG(INFO) << "Phone unit not exist.";
+ return -1;
+ }
+}
+
+string PhoneSet::Id2String(int id) const {
+ if (id < 0 || id > Size()) {
+ //LOG(INFO) << "Phone id not exist.";
+ return "";
+ } else {
+ return phone_[id];
+ }
+}
+
+bool PhoneSet::Find(string phn_str) const {
+ return phn2Id_.count(phn_str) > 0;
+}
+
+int PhoneSet::GetBegSilPhnId() const {
+ return String2Id(UNIT_BEG_SIL_SYMBOL);
+}
+
+int PhoneSet::GetEndSilPhnId() const {
+ return String2Id(UNIT_END_SIL_SYMBOL);
+}
+
+int PhoneSet::GetBlkPhnId() const {
+ return String2Id(UNIT_BLK_SYMBOL);
+}
+
+}
diff --git a/runtime/onnxruntime/src/phone-set.h b/runtime/onnxruntime/src/phone-set.h
new file mode 100644
index 000000000..972910408
--- /dev/null
+++ b/runtime/onnxruntime/src/phone-set.h
@@ -0,0 +1,34 @@
+#ifndef PHONESET_H
+#define PHONESET_H
+
+#include <stdint.h>
+#include <string>
+#include <vector>
+#include <unordered_map>
+#define UNIT_BEG_SIL_SYMBOL "<s>"
+#define UNIT_END_SIL_SYMBOL "</s>"
+#define UNIT_BLK_SYMBOL "<blank>"
+
+using namespace std;
+
+namespace funasr {
+class PhoneSet {
+ public:
+ PhoneSet(const char *filename);
+ ~PhoneSet();
+ int Size() const;
+ int String2Id(string str) const;
+ string Id2String(int id) const;
+ bool Find(string str) const;
+ int GetBegSilPhnId() const;
+ int GetEndSilPhnId() const;
+ int GetBlkPhnId() const;
+
+ private:
+ vector<string> phone_;
+ unordered_map<string, int> phn2Id_;
+ void LoadPhoneSetFromYaml(const char* filename);
+};
+
+} // namespace funasr
+#endif
diff --git a/funasr/runtime/onnxruntime/src/precomp.h b/runtime/onnxruntime/src/precomp.h
similarity index 93%
rename from funasr/runtime/onnxruntime/src/precomp.h
rename to runtime/onnxruntime/src/precomp.h
index 5c49fd6a5..d74608cdc 100644
--- a/funasr/runtime/onnxruntime/src/precomp.h
+++ b/runtime/onnxruntime/src/precomp.h
@@ -49,7 +49,7 @@ using namespace std;
#include "kaldi-native-fbank/csrc/feature-fbank.h"
#include "kaldi-native-fbank/csrc/online-feature.h"
-
+#include "kaldi/decoder/lattice-faster-online-decoder.h"
// mine
#include <glog/logging.h>
@@ -68,6 +68,8 @@ using namespace std;
#include "fsmn-vad.h"
#include "encode_converter.h"
#include "vocab.h"
+#include "phone-set.h"
+#include "wfst-decoder.h"
#include "audio.h"
#include "fsmn-vad-online.h"
#include "tensor.h"
diff --git a/funasr/runtime/onnxruntime/src/predefine-coe.h b/runtime/onnxruntime/src/predefine-coe.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/predefine-coe.h
rename to runtime/onnxruntime/src/predefine-coe.h
diff --git a/funasr/runtime/onnxruntime/src/punc-model.cpp b/runtime/onnxruntime/src/punc-model.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/punc-model.cpp
rename to runtime/onnxruntime/src/punc-model.cpp
diff --git a/funasr/runtime/onnxruntime/src/resample.cpp b/runtime/onnxruntime/src/resample.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/resample.cpp
rename to runtime/onnxruntime/src/resample.cpp
diff --git a/funasr/runtime/onnxruntime/src/resample.h b/runtime/onnxruntime/src/resample.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/resample.h
rename to runtime/onnxruntime/src/resample.h
diff --git a/funasr/runtime/onnxruntime/src/seg_dict.cpp b/runtime/onnxruntime/src/seg_dict.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/seg_dict.cpp
rename to runtime/onnxruntime/src/seg_dict.cpp
diff --git a/funasr/runtime/onnxruntime/src/seg_dict.h b/runtime/onnxruntime/src/seg_dict.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/seg_dict.h
rename to runtime/onnxruntime/src/seg_dict.h
diff --git a/funasr/runtime/onnxruntime/src/tensor.h b/runtime/onnxruntime/src/tensor.h
similarity index 98%
rename from funasr/runtime/onnxruntime/src/tensor.h
rename to runtime/onnxruntime/src/tensor.h
index a2a7bc366..4f05f6d61 100644
--- a/funasr/runtime/onnxruntime/src/tensor.h
+++ b/runtime/onnxruntime/src/tensor.h
@@ -2,7 +2,9 @@
#define TENSOR_H
#include "alignedmem.h"
-
+#include "stdio.h"
+#include <iostream>
+#include <cstring>
using namespace std;
namespace funasr {
diff --git a/funasr/runtime/onnxruntime/src/tokenizer.cpp b/runtime/onnxruntime/src/tokenizer.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/tokenizer.cpp
rename to runtime/onnxruntime/src/tokenizer.cpp
diff --git a/funasr/runtime/onnxruntime/src/tokenizer.h b/runtime/onnxruntime/src/tokenizer.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/tokenizer.h
rename to runtime/onnxruntime/src/tokenizer.h
diff --git a/funasr/runtime/onnxruntime/src/tpass-online-stream.cpp b/runtime/onnxruntime/src/tpass-online-stream.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/tpass-online-stream.cpp
rename to runtime/onnxruntime/src/tpass-online-stream.cpp
diff --git a/funasr/runtime/onnxruntime/src/tpass-stream.cpp b/runtime/onnxruntime/src/tpass-stream.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/tpass-stream.cpp
rename to runtime/onnxruntime/src/tpass-stream.cpp
diff --git a/funasr/runtime/onnxruntime/src/utf8-string.cpp b/runtime/onnxruntime/src/utf8-string.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/utf8-string.cpp
rename to runtime/onnxruntime/src/utf8-string.cpp
diff --git a/funasr/runtime/onnxruntime/src/utf8-string.h b/runtime/onnxruntime/src/utf8-string.h
similarity index 100%
rename from funasr/runtime/onnxruntime/src/utf8-string.h
rename to runtime/onnxruntime/src/utf8-string.h
diff --git a/runtime/onnxruntime/src/util.cpp b/runtime/onnxruntime/src/util.cpp
new file mode 100644
index 000000000..005de5797
--- /dev/null
+++ b/runtime/onnxruntime/src/util.cpp
@@ -0,0 +1,672 @@
+
+#include "precomp.h"
+
+namespace funasr {
+float *LoadParams(const char *filename)
+{
+
+ FILE *fp;
+ fp = fopen(filename, "rb");
+ fseek(fp, 0, SEEK_END);
+ uint32_t nFileLen = ftell(fp);
+ fseek(fp, 0, SEEK_SET);
+
+ float *params_addr = (float *)AlignedMalloc(32, nFileLen);
+ int n = fread(params_addr, 1, nFileLen, fp);
+ fclose(fp);
+
+ return params_addr;
+}
+
+int ValAlign(int val, int align)
+{
+ float tmp = ceil((float)val / (float)align) * (float)align;
+ return (int)tmp;
+}
+
+void DispParams(float *din, int size)
+{
+ int i;
+ for (i = 0; i < size; i++) {
+ printf("%f ", din[i]);
+ }
+ printf("\n");
+}
+void SaveDataFile(const char *filename, void *data, uint32_t len)
+{
+ FILE *fp;
+ fp = fopen(filename, "wb+");
+ fwrite(data, 1, len, fp);
+ fclose(fp);
+}
+
+void BasicNorm(Tensor<float> *&din, float norm)
+{
+
+ int Tmax = din->size[2];
+
+ int i, j;
+ for (i = 0; i < Tmax; i++) {
+ float sum = 0;
+ for (j = 0; j < 512; j++) {
+ int ii = i * 512 + j;
+ sum += din->buff[ii] * din->buff[ii];
+ }
+ float mean = sqrt(sum / 512 + norm);
+ for (j = 0; j < 512; j++) {
+ int ii = i * 512 + j;
+ din->buff[ii] = din->buff[ii] / mean;
+ }
+ }
+}
+
+void FindMax(float *din, int len, float &max_val, int &max_idx)
+{
+ int i;
+ max_val = -INFINITY;
+ max_idx = -1;
+ for (i = 0; i < len; i++) {
+ if (din[i] > max_val) {
+ max_val = din[i];
+ max_idx = i;
+ }
+ }
+}
+
+string PathAppend(const string &p1, const string &p2)
+{
+
+ char sep = '/';
+ string tmp = p1;
+
+#ifdef _WIN32
+ sep = '\\';
+#endif
+
+ if (p1[p1.length()-1] != sep) { // Need to add a
+ tmp += sep; // path separator
+ return (tmp + p2);
+ } else
+ return (p1 + p2);
+}
+
+void Relu(Tensor<float> *din)
+{
+ int i;
+ for (i = 0; i < din->buff_size; i++) {
+ float val = din->buff[i];
+ din->buff[i] = val < 0 ? 0 : val;
+ }
+}
+
+void Swish(Tensor<float> *din)
+{
+ int i;
+ for (i = 0; i < din->buff_size; i++) {
+ float val = din->buff[i];
+ din->buff[i] = val / (1 + exp(-val));
+ }
+}
+
+void Sigmoid(Tensor<float> *din)
+{
+ int i;
+ for (i = 0; i < din->buff_size; i++) {
+ float val = din->buff[i];
+ din->buff[i] = 1 / (1 + exp(-val));
+ }
+}
+
+void DoubleSwish(Tensor<float> *din)
+{
+ int i;
+ for (i = 0; i < din->buff_size; i++) {
+ float val = din->buff[i];
+ din->buff[i] = val / (1 + exp(-val + 1));
+ }
+}
+
+void Softmax(float *din, int mask, int len)
+{
+ float *tmp = (float *)malloc(mask * sizeof(float));
+ int i;
+ float sum = 0;
+ float max = -INFINITY;
+
+ for (i = 0; i < mask; i++) {
+ max = max < din[i] ? din[i] : max;
+ }
+
+ for (i = 0; i < mask; i++) {
+ tmp[i] = exp(din[i] - max);
+ sum += tmp[i];
+ }
+ for (i = 0; i < mask; i++) {
+ din[i] = tmp[i] / sum;
+ }
+ free(tmp);
+ for (i = mask; i < len; i++) {
+ din[i] = 0;
+ }
+}
+
+void LogSoftmax(float *din, int len)
+{
+ float *tmp = (float *)malloc(len * sizeof(float));
+ int i;
+ float sum = 0;
+ for (i = 0; i < len; i++) {
+ tmp[i] = exp(din[i]);
+ sum += tmp[i];
+ }
+ for (i = 0; i < len; i++) {
+ din[i] = log(tmp[i] / sum);
+ }
+ free(tmp);
+}
+
+void Glu(Tensor<float> *din, Tensor<float> *dout)
+{
+ int mm = din->buff_size / 1024;
+ int i, j;
+ for (i = 0; i < mm; i++) {
+ for (j = 0; j < 512; j++) {
+ int in_off = i * 1024 + j;
+ int out_off = i * 512 + j;
+ float a = din->buff[in_off];
+ float b = din->buff[in_off + 512];
+ dout->buff[out_off] = a / (1 + exp(-b));
+ }
+ }
+}
+
+bool is_target_file(const std::string& filename, const std::string target) {
+ std::size_t pos = filename.find_last_of(".");
+ if (pos == std::string::npos) {
+ return false;
+ }
+ std::string extension = filename.substr(pos + 1);
+ return (extension == target);
+}
+
+void KeepChineseCharacterAndSplit(const std::string &input_str,
+ std::vector<std::string> &chinese_characters) {
+ chinese_characters.resize(0);
+ std::vector<U16CHAR_T> u16_buf;
+ u16_buf.resize(std::max(u16_buf.size(), input_str.size() + 1));
+ U16CHAR_T* pu16 = u16_buf.data();
+ U8CHAR_T * pu8 = (U8CHAR_T*)input_str.data();
+ size_t ilen = input_str.size();
+ size_t len = EncodeConverter::Utf8ToUtf16(pu8, ilen, pu16, ilen + 1);
+ for (size_t i = 0; i < len; i++) {
+ if (EncodeConverter::IsChineseCharacter(pu16[i])) {
+ U8CHAR_T u8buf[4];
+ size_t n = EncodeConverter::Utf16ToUtf8(pu16 + i, u8buf);
+ u8buf[n] = '\0';
+ chinese_characters.push_back((const char*)u8buf);
+ }
+ }
+}
+
+void SplitChiEngCharacters(const std::string &input_str,
+ std::vector<std::string> &characters) {
+ characters.resize(0);
+ std::string eng_word = "";
+ U16CHAR_T space = 0x0020;
+ std::vector<U16CHAR_T> u16_buf;
+ u16_buf.resize(std::max(u16_buf.size(), input_str.size() + 1));
+ U16CHAR_T* pu16 = u16_buf.data();
+ U8CHAR_T * pu8 = (U8CHAR_T*)input_str.data();
+ size_t ilen = input_str.size();
+ size_t len = EncodeConverter::Utf8ToUtf16(pu8, ilen, pu16, ilen + 1);
+ for (size_t i = 0; i < len; i++) {
+ if (EncodeConverter::IsChineseCharacter(pu16[i])) {
+ if(!eng_word.empty()){
+ characters.push_back(eng_word);
+ eng_word = "";
+ }
+ U8CHAR_T u8buf[4];
+ size_t n = EncodeConverter::Utf16ToUtf8(pu16 + i, u8buf);
+ u8buf[n] = '\0';
+ characters.push_back((const char*)u8buf);
+ } else if (pu16[i] == space){
+ if(!eng_word.empty()){
+ characters.push_back(eng_word);
+ eng_word = "";
+ }
+ }else{
+ U8CHAR_T u8buf[4];
+ size_t n = EncodeConverter::Utf16ToUtf8(pu16 + i, u8buf);
+ u8buf[n] = '\0';
+ eng_word += (const char*)u8buf;
+ }
+ }
+ if(!eng_word.empty()){
+ characters.push_back(eng_word);
+ eng_word = "";
+ }
+}
+
+std::vector<std::string> split(const std::string &s, char delim) {
+ std::vector<std::string> elems;
+ std::stringstream ss(s);
+ std::string item;
+ while(std::getline(ss, item, delim)) {
+ elems.push_back(item);
+ }
+ return elems;
+}
+
+template<typename T>
+void PrintMat(const std::vector<std::vector<T>> &mat, const std::string &name) {
+ std::cout << name << ":" << std::endl;
+ for (auto item : mat) {
+ for (auto item_ : item) {
+ std::cout << item_ << " ";
+ }
+ std::cout << std::endl;
+ }
+}
+
+size_t Utf8ToCharset(const std::string &input, std::vector<std::string> &output) {
+ std::string ch;
+ for (size_t i = 0, len = 0; i != input.length(); i += len) {
+ unsigned char byte = (unsigned)input[i];
+ if (byte >= 0xFC) // lenght 6
+ len = 6;
+ else if (byte >= 0xF8)
+ len = 5;
+ else if (byte >= 0xF0)
+ len = 4;
+ else if (byte >= 0xE0)
+ len = 3;
+ else if (byte >= 0xC0)
+ len = 2;
+ else
+ len = 1;
+ ch = input.substr(i, len);
+ output.push_back(ch);
+ }
+ return output.size();
+}
+
+int Str2IntFunc(string str)
+{
+ const char *ch_array = str.c_str();
+ if (((ch_array[0] & 0xf0) != 0xe0) || ((ch_array[1] & 0xc0) != 0x80) ||
+ ((ch_array[2] & 0xc0) != 0x80))
+ return 0;
+ int val = ((ch_array[0] & 0x0f) << 12) | ((ch_array[1] & 0x3f) << 6) |
+ (ch_array[2] & 0x3f);
+ return val;
+}
+
+bool IsChinese(string ch)
+{
+ if (ch.size() != 3) {
+ return false;
+ }
+ int unicode = Str2IntFunc(ch);
+ if (unicode >= 19968 && unicode <= 40959) {
+ return true;
+ }
+ return false;
+}
+
+string PostProcess(std::vector<string> &raw_char, std::vector<std::vector<float>> &timestamp_list){
+ std::vector<std::vector<float>> timestamp_merge;
+ int i;
+ list<string> words;
+ int is_pre_english = false;
+ int pre_english_len = 0;
+ int is_combining = false;
+ string combine = "";
+
+ float begin=-1;
+ for (i=0; i<raw_char.size(); i++){
+ string word = raw_char[i];
+ // step1 space character skips
+ if (word == "<s>" || word == "</s>" || word == "<unk>")
+ continue;
+ // step2 combie phoneme to full word
+ {
+ int sub_word = !(word.find("@@") == string::npos);
+ // process word start and middle part
+ if (sub_word) {
+ combine += word.erase(word.length() - 2);
+ if(!is_combining){
+ begin = timestamp_list[i][0];
+ }
+ is_combining = true;
+ continue;
+ }
+ // process word end part
+ else if (is_combining) {
+ combine += word;
+ is_combining = false;
+ word = combine;
+ combine = "";
+ }
+ }
+
+ // step3 process english word deal with space , turn abbreviation to upper case
+ {
+ // input word is chinese, not need process
+ if (IsChinese(word)) {
+ words.push_back(word);
+ timestamp_merge.emplace_back(timestamp_list[i]);
+ is_pre_english = false;
+ }
+ // input word is english word
+ else {
+ // pre word is chinese
+ if (!is_pre_english) {
+ // word[0] = word[0] - 32;
+ words.push_back(word);
+ begin = (begin==-1)?timestamp_list[i][0]:begin;
+ std::vector<float> vec = {begin, timestamp_list[i][1]};
+ timestamp_merge.emplace_back(vec);
+ begin = -1;
+ pre_english_len = word.size();
+ }
+ // pre word is english word
+ else {
+ // single letter turn to upper case
+ // if (word.size() == 1) {
+ // word[0] = word[0] - 32;
+ // }
+
+ if (pre_english_len > 1) {
+ words.push_back(" ");
+ words.push_back(word);
+ begin = (begin==-1)?timestamp_list[i][0]:begin;
+ std::vector<float> vec = {begin, timestamp_list[i][1]};
+ timestamp_merge.emplace_back(vec);
+ begin = -1;
+ pre_english_len = word.size();
+ }
+ else {
+ // if (word.size() > 1) {
+ // words.push_back(" ");
+ // }
+ words.push_back(" ");
+ words.push_back(word);
+ begin = (begin==-1)?timestamp_list[i][0]:begin;
+ std::vector<float> vec = {begin, timestamp_list[i][1]};
+ timestamp_merge.emplace_back(vec);
+ begin = -1;
+ pre_english_len = word.size();
+ }
+ }
+ is_pre_english = true;
+ }
+ }
+ }
+ string stamp_str="";
+ for (i=0; i<timestamp_merge.size(); i++) {
+ stamp_str += std::to_string(timestamp_merge[i][0]);
+ stamp_str += ", ";
+ stamp_str += std::to_string(timestamp_merge[i][1]);
+ if(i!=timestamp_merge.size()-1){
+ stamp_str += ",";
+ }
+ }
+
+ stringstream ss;
+ for (auto it = words.begin(); it != words.end(); it++) {
+ ss << *it;
+ }
+
+ return ss.str()+" | "+stamp_str;
+}
+
+void TimestampOnnx( std::vector<float>& us_alphas,
+ std::vector<float> us_cif_peak,
+ std::vector<string>& char_list,
+ std::string &res_str,
+ std::vector<std::vector<float>> &timestamp_vec,
+ float begin_time,
+ float total_offset){
+ if (char_list.empty()) {
+ return ;
+ }
+
+ const float START_END_THRESHOLD = 5.0;
+ const float MAX_TOKEN_DURATION = 30.0;
+ const float TIME_RATE = 10.0 * 6 / 1000 / 3;
+ // 3 times upsampled, cif_peak is flattened into a 1D array
+ std::vector<float> cif_peak = us_cif_peak;
+ int num_frames = cif_peak.size();
+ if (char_list.back() == "</s>") {
+ char_list.pop_back();
+ }
+ if (char_list.empty()) {
+ return ;
+ }
+ vector<vector<float>> timestamp_list;
+ vector<string> new_char_list;
+ vector<float> fire_place;
+ // for bicif model trained with large data, cif2 actually fires when a character starts
+ // so treat the frames between two peaks as the duration of the former token
+ for (int i = 0; i < num_frames; i++) {
+ if (cif_peak[i] > 1.0 - 1e-4) {
+ fire_place.push_back(i + total_offset);
+ }
+ }
+ int num_peak = fire_place.size();
+ if(num_peak != (int)char_list.size() + 1){
+ float sum = std::accumulate(us_alphas.begin(), us_alphas.end(), 0.0f);
+ float scale = sum/((int)char_list.size() + 1);
+ if(scale == 0){
+ return;
+ }
+ cif_peak.clear();
+ sum = 0.0;
+ for(auto &alpha:us_alphas){
+ alpha = alpha/scale;
+ sum += alpha;
+ cif_peak.emplace_back(sum);
+ if(sum>=1.0 - 1e-4){
+ sum -=(1.0 - 1e-4);
+ }
+ }
+
+ fire_place.clear();
+ for (int i = 0; i < num_frames; i++) {
+ if (cif_peak[i] > 1.0 - 1e-4) {
+ fire_place.push_back(i + total_offset);
+ }
+ }
+ }
+
+ num_peak = fire_place.size();
+ if(fire_place.size() == 0){
+ return;
+ }
+
+ // begin silence
+ if (fire_place[0] > START_END_THRESHOLD) {
+ new_char_list.push_back("<sil>");
+ timestamp_list.push_back({0.0, fire_place[0] * TIME_RATE});
+ }
+
+ // tokens timestamp
+ for (int i = 0; i < num_peak - 1; i++) {
+ new_char_list.push_back(char_list[i]);
+ if (i == num_peak - 2 || MAX_TOKEN_DURATION < 0 || fire_place[i + 1] - fire_place[i] < MAX_TOKEN_DURATION) {
+ timestamp_list.push_back({fire_place[i] * TIME_RATE, fire_place[i + 1] * TIME_RATE});
+ } else {
+ // cut the duration to token and sil of the 0-weight frames last long
+ float _split = fire_place[i] + MAX_TOKEN_DURATION;
+ timestamp_list.push_back({fire_place[i] * TIME_RATE, _split * TIME_RATE});
+ timestamp_list.push_back({_split * TIME_RATE, fire_place[i + 1] * TIME_RATE});
+ new_char_list.push_back("<sil>");
+ }
+ }
+
+ // tail token and end silence
+ if(timestamp_list.size()==0){
+ LOG(ERROR)<<"timestamp_list's size is 0!";
+ return;
+ }
+ if (num_frames - fire_place.back() > START_END_THRESHOLD) {
+ float _end = (num_frames + fire_place.back()) / 2.0;
+ timestamp_list.back()[1] = _end * TIME_RATE;
+ timestamp_list.push_back({_end * TIME_RATE, num_frames * TIME_RATE});
+ new_char_list.push_back("<sil>");
+ } else {
+ timestamp_list.back()[1] = num_frames * TIME_RATE;
+ }
+
+ if (begin_time) { // add offset time in model with vad
+ for (auto& timestamp : timestamp_list) {
+ timestamp[0] += begin_time / 1000.0;
+ timestamp[1] += begin_time / 1000.0;
+ }
+ }
+
+ assert(new_char_list.size() == timestamp_list.size());
+
+ for (int i = 0; i < (int)new_char_list.size(); i++) {
+ res_str += new_char_list[i] + " " + to_string(timestamp_list[i][0]) + " " + to_string(timestamp_list[i][1]) + ";";
+ }
+
+ for (int i = 0; i < (int)new_char_list.size(); i++) {
+ if(new_char_list[i] != "<sil>"){
+ timestamp_vec.push_back(timestamp_list[i]);
+ }
+ }
+}
+
+bool IsTargetFile(const std::string& filename, const std::string target) {
+ std::size_t pos = filename.find_last_of(".");
+ if (pos == std::string::npos) {
+ return false;
+ }
+ std::string extension = filename.substr(pos + 1);
+ return (extension == target);
+}
+
+void Trim(std::string *str) {
+ const char *white_chars = " \t\n\r\f\v";
+
+ std::string::size_type pos = str->find_last_not_of(white_chars);
+ if (pos != std::string::npos) {
+ str->erase(pos + 1);
+ pos = str->find_first_not_of(white_chars);
+ if (pos != std::string::npos) str->erase(0, pos);
+ } else {
+ str->erase(str->begin(), str->end());
+ }
+}
+
+void SplitStringToVector(const std::string &full, const char *delim,
+ bool omit_empty_strings,
+ std::vector<std::string> *out) {
+ size_t start = 0, found = 0, end = full.size();
+ out->clear();
+ while (found != std::string::npos) {
+ found = full.find_first_of(delim, start);
+ // start != end condition is for when the delimiter is at the end
+ if (!omit_empty_strings || (found != start && start != end))
+ out->push_back(full.substr(start, found - start));
+ start = found + 1;
+ }
+}
+
+void ExtractHws(string hws_file, unordered_map<string, int> &hws_map)
+{
+ if(hws_file.empty()){
+ return;
+ }
+ std::string line;
+ std::ifstream ifs_hws(hws_file.c_str());
+ if(!ifs_hws.is_open()){
+ LOG(ERROR) << "Unable to open hotwords file: " << hws_file
+ << ". If you have not set hotwords, please ignore this message.";
+ return;
+ }
+ LOG(INFO) << "hotwords: ";
+ while (getline(ifs_hws, line)) {
+ Trim(&line);
+ if (line.empty()) {
+ continue;
+ }
+ float score = 1.0f;
+ std::vector<std::string> text;
+ SplitStringToVector(line, " ", true, &text);
+
+ if (text.size() > 1) {
+ try{
+ score = std::stof(text[text.size() - 1]);
+ }catch (std::exception const &e)
+ {
+ LOG(ERROR)<<e.what();
+ continue;
+ }
+ } else {
+ continue;
+ }
+ std::string hotword = "";
+ for (size_t i = 0; i < text.size()-1; ++i) {
+ hotword = hotword + text[i];
+ if(i != text.size()-2){
+ hotword = hotword + " ";
+ }
+ }
+
+ LOG(INFO) << hotword << " : " << score;
+ hws_map.emplace(hotword, score);
+ }
+ ifs_hws.close();
+}
+
+void ExtractHws(string hws_file, unordered_map<string, int> &hws_map, string& nn_hotwords_)
+{
+ if(hws_file.empty()){
+ return;
+ }
+ std::string line;
+ std::ifstream ifs_hws(hws_file.c_str());
+ if(!ifs_hws.is_open()){
+ LOG(ERROR) << "Unable to open hotwords file: " << hws_file
+ << ". If you have not set hotwords, please ignore this message.";
+ return;
+ }
+ LOG(INFO) << "hotwords: ";
+ while (getline(ifs_hws, line)) {
+ Trim(&line);
+ if (line.empty()) {
+ continue;
+ }
+ float score = 1.0f;
+ std::vector<std::string> text;
+ SplitStringToVector(line, " ", true, &text);
+
+ if (text.size() > 1) {
+ try{
+ score = std::stof(text[text.size() - 1]);
+ }catch (std::exception const &e)
+ {
+ LOG(ERROR)<<e.what();
+ continue;
+ }
+ } else {
+ continue;
+ }
+ std::string hotword = "";
+ for (size_t i = 0; i < text.size()-1; ++i) {
+ hotword = hotword + text[i];
+ if(i != text.size()-2){
+ hotword = hotword + " ";
+ }
+ }
+
+ nn_hotwords_ += " " + hotword;
+ LOG(INFO) << hotword << " : " << score;
+ hws_map.emplace(hotword, score);
+ }
+ ifs_hws.close();
+}
+
+} // namespace funasr
diff --git a/runtime/onnxruntime/src/util.h b/runtime/onnxruntime/src/util.h
new file mode 100644
index 000000000..3ccfa6b4e
--- /dev/null
+++ b/runtime/onnxruntime/src/util.h
@@ -0,0 +1,61 @@
+#ifndef UTIL_H
+#define UTIL_H
+#include <vector>
+#include <memory>
+#include <unordered_map>
+#include "tensor.h"
+
+using namespace std;
+
+namespace funasr {
+extern float *LoadParams(const char *filename);
+
+extern void SaveDataFile(const char *filename, void *data, uint32_t len);
+extern void Relu(Tensor<float> *din);
+extern void Swish(Tensor<float> *din);
+extern void Sigmoid(Tensor<float> *din);
+extern void DoubleSwish(Tensor<float> *din);
+
+extern void Softmax(float *din, int mask, int len);
+
+extern void LogSoftmax(float *din, int len);
+extern int ValAlign(int val, int align);
+extern void DispParams(float *din, int size);
+
+extern void BasicNorm(Tensor<float> *&din, float norm);
+
+extern void FindMax(float *din, int len, float &max_val, int &max_idx);
+
+extern void Glu(Tensor<float> *din, Tensor<float> *dout);
+
+string PathAppend(const string &p1, const string &p2);
+bool is_target_file(const std::string& filename, const std::string target);
+
+void KeepChineseCharacterAndSplit(const std::string &input_str,
+ std::vector<std::string> &chinese_characters);
+void SplitChiEngCharacters(const std::string &input_str,
+ std::vector<std::string> &characters);
+
+std::vector<std::string> split(const std::string &s, char delim);
+
+template<typename T>
+void PrintMat(const std::vector<std::vector<T>> &mat, const std::string &name);
+void Trim(std::string *str);
+size_t Utf8ToCharset(const std::string &input, std::vector<std::string> &output);
+void SplitStringToVector(const std::string &full, const char *delim,
+ bool omit_empty_strings,
+ std::vector<std::string> *out);
+string PostProcess(std::vector<string> &raw_char,
+ std::vector<std::vector<float>> &timestamp_list);
+void TimestampOnnx( std::vector<float>& us_alphas,
+ std::vector<float> us_cif_peak,
+ std::vector<string>& char_list,
+ std::string &res_str,
+ std::vector<std::vector<float>> &timestamp_vec,
+ float begin_time = 0.0,
+ float total_offset = -1.5);
+bool IsTargetFile(const std::string& filename, const std::string target);
+void ExtractHws(string hws_file, unordered_map<string, int> &hws_map);
+void ExtractHws(string hws_file, unordered_map<string, int> &hws_map, string& nn_hotwords_);
+} // namespace funasr
+#endif
diff --git a/funasr/runtime/onnxruntime/src/vad-model.cpp b/runtime/onnxruntime/src/vad-model.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/src/vad-model.cpp
rename to runtime/onnxruntime/src/vad-model.cpp
diff --git a/funasr/runtime/onnxruntime/src/vocab.cpp b/runtime/onnxruntime/src/vocab.cpp
similarity index 92%
rename from funasr/runtime/onnxruntime/src/vocab.cpp
rename to runtime/onnxruntime/src/vocab.cpp
index 2babc4082..bdedd84f3 100644
--- a/funasr/runtime/onnxruntime/src/vocab.cpp
+++ b/runtime/onnxruntime/src/vocab.cpp
@@ -52,6 +52,16 @@ void Vocab::Vector2String(vector<int> in, std::vector<std::string> &preds)
}
}
+string Vocab::Vector2String(vector<int> in)
+{
+ int i;
+ stringstream ss;
+ for (auto it = in.begin(); it != in.end(); it++) {
+ ss << vocab[*it];
+ }
+ return ss.str();
+}
+
int Str2Int(string str)
{
const char *ch_array = str.c_str();
@@ -63,6 +73,16 @@ int Str2Int(string str)
return val;
}
+string Vocab::Id2String(int id) const
+{
+ if (id < 0 || id >= vocab.size()) {
+ LOG(INFO) << "Error vocabulary id, this id do not exit.";
+ return "";
+ } else {
+ return vocab[id];
+ }
+}
+
bool Vocab::IsChinese(string ch)
{
if (ch.size() != 3) {
@@ -195,7 +215,7 @@ string Vocab::Vector2StringV2(vector<int> in, std::string language)
return ss.str();
}
-int Vocab::Size()
+int Vocab::Size() const
{
return vocab.size();
}
diff --git a/funasr/runtime/onnxruntime/src/vocab.h b/runtime/onnxruntime/src/vocab.h
similarity index 86%
rename from funasr/runtime/onnxruntime/src/vocab.h
rename to runtime/onnxruntime/src/vocab.h
index 23b4bd6e9..8834b972d 100644
--- a/funasr/runtime/onnxruntime/src/vocab.h
+++ b/runtime/onnxruntime/src/vocab.h
@@ -19,10 +19,12 @@ class Vocab {
public:
Vocab(const char *filename);
~Vocab();
- int Size();
+ int Size() const;
bool IsChinese(string ch);
void Vector2String(vector<int> in, std::vector<std::string> &preds);
+ string Vector2String(vector<int> in);
string Vector2StringV2(vector<int> in, std::string language="");
+ string Id2String(int id) const;
string WordFormat(std::string word);
int GetIdByToken(const std::string &token);
};
diff --git a/runtime/onnxruntime/src/wfst-decoder.cpp b/runtime/onnxruntime/src/wfst-decoder.cpp
new file mode 100644
index 000000000..0bd2bff80
--- /dev/null
+++ b/runtime/onnxruntime/src/wfst-decoder.cpp
@@ -0,0 +1,114 @@
+#include <wfst-decoder.h>
+namespace funasr {
+WfstDecoder::WfstDecoder(fst::Fst<fst::StdArc>* lm,
+ PhoneSet* phone_set, Vocab* vocab,
+ float glob_beam, float lat_beam, float am_scale)
+:dec_opts_(glob_beam, lat_beam, am_scale), decodable_(dec_opts_.acoustic_scale),
+ lm_(lm), phone_set_(phone_set), vocab_(vocab) {
+ decoder_ = std::shared_ptr<kaldi::LatticeFasterOnlineDecoder>(
+ new kaldi::LatticeFasterOnlineDecoder(*lm_, dec_opts_));
+}
+
+WfstDecoder::~WfstDecoder() {
+}
+
+void WfstDecoder::StartUtterance() {
+ if (decoder_) {
+ cur_frame_ = 0;
+ cur_token_ = 0;
+ decodable_.Reset();
+ decoder_->InitDecoding();
+ }
+}
+
+void WfstDecoder::EndUtterance() {
+}
+
+string WfstDecoder::Search(float *in, int len, int64_t token_num) {
+ string result;
+ if (len == 0) {
+ return "";
+ }
+ std::vector<std::vector<float>> logp_vec;
+ int blk_phn_id = phone_set_->GetBlkPhnId();
+ for (int i = 0; i < len - 1; i++) {
+ std::vector<float> tmp_logp;
+ for (int j = 0; j < token_num; j++) {
+ tmp_logp.push_back((in + i * token_num)[j]);
+ }
+ logp_vec.push_back(tmp_logp);
+ }
+ for (int i = 0; i < logp_vec.size(); i++) {
+ cur_frame_++;
+ decodable_.AcceptLoglikes(logp_vec[i]);
+ decoder_->AdvanceDecoding(&decodable_, 1);
+ cur_token_++;
+ }
+ if (cur_token_ > 0) {
+ std::vector<int> words;
+ kaldi::Lattice lattice;
+ decoder_->GetBestPath(&lattice, false);
+ std::vector<int> alignment;
+ kaldi::LatticeWeight weight;
+ fst::GetLinearSymbolSequence(lattice, &alignment, &words, &weight);
+ result = vocab_->Vector2StringV2(words);
+ }
+ return result;
+}
+
+string WfstDecoder::FinalizeDecode(bool is_stamp, std::vector<float> us_alphas, std::vector<float> us_cif_peak) {
+ string result;
+ if (cur_token_ > 0) {
+ std::vector<int> words;
+ kaldi::Lattice lattice;
+ decodable_.SetFinished();
+ decoder_->FinalizeDecoding();
+ decoder_->GetBestPath(&lattice, true);
+ std::vector<int> alignment;
+ kaldi::LatticeWeight weight;
+ fst::GetLinearSymbolSequence(lattice, &alignment, &words, &weight);
+
+ if(!is_stamp){
+ return vocab_->Vector2StringV2(words);
+ }else{
+ std::vector<std::string> char_list;
+ std::vector<std::vector<float>> timestamp_list;
+ std::string res_str;
+ vocab_->Vector2String(words, char_list);
+ // split chinese word to char
+ std::vector<std::string> split_chars;
+ for(auto& word:char_list){
+ std::vector<std::string> word2char;
+ SplitChiEngCharacters(word, word2char);
+ split_chars.insert(split_chars.end(), word2char.begin(), word2char.end());
+ }
+ // std::vector<string> raw_char(char_list);
+ TimestampOnnx(us_alphas, us_cif_peak, split_chars, res_str, timestamp_list);
+
+ return PostProcess(split_chars, timestamp_list);
+ }
+ }
+ return result;
+}
+
+void WfstDecoder::LoadHwsRes(int inc_bias, unordered_map<string, int> &hws_map) {
+ try {
+ if (!hws_map.empty()) {
+ bias_lm_ = std::make_shared<BiasLm>(hws_map, inc_bias,
+ *phone_set_, *vocab_);
+ decoder_->SetBiasLm(bias_lm_);
+ }
+ } catch (std::exception const &e) {
+ LOG(ERROR) << "Error when load wfst hotwords resource: " << e.what();
+ exit(0);
+ }
+}
+
+void WfstDecoder::UnloadHwsRes() {
+ if (bias_lm_) {
+ decoder_->ClearBiasLm();
+ bias_lm_.reset();
+ }
+}
+
+} // namespace funasr
diff --git a/runtime/onnxruntime/src/wfst-decoder.h b/runtime/onnxruntime/src/wfst-decoder.h
new file mode 100644
index 000000000..1acf6d89c
--- /dev/null
+++ b/runtime/onnxruntime/src/wfst-decoder.h
@@ -0,0 +1,86 @@
+#ifndef WFST_DECODER_
+#define WFST_DECODER_
+#include "kaldi/decoder/lattice-faster-online-decoder.h"
+#include "model.h"
+#include "fst/fstlib.h"
+#include "fst/symbol-table.h"
+#include "bias-lm.h"
+#include "phone-set.h"
+#include "util.h"
+
+#define MAX_SCORE 10.0f
+namespace funasr {
+class Decodable : public kaldi::DecodableInterface {
+ public:
+ Decodable(float scale = 1.0f) : scale_(scale) {
+ Reset();
+ }
+ void Reset() {
+ num_frames_ = 0;
+ finished_ = false;
+ logp_.clear();
+ }
+
+ int NumFramesReady() const { return num_frames_; }
+
+ bool IsLastFrame(int frame) const {
+ return finished_ && (frame == num_frames_ - 1);
+ }
+
+ float LogLikelihood(int frm, int id) {
+ CHECK_GT(id, 0);
+ CHECK_LT(frm, num_frames_);
+ return scale_ * logp_[id - 1];
+ }
+
+ void AcceptLoglikes(const std::vector<float>& logp) {
+ num_frames_++;
+ logp_ = logp;
+ }
+
+ int NumIndices() const { return 0; }
+ void SetFinished() { finished_ = true; }
+
+ private:
+ int num_frames_ = 0;
+ float scale_ = 1.0f;
+ bool finished_ = false;
+ std::vector<float> logp_;
+};
+
+struct DecodeOptions : public kaldi::LatticeFasterDecoderConfig {
+ DecodeOptions(float glob_beam = 3.0f, float lat_beam = 3.0f, float ac_sc = 10.0f) :
+ kaldi::LatticeFasterDecoderConfig(glob_beam, lat_beam), acoustic_scale(ac_sc) {
+ }
+ float acoustic_scale;
+};
+
+class WfstDecoder {
+ public:
+ WfstDecoder(fst::Fst<fst::StdArc>* lm,
+ PhoneSet* phone_set,
+ Vocab* vocab,
+ float glob_beam,
+ float lat_beam,
+ float am_scale);
+ ~WfstDecoder();
+ void StartUtterance();
+ void EndUtterance();
+ string Search(float *in, int len, int64_t token_nums);
+ string FinalizeDecode(bool is_stamp=false, std::vector<float> us_alphas={0}, std::vector<float> us_cif_peak={0});
+ void LoadHwsRes(int inc_bias, unordered_map<string, int> &hws_map);
+ void UnloadHwsRes();
+
+ private:
+ Vocab* vocab_ = nullptr;
+ PhoneSet* phone_set_ = nullptr;
+ int cur_frame_ = 0;
+ int cur_token_ = 0;
+ DecodeOptions dec_opts_;
+ Decodable decodable_;
+ fst::Fst<fst::StdArc>* lm_ = nullptr;
+ std::shared_ptr<kaldi::LatticeFasterOnlineDecoder> decoder_ = nullptr;
+ std::shared_ptr<BiasLm> bias_lm_ = nullptr;
+};
+} // namespace funasr
+#endif // WFST_DECODER_
diff --git a/funasr/runtime/onnxruntime/third_party/download_ffmpeg.sh b/runtime/onnxruntime/third_party/download_ffmpeg.sh
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/download_ffmpeg.sh
rename to runtime/onnxruntime/third_party/download_ffmpeg.sh
diff --git a/funasr/runtime/onnxruntime/third_party/download_onnxruntime.sh b/runtime/onnxruntime/third_party/download_onnxruntime.sh
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/download_onnxruntime.sh
rename to runtime/onnxruntime/third_party/download_onnxruntime.sh
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/.gitattributes b/runtime/onnxruntime/third_party/gflags/.gitattributes
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/.gitattributes
rename to runtime/onnxruntime/third_party/gflags/.gitattributes
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/.gitmodules b/runtime/onnxruntime/third_party/gflags/.gitmodules
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/.gitmodules
rename to runtime/onnxruntime/third_party/gflags/.gitmodules
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/.travis.yml b/runtime/onnxruntime/third_party/gflags/.travis.yml
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/.travis.yml
rename to runtime/onnxruntime/third_party/gflags/.travis.yml
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/AUTHORS.txt b/runtime/onnxruntime/third_party/gflags/AUTHORS.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/AUTHORS.txt
rename to runtime/onnxruntime/third_party/gflags/AUTHORS.txt
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/CMakeLists.txt b/runtime/onnxruntime/third_party/gflags/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/CMakeLists.txt
rename to runtime/onnxruntime/third_party/gflags/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/COPYING.txt b/runtime/onnxruntime/third_party/gflags/COPYING.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/COPYING.txt
rename to runtime/onnxruntime/third_party/gflags/COPYING.txt
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/ChangeLog.txt b/runtime/onnxruntime/third_party/gflags/ChangeLog.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/ChangeLog.txt
rename to runtime/onnxruntime/third_party/gflags/ChangeLog.txt
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/INSTALL.md b/runtime/onnxruntime/third_party/gflags/INSTALL.md
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/INSTALL.md
rename to runtime/onnxruntime/third_party/gflags/INSTALL.md
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/README.md b/runtime/onnxruntime/third_party/gflags/README.md
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/README.md
rename to runtime/onnxruntime/third_party/gflags/README.md
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/WORKSPACE b/runtime/onnxruntime/third_party/gflags/WORKSPACE
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/WORKSPACE
rename to runtime/onnxruntime/third_party/gflags/WORKSPACE
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/appveyor.yml b/runtime/onnxruntime/third_party/gflags/appveyor.yml
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/appveyor.yml
rename to runtime/onnxruntime/third_party/gflags/appveyor.yml
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/bazel/gflags.bzl b/runtime/onnxruntime/third_party/gflags/bazel/gflags.bzl
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/bazel/gflags.bzl
rename to runtime/onnxruntime/third_party/gflags/bazel/gflags.bzl
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/cmake/README_runtime.txt b/runtime/onnxruntime/third_party/gflags/cmake/README_runtime.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/cmake/README_runtime.txt
rename to runtime/onnxruntime/third_party/gflags/cmake/README_runtime.txt
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/cmake/cmake_uninstall.cmake.in b/runtime/onnxruntime/third_party/gflags/cmake/cmake_uninstall.cmake.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/cmake/cmake_uninstall.cmake.in
rename to runtime/onnxruntime/third_party/gflags/cmake/cmake_uninstall.cmake.in
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/cmake/config.cmake.in b/runtime/onnxruntime/third_party/gflags/cmake/config.cmake.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/cmake/config.cmake.in
rename to runtime/onnxruntime/third_party/gflags/cmake/config.cmake.in
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/cmake/execute_test.cmake b/runtime/onnxruntime/third_party/gflags/cmake/execute_test.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/cmake/execute_test.cmake
rename to runtime/onnxruntime/third_party/gflags/cmake/execute_test.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/cmake/package.cmake.in b/runtime/onnxruntime/third_party/gflags/cmake/package.cmake.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/cmake/package.cmake.in
rename to runtime/onnxruntime/third_party/gflags/cmake/package.cmake.in
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/cmake/package.pc.in b/runtime/onnxruntime/third_party/gflags/cmake/package.pc.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/cmake/package.pc.in
rename to runtime/onnxruntime/third_party/gflags/cmake/package.pc.in
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/cmake/utils.cmake b/runtime/onnxruntime/third_party/gflags/cmake/utils.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/cmake/utils.cmake
rename to runtime/onnxruntime/third_party/gflags/cmake/utils.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/cmake/version.cmake.in b/runtime/onnxruntime/third_party/gflags/cmake/version.cmake.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/cmake/version.cmake.in
rename to runtime/onnxruntime/third_party/gflags/cmake/version.cmake.in
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/config.h b/runtime/onnxruntime/third_party/gflags/src/config.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/config.h
rename to runtime/onnxruntime/third_party/gflags/src/config.h
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/defines.h.in b/runtime/onnxruntime/third_party/gflags/src/defines.h.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/defines.h.in
rename to runtime/onnxruntime/third_party/gflags/src/defines.h.in
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/gflags.cc b/runtime/onnxruntime/third_party/gflags/src/gflags.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/gflags.cc
rename to runtime/onnxruntime/third_party/gflags/src/gflags.cc
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/gflags.h.in b/runtime/onnxruntime/third_party/gflags/src/gflags.h.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/gflags.h.in
rename to runtime/onnxruntime/third_party/gflags/src/gflags.h.in
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/gflags_completions.cc b/runtime/onnxruntime/third_party/gflags/src/gflags_completions.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/gflags_completions.cc
rename to runtime/onnxruntime/third_party/gflags/src/gflags_completions.cc
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/gflags_completions.h.in b/runtime/onnxruntime/third_party/gflags/src/gflags_completions.h.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/gflags_completions.h.in
rename to runtime/onnxruntime/third_party/gflags/src/gflags_completions.h.in
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/gflags_completions.sh b/runtime/onnxruntime/third_party/gflags/src/gflags_completions.sh
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/gflags_completions.sh
rename to runtime/onnxruntime/third_party/gflags/src/gflags_completions.sh
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/gflags_declare.h.in b/runtime/onnxruntime/third_party/gflags/src/gflags_declare.h.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/gflags_declare.h.in
rename to runtime/onnxruntime/third_party/gflags/src/gflags_declare.h.in
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/gflags_ns.h.in b/runtime/onnxruntime/third_party/gflags/src/gflags_ns.h.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/gflags_ns.h.in
rename to runtime/onnxruntime/third_party/gflags/src/gflags_ns.h.in
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/gflags_reporting.cc b/runtime/onnxruntime/third_party/gflags/src/gflags_reporting.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/gflags_reporting.cc
rename to runtime/onnxruntime/third_party/gflags/src/gflags_reporting.cc
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/mutex.h b/runtime/onnxruntime/third_party/gflags/src/mutex.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/mutex.h
rename to runtime/onnxruntime/third_party/gflags/src/mutex.h
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/util.h b/runtime/onnxruntime/third_party/gflags/src/util.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/util.h
rename to runtime/onnxruntime/third_party/gflags/src/util.h
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/windows_port.cc b/runtime/onnxruntime/third_party/gflags/src/windows_port.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/windows_port.cc
rename to runtime/onnxruntime/third_party/gflags/src/windows_port.cc
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/src/windows_port.h b/runtime/onnxruntime/third_party/gflags/src/windows_port.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/src/windows_port.h
rename to runtime/onnxruntime/third_party/gflags/src/windows_port.h
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/CMakeLists.txt b/runtime/onnxruntime/third_party/gflags/test/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/CMakeLists.txt
rename to runtime/onnxruntime/third_party/gflags/test/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/config/CMakeLists.txt b/runtime/onnxruntime/third_party/gflags/test/config/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/config/CMakeLists.txt
rename to runtime/onnxruntime/third_party/gflags/test/config/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/config/main.cc b/runtime/onnxruntime/third_party/gflags/test/config/main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/config/main.cc
rename to runtime/onnxruntime/third_party/gflags/test/config/main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/flagfile.1 b/runtime/onnxruntime/third_party/gflags/test/flagfile.1
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/flagfile.1
rename to runtime/onnxruntime/third_party/gflags/test/flagfile.1
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/flagfile.2 b/runtime/onnxruntime/third_party/gflags/test/flagfile.2
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/flagfile.2
rename to runtime/onnxruntime/third_party/gflags/test/flagfile.2
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/flagfile.3 b/runtime/onnxruntime/third_party/gflags/test/flagfile.3
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/flagfile.3
rename to runtime/onnxruntime/third_party/gflags/test/flagfile.3
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/gflags_build.py.in b/runtime/onnxruntime/third_party/gflags/test/gflags_build.py.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/gflags_build.py.in
rename to runtime/onnxruntime/third_party/gflags/test/gflags_build.py.in
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/gflags_declare_flags.cc b/runtime/onnxruntime/third_party/gflags/test/gflags_declare_flags.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/gflags_declare_flags.cc
rename to runtime/onnxruntime/third_party/gflags/test/gflags_declare_flags.cc
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/gflags_declare_test.cc b/runtime/onnxruntime/third_party/gflags/test/gflags_declare_test.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/gflags_declare_test.cc
rename to runtime/onnxruntime/third_party/gflags/test/gflags_declare_test.cc
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/gflags_strip_flags_test.cc b/runtime/onnxruntime/third_party/gflags/test/gflags_strip_flags_test.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/gflags_strip_flags_test.cc
rename to runtime/onnxruntime/third_party/gflags/test/gflags_strip_flags_test.cc
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/gflags_strip_flags_test.cmake b/runtime/onnxruntime/third_party/gflags/test/gflags_strip_flags_test.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/gflags_strip_flags_test.cmake
rename to runtime/onnxruntime/third_party/gflags/test/gflags_strip_flags_test.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/gflags_unittest.cc b/runtime/onnxruntime/third_party/gflags/test/gflags_unittest.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/gflags_unittest.cc
rename to runtime/onnxruntime/third_party/gflags/test/gflags_unittest.cc
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/gflags_unittest_flagfile b/runtime/onnxruntime/third_party/gflags/test/gflags_unittest_flagfile
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/gflags_unittest_flagfile
rename to runtime/onnxruntime/third_party/gflags/test/gflags_unittest_flagfile
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/nc/CMakeLists.txt b/runtime/onnxruntime/third_party/gflags/test/nc/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/nc/CMakeLists.txt
rename to runtime/onnxruntime/third_party/gflags/test/nc/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/gflags/test/nc/gflags_nc.cc b/runtime/onnxruntime/third_party/gflags/test/nc/gflags_nc.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/gflags/test/nc/gflags_nc.cc
rename to runtime/onnxruntime/third_party/gflags/test/nc/gflags_nc.cc
diff --git a/funasr/runtime/onnxruntime/third_party/glog/CMakeLists.txt b/runtime/onnxruntime/third_party/glog/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/CMakeLists.txt
rename to runtime/onnxruntime/third_party/glog/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/glog/cmake/DetermineGflagsNamespace.cmake b/runtime/onnxruntime/third_party/glog/cmake/DetermineGflagsNamespace.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/cmake/DetermineGflagsNamespace.cmake
rename to runtime/onnxruntime/third_party/glog/cmake/DetermineGflagsNamespace.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/glog/cmake/FindUnwind.cmake b/runtime/onnxruntime/third_party/glog/cmake/FindUnwind.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/cmake/FindUnwind.cmake
rename to runtime/onnxruntime/third_party/glog/cmake/FindUnwind.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/glog/cmake/GetCacheVariables.cmake b/runtime/onnxruntime/third_party/glog/cmake/GetCacheVariables.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/cmake/GetCacheVariables.cmake
rename to runtime/onnxruntime/third_party/glog/cmake/GetCacheVariables.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest1.cmake b/runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest1.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest1.cmake
rename to runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest1.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest2.cmake b/runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest2.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest2.cmake
rename to runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest2.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest3.cmake b/runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest3.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest3.cmake
rename to runtime/onnxruntime/third_party/glog/cmake/RunCleanerTest3.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/glog/cmake/TestInitPackageConfig.cmake b/runtime/onnxruntime/third_party/glog/cmake/TestInitPackageConfig.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/cmake/TestInitPackageConfig.cmake
rename to runtime/onnxruntime/third_party/glog/cmake/TestInitPackageConfig.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/glog/cmake/TestPackageConfig.cmake b/runtime/onnxruntime/third_party/glog/cmake/TestPackageConfig.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/cmake/TestPackageConfig.cmake
rename to runtime/onnxruntime/third_party/glog/cmake/TestPackageConfig.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/glog/glog-config.cmake.in b/runtime/onnxruntime/third_party/glog/glog-config.cmake.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/glog-config.cmake.in
rename to runtime/onnxruntime/third_party/glog/glog-config.cmake.in
diff --git a/funasr/runtime/onnxruntime/third_party/glog/glog-modules.cmake.in b/runtime/onnxruntime/third_party/glog/glog-modules.cmake.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/glog-modules.cmake.in
rename to runtime/onnxruntime/third_party/glog/glog-modules.cmake.in
diff --git a/funasr/runtime/onnxruntime/third_party/glog/libglog.pc.in b/runtime/onnxruntime/third_party/glog/libglog.pc.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/libglog.pc.in
rename to runtime/onnxruntime/third_party/glog/libglog.pc.in
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/base/commandlineflags.h b/runtime/onnxruntime/third_party/glog/src/base/commandlineflags.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/base/commandlineflags.h
rename to runtime/onnxruntime/third_party/glog/src/base/commandlineflags.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/base/googleinit.h b/runtime/onnxruntime/third_party/glog/src/base/googleinit.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/base/googleinit.h
rename to runtime/onnxruntime/third_party/glog/src/base/googleinit.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/base/mutex.h b/runtime/onnxruntime/third_party/glog/src/base/mutex.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/base/mutex.h
rename to runtime/onnxruntime/third_party/glog/src/base/mutex.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/config.h b/runtime/onnxruntime/third_party/glog/src/config.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/config.h
rename to runtime/onnxruntime/third_party/glog/src/config.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/config.h.cmake.in b/runtime/onnxruntime/third_party/glog/src/config.h.cmake.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/config.h.cmake.in
rename to runtime/onnxruntime/third_party/glog/src/config.h.cmake.in
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/demangle.cc b/runtime/onnxruntime/third_party/glog/src/demangle.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/demangle.cc
rename to runtime/onnxruntime/third_party/glog/src/demangle.cc
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/demangle.h b/runtime/onnxruntime/third_party/glog/src/demangle.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/demangle.h
rename to runtime/onnxruntime/third_party/glog/src/demangle.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/fuzz_demangle.cc b/runtime/onnxruntime/third_party/glog/src/fuzz_demangle.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/fuzz_demangle.cc
rename to runtime/onnxruntime/third_party/glog/src/fuzz_demangle.cc
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/glog/export.h b/runtime/onnxruntime/third_party/glog/src/glog/export.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/glog/export.h
rename to runtime/onnxruntime/third_party/glog/src/glog/export.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/glog/log_severity.h b/runtime/onnxruntime/third_party/glog/src/glog/log_severity.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/glog/log_severity.h
rename to runtime/onnxruntime/third_party/glog/src/glog/log_severity.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/glog/logging.h b/runtime/onnxruntime/third_party/glog/src/glog/logging.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/glog/logging.h
rename to runtime/onnxruntime/third_party/glog/src/glog/logging.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/glog/logging.h.in b/runtime/onnxruntime/third_party/glog/src/glog/logging.h.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/glog/logging.h.in
rename to runtime/onnxruntime/third_party/glog/src/glog/logging.h.in
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/glog/platform.h b/runtime/onnxruntime/third_party/glog/src/glog/platform.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/glog/platform.h
rename to runtime/onnxruntime/third_party/glog/src/glog/platform.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/glog/raw_logging.h b/runtime/onnxruntime/third_party/glog/src/glog/raw_logging.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/glog/raw_logging.h
rename to runtime/onnxruntime/third_party/glog/src/glog/raw_logging.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/glog/raw_logging.h.in b/runtime/onnxruntime/third_party/glog/src/glog/raw_logging.h.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/glog/raw_logging.h.in
rename to runtime/onnxruntime/third_party/glog/src/glog/raw_logging.h.in
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/glog/stl_logging.h b/runtime/onnxruntime/third_party/glog/src/glog/stl_logging.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/glog/stl_logging.h
rename to runtime/onnxruntime/third_party/glog/src/glog/stl_logging.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/glog/stl_logging.h.in b/runtime/onnxruntime/third_party/glog/src/glog/stl_logging.h.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/glog/stl_logging.h.in
rename to runtime/onnxruntime/third_party/glog/src/glog/stl_logging.h.in
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/glog/vlog_is_on.h b/runtime/onnxruntime/third_party/glog/src/glog/vlog_is_on.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/glog/vlog_is_on.h
rename to runtime/onnxruntime/third_party/glog/src/glog/vlog_is_on.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/glog/vlog_is_on.h.in b/runtime/onnxruntime/third_party/glog/src/glog/vlog_is_on.h.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/glog/vlog_is_on.h.in
rename to runtime/onnxruntime/third_party/glog/src/glog/vlog_is_on.h.in
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/logging.cc b/runtime/onnxruntime/third_party/glog/src/logging.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/logging.cc
rename to runtime/onnxruntime/third_party/glog/src/logging.cc
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/mock-log.h b/runtime/onnxruntime/third_party/glog/src/mock-log.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/mock-log.h
rename to runtime/onnxruntime/third_party/glog/src/mock-log.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/raw_logging.cc b/runtime/onnxruntime/third_party/glog/src/raw_logging.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/raw_logging.cc
rename to runtime/onnxruntime/third_party/glog/src/raw_logging.cc
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/signalhandler.cc b/runtime/onnxruntime/third_party/glog/src/signalhandler.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/signalhandler.cc
rename to runtime/onnxruntime/third_party/glog/src/signalhandler.cc
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/stacktrace.h b/runtime/onnxruntime/third_party/glog/src/stacktrace.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/stacktrace.h
rename to runtime/onnxruntime/third_party/glog/src/stacktrace.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_generic-inl.h b/runtime/onnxruntime/third_party/glog/src/stacktrace_generic-inl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_generic-inl.h
rename to runtime/onnxruntime/third_party/glog/src/stacktrace_generic-inl.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_libunwind-inl.h b/runtime/onnxruntime/third_party/glog/src/stacktrace_libunwind-inl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_libunwind-inl.h
rename to runtime/onnxruntime/third_party/glog/src/stacktrace_libunwind-inl.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_powerpc-inl.h b/runtime/onnxruntime/third_party/glog/src/stacktrace_powerpc-inl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_powerpc-inl.h
rename to runtime/onnxruntime/third_party/glog/src/stacktrace_powerpc-inl.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_unittest.cc b/runtime/onnxruntime/third_party/glog/src/stacktrace_unittest.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_unittest.cc
rename to runtime/onnxruntime/third_party/glog/src/stacktrace_unittest.cc
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_unwind-inl.h b/runtime/onnxruntime/third_party/glog/src/stacktrace_unwind-inl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_unwind-inl.h
rename to runtime/onnxruntime/third_party/glog/src/stacktrace_unwind-inl.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_windows-inl.h b/runtime/onnxruntime/third_party/glog/src/stacktrace_windows-inl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_windows-inl.h
rename to runtime/onnxruntime/third_party/glog/src/stacktrace_windows-inl.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_x86-inl.h b/runtime/onnxruntime/third_party/glog/src/stacktrace_x86-inl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/stacktrace_x86-inl.h
rename to runtime/onnxruntime/third_party/glog/src/stacktrace_x86-inl.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/symbolize.cc b/runtime/onnxruntime/third_party/glog/src/symbolize.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/symbolize.cc
rename to runtime/onnxruntime/third_party/glog/src/symbolize.cc
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/symbolize.h b/runtime/onnxruntime/third_party/glog/src/symbolize.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/symbolize.h
rename to runtime/onnxruntime/third_party/glog/src/symbolize.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/utilities.cc b/runtime/onnxruntime/third_party/glog/src/utilities.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/utilities.cc
rename to runtime/onnxruntime/third_party/glog/src/utilities.cc
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/utilities.h b/runtime/onnxruntime/third_party/glog/src/utilities.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/utilities.h
rename to runtime/onnxruntime/third_party/glog/src/utilities.h
diff --git a/funasr/runtime/onnxruntime/third_party/glog/src/vlog_is_on.cc b/runtime/onnxruntime/third_party/glog/src/vlog_is_on.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/glog/src/vlog_is_on.cc
rename to runtime/onnxruntime/third_party/glog/src/vlog_is_on.cc
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/DictTrie.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/DictTrie.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/DictTrie.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/DictTrie.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/FullSegment.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/FullSegment.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/FullSegment.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/FullSegment.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/HMMModel.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/HMMModel.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/HMMModel.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/HMMModel.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/HMMSegment.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/HMMSegment.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/HMMSegment.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/HMMSegment.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/Jieba.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/Jieba.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/Jieba.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/Jieba.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/KeywordExtractor.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/KeywordExtractor.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/KeywordExtractor.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/KeywordExtractor.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/MPSegment.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/MPSegment.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/MPSegment.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/MPSegment.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/MixSegment.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/MixSegment.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/MixSegment.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/MixSegment.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/PosTagger.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/PosTagger.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/PosTagger.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/PosTagger.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/PreFilter.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/PreFilter.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/PreFilter.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/PreFilter.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/QuerySegment.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/QuerySegment.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/QuerySegment.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/QuerySegment.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/SegmentBase.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/SegmentBase.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/SegmentBase.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/SegmentBase.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/SegmentTagged.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/SegmentTagged.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/SegmentTagged.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/SegmentTagged.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/TextRankExtractor.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/TextRankExtractor.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/TextRankExtractor.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/TextRankExtractor.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/Trie.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/Trie.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/Trie.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/Trie.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/Unicode.hpp b/runtime/onnxruntime/third_party/jieba/include/cppjieba/Unicode.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/cppjieba/Unicode.hpp
rename to runtime/onnxruntime/third_party/jieba/include/cppjieba/Unicode.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/ArgvContext.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/ArgvContext.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/ArgvContext.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/ArgvContext.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/BlockingQueue.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/BlockingQueue.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/BlockingQueue.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/BlockingQueue.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/BoundedBlockingQueue.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/BoundedBlockingQueue.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/BoundedBlockingQueue.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/BoundedBlockingQueue.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/BoundedQueue.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/BoundedQueue.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/BoundedQueue.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/BoundedQueue.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Closure.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/Closure.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Closure.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/Closure.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Colors.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/Colors.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Colors.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/Colors.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Condition.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/Condition.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Condition.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/Condition.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Config.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/Config.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Config.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/Config.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/FileLock.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/FileLock.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/FileLock.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/FileLock.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/ForcePublic.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/ForcePublic.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/ForcePublic.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/ForcePublic.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/LocalVector.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/LocalVector.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/LocalVector.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/LocalVector.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Logging.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/Logging.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Logging.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/Logging.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Md5.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/Md5.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Md5.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/Md5.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/MutexLock.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/MutexLock.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/MutexLock.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/MutexLock.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/NonCopyable.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/NonCopyable.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/NonCopyable.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/NonCopyable.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/StdExtension.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/StdExtension.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/StdExtension.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/StdExtension.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/StringUtil.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/StringUtil.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/StringUtil.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/StringUtil.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Thread.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/Thread.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/Thread.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/Thread.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/jieba/include/limonp/ThreadPool.hpp b/runtime/onnxruntime/third_party/jieba/include/limonp/ThreadPool.hpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/jieba/include/limonp/ThreadPool.hpp
rename to runtime/onnxruntime/third_party/jieba/include/limonp/ThreadPool.hpp
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/CMakeLists.txt b/runtime/onnxruntime/third_party/kaldi-native-fbank/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/CMakeLists.txt
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/FetchContent.cmake b/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/FetchContent.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/FetchContent.cmake
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/FetchContent.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/FetchContent/CMakeLists.cmake.in b/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/FetchContent/CMakeLists.cmake.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/FetchContent/CMakeLists.cmake.in
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/FetchContent/CMakeLists.cmake.in
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/README.md b/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/README.md
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/README.md
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/Modules/README.md
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/cmake_extension.py b/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/cmake_extension.py
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/cmake_extension.py
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/cmake_extension.py
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/googletest.cmake b/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/googletest.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/googletest.cmake
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/googletest.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/pybind11.cmake b/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/pybind11.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/pybind11.cmake
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/cmake/pybind11.cmake
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/CMakeLists.txt b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/CMakeLists.txt
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/CMakeLists.txt b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/CMakeLists.txt
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/CMakeLists.txt.bak b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/CMakeLists.txt.bak
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/CMakeLists.txt.bak
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/CMakeLists.txt.bak
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-fbank.cc b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-fbank.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-fbank.cc
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-fbank.cc
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-fbank.h b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-fbank.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-fbank.h
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-fbank.h
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-functions.cc b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-functions.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-functions.cc
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-functions.cc
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-functions.h b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-functions.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-functions.h
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-functions.h
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-window.cc b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-window.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-window.cc
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-window.cc
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-window.h b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-window.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-window.h
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/feature-window.h
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/fftsg.c b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/fftsg.c
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/fftsg.c
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/fftsg.c
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/log.cc b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/log.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/log.cc
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/log.cc
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/log.h b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/log.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/log.h
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/log.h
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/mel-computations.cc b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/mel-computations.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/mel-computations.cc
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/mel-computations.cc
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/mel-computations.h b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/mel-computations.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/mel-computations.h
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/mel-computations.h
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/online-feature.cc b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/online-feature.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/online-feature.cc
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/online-feature.cc
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/online-feature.h b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/online-feature.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/online-feature.h
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/online-feature.h
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/rfft.cc b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/rfft.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/rfft.cc
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/rfft.cc
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/rfft.h b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/rfft.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/rfft.h
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/rfft.h
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-log.cc b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-log.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-log.cc
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-log.cc
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-online-fbank.cc b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-online-fbank.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-online-fbank.cc
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-online-fbank.cc
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-online-feature.cc b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-online-feature.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-online-feature.cc
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-online-feature.cc
diff --git a/funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-rfft.cc b/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-rfft.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-rfft.cc
rename to runtime/onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc/test-rfft.cc
diff --git a/runtime/onnxruntime/third_party/kaldi/CMakeLists.txt b/runtime/onnxruntime/third_party/kaldi/CMakeLists.txt
new file mode 100644
index 000000000..1ff94d8af
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/CMakeLists.txt
@@ -0,0 +1,51 @@
+cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
+
+project(kaldi)
+
+add_library(kaldi-util
+ base/kaldi-error.cc
+ base/kaldi-math.cc
+ util/kaldi-io.cc
+ util/parse-options.cc
+ util/simple-io-funcs.cc
+ util/text-utils.cc
+)
+#target_link_libraries(kaldi-util PUBLIC utils)
+
+add_library(kaldi-decoder
+ lat/determinize-lattice-pruned.cc
+ lat/lattice-functions.cc
+ decoder/lattice-faster-decoder.cc
+ decoder/lattice-faster-online-decoder.cc
+)
+target_link_libraries(kaldi-decoder PUBLIC kaldi-util dl)
+
+include_directories(${CMAKE_SOURCE_DIR}/build/third_party/glog)
+include_directories(${CMAKE_SOURCE_DIR}/third_party/glog/src)
+include_directories(${CMAKE_SOURCE_DIR}/third_party/gflags/src/include)
+if(TRUE)
+ # Arpa binary
+ add_executable(arpa2fst
+ lm/arpa-file-parser.cc
+ lm/arpa-lm-compiler.cc
+ lmbin/arpa2fst.cc
+ )
+ target_link_libraries(arpa2fst PUBLIC kaldi-util fst dl)
+
+ # FST tools binary
+ set(FST_BINS
+ fstaddselfloops
+ fstdeterminizestar
+ fstisstochastic
+ fstminimizeencoded
+ fsttablecompose
+ )
+
+ foreach(name IN LISTS FST_BINS)
+ add_executable(${name}
+ fstbin/${name}.cc
+ fstext/kaldi-fst-io.cc
+ )
+ target_link_libraries(${name} PUBLIC kaldi-util fst dl)
+ endforeach()
+endif()
diff --git a/runtime/onnxruntime/third_party/kaldi/base/Makefile b/runtime/onnxruntime/third_party/kaldi/base/Makefile
new file mode 100644
index 000000000..49af4f87f
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/Makefile
@@ -0,0 +1,27 @@
+# Whenever make is run in this directory, call ./get_version.sh as the
+# first thing. This script regenereates ./version.h if necessary, e.g.
+# if it does not already exist or if the version number has changed.
+LOG := $(shell ./get_version.sh; echo " $$?")
+ifneq ($(strip $(LOG)), 0)
+ RC := $(lastword $(LOG))
+ OUT := $(wordlist 1,$(shell echo $$(($(words $(LOG))-1))),$(LOG))
+ ifeq ($(RC),0)
+ $(info $(OUT))
+ else
+ $(error $(OUT))
+ endif
+endif
+
+all:
+
+include ../kaldi.mk
+
+TESTFILES = kaldi-math-test io-funcs-test kaldi-error-test timer-test
+
+OBJFILES = kaldi-math.o kaldi-error.o io-funcs.o kaldi-utils.o timer.o
+
+LIBNAME = kaldi-base
+
+ADDLIBS =
+
+include ../makefiles/default_rules.mk
diff --git a/runtime/onnxruntime/third_party/kaldi/base/get_version.sh b/runtime/onnxruntime/third_party/kaldi/base/get_version.sh
new file mode 100755
index 000000000..610bc2208
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/get_version.sh
@@ -0,0 +1,94 @@
+#!/usr/bin/env bash
+
+# Copyright 2017 University of Southern California (Author: Dogan Can)
+
+# See ../../COPYING for clarification regarding multiple authors
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+# WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+# MERCHANTABLITY OR NON-INFRINGEMENT.
+# See the Apache 2 License for the specific language governing permissions and
+# limitations under the License.
+
+
+# Kaldi versioning is loosely based on the semantic versioning scheme. This
+# script tries to work out the version string from the partial version number
+# specified in src/.version along with the recent git history. By convention
+# src/.version specifies the first two components (MAJOR.MINOR) of the version
+# number. The third component (PATCH) is determined by counting how many
+# commits there are that are newer than than the last commit modifiying
+# src/.version. If there are uncommitted changes in the src/ directory, then
+# the version string is extended with a suffix (~N) specifiying the number of
+# files with uncommitted changes. The last component of the version string is
+# the abbreviated hash of the HEAD commit. If git history is not available or
+# if the file src/.short_version exists, then the version string defaults to
+# the number specified in src/.version.
+
+set -e
+
+# Change working directory to the directory where this script is located.
+cd "$(dirname ${BASH_SOURCE[0]})"
+
+# Read the partial version number specified in the first line of src/.version.
+version=$(head -1 ../.version)
+
+if [ -e ../.short_version ]; then
+ echo "$0: File src/.short_version exists."
+ echo "$0: Stopping the construction of full version number from git history."
+elif ! [[ $version =~ ^[0-9][0-9]*.[0-9][0-9]*$ ]]; then
+ echo "$0: The version number \"$version\" specified in src/.version is not" \
+ "in MAJOR.MINOR format."
+ echo "$0: Stopping the construction of full version number from git history."
+elif ! which git >&/dev/null; then
+ echo "$0: Git is not installed."
+ echo "$0: Using the version number \"$version\" specified in src/.version."
+elif [ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" != true ]; then
+ echo "$0: Git history is not available."
+ echo "$0: Using the version number \"$version\" specified in src/.version."
+else
+ # Figure out patch number.
+ version_commit=$(git log -1 --pretty=oneline ../.version | awk '{print $1}')
+ patch_number=$(git rev-list ${version_commit}..HEAD | wc -l | awk '{print $1}')
+ version="$version.$patch_number"
+
+ # Check for uncommitted changes in src/.
+ uncommitted_changes=$(git diff-index HEAD -- .. | wc -l | awk '{print $1}')
+ if [ $uncommitted_changes -gt 0 ]; then
+ # Add suffix ~N if there are N files in src/ with uncommitted changes
+ version="$version~$uncommitted_changes"
+ fi
+
+ # Figure out HEAD commit SHA-1.
+ head_commit=$(git log -1 --pretty=oneline | awk '{print $1}')
+ head_commit_short=$(git log -1 --oneline --abbrev=4 | awk '{print $1}')
+ version="$version-${head_commit_short}"
+fi
+
+# Empty version number is not allowed.
+if [ -z "$version" ]; then
+ version="?"
+fi
+
+# Write version info to a temporary file.
+temp=$(mktemp /tmp/temp.XXXXXX)
+trap 'rm -f "$temp"' EXIT
+echo "// This file was automatically created by ./get_version.sh." > $temp
+echo "// It is only included by ./kaldi-error.cc." >> $temp
+echo "#define KALDI_VERSION \"$version\"" >> $temp
+if [ -n "$head_commit" ]; then
+ echo "#define KALDI_GIT_HEAD \"$head_commit\"" >> $temp
+fi
+
+# Overwrite ./version.h with the temporary file if they are different.
+if ! cmp -s $temp version.h; then
+ cp $temp version.h
+ chmod 644 version.h
+fi
+exit 0
diff --git a/runtime/onnxruntime/third_party/kaldi/base/io-funcs-inl.h b/runtime/onnxruntime/third_party/kaldi/base/io-funcs-inl.h
new file mode 100644
index 000000000..b703ef5ad
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/io-funcs-inl.h
@@ -0,0 +1,327 @@
+// base/io-funcs-inl.h
+
+// Copyright 2009-2011 Microsoft Corporation; Saarland University;
+// Jan Silovsky; Yanmin Qian;
+// Johns Hopkins University (Author: Daniel Povey)
+// 2016 Xiaohui Zhang
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_BASE_IO_FUNCS_INL_H_
+#define KALDI_BASE_IO_FUNCS_INL_H_ 1
+
+// Do not include this file directly. It is included by base/io-funcs.h
+
+#include <limits>
+#include <vector>
+
+namespace kaldi {
+
+// Template that covers integers.
+template<class T> void WriteBasicType(std::ostream &os,
+ bool binary, T t) {
+ // Compile time assertion that this is not called with a wrong type.
+ KALDI_ASSERT_IS_INTEGER_TYPE(T);
+ if (binary) {
+ char len_c = (std::numeric_limits<T>::is_signed ? 1 : -1)
+ * static_cast<char>(sizeof(t));
+ os.put(len_c);
+ os.write(reinterpret_cast<const char *>(&t), sizeof(t));
+ } else {
+ if (sizeof(t) == 1)
+ os << static_cast<int16>(t) << " ";
+ else
+ os << t << " ";
+ }
+ if (os.fail()) {
+ KALDI_ERR << "Write failure in WriteBasicType.";
+ }
+}
+
+// Template that covers integers.
+template<class T> inline void ReadBasicType(std::istream &is,
+ bool binary, T *t) {
+ KALDI_PARANOID_ASSERT(t != NULL);
+ // Compile time assertion that this is not called with a wrong type.
+ KALDI_ASSERT_IS_INTEGER_TYPE(T);
+ if (binary) {
+ int len_c_in = is.get();
+ if (len_c_in == -1)
+ KALDI_ERR << "ReadBasicType: encountered end of stream.";
+ char len_c = static_cast<char>(len_c_in), len_c_expected
+ = (std::numeric_limits<T>::is_signed ? 1 : -1)
+ * static_cast<char>(sizeof(*t));
+ if (len_c != len_c_expected) {
+ KALDI_ERR << "ReadBasicType: did not get expected integer type, "
+ << static_cast<int>(len_c)
+ << " vs. " << static_cast<int>(len_c_expected)
+ << ". You can change this code to successfully"
+ << " read it later, if needed.";
+ // insert code here to read "wrong" type. Might have a switch statement.
+ }
+ is.read(reinterpret_cast<char *>(t), sizeof(*t));
+ } else {
+ if (sizeof(*t) == 1) {
+ int16 i;
+ is >> i;
+ *t = i;
+ } else {
+ is >> *t;
+ }
+ }
+ if (is.fail()) {
+ KALDI_ERR << "Read failure in ReadBasicType, file position is "
+ << is.tellg() << ", next char is " << is.peek();
+ }
+}
+
+// Template that covers integers.
+template<class T>
+inline void WriteIntegerPairVector(std::ostream &os, bool binary,
+ const std::vector<std::pair<T, T> > &v) {
+ // Compile time assertion that this is not called with a wrong type.
+ KALDI_ASSERT_IS_INTEGER_TYPE(T);
+ if (binary) {
+ char sz = sizeof(T); // this is currently just a check.
+ os.write(&sz, 1);
+ int32 vecsz = static_cast<int32>(v.size());
+ KALDI_ASSERT((size_t)vecsz == v.size());
+ os.write(reinterpret_cast<const char *>(&vecsz), sizeof(vecsz));
+ if (vecsz != 0) {
+ os.write(reinterpret_cast<const char *>(&(v[0])), sizeof(T) * vecsz * 2);
+ }
+ } else {
+ // focus here is on prettiness of text form rather than
+ // efficiency of reading-in.
+ // reading-in is dominated by low-level operations anyway:
+ // for efficiency use binary.
+ os << "[ ";
+ typename std::vector<std::pair<T, T> >::const_iterator iter = v.begin(),
+ end = v.end();
+ for (; iter != end; ++iter) {
+ if (sizeof(T) == 1)
+ os << static_cast<int16>(iter->first) << ','
+ << static_cast<int16>(iter->second) << ' ';
+ else
+ os << iter->first << ','
+ << iter->second << ' ';
+ }
+ os << "]\n";
+ }
+ if (os.fail()) {
+ KALDI_ERR << "Write failure in WriteIntegerPairVector.";
+ }
+}
+
+// Template that covers integers.
+template<class T>
+inline void ReadIntegerPairVector(std::istream &is, bool binary,
+ std::vector<std::pair<T, T> > *v) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(T);
+ KALDI_ASSERT(v != NULL);
+ if (binary) {
+ int sz = is.peek();
+ if (sz == sizeof(T)) {
+ is.get();
+ } else { // this is currently just a check.
+ KALDI_ERR << "ReadIntegerPairVector: expected to see type of size "
+ << sizeof(T) << ", saw instead " << sz << ", at file position "
+ << is.tellg();
+ }
+ int32 vecsz;
+ is.read(reinterpret_cast<char *>(&vecsz), sizeof(vecsz));
+ if (is.fail() || vecsz < 0) goto bad;
+ v->resize(vecsz);
+ if (vecsz > 0) {
+ is.read(reinterpret_cast<char *>(&((*v)[0])), sizeof(T)*vecsz*2);
+ }
+ } else {
+ std::vector<std::pair<T, T> > tmp_v; // use temporary so v doesn't use extra memory
+ // due to resizing.
+ is >> std::ws;
+ if (is.peek() != static_cast<int>('[')) {
+ KALDI_ERR << "ReadIntegerPairVector: expected to see [, saw "
+ << is.peek() << ", at file position " << is.tellg();
+ }
+ is.get(); // consume the '['.
+ is >> std::ws; // consume whitespace.
+ while (is.peek() != static_cast<int>(']')) {
+ if (sizeof(T) == 1) { // read/write chars as numbers.
+ int16 next_t1, next_t2;
+ is >> next_t1;
+ if (is.fail()) goto bad;
+ if (is.peek() != static_cast<int>(','))
+ KALDI_ERR << "ReadIntegerPairVector: expected to see ',', saw "
+ << is.peek() << ", at file position " << is.tellg();
+ is.get(); // consume the ','.
+ is >> next_t2 >> std::ws;
+ if (is.fail()) goto bad;
+ else
+ tmp_v.push_back(std::make_pair<T, T>((T)next_t1, (T)next_t2));
+ } else {
+ T next_t1, next_t2;
+ is >> next_t1;
+ if (is.fail()) goto bad;
+ if (is.peek() != static_cast<int>(','))
+ KALDI_ERR << "ReadIntegerPairVector: expected to see ',', saw "
+ << is.peek() << ", at file position " << is.tellg();
+ is.get(); // consume the ','.
+ is >> next_t2 >> std::ws;
+ if (is.fail()) goto bad;
+ else
+ tmp_v.push_back(std::pair<T, T>(next_t1, next_t2));
+ }
+ }
+ is.get(); // get the final ']'.
+ *v = tmp_v; // could use std::swap to use less temporary memory, but this
+ // uses less permanent memory.
+ }
+ if (!is.fail()) return;
+ bad:
+ KALDI_ERR << "ReadIntegerPairVector: read failure at file position "
+ << is.tellg();
+}
+
+template<class T> inline void WriteIntegerVector(std::ostream &os, bool binary,
+ const std::vector<T> &v) {
+ // Compile time assertion that this is not called with a wrong type.
+ KALDI_ASSERT_IS_INTEGER_TYPE(T);
+ if (binary) {
+ char sz = sizeof(T); // this is currently just a check.
+ os.write(&sz, 1);
+ int32 vecsz = static_cast<int32>(v.size());
+ KALDI_ASSERT((size_t)vecsz == v.size());
+ os.write(reinterpret_cast<const char *>(&vecsz), sizeof(vecsz));
+ if (vecsz != 0) {
+ os.write(reinterpret_cast<const char *>(&(v[0])), sizeof(T)*vecsz);
+ }
+ } else {
+ // focus here is on prettiness of text form rather than
+ // efficiency of reading-in.
+ // reading-in is dominated by low-level operations anyway:
+ // for efficiency use binary.
+ os << "[ ";
+ typename std::vector<T>::const_iterator iter = v.begin(), end = v.end();
+ for (; iter != end; ++iter) {
+ if (sizeof(T) == 1)
+ os << static_cast<int16>(*iter) << " ";
+ else
+ os << *iter << " ";
+ }
+ os << "]\n";
+ }
+ if (os.fail()) {
+ KALDI_ERR << "Write failure in WriteIntegerVector.";
+ }
+}
+
+
+template<class T> inline void ReadIntegerVector(std::istream &is,
+ bool binary,
+ std::vector<T> *v) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(T);
+ KALDI_ASSERT(v != NULL);
+ if (binary) {
+ int sz = is.peek();
+ if (sz == sizeof(T)) {
+ is.get();
+ } else { // this is currently just a check.
+ KALDI_ERR << "ReadIntegerVector: expected to see type of size "
+ << sizeof(T) << ", saw instead " << sz << ", at file position "
+ << is.tellg();
+ }
+ int32 vecsz;
+ is.read(reinterpret_cast<char *>(&vecsz), sizeof(vecsz));
+ if (is.fail() || vecsz < 0) goto bad;
+ v->resize(vecsz);
+ if (vecsz > 0) {
+ is.read(reinterpret_cast<char *>(&((*v)[0])), sizeof(T)*vecsz);
+ }
+ } else {
+ std::vector<T> tmp_v; // use temporary so v doesn't use extra memory
+ // due to resizing.
+ is >> std::ws;
+ if (is.peek() != static_cast<int>('[')) {
+ KALDI_ERR << "ReadIntegerVector: expected to see [, saw "
+ << is.peek() << ", at file position " << is.tellg();
+ }
+ is.get(); // consume the '['.
+ is >> std::ws; // consume whitespace.
+ while (is.peek() != static_cast<int>(']')) {
+ if (sizeof(T) == 1) { // read/write chars as numbers.
+ int16 next_t;
+ is >> next_t >> std::ws;
+ if (is.fail()) goto bad;
+ else
+ tmp_v.push_back((T)next_t);
+ } else {
+ T next_t;
+ is >> next_t >> std::ws;
+ if (is.fail()) goto bad;
+ else
+ tmp_v.push_back(next_t);
+ }
+ }
+ is.get(); // get the final ']'.
+ *v = tmp_v; // could use std::swap to use less temporary memory, but this
+ // uses less permanent memory.
+ }
+ if (!is.fail()) return;
+ bad:
+ KALDI_ERR << "ReadIntegerVector: read failure at file position "
+ << is.tellg();
+}
+
+
+// Initialize an opened stream for writing by writing an optional binary
+// header and modifying the floating-point precision.
+inline void InitKaldiOutputStream(std::ostream &os, bool binary) {
+ // This does not throw exceptions (does not check for errors).
+ if (binary) {
+ os.put('\0');
+ os.put('B');
+ }
+ // Note, in non-binary mode we may at some point want to mess with
+ // the precision a bit.
+ // 7 is a bit more than the precision of float..
+ if (os.precision() < 7)
+ os.precision(7);
+}
+
+/// Initialize an opened stream for reading by detecting the binary header and
+// setting the "binary" value appropriately.
+inline bool InitKaldiInputStream(std::istream &is, bool *binary) {
+ // Sets the 'binary' variable.
+ // Throws exception in the very unusual situation that stream
+ // starts with '\0' but not then 'B'.
+
+ if (is.peek() == '\0') { // seems to be binary
+ is.get();
+ if (is.peek() != 'B') {
+ return false;
+ }
+ is.get();
+ *binary = true;
+ return true;
+ } else {
+ *binary = false;
+ return true;
+ }
+}
+
+} // end namespace kaldi.
+
+#endif // KALDI_BASE_IO_FUNCS_INL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/base/io-funcs-test.cc b/runtime/onnxruntime/third_party/kaldi/base/io-funcs-test.cc
new file mode 100644
index 000000000..dd05326d5
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/io-funcs-test.cc
@@ -0,0 +1,160 @@
+// base/io-funcs-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#include "base/io-funcs.h"
+#include "base/kaldi-math.h"
+
+namespace kaldi {
+
+void UnitTestIo(bool binary) {
+ {
+ const char *filename = "tmpf";
+ std::ofstream outfile(filename, std::ios_base::out | std::ios_base::binary);
+ InitKaldiOutputStream(outfile, binary);
+ if (!binary) outfile << "\t";
+ int64 i1 = Rand() % 10000;
+ WriteBasicType(outfile, binary, i1);
+ uint16 i2 = Rand() % 10000;
+ WriteBasicType(outfile, binary, i2);
+ if (!binary) outfile << "\t";
+ char c = Rand();
+ WriteBasicType(outfile, binary, c);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ std::vector<int32> vec1;
+ WriteIntegerVector(outfile, binary, vec1);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ std::vector<uint16> vec2;
+ for (size_t i = 0; i < 10; i++) vec2.push_back(Rand()%100 - 10);
+ WriteIntegerVector(outfile, binary, vec2);
+ if (!binary) outfile << " \n";
+ std::vector<char> vec3;
+
+ int32 size = RandInt(0, 10);
+ for (size_t i = 0; i < size; i++) vec3.push_back(Rand()%100);
+ WriteIntegerVector(outfile, binary, vec3);
+ std::vector<std::pair<int32, int32> > vec4;
+ WriteIntegerPairVector(outfile, binary, vec4);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ std::vector<std::pair<uint16, uint16> > vec5;
+ for (size_t i = 0; i < size; i++) vec5.push_back(std::make_pair<uint16, uint16>(Rand()%100 - 10, Rand()%100 - 10));
+ WriteIntegerPairVector(outfile, binary, vec5);
+ if (!binary) outfile << " \n";
+ std::vector<std::pair<char, char> > vec6;
+ for (size_t i = 0; i < size; i++) vec6.push_back(std::make_pair<char, char>(Rand()%100, Rand()%100));
+ WriteIntegerPairVector(outfile, binary, vec6);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ const char *token1 = "Hi";
+ WriteToken(outfile, binary, token1);
+ if (!binary) outfile << " \n";
+ std::string token2 = "There.";
+ WriteToken(outfile, binary, token2);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ std::string token3 = "You.";
+ WriteToken(outfile, binary, token3);
+ if (!binary && Rand()%2 == 0) outfile << " ";
+ float f1 = RandUniform();
+ WriteBasicType(outfile, binary, f1);
+ if (!binary && Rand()%2 == 0) outfile << "\t";
+ float f2 = RandUniform();
+ WriteBasicType(outfile, binary, f2);
+ double d1 = RandUniform();
+ WriteBasicType(outfile, binary, d1);
+ if (!binary && Rand()%2 == 0) outfile << "\t";
+ double d2 = RandUniform();
+ WriteBasicType(outfile, binary, d2);
+ if (!binary && Rand()%2 == 0) outfile << "\t";
+ outfile.close();
+
+ {
+ std::ifstream infile(filename, std::ios_base::in | std::ios_base::binary);
+ bool binary_in;
+ InitKaldiInputStream(infile, &binary_in);
+ int64 i1_in;
+ ReadBasicType(infile, binary_in, &i1_in);
+ KALDI_ASSERT(i1_in == i1);
+ uint16 i2_in;
+ ReadBasicType(infile, binary_in, &i2_in);
+ KALDI_ASSERT(i2_in == i2);
+ char c_in;
+ ReadBasicType(infile, binary_in, &c_in);
+ KALDI_ASSERT(c_in == c);
+ std::vector<int32> vec1_in;
+ ReadIntegerVector(infile, binary_in, &vec1_in);
+ KALDI_ASSERT(vec1_in == vec1);
+ std::vector<uint16> vec2_in;
+ ReadIntegerVector(infile, binary_in, &vec2_in);
+ KALDI_ASSERT(vec2_in == vec2);
+ std::vector<char> vec3_in;
+ ReadIntegerVector(infile, binary_in, &vec3_in);
+ KALDI_ASSERT(vec3_in == vec3);
+ std::vector<std::pair<int32, int32> > vec4_in;
+ ReadIntegerPairVector(infile, binary_in, &vec4_in);
+ KALDI_ASSERT(vec4_in == vec4);
+ std::vector<std::pair<uint16, uint16> > vec5_in;
+ ReadIntegerPairVector(infile, binary_in, &vec5_in);
+ KALDI_ASSERT(vec5_in == vec5);
+ std::vector<std::pair<char, char> > vec6_in;
+ ReadIntegerPairVector(infile, binary_in, &vec6_in);
+ KALDI_ASSERT(vec6_in == vec6);
+ std::string token1_in, token2_in;
+ KALDI_ASSERT(Peek(infile, binary_in) == static_cast<int>(*token1));
+ KALDI_ASSERT(PeekToken(infile, binary_in) == static_cast<int>(*token1));
+ // Note:
+ // the stuff with skipping over '<' is tested in ../util/kaldi-io-test.cc,
+ // since we need to make sure it works with pipes.
+ ReadToken(infile, binary_in, &token1_in);
+ KALDI_ASSERT(token1_in == std::string(token1));
+ ReadToken(infile, binary_in, &token2_in);
+ KALDI_ASSERT(token2_in == std::string(token2));
+ if (Rand() % 2 == 0)
+ ExpectToken(infile, binary_in, token3.c_str());
+ else
+ ExpectToken(infile, binary_in, token3);
+ float f1_in; // same type.
+ ReadBasicType(infile, binary_in, &f1_in);
+ AssertEqual(f1_in, f1);
+ double f2_in; // wrong type.
+ ReadBasicType(infile, binary_in, &f2_in);
+ AssertEqual(f2_in, f2);
+ double d1_in; // same type.
+ ReadBasicType(infile, binary_in, &d1_in);
+ AssertEqual(d1_in, d1);
+ float d2_in; // wrong type.
+ ReadBasicType(infile, binary_in, &d2_in);
+ AssertEqual(d2_in, d2);
+ KALDI_ASSERT(Peek(infile, binary_in) == -1);
+ KALDI_ASSERT(PeekToken(infile, binary_in) == -1);
+ }
+ unlink(filename);
+ }
+}
+
+
+
+} // end namespace kaldi.
+
+int main() {
+ using namespace kaldi;
+ for (size_t i = 0; i < 10; i++) {
+ UnitTestIo(false);
+ UnitTestIo(true);
+ }
+ KALDI_ASSERT(1); // just to check that KALDI_ASSERT does not fail for 1.
+ return 0;
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/base/io-funcs.cc b/runtime/onnxruntime/third_party/kaldi/base/io-funcs.cc
new file mode 100644
index 000000000..150f74099
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/io-funcs.cc
@@ -0,0 +1,218 @@
+// base/io-funcs.cc
+
+// Copyright 2009-2011 Microsoft Corporation; Saarland University
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "base/io-funcs.h"
+#include "base/kaldi-math.h"
+
+namespace kaldi {
+
+template<>
+void WriteBasicType<bool>(std::ostream &os, bool binary, bool b) {
+ os << (b ? "T":"F");
+ if (!binary) os << " ";
+ if (os.fail())
+ KALDI_ERR << "Write failure in WriteBasicType<bool>";
+}
+
+template<>
+void ReadBasicType<bool>(std::istream &is, bool binary, bool *b) {
+ KALDI_PARANOID_ASSERT(b != NULL);
+ if (!binary) is >> std::ws; // eat up whitespace.
+ char c = is.peek();
+ if (c == 'T') {
+ *b = true;
+ is.get();
+ } else if (c == 'F') {
+ *b = false;
+ is.get();
+ } else {
+ KALDI_ERR << "Read failure in ReadBasicType<bool>, file position is "
+ << is.tellg() << ", next char is " << CharToString(c);
+ }
+}
+
+template<>
+void WriteBasicType<float>(std::ostream &os, bool binary, float f) {
+ if (binary) {
+ char c = sizeof(f);
+ os.put(c);
+ os.write(reinterpret_cast<const char *>(&f), sizeof(f));
+ } else {
+ os << f << " ";
+ }
+}
+
+template<>
+void WriteBasicType<double>(std::ostream &os, bool binary, double f) {
+ if (binary) {
+ char c = sizeof(f);
+ os.put(c);
+ os.write(reinterpret_cast<const char *>(&f), sizeof(f));
+ } else {
+ os << f << " ";
+ }
+}
+
+template<>
+void ReadBasicType<float>(std::istream &is, bool binary, float *f) {
+ KALDI_PARANOID_ASSERT(f != NULL);
+ if (binary) {
+ double d;
+ int c = is.peek();
+ if (c == sizeof(*f)) {
+ is.get();
+ is.read(reinterpret_cast<char*>(f), sizeof(*f));
+ } else if (c == sizeof(d)) {
+ ReadBasicType(is, binary, &d);
+ *f = d;
+ } else {
+ KALDI_ERR << "ReadBasicType: expected float, saw " << is.peek()
+ << ", at file position " << is.tellg();
+ }
+ } else {
+ is >> *f;
+ }
+ if (is.fail()) {
+ KALDI_ERR << "ReadBasicType: failed to read, at file position "
+ << is.tellg();
+ }
+}
+
+template<>
+void ReadBasicType<double>(std::istream &is, bool binary, double *d) {
+ KALDI_PARANOID_ASSERT(d != NULL);
+ if (binary) {
+ float f;
+ int c = is.peek();
+ if (c == sizeof(*d)) {
+ is.get();
+ is.read(reinterpret_cast<char*>(d), sizeof(*d));
+ } else if (c == sizeof(f)) {
+ ReadBasicType(is, binary, &f);
+ *d = f;
+ } else {
+ KALDI_ERR << "ReadBasicType: expected float, saw " << is.peek()
+ << ", at file position " << is.tellg();
+ }
+ } else {
+ is >> *d;
+ }
+ if (is.fail()) {
+ KALDI_ERR << "ReadBasicType: failed to read, at file position "
+ << is.tellg();
+ }
+}
+
+void CheckToken(const char *token) {
+ if (*token == '\0')
+ KALDI_ERR << "Token is empty (not a valid token)";
+ const char *orig_token = token;
+ while (*token != '\0') {
+ if (::isspace(*token))
+ KALDI_ERR << "Token is not a valid token (contains space): '"
+ << orig_token << "'";
+ token++;
+ }
+}
+
+void WriteToken(std::ostream &os, bool binary, const char *token) {
+ // binary mode is ignored;
+ // we use space as termination character in either case.
+ KALDI_ASSERT(token != NULL);
+ CheckToken(token); // make sure it's valid (can be read back)
+ os << token << " ";
+ if (os.fail()) {
+ KALDI_ERR << "Write failure in WriteToken.";
+ }
+}
+
+int Peek(std::istream &is, bool binary) {
+ if (!binary) is >> std::ws; // eat up whitespace.
+ return is.peek();
+}
+
+void WriteToken(std::ostream &os, bool binary, const std::string & token) {
+ WriteToken(os, binary, token.c_str());
+}
+
+void ReadToken(std::istream &is, bool binary, std::string *str) {
+ KALDI_ASSERT(str != NULL);
+ if (!binary) is >> std::ws; // consume whitespace.
+ is >> *str;
+ if (is.fail()) {
+ KALDI_ERR << "ReadToken, failed to read token at file position "
+ << is.tellg();
+ }
+ if (!isspace(is.peek())) {
+ KALDI_ERR << "ReadToken, expected space after token, saw instead "
+ << CharToString(static_cast<char>(is.peek()))
+ << ", at file position " << is.tellg();
+ }
+ is.get(); // consume the space.
+}
+
+int PeekToken(std::istream &is, bool binary) {
+ if (!binary) is >> std::ws; // consume whitespace.
+ bool read_bracket;
+ if (static_cast<char>(is.peek()) == '<') {
+ read_bracket = true;
+ is.get();
+ } else {
+ read_bracket = false;
+ }
+ int ans = is.peek();
+ if (read_bracket) {
+ if (!is.unget()) {
+ // Clear the bad bit. This code can be (and is in fact) reached, since the
+ // C++ standard does not guarantee that a call to unget() must succeed.
+ is.clear();
+ }
+ }
+ return ans;
+}
+
+
+void ExpectToken(std::istream &is, bool binary, const char *token) {
+ int pos_at_start = is.tellg();
+ KALDI_ASSERT(token != NULL);
+ CheckToken(token); // make sure it's valid (can be read back)
+ if (!binary) is >> std::ws; // consume whitespace.
+ std::string str;
+ is >> str;
+ is.get(); // consume the space.
+ if (is.fail()) {
+ KALDI_ERR << "Failed to read token [started at file position "
+ << pos_at_start << "], expected " << token;
+ }
+ // The second half of the '&&' expression below is so that if we're expecting
+ // "<Foo>", we will accept "Foo>" instead. This is so that the model-reading
+ // code will tolerate errors in PeekToken where is.unget() failed; search for
+ // is.clear() in PeekToken() for an explanation.
+ if (strcmp(str.c_str(), token) != 0 &&
+ !(token[0] == '<' && strcmp(str.c_str(), token + 1) == 0)) {
+ KALDI_ERR << "Expected token \"" << token << "\", got instead \""
+ << str <<"\".";
+ }
+}
+
+void ExpectToken(std::istream &is, bool binary, const std::string &token) {
+ ExpectToken(is, binary, token.c_str());
+}
+
+} // end namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/base/io-funcs.h b/runtime/onnxruntime/third_party/kaldi/base/io-funcs.h
new file mode 100644
index 000000000..895f661ec
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/io-funcs.h
@@ -0,0 +1,245 @@
+// base/io-funcs.h
+
+// Copyright 2009-2011 Microsoft Corporation; Saarland University;
+// Jan Silovsky; Yanmin Qian
+// 2016 Xiaohui Zhang
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_BASE_IO_FUNCS_H_
+#define KALDI_BASE_IO_FUNCS_H_
+
+// This header only contains some relatively low-level I/O functions.
+// The full Kaldi I/O declarations are in ../util/kaldi-io.h
+// and ../util/kaldi-table.h
+// They were put in util/ in order to avoid making the Matrix library
+// dependent on them.
+
+#include <cctype>
+#include <vector>
+#include <string>
+
+#include "base/kaldi-common.h"
+#include "base/io-funcs-inl.h"
+
+namespace kaldi {
+
+
+
+/*
+ This comment describes the Kaldi approach to I/O. All objects can be written
+ and read in two modes: binary and text. In addition we want to make the I/O
+ work if we redefine the typedef "BaseFloat" between floats and doubles.
+ We also want to have control over whitespace in text mode without affecting
+ the meaning of the file, for pretty-printing purposes.
+
+ Errors are handled by throwing a KaldiFatalError exception.
+
+ For integer and floating-point types (and boolean values):
+
+ WriteBasicType(std::ostream &, bool binary, const T&);
+ ReadBasicType(std::istream &, bool binary, T*);
+
+ and we expect these functions to be defined in such a way that they work when
+ the type T changes between float and double, so you can read float into double
+ and vice versa]. Note that for efficiency and space-saving reasons, the Vector
+ and Matrix classes do not use these functions [but they preserve the type
+ interchangeability in their own way]
+
+ For a class (or struct) C:
+ class C {
+ ..
+ Write(std::ostream &, bool binary, [possibly extra optional args for specific classes]) const;
+ Read(std::istream &, bool binary, [possibly extra optional args for specific classes]);
+ ..
+ }
+ NOTE: The only actual optional args we used are the "add" arguments in
+ Vector/Matrix classes, which specify whether we should sum the data already
+ in the class with the data being read.
+
+ For types which are typedef's involving stl classes, I/O is as follows:
+ typedef std::vector<std::pair<A, B> > MyTypedefName;
+
+ The user should define something like:
+
+ WriteMyTypedefName(std::ostream &, bool binary, const MyTypedefName &t);
+ ReadMyTypedefName(std::ostream &, bool binary, MyTypedefName *t);
+
+ The user would have to write these functions.
+
+ For a type std::vector<T>:
+
+ void WriteIntegerVector(std::ostream &os, bool binary, const std::vector<T> &v);
+ void ReadIntegerVector(std::istream &is, bool binary, std::vector<T> *v);
+
+ For other types, e.g. vectors of pairs, the user should create a routine of the
+ type WriteMyTypedefName. This is to avoid introducing confusing templated functions;
+ we could easily create templated functions to handle most of these cases but they
+ would have to share the same name.
+
+ It also often happens that the user needs to write/read special tokens as part
+ of a file. These might be class headers, or separators/identifiers in the class.
+ We provide special functions for manipulating these. These special tokens must
+ be nonempty and must not contain any whitespace.
+
+ void WriteToken(std::ostream &os, bool binary, const char*);
+ void WriteToken(std::ostream &os, bool binary, const std::string & token);
+ int Peek(std::istream &is, bool binary);
+ void ReadToken(std::istream &is, bool binary, std::string *str);
+ void PeekToken(std::istream &is, bool binary, std::string *str);
+
+ WriteToken writes the token and one space (whether in binary or text mode).
+
+ Peek returns the first character of the next token, by consuming whitespace
+ (in text mode) and then returning the peek() character. It returns -1 at EOF;
+ it doesn't throw. It's useful if a class can have various forms based on
+ typedefs and virtual classes, and wants to know which version to read.
+
+ ReadToken allows the caller to obtain the next token. PeekToken works just
+ like ReadToken, but seeks back to the beginning of the token. A subsequent
+ call to ReadToken will read the same token again. This is useful when
+ different object types are written to the same file; using PeekToken one can
+ decide which of the objects to read.
+
+ There is currently no special functionality for writing/reading strings (where the strings
+ contain data rather than "special tokens" that are whitespace-free and nonempty). This is
+ because Kaldi is structured in such a way that strings don't appear, except as OpenFst symbol
+ table entries (and these have their own format).
+
+
+ NOTE: you should not call ReadIntegerType and WriteIntegerType with types,
+ such as int and size_t, that are machine-independent -- at least not
+ if you want your file formats to port between machines. Use int32 and
+ int64 where necessary. There is no way to detect this using compile-time
+ assertions because C++ only keeps track of the internal representation of
+ the type.
+*/
+
+/// \addtogroup io_funcs_basic
+/// @{
+
+
+/// WriteBasicType is the name of the write function for bool, integer types,
+/// and floating-point types. They all throw on error.
+template<class T> void WriteBasicType(std::ostream &os, bool binary, T t);
+
+/// ReadBasicType is the name of the read function for bool, integer types,
+/// and floating-point types. They all throw on error.
+template<class T> void ReadBasicType(std::istream &is, bool binary, T *t);
+
+
+// Declare specialization for bool.
+template<>
+void WriteBasicType<bool>(std::ostream &os, bool binary, bool b);
+
+template <>
+void ReadBasicType<bool>(std::istream &is, bool binary, bool *b);
+
+// Declare specializations for float and double.
+template<>
+void WriteBasicType<float>(std::ostream &os, bool binary, float f);
+
+template<>
+void WriteBasicType<double>(std::ostream &os, bool binary, double f);
+
+template<>
+void ReadBasicType<float>(std::istream &is, bool binary, float *f);
+
+template<>
+void ReadBasicType<double>(std::istream &is, bool binary, double *f);
+
+// Define ReadBasicType that accepts an "add" parameter to add to
+// the destination. Caution: if used in Read functions, be careful
+// to initialize the parameters concerned to zero in the default
+// constructor.
+template<class T>
+inline void ReadBasicType(std::istream &is, bool binary, T *t, bool add) {
+ if (!add) {
+ ReadBasicType(is, binary, t);
+ } else {
+ T tmp = T(0);
+ ReadBasicType(is, binary, &tmp);
+ *t += tmp;
+ }
+}
+
+/// Function for writing STL vectors of integer types.
+template<class T> inline void WriteIntegerVector(std::ostream &os, bool binary,
+ const std::vector<T> &v);
+
+/// Function for reading STL vector of integer types.
+template<class T> inline void ReadIntegerVector(std::istream &is, bool binary,
+ std::vector<T> *v);
+
+/// Function for writing STL vectors of pairs of integer types.
+template<class T>
+inline void WriteIntegerPairVector(std::ostream &os, bool binary,
+ const std::vector<std::pair<T, T> > &v);
+
+/// Function for reading STL vector of pairs of integer types.
+template<class T>
+inline void ReadIntegerPairVector(std::istream &is, bool binary,
+ std::vector<std::pair<T, T> > *v);
+
+/// The WriteToken functions are for writing nonempty sequences of non-space
+/// characters. They are not for general strings.
+void WriteToken(std::ostream &os, bool binary, const char *token);
+void WriteToken(std::ostream &os, bool binary, const std::string & token);
+
+/// Peek consumes whitespace (if binary == false) and then returns the peek()
+/// value of the stream.
+int Peek(std::istream &is, bool binary);
+
+/// ReadToken gets the next token and puts it in str (exception on failure). If
+/// PeekToken() had been previously called, it is possible that the stream had
+/// failed to unget the starting '<' character. In this case ReadToken() returns
+/// the token string without the leading '<'. You must be prepared to handle
+/// this case. ExpectToken() handles this internally, and is not affected.
+void ReadToken(std::istream &is, bool binary, std::string *token);
+
+/// PeekToken will return the first character of the next token, or -1 if end of
+/// file. It's the same as Peek(), except if the first character is '<' it will
+/// skip over it and will return the next character. It will attempt to unget
+/// the '<' so the stream is where it was before you did PeekToken(), however,
+/// this is not guaranteed (see ReadToken()).
+int PeekToken(std::istream &is, bool binary);
+
+/// ExpectToken tries to read in the given token, and throws an exception
+/// on failure.
+void ExpectToken(std::istream &is, bool binary, const char *token);
+void ExpectToken(std::istream &is, bool binary, const std::string & token);
+
+/// ExpectPretty attempts to read the text in "token", but only in non-binary
+/// mode. Throws exception on failure. It expects an exact match except that
+/// arbitrary whitespace matches arbitrary whitespace.
+void ExpectPretty(std::istream &is, bool binary, const char *token);
+void ExpectPretty(std::istream &is, bool binary, const std::string & token);
+
+/// @} end "addtogroup io_funcs_basic"
+
+
+/// InitKaldiOutputStream initializes an opened stream for writing by writing an
+/// optional binary header and modifying the floating-point precision; it will
+/// typically not be called by users directly.
+inline void InitKaldiOutputStream(std::ostream &os, bool binary);
+
+/// InitKaldiInputStream initializes an opened stream for reading by detecting
+/// the binary header and setting the "binary" value appropriately;
+/// It will typically not be called by users directly.
+inline bool InitKaldiInputStream(std::istream &is, bool *binary);
+
+} // end namespace kaldi.
+#endif // KALDI_BASE_IO_FUNCS_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/base/kaldi-common.h b/runtime/onnxruntime/third_party/kaldi/base/kaldi-common.h
new file mode 100644
index 000000000..264565d18
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/kaldi-common.h
@@ -0,0 +1,41 @@
+// base/kaldi-common.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_BASE_KALDI_COMMON_H_
+#define KALDI_BASE_KALDI_COMMON_H_ 1
+
+#include <cstddef>
+#include <cstdlib>
+#include <cstring> // C string stuff like strcpy
+#include <string>
+#include <sstream>
+#include <stdexcept>
+#include <cassert>
+#include <vector>
+#include <iostream>
+#include <fstream>
+
+#include "base/kaldi-utils.h"
+#include "base/kaldi-error.h"
+#include "base/kaldi-types.h"
+#include "base/io-funcs.h"
+#include "base/kaldi-math.h"
+#include "base/timer.h"
+
+#endif // KALDI_BASE_KALDI_COMMON_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/base/kaldi-error-test.cc b/runtime/onnxruntime/third_party/kaldi/base/kaldi-error-test.cc
new file mode 100644
index 000000000..31440edf3
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/kaldi-error-test.cc
@@ -0,0 +1,82 @@
+// base/kaldi-error-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "base/kaldi-common.h"
+
+// testing that we get the stack trace.
+namespace kaldi {
+
+void MyFunction2() { KALDI_ERR << "Ignore this error"; }
+
+void MyFunction1() { MyFunction2(); }
+
+void UnitTestError() {
+ {
+ std::cerr << "Ignore next error:\n";
+ MyFunction1();
+ }
+}
+
+void VerifySymbolRange(const std::string &trace, const bool want_found,
+ const std::string &want_symbol) {
+ size_t begin, end;
+ const bool found = internal::LocateSymbolRange(trace, &begin, &end);
+ if (found != want_found) {
+ KALDI_ERR << "Found mismatch, got " << found << " want " << want_found;
+ }
+ if (!found) {
+ return;
+ }
+ const std::string symbol = trace.substr(begin, end - begin);
+ if (symbol != want_symbol) {
+ KALDI_ERR << "Symbol mismatch, got " << symbol << " want " << want_symbol;
+ }
+}
+
+void TestLocateSymbolRange() {
+ VerifySymbolRange("", false, "");
+ VerifySymbolRange(
+ R"TRACE(./kaldi-error-test(_ZN5kaldi13UnitTestErrorEv+0xb) [0x804965d])TRACE",
+ true, "_ZN5kaldi13UnitTestErrorEv");
+ // It is ok thread_start is not found because it is a C symbol.
+ VerifySymbolRange(
+ R"TRACE(31 libsystem_pthread.dylib 0x00007fff6fe4e40d thread_start + 13)TRACE",
+ false, "");
+ VerifySymbolRange(
+ R"TRACE(0 server 0x000000010f67614d _ZNK5kaldi13MessageLogger10LogMessageEv + 813)TRACE",
+ true, "_ZNK5kaldi13MessageLogger10LogMessageEv");
+ VerifySymbolRange(
+ R"TRACE(29 libsystem_pthread.dylib 0x00007fff6fe4f2eb _pthread_body + 126)TRACE",
+ true, "_pthread_body");
+}
+
+} // namespace kaldi
+
+int main() {
+ kaldi::TestLocateSymbolRange();
+
+ kaldi::SetProgramName("/foo/bar/kaldi-error-test");
+ try {
+ kaldi::UnitTestError();
+ KALDI_ASSERT(0); // should not happen.
+ exit(1);
+ } catch (kaldi::KaldiFatalError &e) {
+ std::cout << "The error we generated was: '" << e.KaldiMessage() << "'\n";
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/base/kaldi-error.cc b/runtime/onnxruntime/third_party/kaldi/base/kaldi-error.cc
new file mode 100644
index 000000000..2970bbeaa
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/kaldi-error.cc
@@ -0,0 +1,248 @@
+// base/kaldi-error.cc
+
+// Copyright 2019 LAIX (Yi Sun)
+// Copyright 2019 SmartAction LLC (kkm)
+// Copyright 2016 Brno University of Technology (author: Karel Vesely)
+// Copyright 2009-2011 Microsoft Corporation; Lukas Burget; Ondrej Glembek
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifdef HAVE_EXECINFO_H
+#include <execinfo.h> // To get stack trace in error messages.
+// If this #include fails there is an error in the Makefile, it does not
+// support your platform well. Make sure HAVE_EXECINFO_H is undefined,
+// and the code will compile.
+#ifdef HAVE_CXXABI_H
+#include <cxxabi.h> // For name demangling.
+// Useful to decode the stack trace, but only used if we have execinfo.h
+#endif // HAVE_CXXABI_H
+#endif // HAVE_EXECINFO_H
+
+#include "base/kaldi-common.h"
+#include "base/kaldi-error.h"
+
+// KALDI_GIT_HEAD is useless currently in full repo
+//#if !defined(KALDI_VERSION)
+//#include "base/version.h"
+//#endif
+
+namespace kaldi {
+
+/***** GLOBAL VARIABLES FOR LOGGING *****/
+
+int32 g_kaldi_verbose_level = 0;
+static std::string program_name;
+static LogHandler log_handler = NULL;
+
+void SetProgramName(const char *basename) {
+ // Using the 'static std::string' for the program name is mostly harmless,
+ // because (a) Kaldi logging is undefined before main(), and (b) no stdc++
+ // string implementation has been found in the wild that would not be just
+ // an empty string when zero-initialized but not yet constructed.
+ program_name = basename;
+}
+
+/***** HELPER FUNCTIONS *****/
+
+// Trim filename to at most 1 trailing directory long. Given a filename like
+// "/a/b/c/d/e/f.cc", return "e/f.cc". Support both '/' and '\' as the path
+// separator.
+static const char *GetShortFileName(const char *path) {
+ if (path == nullptr)
+ return "";
+
+ const char *prev = path, *last = path;
+ while ((path = std::strpbrk(path, "\\/")) != nullptr) {
+ ++path;
+ prev = last;
+ last = path;
+ }
+ return prev;
+}
+
+/***** STACK TRACE *****/
+
+namespace internal {
+bool LocateSymbolRange(const std::string &trace_name, size_t *begin,
+ size_t *end) {
+ // Find the first '_' with leading ' ' or '('.
+ *begin = std::string::npos;
+ for (size_t i = 1; i < trace_name.size(); i++) {
+ if (trace_name[i] != '_') {
+ continue;
+ }
+ if (trace_name[i - 1] == ' ' || trace_name[i - 1] == '(') {
+ *begin = i;
+ break;
+ }
+ }
+ if (*begin == std::string::npos) {
+ return false;
+ }
+ *end = trace_name.find_first_of(" +", *begin);
+ return *end != std::string::npos;
+}
+} // namespace internal
+
+#ifdef HAVE_EXECINFO_H
+static std::string Demangle(std::string trace_name) {
+#ifndef HAVE_CXXABI_H
+ return trace_name;
+#else // HAVE_CXXABI_H
+ // Try demangle the symbol. We are trying to support the following formats
+ // produced by different platforms:
+ //
+ // Linux:
+ // ./kaldi-error-test(_ZN5kaldi13UnitTestErrorEv+0xb) [0x804965d]
+ //
+ // Mac:
+ // 0 server 0x000000010f67614d _ZNK5kaldi13MessageLogger10LogMessageEv + 813
+ //
+ // We want to extract the name e.g., '_ZN5kaldi13UnitTestErrorEv' and
+ // demangle it info a readable name like kaldi::UnitTextError.
+ size_t begin, end;
+ if (!internal::LocateSymbolRange(trace_name, &begin, &end)) {
+ return trace_name;
+ }
+ std::string symbol = trace_name.substr(begin, end - begin);
+ int status;
+ char *demangled_name = abi::__cxa_demangle(symbol.c_str(), 0, 0, &status);
+ if (status == 0 && demangled_name != nullptr) {
+ symbol = demangled_name;
+ free(demangled_name);
+ }
+ return trace_name.substr(0, begin) + symbol +
+ trace_name.substr(end, std::string::npos);
+#endif // HAVE_CXXABI_H
+}
+#endif // HAVE_EXECINFO_H
+
+static std::string KaldiGetStackTrace() {
+ std::string ans;
+#ifdef HAVE_EXECINFO_H
+ const size_t KALDI_MAX_TRACE_SIZE = 50;
+ const size_t KALDI_MAX_TRACE_PRINT = 50; // Must be even.
+ // Buffer for the trace.
+ void *trace[KALDI_MAX_TRACE_SIZE];
+ // Get the trace.
+ size_t size = backtrace(trace, KALDI_MAX_TRACE_SIZE);
+ // Get the trace symbols.
+ char **trace_symbol = backtrace_symbols(trace, size);
+ if (trace_symbol == NULL)
+ return ans;
+
+ // Compose a human-readable backtrace string.
+ ans += "[ Stack-Trace: ]\n";
+ if (size <= KALDI_MAX_TRACE_PRINT) {
+ for (size_t i = 0; i < size; i++) {
+ ans += Demangle(trace_symbol[i]) + "\n";
+ }
+ } else { // Print out first+last (e.g.) 5.
+ for (size_t i = 0; i < KALDI_MAX_TRACE_PRINT / 2; i++) {
+ ans += Demangle(trace_symbol[i]) + "\n";
+ }
+ ans += ".\n.\n.\n";
+ for (size_t i = size - KALDI_MAX_TRACE_PRINT / 2; i < size; i++) {
+ ans += Demangle(trace_symbol[i]) + "\n";
+ }
+ if (size == KALDI_MAX_TRACE_SIZE)
+ ans += ".\n.\n.\n"; // Stack was too long, probably a bug.
+ }
+
+ // We must free the array of pointers allocated by backtrace_symbols(),
+ // but not the strings themselves.
+ free(trace_symbol);
+#endif // HAVE_EXECINFO_H
+ return ans;
+}
+
+/***** KALDI LOGGING *****/
+
+MessageLogger::MessageLogger(LogMessageEnvelope::Severity severity,
+ const char *func, const char *file, int32 line) {
+ // Obviously, we assume the strings survive the destruction of this object.
+ envelope_.severity = severity;
+ envelope_.func = func;
+ envelope_.file = GetShortFileName(file); // Points inside 'file'.
+ envelope_.line = line;
+}
+
+void MessageLogger::LogMessage() const {
+ // Send to the logging handler if provided.
+ if (log_handler != NULL) {
+ log_handler(envelope_, GetMessage().c_str());
+ return;
+ }
+
+ // Otherwise, use the default Kaldi logging.
+ // Build the log-message header.
+ std::stringstream full_message;
+ if (envelope_.severity > LogMessageEnvelope::kInfo) {
+ full_message << "VLOG[" << envelope_.severity << "] (";
+ } else {
+ switch (envelope_.severity) {
+ case LogMessageEnvelope::kInfo:
+ //full_message << "LOG (\n";
+ break;
+ case LogMessageEnvelope::kWarning:
+ //full_message << "WARNING (\n";
+ break;
+ case LogMessageEnvelope::kAssertFailed:
+ full_message << "ASSERTION_FAILED (\n";
+ break;
+ case LogMessageEnvelope::kError:
+ default: // If not the ERROR, it still an error!
+ full_message << "ERROR (\n";
+ break;
+ }
+ }
+ // Add other info from the envelope and the message text.
+ //full_message << program_name.c_str() << "[" KALDI_VERSION "]" << ':'
+ // << envelope_.func << "():" << envelope_.file << ':'
+ // << envelope_.line << ") " << GetMessage().c_str();
+
+ // Add stack trace for errors and assertion failures, if available.
+ if (envelope_.severity < LogMessageEnvelope::kWarning) {
+ const std::string &stack_trace = KaldiGetStackTrace();
+ if (!stack_trace.empty()) {
+ full_message << "\n\n" << stack_trace;
+ }
+ }
+
+ // Print the complete message to stderr.
+ std::cerr << full_message.str();
+}
+
+/***** KALDI ASSERTS *****/
+
+void KaldiAssertFailure_(const char *func, const char *file, int32 line,
+ const char *cond_str) {
+ MessageLogger::Log() =
+ MessageLogger(LogMessageEnvelope::kAssertFailed, func, file, line)
+ << "Assertion failed: (" << cond_str << ")";
+ fflush(NULL); // Flush all pending buffers, abort() may not flush stderr.
+ std::abort();
+}
+
+/***** THIRD-PARTY LOG-HANDLER *****/
+
+LogHandler SetLogHandler(LogHandler handler) {
+ LogHandler old_handler = log_handler;
+ log_handler = handler;
+ return old_handler;
+}
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/base/kaldi-error.h b/runtime/onnxruntime/third_party/kaldi/base/kaldi-error.h
new file mode 100644
index 000000000..b150a02d4
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/kaldi-error.h
@@ -0,0 +1,231 @@
+// base/kaldi-error.h
+
+// Copyright 2019 LAIX (Yi Sun)
+// Copyright 2019 SmartAction LLC (kkm)
+// Copyright 2016 Brno University of Technology (author: Karel Vesely)
+// Copyright 2009-2011 Microsoft Corporation; Ondrej Glembek; Lukas Burget;
+// Saarland University
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_BASE_KALDI_ERROR_H_
+#define KALDI_BASE_KALDI_ERROR_H_ 1
+
+#include <cstdio>
+#include <cstring>
+#include <sstream>
+#include <stdexcept>
+#include <string>
+#include <vector>
+
+#include "base/kaldi-types.h"
+#include "base/kaldi-utils.h"
+/* Important that this file does not depend on any other kaldi headers. */
+
+#ifdef _MSC_VER
+#define __func__ __FUNCTION__
+#endif
+
+namespace kaldi {
+
+/// \addtogroup error_group
+/// @{
+
+/***** PROGRAM NAME AND VERBOSITY LEVEL *****/
+
+/// Called by ParseOptions to set base name (no directory) of the executing
+/// program. The name is printed in logging code along with every message,
+/// because in our scripts, we often mix together the stderr of many programs.
+/// This function is very thread-unsafe.
+void SetProgramName(const char *basename);
+
+/// This is set by util/parse-options.{h,cc} if you set --verbose=? option.
+/// Do not use directly, prefer {Get,Set}VerboseLevel().
+extern int32 g_kaldi_verbose_level;
+
+/// Get verbosity level, usually set via command line '--verbose=' switch.
+inline int32 GetVerboseLevel() { return g_kaldi_verbose_level; }
+
+/// This should be rarely used, except by programs using Kaldi as library;
+/// command-line programs set the verbose level automatically from ParseOptions.
+inline void SetVerboseLevel(int32 i) { g_kaldi_verbose_level = i; }
+
+/***** KALDI LOGGING *****/
+
+/// Log message severity and source location info.
+struct LogMessageEnvelope {
+ /// Message severity. In addition to these levels, positive values (1 to 6)
+ /// specify verbose logging level. Verbose messages are produced only when
+ /// SetVerboseLevel() has been called to set logging level to at least the
+ /// corresponding value.
+ enum Severity {
+ kAssertFailed = -3, //!< Assertion failure. abort() will be called.
+ kError = -2, //!< Fatal error. KaldiFatalError will be thrown.
+ kWarning = -1, //!< Indicates a recoverable but abnormal condition.
+ kInfo = 0, //!< Informational message.
+ };
+ int severity; //!< A Severity value, or positive verbosity level.
+ const char *func; //!< Name of the function invoking the logging.
+ const char *file; //!< Source file name with up to 1 leading directory.
+ int32 line; //<! Line number in the source file.
+};
+
+/// Kaldi fatal runtime error exception. This exception is thrown from any use
+/// of the KALDI_ERR logging macro after the logging function, either set by
+/// SetLogHandler(), or the Kaldi's internal one, has returned.
+class KaldiFatalError : public std::runtime_error {
+public:
+ explicit KaldiFatalError(const std::string &message)
+ : std::runtime_error(message) {}
+ explicit KaldiFatalError(const char *message) : std::runtime_error(message) {}
+
+ /// Returns the exception name, "kaldi::KaldiFatalError".
+ virtual const char *what() const noexcept override {
+ return "kaldi::KaldiFatalError";
+ }
+
+ /// Returns the Kaldi error message logged by KALDI_ERR.
+ const char *KaldiMessage() const { return std::runtime_error::what(); }
+};
+
+// Class MessageLogger is the workhorse behind the KALDI_ASSERT, KALDI_ERR,
+// KALDI_WARN, KALDI_LOG and KALDI_VLOG macros. It formats the message, then
+// either prints it to stderr or passes to the custom logging handler if
+// provided. Then, in case of the error, throws a KaldiFatalError exception, or
+// in case of failed KALDI_ASSERT, calls std::abort().
+class MessageLogger {
+public:
+ /// The constructor stores the message's "envelope", a set of data which
+ // identifies the location in source which is sending the message to log.
+ // The pointers to strings are stored internally, and not owned or copied,
+ // so that their storage must outlive this object.
+ MessageLogger(LogMessageEnvelope::Severity severity, const char *func,
+ const char *file, int32 line);
+
+ // The stream insertion operator, used in e.g. 'KALDI_LOG << "Message"'.
+ template <typename T> MessageLogger &operator<<(const T &val) {
+ ss_ << val;
+ return *this;
+ }
+
+ // When assigned a MessageLogger, log its contents.
+ struct Log final {
+ void operator=(const MessageLogger &logger) { logger.LogMessage(); }
+ };
+
+ // When assigned a MessageLogger, log its contents and then throw
+ // a KaldiFatalError.
+ struct LogAndThrow final {
+ [[noreturn]] void operator=(const MessageLogger &logger) {
+ logger.LogMessage();
+ throw KaldiFatalError(logger.GetMessage());
+ }
+ };
+
+private:
+ std::string GetMessage() const { return ss_.str(); }
+ void LogMessage() const;
+
+ LogMessageEnvelope envelope_;
+ std::ostringstream ss_;
+};
+
+// Logging macros.
+#define KALDI_ERR \
+ ::kaldi::MessageLogger::LogAndThrow() = ::kaldi::MessageLogger( \
+ ::kaldi::LogMessageEnvelope::kError, __func__, __FILE__, __LINE__)
+#define KALDI_WARN \
+ ::kaldi::MessageLogger::Log() = ::kaldi::MessageLogger( \
+ ::kaldi::LogMessageEnvelope::kWarning, __func__, __FILE__, __LINE__)
+#define KALDI_LOG \
+ ::kaldi::MessageLogger::Log() = ::kaldi::MessageLogger( \
+ ::kaldi::LogMessageEnvelope::kInfo, __func__, __FILE__, __LINE__)
+#define KALDI_VLOG(v) \
+ if ((v) <= ::kaldi::GetVerboseLevel()) \
+ ::kaldi::MessageLogger::Log() = \
+ ::kaldi::MessageLogger((::kaldi::LogMessageEnvelope::Severity)(v), \
+ __func__, __FILE__, __LINE__)
+
+/***** KALDI ASSERTS *****/
+
+[[noreturn]] void KaldiAssertFailure_(const char *func, const char *file,
+ int32 line, const char *cond_str);
+
+// Note on KALDI_ASSERT and KALDI_PARANOID_ASSERT:
+//
+// A single block {} around if /else does not work, because it causes
+// syntax error (unmatched else block) in the following code:
+//
+// if (condition)
+// KALDI_ASSERT(condition2);
+// else
+// SomethingElse();
+//
+// do {} while(0) -- note there is no semicolon at the end! -- works nicely,
+// and compilers will be able to optimize the loop away (as the condition
+// is always false).
+//
+// Also see KALDI_COMPILE_TIME_ASSERT, defined in base/kaldi-utils.h, and
+// KALDI_ASSERT_IS_INTEGER_TYPE and KALDI_ASSERT_IS_FLOATING_TYPE, also defined
+// there.
+#ifndef NDEBUG
+#define KALDI_ASSERT(cond) \
+ do { \
+ if (cond) \
+ (void)0; \
+ else \
+ ::kaldi::KaldiAssertFailure_(__func__, __FILE__, __LINE__, #cond); \
+ } while (0)
+#else
+#define KALDI_ASSERT(cond) (void)0
+#endif
+
+// Some more expensive asserts only checked if this defined.
+#ifdef KALDI_PARANOID
+#define KALDI_PARANOID_ASSERT(cond) \
+ do { \
+ if (cond) \
+ (void)0; \
+ else \
+ ::kaldi::KaldiAssertFailure_(__func__, __FILE__, __LINE__, #cond); \
+ } while (0)
+#else
+#define KALDI_PARANOID_ASSERT(cond) (void)0
+#endif
+
+/***** THIRD-PARTY LOG-HANDLER *****/
+
+/// Type of third-party logging function.
+typedef void (*LogHandler)(const LogMessageEnvelope &envelope,
+ const char *message);
+
+/// Set logging handler. If called with a non-NULL function pointer, the
+/// function pointed by it is called to send messages to a caller-provided log.
+/// If called with a NULL pointer, restores default Kaldi error logging to
+/// stderr. This function is obviously not thread safe; the log handler must be.
+/// Returns a previously set logging handler pointer, or NULL.
+LogHandler SetLogHandler(LogHandler);
+
+/// @} end "addtogroup error_group"
+
+//// Functions within internal is exported for testing only, do not use.
+//namespace internal {
+//bool LocateSymbolRange(const std::string &trace_name, size_t *begin,
+// size_t *end);
+//} // namespace internal
+} // namespace kaldi
+
+#endif // KALDI_BASE_KALDI_ERROR_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/base/kaldi-math-test.cc b/runtime/onnxruntime/third_party/kaldi/base/kaldi-math-test.cc
new file mode 100644
index 000000000..8d6e6164e
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/kaldi-math-test.cc
@@ -0,0 +1,334 @@
+// base/kaldi-math-test.cc
+//
+// Copyright 2009-2011 Microsoft Corporation; Yanmin Qian; Jan Silovsky
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#include "base/kaldi-math.h"
+#include <limits>
+#include "base/timer.h"
+
+namespace kaldi {
+
+template<class I> void UnitTestGcdLcmTpl() {
+ for (I a = 1; a < 15; a++) { // a is min gcd.
+ I b = (I)(Rand() % 10);
+ I c = (I)(Rand() % 10);
+ if (std::numeric_limits<I>::is_signed) {
+ if (Rand() % 2 == 0) b = -b;
+ if (Rand() % 2 == 0) c = -c;
+ }
+ if (b == 0 && c == 0) continue; // gcd not defined for such numbers.
+ I g = Gcd(b*a, c*a);
+ KALDI_ASSERT(g >= a);
+ KALDI_ASSERT((b*a) % g == 0);
+ KALDI_ASSERT((c*a) % g == 0);
+
+ // test least common multiple
+ if (b <= 0 || c <= 0) continue; // lcm not defined unless both positive.
+ I h = Lcm(b*a, c*a);
+ KALDI_ASSERT(h != 0 && (h % (b*a)) == 0 &&
+ (h % (c*a)) == 0);
+ }
+}
+
+void UnitTestRoundUpToNearestPowerOfTwo() {
+ KALDI_ASSERT(RoundUpToNearestPowerOfTwo(1) == 1);
+ KALDI_ASSERT(RoundUpToNearestPowerOfTwo(2) == 2);
+ KALDI_ASSERT(RoundUpToNearestPowerOfTwo(3) == 4);
+ KALDI_ASSERT(RoundUpToNearestPowerOfTwo(4) == 4);
+ KALDI_ASSERT(RoundUpToNearestPowerOfTwo(7) == 8);
+ KALDI_ASSERT(RoundUpToNearestPowerOfTwo(8) == 8);
+ KALDI_ASSERT(RoundUpToNearestPowerOfTwo(255) == 256);
+ KALDI_ASSERT(RoundUpToNearestPowerOfTwo(256) == 256);
+ KALDI_ASSERT(RoundUpToNearestPowerOfTwo(257) == 512);
+ KALDI_ASSERT(RoundUpToNearestPowerOfTwo(1073700000) == 1073741824);
+}
+
+void UnitTestDivideRoundingDown() {
+ for (int32 i = 0; i < 100; i++) {
+ int32 a = RandInt(-100, 100);
+ int32 b = 0;
+ while (b == 0)
+ b = RandInt(-100, 100);
+ KALDI_ASSERT(DivideRoundingDown(a, b) ==
+ std::floor(static_cast<double>(a) / static_cast<double>(b)));
+ }
+}
+
+void UnitTestGcdLcm() {
+ UnitTestGcdLcmTpl<int>();
+ UnitTestGcdLcmTpl<size_t>();
+ UnitTestGcdLcmTpl<int16>();
+}
+
+void UnitTestRand() {
+ // Testing random-number generation.
+ std::cout << "Testing random-number generation. "
+ << "If there is an error this may not terminate.\n";
+ std::cout << "If this does not terminate, look more closely. "
+ << "There might be a problem [but might not be]\n";
+ for (int i = 1; i < 10; i++) {
+ { // test RandUniform.
+ std::cout << "Test RandUniform\n";
+ KALDI_ASSERT(RandUniform() >= 0 && RandUniform() <= 1);
+ float sum = RandUniform()-0.5;
+ for (int j = 0; ; j++) {
+ sum += RandUniform()-0.5;
+ if (std::abs(sum) < 0.5*sqrt(static_cast<double>(j))) break;
+ }
+ }
+ { // test RandGauss.
+ float sum = RandGauss();
+ for (int j = 0; ; j++) {
+ sum += RandGauss();
+ if (std::abs(sum) < 0.5*sqrt(static_cast<double>(j))) break;
+ }
+ }
+ { // test RandGauss.
+ float sum = RandGauss();
+ for (int j = 0; ; j++) {
+ float a, b;
+ RandGauss2(&a, &b);
+ if (i % 2 == 0) sum += a;
+ else
+ sum += b;
+ if (std::abs(sum) < 0.5*sqrt(static_cast<double>(j))) break;
+ }
+ }
+ { // test poisson_Rand().
+ KALDI_ASSERT(RandPoisson(3.0) >= 0);
+ KALDI_ASSERT(RandPoisson(0.0) == 0);
+ std::cout << "Test RandPoisson\n";
+ float lambda = RandUniform() * 3.0; // between 0 and 3.
+ double sum = RandPoisson(lambda) - lambda; // expected value is zero.
+ for (int j = 0; ; j++) {
+ sum += RandPoisson(lambda) - lambda;
+ if (std::abs(sum) < 0.5*sqrt(static_cast<double>(j))) break;
+ }
+ }
+
+ { // test WithProb().
+ for (int32 i = 0; i < 10; i++) {
+ KALDI_ASSERT((WithProb(0.0) == false) && (WithProb(1.0) == true));
+ }
+ {
+ int32 tot = 0, n = 10000;
+ BaseFloat p = 0.5;
+ for (int32 i = 0; i < n; i++)
+ tot += WithProb(p);
+ KALDI_ASSERT(tot > (n * p * 0.8) && tot < (n * p * 1.2));
+ }
+ {
+ int32 tot = 0, n = 10000;
+ BaseFloat p = 0.25;
+ for (int32 i = 0; i < n; i++)
+ tot += WithProb(p);
+ KALDI_ASSERT(tot > (n * p * 0.8) && tot < (n * p * 1.2));
+ }
+ }
+ { // test RandInt().
+ KALDI_ASSERT(RandInt(0, 3) >= 0 && RandInt(0, 3) <= 3);
+
+ std::cout << "Test RandInt\n";
+ int minint = Rand() % 200;
+ int maxint = minint + 1 + Rand() % 20;
+
+ float sum = RandInt(minint, maxint) + 0.5*(minint+maxint);
+ for (int j = 0; ; j++) {
+ sum += RandInt(minint, maxint) - 0.5*(minint+maxint);
+ if (std::abs(static_cast<float>(sum)) <
+ 0.5*sqrt(static_cast<double>(j))*(maxint-minint)) break;
+ }
+ }
+ { // test RandPrune in basic way.
+ KALDI_ASSERT(RandPrune(1.1, 1.0) == 1.1);
+ KALDI_ASSERT(RandPrune(0.0, 0.0) == 0.0);
+ KALDI_ASSERT(RandPrune(-1.1, 1.0) == -1.1);
+ KALDI_ASSERT(RandPrune(0.0, 1.0) == 0.0);
+ KALDI_ASSERT(RandPrune(0.5, 1.0) >= 0.0);
+ KALDI_ASSERT(RandPrune(-0.5, 1.0) <= 0.0);
+ BaseFloat f = RandPrune(-0.5, 1.0);
+ KALDI_ASSERT(f == 0.0 || f == -1.0);
+ f = RandPrune(0.5, 1.0);
+ KALDI_ASSERT(f == 0.0 || f == 1.0);
+ }
+ }
+}
+
+void UnitTestLogAddSub() {
+ for (int i = 0; i < 100; i++) {
+ double f1 = Rand() % 10000, f2 = Rand() % 20;
+ double add1 = Exp(LogAdd(Log(f1), Log(f2)));
+ double add2 = Exp(LogAdd(Log(f2), Log(f1)));
+ double add = f1 + f2, thresh = add*0.00001;
+ KALDI_ASSERT(std::abs(add-add1) < thresh && std::abs(add-add2) < thresh);
+
+
+ try {
+ double f2_check = Exp(LogSub(Log(add), Log(f1))),
+ thresh = (f2*0.01)+0.001;
+ KALDI_ASSERT(std::abs(f2_check-f2) < thresh);
+ } catch(...) {
+ KALDI_ASSERT(f2 == 0); // It will probably crash for f2=0.
+ }
+ }
+}
+
+void UnitTestDefines() { // Yes, we even unit-test the preprocessor statements.
+ KALDI_ASSERT(Exp(kLogZeroFloat) == 0.0);
+ KALDI_ASSERT(Exp(kLogZeroDouble) == 0.0);
+ BaseFloat den = 0.0;
+ KALDI_ASSERT(KALDI_ISNAN(0.0 / den));
+ KALDI_ASSERT(!KALDI_ISINF(0.0 / den));
+ KALDI_ASSERT(!KALDI_ISFINITE(0.0 / den));
+ KALDI_ASSERT(!KALDI_ISNAN(1.0 / den));
+ KALDI_ASSERT(KALDI_ISINF(1.0 / den));
+ KALDI_ASSERT(!KALDI_ISFINITE(1.0 / den));
+ KALDI_ASSERT(KALDI_ISFINITE(0.0));
+ KALDI_ASSERT(!KALDI_ISINF(0.0));
+ KALDI_ASSERT(!KALDI_ISNAN(0.0));
+
+ std::cout << 1.0+DBL_EPSILON;
+ std::cout << 1.0 + 0.5*DBL_EPSILON;
+ KALDI_ASSERT(1.0 + DBL_EPSILON != 1.0 && 1.0 + (0.5*DBL_EPSILON) == 1.0
+ && "If this test fails, you can probably just comment it out-- "
+ "may mean your CPU exceeds expected floating point precision");
+ KALDI_ASSERT(1.0f + FLT_EPSILON != 1.0f && 1.0f + (0.5f*FLT_EPSILON) == 1.0f
+ && "If this test fails, you can probably just comment it out-- "
+ "may mean your CPU exceeds expected floating point precision");
+ KALDI_ASSERT(std::abs(sin(M_PI)) < 1.0e-05
+ && std::abs(cos(M_PI)+1.0) < 1.0e-05);
+ KALDI_ASSERT(std::abs(sin(M_2PI)) < 1.0e-05
+ && std::abs(cos(M_2PI)-1.0) < 1.0e-05);
+ KALDI_ASSERT(std::abs(sin(Exp(M_LOG_2PI))) < 1.0e-05);
+ KALDI_ASSERT(std::abs(cos(Exp(M_LOG_2PI)) - 1.0) < 1.0e-05);
+}
+
+void UnitTestAssertFunc() { // Testing Assert** *functions
+ for (int i = 1; i < 100; i++) {
+ float f1 = Rand() % 10000 + 1, f2 = Rand() % 20 + 1;
+ float tmp1 = f1 * f2;
+ float tmp2 = (1/f1 + 1/f2);
+ float add = f1 + f2;
+ float addeql = tmp1 * tmp2;
+ float thresh = 0.00001;
+ AssertEqual(add, addeql, thresh); // test AssertEqual()
+ }
+}
+
+template<class I> void UnitTestFactorizeTpl() {
+ for (int p= 0; p < 100; p++) {
+ I m = Rand() % 100000;
+ if (m >= 1) {
+ std::vector<I> factors;
+ Factorize(m, &factors);
+ I m2 = 1;
+ for (size_t i = 0; i < factors.size(); i++) {
+ m2 *= factors[i];
+ if (i+1 < factors.size())
+ KALDI_ASSERT(factors[i+1] >= factors[i]); // check sorted.
+ }
+ KALDI_ASSERT(m2 == m); // check correctness.
+ }
+ }
+}
+
+void UnitTestFactorize() {
+ UnitTestFactorizeTpl<int>();
+ UnitTestFactorizeTpl<size_t>();
+ UnitTestFactorizeTpl<int16>();
+}
+
+void UnitTestApproxEqual() {
+ KALDI_ASSERT(ApproxEqual(1.0, 1.00001));
+ KALDI_ASSERT(ApproxEqual(1.0, 1.00001, 0.001));
+ KALDI_ASSERT(!ApproxEqual(1.0, 1.1));
+ KALDI_ASSERT(!ApproxEqual(1.0, 1.01, 0.001));
+ KALDI_ASSERT(!ApproxEqual(1.0, 0.0));
+ KALDI_ASSERT(ApproxEqual(0.0, 0.0));
+ KALDI_ASSERT(!ApproxEqual(0.0, 0.00001));
+ KALDI_ASSERT(!ApproxEqual(std::numeric_limits<float>::infinity(),
+ -std::numeric_limits<float>::infinity()));
+ KALDI_ASSERT(ApproxEqual(std::numeric_limits<float>::infinity(),
+ std::numeric_limits<float>::infinity()));
+ KALDI_ASSERT(ApproxEqual(-std::numeric_limits<float>::infinity(),
+ -std::numeric_limits<float>::infinity()));
+ KALDI_ASSERT(!ApproxEqual(-std::numeric_limits<float>::infinity(),
+ 0));
+ KALDI_ASSERT(!ApproxEqual(-std::numeric_limits<float>::infinity(),
+ 1));
+}
+
+template<class Real>
+void UnitTestExpSpeed() {
+ Real sum = 0.0; // compute the sum to avoid optimizing it away.
+ Real time = 0.01; // how long this should last.
+ int block_size = 10;
+ int num_ops = 0;
+ Timer tim;
+ while (tim.Elapsed() < time) {
+ for (int i = 0; i < block_size; i++) {
+ sum += Exp((Real)i);
+ }
+ num_ops += block_size;
+ }
+ KALDI_ASSERT(sum > 0.0); // make it harder for the compiler to optimize Exp
+ // away, as we have a conditional.
+ Real flops = 1.0e-06 * num_ops / tim.Elapsed();
+ KALDI_LOG << "Megaflops doing Exp("
+ << (sizeof(Real) == 4 ? "float" : "double") << ") is " << flops;
+}
+
+
+template<class Real>
+void UnitTestLogSpeed() {
+ Real sum = 0.0; // compute the sum to avoid optimizing it away.
+ Real time = 0.01; // how long this should last.
+ int block_size = 10;
+ int num_ops = 0;
+ Timer tim;
+ while (tim.Elapsed() < time) {
+ for (int i = 0; i < block_size; i++) {
+ sum += Log(static_cast<float>(i + 1));
+ }
+ num_ops += block_size;
+ }
+ KALDI_ASSERT(sum > 0.0); // make it harder for the compiler to optimize Log
+ // away, as we have a conditional.
+ Real flops = 1.0e-06 * num_ops / tim.Elapsed();
+ KALDI_LOG << "Megaflops doing Log("
+ << (sizeof(Real) == 4 ? "float" : "double") << ") is " << flops;
+}
+
+} // end namespace kaldi.
+
+int main() {
+ using namespace kaldi;
+ UnitTestApproxEqual();
+ UnitTestGcdLcm();
+ UnitTestFactorize();
+ UnitTestDefines();
+ UnitTestLogAddSub();
+ UnitTestRand();
+ UnitTestAssertFunc();
+ UnitTestRoundUpToNearestPowerOfTwo();
+ UnitTestDivideRoundingDown();
+ UnitTestExpSpeed<float>();
+ UnitTestExpSpeed<double>();
+ UnitTestLogSpeed<float>();
+ UnitTestLogSpeed<double>();
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/base/kaldi-math.cc b/runtime/onnxruntime/third_party/kaldi/base/kaldi-math.cc
new file mode 100644
index 000000000..f60d6c0ac
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/kaldi-math.cc
@@ -0,0 +1,162 @@
+// base/kaldi-math.cc
+
+// Copyright 2009-2011 Microsoft Corporation; Yanmin Qian;
+// Saarland University; Jan Silovsky
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "base/kaldi-math.h"
+#ifndef _MSC_VER
+#include <stdlib.h>
+#include <unistd.h>
+#endif
+#include <string>
+#include <mutex>
+
+namespace kaldi {
+// These routines are tested in matrix/matrix-test.cc
+
+int32 RoundUpToNearestPowerOfTwo(int32 n) {
+ KALDI_ASSERT(n > 0);
+ n--;
+ n |= n >> 1;
+ n |= n >> 2;
+ n |= n >> 4;
+ n |= n >> 8;
+ n |= n >> 16;
+ return n+1;
+}
+
+static std::mutex _RandMutex;
+
+int Rand(struct RandomState* state) {
+#if !defined(_POSIX_THREAD_SAFE_FUNCTIONS)
+ // On Windows and Cygwin, just call Rand()
+ return rand();
+#else
+ if (state) {
+ return rand_r(&(state->seed));
+ } else {
+ std::lock_guard<std::mutex> lock(_RandMutex);
+ return rand();
+ }
+#endif
+}
+
+RandomState::RandomState() {
+ // we initialize it as Rand() + 27437 instead of just Rand(), because on some
+ // systems, e.g. at the very least Mac OSX Yosemite and later, it seems to be
+ // the case that rand_r when initialized with rand() will give you the exact
+ // same sequence of numbers that rand() will give if you keep calling rand()
+ // after that initial call. This can cause problems with repeated sequences.
+ // For example if you initialize two RandomState structs one after the other
+ // without calling rand() in between, they would give you the same sequence
+ // offset by one (if we didn't have the "+ 27437" in the code). 27437 is just
+ // a randomly chosen prime number.
+ seed = unsigned(Rand()) + 27437;
+}
+
+bool WithProb(BaseFloat prob, struct RandomState* state) {
+ KALDI_ASSERT(prob >= 0 && prob <= 1.1); // prob should be <= 1.0,
+ // but we allow slightly larger values that could arise from roundoff in
+ // previous calculations.
+ KALDI_COMPILE_TIME_ASSERT(RAND_MAX > 128 * 128);
+ if (prob == 0) return false;
+ else if (prob == 1.0) return true;
+ else if (prob * RAND_MAX < 128.0) {
+ // prob is very small but nonzero, and the "main algorithm"
+ // wouldn't work that well. So: with probability 1/128, we
+ // return WithProb (prob * 128), else return false.
+ if (Rand(state) < RAND_MAX / 128) { // with probability 128...
+ // Note: we know that prob * 128.0 < 1.0, because
+ // we asserted RAND_MAX > 128 * 128.
+ return WithProb(prob * 128.0);
+ } else {
+ return false;
+ }
+ } else {
+ return (Rand(state) < ((RAND_MAX + static_cast<BaseFloat>(1.0)) * prob));
+ }
+}
+
+int32 RandInt(int32 min_val, int32 max_val, struct RandomState* state) {
+ // This is not exact.
+ KALDI_ASSERT(max_val >= min_val);
+ if (max_val == min_val) return min_val;
+
+#ifdef _MSC_VER
+ // RAND_MAX is quite small on Windows -> may need to handle larger numbers.
+ if (RAND_MAX > (max_val-min_val)*8) {
+ // *8 to avoid large inaccuracies in probability, from the modulus...
+ return min_val +
+ ((unsigned int)Rand(state) % (unsigned int)(max_val+1-min_val));
+ } else {
+ if ((unsigned int)(RAND_MAX*RAND_MAX) >
+ (unsigned int)((max_val+1-min_val)*8)) {
+ // *8 to avoid inaccuracies in probability, from the modulus...
+ return min_val + ( (unsigned int)( (Rand(state)+RAND_MAX*Rand(state)))
+ % (unsigned int)(max_val+1-min_val));
+ } else {
+ KALDI_ERR << "rand_int failed because we do not support such large "
+ "random numbers. (Extend this function).";
+ }
+ }
+#else
+ return min_val +
+ (static_cast<int32>(Rand(state)) % static_cast<int32>(max_val+1-min_val));
+#endif
+}
+
+// Returns poisson-distributed random number.
+// Take care: this takes time proportional
+// to lambda. Faster algorithms exist but are more complex.
+int32 RandPoisson(float lambda, struct RandomState* state) {
+ // Knuth's algorithm.
+ KALDI_ASSERT(lambda >= 0);
+ float L = expf(-lambda), p = 1.0;
+ int32 k = 0;
+ do {
+ k++;
+ float u = RandUniform(state);
+ p *= u;
+ } while (p > L);
+ return k-1;
+}
+
+void RandGauss2(float *a, float *b, RandomState *state) {
+ KALDI_ASSERT(a);
+ KALDI_ASSERT(b);
+ float u1 = RandUniform(state);
+ float u2 = RandUniform(state);
+ u1 = sqrtf(-2.0f * logf(u1));
+ u2 = 2.0f * M_PI * u2;
+ *a = u1 * cosf(u2);
+ *b = u1 * sinf(u2);
+}
+
+void RandGauss2(double *a, double *b, RandomState *state) {
+ KALDI_ASSERT(a);
+ KALDI_ASSERT(b);
+ float a_float, b_float;
+ // Just because we're using doubles doesn't mean we need super-high-quality
+ // random numbers, so we just use the floating-point version internally.
+ RandGauss2(&a_float, &b_float, state);
+ *a = a_float;
+ *b = b_float;
+}
+
+
+} // end namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/base/kaldi-math.h b/runtime/onnxruntime/third_party/kaldi/base/kaldi-math.h
new file mode 100644
index 000000000..93c265ee9
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/kaldi-math.h
@@ -0,0 +1,363 @@
+// base/kaldi-math.h
+
+// Copyright 2009-2011 Ondrej Glembek; Microsoft Corporation; Yanmin Qian;
+// Jan Silovsky; Saarland University
+//
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_BASE_KALDI_MATH_H_
+#define KALDI_BASE_KALDI_MATH_H_ 1
+
+#ifdef _MSC_VER
+#include <float.h>
+#endif
+
+#include <cmath>
+#include <limits>
+#include <vector>
+
+#include "base/kaldi-types.h"
+#include "base/kaldi-common.h"
+
+
+#ifndef DBL_EPSILON
+#define DBL_EPSILON 2.2204460492503131e-16
+#endif
+#ifndef FLT_EPSILON
+#define FLT_EPSILON 1.19209290e-7f
+#endif
+
+#ifndef M_PI
+#define M_PI 3.1415926535897932384626433832795
+#endif
+
+#ifndef M_SQRT2
+#define M_SQRT2 1.4142135623730950488016887
+#endif
+
+#ifndef M_2PI
+#define M_2PI 6.283185307179586476925286766559005
+#endif
+
+#ifndef M_SQRT1_2
+#define M_SQRT1_2 0.7071067811865475244008443621048490
+#endif
+
+#ifndef M_LOG_2PI
+#define M_LOG_2PI 1.8378770664093454835606594728112
+#endif
+
+#ifndef M_LN2
+#define M_LN2 0.693147180559945309417232121458
+#endif
+
+#ifndef M_LN10
+#define M_LN10 2.302585092994045684017991454684
+#endif
+
+
+#define KALDI_ISNAN std::isnan
+#define KALDI_ISINF std::isinf
+#define KALDI_ISFINITE(x) std::isfinite(x)
+
+#if !defined(KALDI_SQR)
+# define KALDI_SQR(x) ((x) * (x))
+#endif
+
+namespace kaldi {
+
+#if !defined(_MSC_VER) || (_MSC_VER >= 1900)
+inline double Exp(double x) { return exp(x); }
+#ifndef KALDI_NO_EXPF
+inline float Exp(float x) { return expf(x); }
+#else
+inline float Exp(float x) { return exp(static_cast<double>(x)); }
+#endif // KALDI_NO_EXPF
+#else
+inline double Exp(double x) { return exp(x); }
+#if !defined(__INTEL_COMPILER) && _MSC_VER == 1800 && defined(_M_X64)
+// Microsoft CL v18.0 buggy 64-bit implementation of
+// expf() incorrectly returns -inf for exp(-inf).
+inline float Exp(float x) { return exp(static_cast<double>(x)); }
+#else
+inline float Exp(float x) { return expf(x); }
+#endif // !defined(__INTEL_COMPILER) && _MSC_VER == 1800 && defined(_M_X64)
+#endif // !defined(_MSC_VER) || (_MSC_VER >= 1900)
+
+inline double Log(double x) { return log(x); }
+inline float Log(float x) { return logf(x); }
+
+#if !defined(_MSC_VER) || (_MSC_VER >= 1700)
+inline double Log1p(double x) { return log1p(x); }
+inline float Log1p(float x) { return log1pf(x); }
+#else
+inline double Log1p(double x) {
+ const double cutoff = 1.0e-08;
+ if (x < cutoff)
+ return x - 0.5 * x * x;
+ else
+ return Log(1.0 + x);
+}
+
+inline float Log1p(float x) {
+ const float cutoff = 1.0e-07;
+ if (x < cutoff)
+ return x - 0.5 * x * x;
+ else
+ return Log(1.0 + x);
+}
+#endif
+
+static const double kMinLogDiffDouble = Log(DBL_EPSILON); // negative!
+static const float kMinLogDiffFloat = Log(FLT_EPSILON); // negative!
+
+// -infinity
+const float kLogZeroFloat = -std::numeric_limits<float>::infinity();
+const double kLogZeroDouble = -std::numeric_limits<double>::infinity();
+const BaseFloat kLogZeroBaseFloat = -std::numeric_limits<BaseFloat>::infinity();
+
+// Returns a random integer between 0 and RAND_MAX, inclusive
+int Rand(struct RandomState* state = NULL);
+
+// State for thread-safe random number generator
+struct RandomState {
+ RandomState();
+ unsigned seed;
+};
+
+// Returns a random integer between first and last inclusive.
+int32 RandInt(int32 first, int32 last, struct RandomState* state = NULL);
+
+// Returns true with probability "prob",
+bool WithProb(BaseFloat prob, struct RandomState* state = NULL);
+// with 0 <= prob <= 1 [we check this].
+// Internally calls Rand(). This function is carefully implemented so
+// that it should work even if prob is very small.
+
+/// Returns a random number strictly between 0 and 1.
+inline float RandUniform(struct RandomState* state = NULL) {
+ return static_cast<float>((Rand(state) + 1.0) / (RAND_MAX+2.0));
+}
+
+inline float RandGauss(struct RandomState* state = NULL) {
+ return static_cast<float>(sqrtf (-2 * Log(RandUniform(state)))
+ * cosf(2*M_PI*RandUniform(state)));
+}
+
+// Returns poisson-distributed random number. Uses Knuth's algorithm.
+// Take care: this takes time proportional
+// to lambda. Faster algorithms exist but are more complex.
+int32 RandPoisson(float lambda, struct RandomState* state = NULL);
+
+// Returns a pair of gaussian random numbers. Uses Box-Muller transform
+void RandGauss2(float *a, float *b, RandomState *state = NULL);
+void RandGauss2(double *a, double *b, RandomState *state = NULL);
+
+// Also see Vector<float,double>::RandCategorical().
+
+// This is a randomized pruning mechanism that preserves expectations,
+// that we typically use to prune posteriors.
+template<class Float>
+inline Float RandPrune(Float post, BaseFloat prune_thresh,
+ struct RandomState* state = NULL) {
+ KALDI_ASSERT(prune_thresh >= 0.0);
+ if (post == 0.0 || std::abs(post) >= prune_thresh)
+ return post;
+ return (post >= 0 ? 1.0 : -1.0) *
+ (RandUniform(state) <= fabs(post)/prune_thresh ? prune_thresh : 0.0);
+}
+
+// returns log(exp(x) + exp(y)).
+inline double LogAdd(double x, double y) {
+ double diff;
+
+ if (x < y) {
+ diff = x - y;
+ x = y;
+ } else {
+ diff = y - x;
+ }
+ // diff is negative. x is now the larger one.
+
+ if (diff >= kMinLogDiffDouble) {
+ double res;
+ res = x + Log1p(Exp(diff));
+ return res;
+ } else {
+ return x; // return the larger one.
+ }
+}
+
+
+// returns log(exp(x) + exp(y)).
+inline float LogAdd(float x, float y) {
+ float diff;
+
+ if (x < y) {
+ diff = x - y;
+ x = y;
+ } else {
+ diff = y - x;
+ }
+ // diff is negative. x is now the larger one.
+
+ if (diff >= kMinLogDiffFloat) {
+ float res;
+ res = x + Log1p(Exp(diff));
+ return res;
+ } else {
+ return x; // return the larger one.
+ }
+}
+
+
+// returns log(exp(x) - exp(y)).
+inline double LogSub(double x, double y) {
+ if (y >= x) { // Throws exception if y>=x.
+ if (y == x)
+ return kLogZeroDouble;
+ else
+ KALDI_ERR << "Cannot subtract a larger from a smaller number.";
+ }
+
+ double diff = y - x; // Will be negative.
+ double res = x + Log(1.0 - Exp(diff));
+
+ // res might be NAN if diff ~0.0, and 1.0-exp(diff) == 0 to machine precision
+ if (KALDI_ISNAN(res))
+ return kLogZeroDouble;
+ return res;
+}
+
+
+// returns log(exp(x) - exp(y)).
+inline float LogSub(float x, float y) {
+ if (y >= x) { // Throws exception if y>=x.
+ if (y == x)
+ return kLogZeroDouble;
+ else
+ KALDI_ERR << "Cannot subtract a larger from a smaller number.";
+ }
+
+ float diff = y - x; // Will be negative.
+ float res = x + Log(1.0f - Exp(diff));
+
+ // res might be NAN if diff ~0.0, and 1.0-exp(diff) == 0 to machine precision
+ if (KALDI_ISNAN(res))
+ return kLogZeroFloat;
+ return res;
+}
+
+/// return abs(a - b) <= relative_tolerance * (abs(a)+abs(b)).
+static inline bool ApproxEqual(float a, float b,
+ float relative_tolerance = 0.001) {
+ // a==b handles infinities.
+ if (a == b) return true;
+ float diff = std::abs(a-b);
+ if (diff == std::numeric_limits<float>::infinity()
+ || diff != diff) return false; // diff is +inf or nan.
+ return (diff <= relative_tolerance*(std::abs(a)+std::abs(b)));
+}
+
+/// assert abs(a - b) <= relative_tolerance * (abs(a)+abs(b))
+static inline void AssertEqual(float a, float b,
+ float relative_tolerance = 0.001) {
+ // a==b handles infinities.
+ KALDI_ASSERT(ApproxEqual(a, b, relative_tolerance));
+}
+
+
+// RoundUpToNearestPowerOfTwo does the obvious thing. It crashes if n <= 0.
+int32 RoundUpToNearestPowerOfTwo(int32 n);
+
+/// Returns a / b, rounding towards negative infinity in all cases.
+static inline int32 DivideRoundingDown(int32 a, int32 b) {
+ KALDI_ASSERT(b != 0);
+ if (a * b >= 0)
+ return a / b;
+ else if (a < 0)
+ return (a - b + 1) / b;
+ else
+ return (a - b - 1) / b;
+}
+
+template<class I> I Gcd(I m, I n) {
+ if (m == 0 || n == 0) {
+ if (m == 0 && n == 0) { // gcd not defined, as all integers are divisors.
+ KALDI_ERR << "Undefined GCD since m = 0, n = 0.";
+ }
+ return (m == 0 ? (n > 0 ? n : -n) : ( m > 0 ? m : -m));
+ // return absolute value of whichever is nonzero
+ }
+ // could use compile-time assertion
+ // but involves messing with complex template stuff.
+ KALDI_ASSERT(std::numeric_limits<I>::is_integer);
+ while (1) {
+ m %= n;
+ if (m == 0) return (n > 0 ? n : -n);
+ n %= m;
+ if (n == 0) return (m > 0 ? m : -m);
+ }
+}
+
+/// Returns the least common multiple of two integers. Will
+/// crash unless the inputs are positive.
+template<class I> I Lcm(I m, I n) {
+ KALDI_ASSERT(m > 0 && n > 0);
+ I gcd = Gcd(m, n);
+ return gcd * (m/gcd) * (n/gcd);
+}
+
+
+template<class I> void Factorize(I m, std::vector<I> *factors) {
+ // Splits a number into its prime factors, in sorted order from
+ // least to greatest, with duplication. A very inefficient
+ // algorithm, which is mainly intended for use in the
+ // mixed-radix FFT computation (where we assume most factors
+ // are small).
+ KALDI_ASSERT(factors != NULL);
+ KALDI_ASSERT(m >= 1); // Doesn't work for zero or negative numbers.
+ factors->clear();
+ I small_factors[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
+
+ // First try small factors.
+ for (I i = 0; i < 10; i++) {
+ if (m == 1) return; // We're done.
+ while (m % small_factors[i] == 0) {
+ m /= small_factors[i];
+ factors->push_back(small_factors[i]);
+ }
+ }
+ // Next try all odd numbers starting from 31.
+ for (I j = 31;; j += 2) {
+ if (m == 1) return;
+ while (m % j == 0) {
+ m /= j;
+ factors->push_back(j);
+ }
+ }
+}
+
+inline double Hypot(double x, double y) { return hypot(x, y); }
+inline float Hypot(float x, float y) { return hypotf(x, y); }
+
+
+
+
+} // namespace kaldi
+
+
+#endif // KALDI_BASE_KALDI_MATH_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/base/kaldi-types.h b/runtime/onnxruntime/third_party/kaldi/base/kaldi-types.h
new file mode 100644
index 000000000..7ebf4f853
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/kaldi-types.h
@@ -0,0 +1,75 @@
+// base/kaldi-types.h
+
+// Copyright 2009-2011 Microsoft Corporation; Saarland University;
+// Jan Silovsky; Yanmin Qian
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_BASE_KALDI_TYPES_H_
+#define KALDI_BASE_KALDI_TYPES_H_ 1
+
+namespace kaldi {
+// TYPEDEFS ..................................................................
+#if (KALDI_DOUBLEPRECISION != 0)
+typedef double BaseFloat;
+#else
+typedef float BaseFloat;
+#endif
+}
+
+#ifdef _MSC_VER
+#include <basetsd.h>
+#define ssize_t SSIZE_T
+#endif
+
+// we can do this a different way if some platform
+// we find in the future lacks stdint.h
+#include <stdint.h>
+
+// for discussion on what to do if you need compile kaldi
+// without OpenFST, see the bottom of this this file
+#include <fst/types.h>
+
+namespace kaldi {
+ using ::int16;
+ using ::int32;
+ using ::int64;
+ using ::uint16;
+ using ::uint32;
+ using ::uint64;
+ typedef float float32;
+ typedef double double64;
+} // end namespace kaldi
+
+// In a theoretical case you decide compile Kaldi without the OpenFST
+// comment the previous namespace statement and uncomment the following
+/*
+namespace kaldi {
+ typedef int8_t int8;
+ typedef int16_t int16;
+ typedef int32_t int32;
+ typedef int64_t int64;
+
+ typedef uint8_t uint8;
+ typedef uint16_t uint16;
+ typedef uint32_t uint32;
+ typedef uint64_t uint64;
+ typedef float float32;
+ typedef double double64;
+} // end namespace kaldi
+*/
+
+#endif // KALDI_BASE_KALDI_TYPES_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/base/kaldi-utils.cc b/runtime/onnxruntime/third_party/kaldi/base/kaldi-utils.cc
new file mode 100644
index 000000000..0c0f1d4f3
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/kaldi-utils.cc
@@ -0,0 +1,46 @@
+// base/kaldi-utils.cc
+// Copyright 2009-2011 Karel Vesely; Yanmin Qian; Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "base/kaldi-utils.h"
+
+#include <cctype>
+#include <chrono>
+#include <cstdio>
+#include <thread>
+
+
+namespace kaldi {
+
+std::string CharToString(const char &c) {
+ char buf[20];
+ if (std::isprint(c))
+ std::snprintf(buf, sizeof(buf), "\'%c\'", c);
+ else
+ std::snprintf(buf, sizeof(buf), "[character %d]", static_cast<int>(c));
+ return buf;
+}
+
+void Sleep(double sec) {
+ // duration_cast<> rounds down, add 0.5 to compensate.
+ auto dur_nanos = std::chrono::duration<double, std::nano>(sec * 1E9 + 0.5);
+ auto dur_syshires = std::chrono::duration_cast<
+ typename std::chrono::high_resolution_clock::duration>(dur_nanos);
+ std::this_thread::sleep_for(dur_syshires);
+}
+
+} // end namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/base/kaldi-utils.h b/runtime/onnxruntime/third_party/kaldi/base/kaldi-utils.h
new file mode 100644
index 000000000..9f2c897ba
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/kaldi-utils.h
@@ -0,0 +1,162 @@
+// base/kaldi-utils.h
+
+// Copyright 2009-2011 Ondrej Glembek; Microsoft Corporation;
+// Saarland University; Karel Vesely; Yanmin Qian
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_BASE_KALDI_UTILS_H_
+#define KALDI_BASE_KALDI_UTILS_H_ 1
+
+#if _MSC_VER
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN 1
+#endif
+#ifndef NOMINMAX
+#define NOMINMAX 1
+#endif
+#include <windows.h>
+#endif
+
+#ifdef _MSC_VER
+#include <stdio.h>
+#define unlink _unlink
+#else
+#include <unistd.h>
+#endif
+
+#include <limits>
+#include <string>
+
+#if defined(_MSC_VER)
+#pragma warning(disable: 4244 4056 4305 4800 4267 4996 4756 4661)
+#if _MSC_VER < 1400
+#define __restrict__
+#else
+#define __restrict__ __restrict
+#endif
+#endif
+
+#if defined(_MSC_VER)
+# define KALDI_MEMALIGN(align, size, pp_orig) \
+ (*(pp_orig) = _aligned_malloc(size, align))
+# define KALDI_MEMALIGN_FREE(x) _aligned_free(x)
+#elif defined(__CYGWIN__)
+# define KALDI_MEMALIGN(align, size, pp_orig) \
+ (*(pp_orig) = aligned_alloc(align, size))
+# define KALDI_MEMALIGN_FREE(x) free(x)
+#else
+# define KALDI_MEMALIGN(align, size, pp_orig) \
+ (!posix_memalign(pp_orig, align, size) ? *(pp_orig) : NULL)
+# define KALDI_MEMALIGN_FREE(x) free(x)
+#endif
+
+#ifdef __ICC
+#pragma warning(disable: 383) // ICPC remark we don't want.
+#pragma warning(disable: 810) // ICPC remark we don't want.
+#pragma warning(disable: 981) // ICPC remark we don't want.
+#pragma warning(disable: 1418) // ICPC remark we don't want.
+#pragma warning(disable: 444) // ICPC remark we don't want.
+#pragma warning(disable: 869) // ICPC remark we don't want.
+#pragma warning(disable: 1287) // ICPC remark we don't want.
+#pragma warning(disable: 279) // ICPC remark we don't want.
+#pragma warning(disable: 981) // ICPC remark we don't want.
+#endif
+
+
+namespace kaldi {
+
+
+// CharToString prints the character in a human-readable form, for debugging.
+std::string CharToString(const char &c);
+
+
+inline int MachineIsLittleEndian() {
+ int check = 1;
+ return (*reinterpret_cast<char*>(&check) != 0);
+}
+
+// This function kaldi::Sleep() provides a portable way
+// to sleep for a possibly fractional
+// number of seconds. On Windows it's only accurate to microseconds.
+void Sleep(double seconds);
+}
+
+#define KALDI_SWAP8(a) do { \
+ int t = (reinterpret_cast<char*>(&a))[0];\
+ (reinterpret_cast<char*>(&a))[0]=(reinterpret_cast<char*>(&a))[7];\
+ (reinterpret_cast<char*>(&a))[7]=t;\
+ t = (reinterpret_cast<char*>(&a))[1];\
+ (reinterpret_cast<char*>(&a))[1]=(reinterpret_cast<char*>(&a))[6];\
+ (reinterpret_cast<char*>(&a))[6]=t;\
+ t = (reinterpret_cast<char*>(&a))[2];\
+ (reinterpret_cast<char*>(&a))[2]=(reinterpret_cast<char*>(&a))[5];\
+ (reinterpret_cast<char*>(&a))[5]=t;\
+ t = (reinterpret_cast<char*>(&a))[3];\
+ (reinterpret_cast<char*>(&a))[3]=(reinterpret_cast<char*>(&a))[4];\
+ (reinterpret_cast<char*>(&a))[4]=t;} while (0)
+#define KALDI_SWAP4(a) do { \
+ int t = (reinterpret_cast<char*>(&a))[0];\
+ (reinterpret_cast<char*>(&a))[0]=(reinterpret_cast<char*>(&a))[3];\
+ (reinterpret_cast<char*>(&a))[3]=t;\
+ t = (reinterpret_cast<char*>(&a))[1];\
+ (reinterpret_cast<char*>(&a))[1]=(reinterpret_cast<char*>(&a))[2];\
+ (reinterpret_cast<char*>(&a))[2]=t;} while (0)
+#define KALDI_SWAP2(a) do { \
+ int t = (reinterpret_cast<char*>(&a))[0];\
+ (reinterpret_cast<char*>(&a))[0]=(reinterpret_cast<char*>(&a))[1];\
+ (reinterpret_cast<char*>(&a))[1]=t;} while (0)
+
+
+///\brief Declare deleted copy constructor and copy assignment operator=().
+///
+/// Use this macro in the \e public part of a class declaration in a header
+/// file, next to its constructors, so that uncopyability of the type is
+/// clearly readable. Place a semicolon after it.
+///\param type The exact enclosing class name.
+#define KALDI_DISALLOW_COPY_AND_ASSIGN(type) \
+ type(const type&) = delete; \
+ type& operator=(const type&) = delete
+
+#if __cplusplus >= 201703L
+#define KALDI_COMPILE_TIME_ASSERT static_assert
+#else
+#define KALDI_COMPILE_TIME_ASSERT(b) static_assert((b), #b)
+#endif
+
+#define KALDI_ASSERT_IS_INTEGER_TYPE(I) \
+ KALDI_COMPILE_TIME_ASSERT(std::numeric_limits<I>::is_specialized \
+ && std::numeric_limits<I>::is_integer)
+
+#define KALDI_ASSERT_IS_FLOATING_TYPE(F) \
+ KALDI_COMPILE_TIME_ASSERT(std::numeric_limits<F>::is_specialized \
+ && !std::numeric_limits<F>::is_integer)
+
+#if defined(_MSC_VER)
+#define KALDI_STRCASECMP _stricmp
+#elif defined(__CYGWIN__)
+#include <strings.h>
+#define KALDI_STRCASECMP strcasecmp
+#else
+#define KALDI_STRCASECMP strcasecmp
+#endif
+#ifdef _MSC_VER
+# define KALDI_STRTOLL(cur_cstr, end_cstr) _strtoi64(cur_cstr, end_cstr, 10);
+#else
+# define KALDI_STRTOLL(cur_cstr, end_cstr) strtoll(cur_cstr, end_cstr, 10);
+#endif
+
+#endif // KALDI_BASE_KALDI_UTILS_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/base/timer-test.cc b/runtime/onnxruntime/third_party/kaldi/base/timer-test.cc
new file mode 100644
index 000000000..86a20b486
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/timer-test.cc
@@ -0,0 +1,45 @@
+// base/timer-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2014 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "base/timer.h"
+#include "base/kaldi-common.h"
+#include "base/kaldi-utils.h"
+
+
+namespace kaldi {
+
+void TimerTest() {
+ float time_secs = 0.025 * (rand() % 10);
+ std::cout << "target is " << time_secs << "\n";
+ Timer timer;
+ Sleep(time_secs);
+ BaseFloat f = timer.Elapsed();
+ std::cout << "time is " << f << std::endl;
+ if (fabs(time_secs - f) > 0.05)
+ KALDI_ERR << "Timer fail: waited " << f << " seconds instead of "
+ << time_secs << " secs.";
+}
+}
+
+
+int main() {
+ for (int i = 0; i < 4; i++)
+ kaldi::TimerTest();
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/base/timer.cc b/runtime/onnxruntime/third_party/kaldi/base/timer.cc
new file mode 100644
index 000000000..ce4ef2927
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/timer.cc
@@ -0,0 +1,85 @@
+// base/timer.cc
+
+// Copyright 2018 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "base/timer.h"
+#include "base/kaldi-error.h"
+#include <algorithm>
+#include <iomanip>
+#include <map>
+#include <unordered_map>
+
+namespace kaldi {
+
+class ProfileStats {
+ public:
+ void AccStats(const char *function_name, double elapsed) {
+ std::unordered_map<const char*, ProfileStatsEntry>::iterator
+ iter = map_.find(function_name);
+ if (iter == map_.end()) {
+ map_[function_name] = ProfileStatsEntry(function_name);
+ map_[function_name].total_time = elapsed;
+ } else {
+ iter->second.total_time += elapsed;
+ }
+ }
+ ~ProfileStats() {
+ // This map makes sure we agglomerate the time if there were any duplicate
+ // addresses of strings.
+ std::unordered_map<std::string, double> total_time;
+ for (auto iter = map_.begin(); iter != map_.end(); iter++)
+ total_time[iter->second.name] += iter->second.total_time;
+
+ ReverseSecondComparator comp;
+ std::vector<std::pair<std::string, double> > pairs(total_time.begin(),
+ total_time.end());
+ std::sort(pairs.begin(), pairs.end(), comp);
+ for (size_t i = 0; i < pairs.size(); i++) {
+ KALDI_LOG << "Time taken in " << pairs[i].first << " is "
+ << std::fixed << std::setprecision(2) << pairs[i].second << "s.";
+ }
+ }
+ private:
+
+ struct ProfileStatsEntry {
+ std::string name;
+ double total_time;
+ ProfileStatsEntry() { }
+ ProfileStatsEntry(const char *name): name(name) { }
+ };
+
+ struct ReverseSecondComparator {
+ bool operator () (const std::pair<std::string, double> &a,
+ const std::pair<std::string, double> &b) {
+ return a.second > b.second;
+ }
+ };
+
+ // Note: this map is keyed on the address of the string, there is no proper
+ // hash function. The assumption is that the strings are compile-time
+ // constants.
+ std::unordered_map<const char*, ProfileStatsEntry> map_;
+};
+
+ProfileStats g_profile_stats;
+
+Profiler::~Profiler() {
+ g_profile_stats.AccStats(name_, tim_.Elapsed());
+}
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/base/timer.h b/runtime/onnxruntime/third_party/kaldi/base/timer.h
new file mode 100644
index 000000000..0e0337663
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/base/timer.h
@@ -0,0 +1,115 @@
+// base/timer.h
+
+// Copyright 2009-2011 Ondrej Glembek; Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#ifndef KALDI_BASE_TIMER_H_
+#define KALDI_BASE_TIMER_H_
+
+#include "base/kaldi-utils.h"
+#include "base/kaldi-error.h"
+
+
+#if defined(_MSC_VER) || defined(MINGW)
+
+namespace kaldi {
+class Timer {
+ public:
+ Timer() { Reset(); }
+
+ // You can initialize with bool to control whether or not you want the time to
+ // be set when the object is created.
+ explicit Timer(bool set_timer) { if (set_timer) Reset(); }
+
+ void Reset() {
+ QueryPerformanceCounter(&time_start_);
+ }
+ double Elapsed() const {
+ LARGE_INTEGER time_end;
+ LARGE_INTEGER freq;
+ QueryPerformanceCounter(&time_end);
+
+ if (QueryPerformanceFrequency(&freq) == 0) {
+ // Hardware does not support this.
+ return 0.0;
+ }
+ return (static_cast<double>(time_end.QuadPart) -
+ static_cast<double>(time_start_.QuadPart)) /
+ (static_cast<double>(freq.QuadPart));
+ }
+ private:
+ LARGE_INTEGER time_start_;
+};
+
+
+#else
+#include <sys/time.h>
+#include <unistd.h>
+
+namespace kaldi {
+class Timer {
+ public:
+ Timer() { Reset(); }
+
+ // You can initialize with bool to control whether or not you want the time to
+ // be set when the object is created.
+ explicit Timer(bool set_timer) { if (set_timer) Reset(); }
+
+ void Reset() { gettimeofday(&this->time_start_, &time_zone_); }
+
+ /// Returns time in seconds.
+ double Elapsed() const {
+ struct timeval time_end;
+ struct timezone time_zone;
+ gettimeofday(&time_end, &time_zone);
+ double t1, t2;
+ t1 = static_cast<double>(time_start_.tv_sec) +
+ static_cast<double>(time_start_.tv_usec)/(1000*1000);
+ t2 = static_cast<double>(time_end.tv_sec) +
+ static_cast<double>(time_end.tv_usec)/(1000*1000);
+ return t2-t1;
+ }
+
+ private:
+ struct timeval time_start_;
+ struct timezone time_zone_;
+};
+
+#endif
+
+class Profiler {
+ public:
+ // Caution: the 'const char' should always be a string constant; for speed,
+ // internally the profiling code uses the address of it as a lookup key.
+ Profiler(const char *function_name): name_(function_name) { }
+ ~Profiler();
+ private:
+ Timer tim_;
+ const char *name_;
+};
+
+// To add timing info for a function, you just put
+// KALDI_PROFILE;
+// at the beginning of the function. Caution: this doesn't
+// include the class name.
+#define KALDI_PROFILE Profiler _profiler(__func__)
+
+
+
+} // namespace kaldi
+
+
+#endif // KALDI_BASE_TIMER_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/Makefile b/runtime/onnxruntime/third_party/kaldi/decoder/Makefile
new file mode 100644
index 000000000..a814931f6
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/Makefile
@@ -0,0 +1,20 @@
+all:
+
+EXTRA_CXXFLAGS = -Wno-sign-compare
+include ../kaldi.mk
+
+TESTFILES =
+
+OBJFILES = training-graph-compiler.o lattice-simple-decoder.o lattice-faster-decoder.o \
+ lattice-faster-online-decoder.o simple-decoder.o faster-decoder.o \
+ decoder-wrappers.o grammar-fst.o decodable-matrix.o \
+ lattice-incremental-decoder.o lattice-incremental-online-decoder.o
+
+LIBNAME = kaldi-decoder
+
+ADDLIBS = ../lat/kaldi-lat.a ../fstext/kaldi-fstext.a ../hmm/kaldi-hmm.a \
+ ../transform/kaldi-transform.a ../gmm/kaldi-gmm.a \
+ ../tree/kaldi-tree.a ../util/kaldi-util.a ../matrix/kaldi-matrix.a \
+ ../base/kaldi-base.a
+
+include ../makefiles/default_rules.mk
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/biglm-faster-decoder.h b/runtime/onnxruntime/third_party/kaldi/decoder/biglm-faster-decoder.h
new file mode 100644
index 000000000..8e36deb8b
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/biglm-faster-decoder.h
@@ -0,0 +1,502 @@
+// decoder/biglm-faster-decoder.h
+
+// Copyright 2009-2011 Microsoft Corporation, Gilles Boulianne
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_DECODER_BIGLM_FASTER_DECODER_H_
+#define KALDI_DECODER_BIGLM_FASTER_DECODER_H_
+
+#include "util/stl-utils.h"
+#include "util/hash-list.h"
+#include "fst/fstlib.h"
+#include "itf/decodable-itf.h"
+#include "lat/kaldi-lattice.h" // for CompactLatticeArc
+#include "decoder/faster-decoder.h" // for options class
+#include "fstext/deterministic-fst.h"
+
+namespace kaldi {
+
+struct BiglmFasterDecoderOptions: public FasterDecoderOptions {
+ BiglmFasterDecoderOptions() {
+ min_active = 200;
+ }
+};
+
+/** This is as FasterDecoder, but does online composition between
+ HCLG and the "difference language model", which is a deterministic
+ FST that represents the difference between the language model you want
+ and the language model you compiled HCLG with. The class
+ DeterministicOnDemandFst follows through the epsilons in G for you
+ (assuming G is a standard backoff language model) and makes it look
+ like a determinized FST. Actually, in practice,
+ DeterministicOnDemandFst operates in a mode where it composes two
+ G's together; one has negated likelihoods and works by removing the
+ LM probabilities that you made HCLG with, and one is the language model
+ you want to use.
+*/
+class BiglmFasterDecoder {
+ public:
+ typedef fst::StdArc Arc;
+ typedef Arc::Label Label;
+ typedef Arc::StateId StateId;
+ // A PairId will be constructed as: (StateId in fst) + (StateId in lm_diff_fst) << 32;
+ typedef uint64 PairId;
+ typedef Arc::Weight Weight;
+
+ // This constructor is the same as for FasterDecoder, except the second
+ // argument (lm_diff_fst) is new; it's an FST (actually, a
+ // DeterministicOnDemandFst) that represents the difference in LM scores
+ // between the LM we want and the LM the decoding-graph "fst" was built with.
+ // See e.g. gmm-decode-biglm-faster.cc for an example of how this is called.
+ // Basically, we are using fst o lm_diff_fst (where o is composition)
+ // as the decoding graph. Instead of having everything indexed by the state in
+ // "fst", we now index by the pair of states in (fst, lm_diff_fst).
+ // Whenever we cross a word, we need to propagate the state within
+ // lm_diff_fst.
+ BiglmFasterDecoder(const fst::Fst<fst::StdArc> &fst,
+ const BiglmFasterDecoderOptions &opts,
+ fst::DeterministicOnDemandFst<fst::StdArc> *lm_diff_fst):
+ fst_(fst), lm_diff_fst_(lm_diff_fst), opts_(opts), warned_noarc_(false) {
+ KALDI_ASSERT(opts_.hash_ratio >= 1.0); // less doesn't make much sense.
+ KALDI_ASSERT(opts_.max_active > 1);
+ KALDI_ASSERT(fst.Start() != fst::kNoStateId &&
+ lm_diff_fst->Start() != fst::kNoStateId);
+ toks_.SetSize(1000); // just so on the first frame we do something reasonable.
+ }
+
+ void SetOptions(const BiglmFasterDecoderOptions &opts) { opts_ = opts; }
+
+ ~BiglmFasterDecoder() {
+ ClearToks(toks_.Clear());
+ }
+
+ void Decode(DecodableInterface *decodable) {
+ // clean up from last time:
+ ClearToks(toks_.Clear());
+ PairId start_pair = ConstructPair(fst_.Start(), lm_diff_fst_->Start());
+ Arc dummy_arc(0, 0, Weight::One(), fst_.Start()); // actually, the last element of
+ // the Arcs (fst_.Start(), here) is never needed.
+ toks_.Insert(start_pair, new Token(dummy_arc, NULL));
+ ProcessNonemitting(std::numeric_limits<float>::max());
+ for (int32 frame = 0; !decodable->IsLastFrame(frame-1); frame++) {
+ BaseFloat weight_cutoff = ProcessEmitting(decodable, frame);
+ ProcessNonemitting(weight_cutoff);
+ }
+ }
+
+ bool ReachedFinal() {
+ for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail) {
+ PairId state_pair = e->key;
+ StateId state = PairToState(state_pair),
+ lm_state = PairToLmState(state_pair);
+ Weight this_weight =
+ Times(e->val->weight_,
+ Times(fst_.Final(state), lm_diff_fst_->Final(lm_state)));
+ if (this_weight != Weight::Zero())
+ return true;
+ }
+ return false;
+ }
+
+ bool GetBestPath(fst::MutableFst<LatticeArc> *fst_out,
+ bool use_final_probs = true) {
+ // GetBestPath gets the decoding output. If "use_final_probs" is true
+ // AND we reached a final state, it limits itself to final states;
+ // otherwise it gets the most likely token not taking into
+ // account final-probs. fst_out will be empty (Start() == kNoStateId) if
+ // nothing was available. It returns true if it got output (thus, fst_out
+ // will be nonempty).
+ fst_out->DeleteStates();
+ Token *best_tok = NULL;
+ Weight best_final = Weight::Zero(); // set only if is_final == true. The
+ // final-prob corresponding to the best final token (i.e. the one with best
+ // weight best_weight, below).
+ bool is_final = ReachedFinal();
+ if (!is_final) {
+ for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail)
+ if (best_tok == NULL || *best_tok < *(e->val) )
+ best_tok = e->val;
+ } else {
+ Weight best_weight = Weight::Zero();
+ for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail) {
+ Weight fst_final = fst_.Final(PairToState(e->key)),
+ lm_final = lm_diff_fst_->Final(PairToLmState(e->key)),
+ final = Times(fst_final, lm_final);
+ Weight this_weight = Times(e->val->weight_, final);
+ if (this_weight != Weight::Zero() &&
+ this_weight.Value() < best_weight.Value()) {
+ best_weight = this_weight;
+ best_final = final;
+ best_tok = e->val;
+ }
+ }
+ }
+ if (best_tok == NULL) return false; // No output.
+
+ std::vector<LatticeArc> arcs_reverse; // arcs in reverse order.
+
+ for (Token *tok = best_tok; tok != NULL; tok = tok->prev_) {
+ BaseFloat tot_cost = tok->weight_.Value() -
+ (tok->prev_ ? tok->prev_->weight_.Value() : 0.0),
+ graph_cost = tok->arc_.weight.Value(),
+ ac_cost = tot_cost - graph_cost;
+ LatticeArc l_arc(tok->arc_.ilabel,
+ tok->arc_.olabel,
+ LatticeWeight(graph_cost, ac_cost),
+ tok->arc_.nextstate);
+ arcs_reverse.push_back(l_arc);
+ }
+ KALDI_ASSERT(arcs_reverse.back().nextstate == fst_.Start());
+ arcs_reverse.pop_back(); // that was a "fake" token... gives no info.
+
+ StateId cur_state = fst_out->AddState();
+ fst_out->SetStart(cur_state);
+ for (ssize_t i = static_cast<ssize_t>(arcs_reverse.size())-1; i >= 0; i--) {
+ LatticeArc arc = arcs_reverse[i];
+ arc.nextstate = fst_out->AddState();
+ fst_out->AddArc(cur_state, arc);
+ cur_state = arc.nextstate;
+ }
+ if (is_final && use_final_probs) {
+ fst_out->SetFinal(cur_state, LatticeWeight(best_final.Value(), 0.0));
+ } else {
+ fst_out->SetFinal(cur_state, LatticeWeight::One());
+ }
+ RemoveEpsLocal(fst_out);
+ return true;
+ }
+
+ private:
+ inline PairId ConstructPair(StateId fst_state, StateId lm_state) {
+ return static_cast<PairId>(fst_state) + (static_cast<PairId>(lm_state) << 32);
+ }
+
+ static inline StateId PairToState(PairId state_pair) {
+ return static_cast<StateId>(static_cast<uint32>(state_pair));
+ }
+ static inline StateId PairToLmState(PairId state_pair) {
+ return static_cast<StateId>(static_cast<uint32>(state_pair >> 32));
+ }
+
+ class Token {
+ public:
+ Arc arc_; // contains only the graph part of the cost,
+ // including the part in "fst" (== HCLG) plus lm_diff_fst.
+ // We can work out the acoustic part from difference between
+ // "weight_" and prev->weight_.
+ Token *prev_;
+ int32 ref_count_;
+ Weight weight_; // weight up to current point.
+ inline Token(const Arc &arc, Weight &ac_weight, Token *prev):
+ arc_(arc), prev_(prev), ref_count_(1) {
+ if (prev) {
+ prev->ref_count_++;
+ weight_ = Times(Times(prev->weight_, arc.weight), ac_weight);
+ } else {
+ weight_ = Times(arc.weight, ac_weight);
+ }
+ }
+ inline Token(const Arc &arc, Token *prev):
+ arc_(arc), prev_(prev), ref_count_(1) {
+ if (prev) {
+ prev->ref_count_++;
+ weight_ = Times(prev->weight_, arc.weight);
+ } else {
+ weight_ = arc.weight;
+ }
+ }
+ inline bool operator < (const Token &other) {
+ return weight_.Value() > other.weight_.Value();
+ // This makes sense for log + tropical semiring.
+ }
+
+ inline ~Token() {
+ KALDI_ASSERT(ref_count_ == 1);
+ if (prev_ != NULL) TokenDelete(prev_);
+ }
+ inline static void TokenDelete(Token *tok) {
+ if (tok->ref_count_ == 1) {
+ delete tok;
+ } else {
+ tok->ref_count_--;
+ }
+ }
+ };
+ typedef HashList<PairId, Token*>::Elem Elem;
+
+
+ /// Gets the weight cutoff. Also counts the active tokens.
+ BaseFloat GetCutoff(Elem *list_head, size_t *tok_count,
+ BaseFloat *adaptive_beam, Elem **best_elem) {
+ BaseFloat best_weight = 1.0e+10; // positive == high cost == bad.
+ size_t count = 0;
+ if (opts_.max_active == std::numeric_limits<int32>::max() &&
+ opts_.min_active == 0) {
+ for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
+ BaseFloat w = static_cast<BaseFloat>(e->val->weight_.Value());
+ if (w < best_weight) {
+ best_weight = w;
+ if (best_elem) *best_elem = e;
+ }
+ }
+ if (tok_count != NULL) *tok_count = count;
+ if (adaptive_beam != NULL) *adaptive_beam = opts_.beam;
+ return best_weight + opts_.beam;
+ } else {
+ tmp_array_.clear();
+ for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
+ BaseFloat w = e->val->weight_.Value();
+ tmp_array_.push_back(w);
+ if (w < best_weight) {
+ best_weight = w;
+ if (best_elem) *best_elem = e;
+ }
+ }
+ if (tok_count != NULL) *tok_count = count;
+
+ BaseFloat beam_cutoff = best_weight + opts_.beam,
+ min_active_cutoff = std::numeric_limits<BaseFloat>::infinity(),
+ max_active_cutoff = std::numeric_limits<BaseFloat>::infinity();
+
+ if (tmp_array_.size() > static_cast<size_t>(opts_.max_active)) {
+ std::nth_element(tmp_array_.begin(),
+ tmp_array_.begin() + opts_.max_active,
+ tmp_array_.end());
+ max_active_cutoff = tmp_array_[opts_.max_active];
+ }
+ if (tmp_array_.size() > static_cast<size_t>(opts_.min_active)) {
+ if (opts_.min_active == 0) min_active_cutoff = best_weight;
+ else {
+ std::nth_element(tmp_array_.begin(),
+ tmp_array_.begin() + opts_.min_active,
+ tmp_array_.size() > static_cast<size_t>(opts_.max_active) ?
+ tmp_array_.begin() + opts_.max_active :
+ tmp_array_.end());
+ min_active_cutoff = tmp_array_[opts_.min_active];
+ }
+ }
+
+ if (max_active_cutoff < beam_cutoff) { // max_active is tighter than beam.
+ if (adaptive_beam)
+ *adaptive_beam = max_active_cutoff - best_weight + opts_.beam_delta;
+ return max_active_cutoff;
+ } else if (min_active_cutoff > beam_cutoff) { // min_active is looser than beam.
+ if (adaptive_beam)
+ *adaptive_beam = min_active_cutoff - best_weight + opts_.beam_delta;
+ return min_active_cutoff;
+ } else {
+ *adaptive_beam = opts_.beam;
+ return beam_cutoff;
+ }
+ }
+ }
+
+ void PossiblyResizeHash(size_t num_toks) {
+ size_t new_sz = static_cast<size_t>(static_cast<BaseFloat>(num_toks)
+ * opts_.hash_ratio);
+ if (new_sz > toks_.Size()) {
+ toks_.SetSize(new_sz);
+ }
+ }
+
+ inline StateId PropagateLm(StateId lm_state,
+ Arc *arc) { // returns new LM state.
+ if (arc->olabel == 0) {
+ return lm_state; // no change in LM state if no word crossed.
+ } else { // Propagate in the LM-diff FST.
+ Arc lm_arc;
+ bool ans = lm_diff_fst_->GetArc(lm_state, arc->olabel, &lm_arc);
+ if (!ans) { // this case is unexpected for statistical LMs.
+ if (!warned_noarc_) {
+ warned_noarc_ = true;
+ KALDI_WARN << "No arc available in LM (unlikely to be correct "
+ "if a statistical language model); will not warn again";
+ }
+ arc->weight = Weight::Zero();
+ return lm_state; // doesn't really matter what we return here; will
+ // be pruned.
+ } else {
+ arc->weight = Times(arc->weight, lm_arc.weight);
+ arc->olabel = lm_arc.olabel; // probably will be the same.
+ return lm_arc.nextstate; // return the new LM state.
+ }
+ }
+ }
+
+ // ProcessEmitting returns the likelihood cutoff used.
+ BaseFloat ProcessEmitting(DecodableInterface *decodable, int frame) {
+ Elem *last_toks = toks_.Clear();
+ size_t tok_cnt;
+ BaseFloat adaptive_beam;
+ Elem *best_elem = NULL;
+ BaseFloat weight_cutoff = GetCutoff(last_toks, &tok_cnt,
+ &adaptive_beam, &best_elem);
+ PossiblyResizeHash(tok_cnt); // This makes sure the hash is always big enough.
+
+ // This is the cutoff we use after adding in the log-likes (i.e.
+ // for the next frame). This is a bound on the cutoff we will use
+ // on the next frame.
+ BaseFloat next_weight_cutoff = 1.0e+10;
+
+ // First process the best token to get a hopefully
+ // reasonably tight bound on the next cutoff.
+ if (best_elem) {
+ PairId state_pair = best_elem->key;
+ StateId state = PairToState(state_pair),
+ lm_state = PairToLmState(state_pair);
+ Token *tok = best_elem->val;
+ for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ Arc arc = aiter.Value();
+ if (arc.ilabel != 0) { // we'd propagate..
+ PropagateLm(lm_state, &arc); // may affect "arc.weight".
+ // We don't need the return value (the new LM state).
+ BaseFloat ac_cost = - decodable->LogLikelihood(frame, arc.ilabel),
+ new_weight = arc.weight.Value() + tok->weight_.Value() + ac_cost;
+ if (new_weight + adaptive_beam < next_weight_cutoff)
+ next_weight_cutoff = new_weight + adaptive_beam;
+ }
+ }
+ }
+
+ // the tokens are now owned here, in last_toks, and the hash is empty.
+ // 'owned' is a complex thing here; the point is we need to call toks_.Delete(e)
+ // on each elem 'e' to let toks_ know we're done with them.
+ for (Elem *e = last_toks, *e_tail; e != NULL; e = e_tail) { // loop this way
+ // because we delete "e" as we go.
+ PairId state_pair = e->key;
+ StateId state = PairToState(state_pair),
+ lm_state = PairToLmState(state_pair);
+ Token *tok = e->val;
+ if (tok->weight_.Value() < weight_cutoff) { // not pruned.
+ KALDI_ASSERT(state == tok->arc_.nextstate);
+ for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ Arc arc = aiter.Value();
+ if (arc.ilabel != 0) { // propagate.
+ StateId next_lm_state = PropagateLm(lm_state, &arc);
+ Weight ac_weight(-decodable->LogLikelihood(frame, arc.ilabel));
+ BaseFloat new_weight = arc.weight.Value() + tok->weight_.Value()
+ + ac_weight.Value();
+ if (new_weight < next_weight_cutoff) { // not pruned..
+ PairId next_pair = ConstructPair(arc.nextstate, next_lm_state);
+ Token *new_tok = new Token(arc, ac_weight, tok);
+ Elem *e_found = toks_.Insert(next_pair, new_tok);
+ if (new_weight + adaptive_beam < next_weight_cutoff)
+ next_weight_cutoff = new_weight + adaptive_beam;
+ if (e_found->val != new_tok) {
+ if (*(e_found->val) < *new_tok) {
+ Token::TokenDelete(e_found->val);
+ e_found->val = new_tok;
+ } else {
+ Token::TokenDelete(new_tok);
+ }
+ }
+ }
+ }
+ }
+ }
+ e_tail = e->tail;
+ Token::TokenDelete(e->val);
+ toks_.Delete(e);
+ }
+ return next_weight_cutoff;
+ }
+
+ // TODO: first time we go through this, could avoid using the queue.
+ void ProcessNonemitting(BaseFloat cutoff) {
+ // Processes nonemitting arcs for one frame.
+ KALDI_ASSERT(queue_.empty());
+ for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail)
+ queue_.push_back(e);
+ while (!queue_.empty()) {
+ const Elem *e = queue_.back();
+ queue_.pop_back();
+ PairId state_pair = e->key;
+ Token *tok = e->val; // would segfault if state not
+ // in toks_ but this can't happen.
+ if (tok->weight_.Value() > cutoff) { // Don't bother processing successors.
+ continue;
+ }
+ KALDI_ASSERT(tok != NULL);
+ StateId state = PairToState(state_pair),
+ lm_state = PairToLmState(state_pair);
+ for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc_ref = aiter.Value();
+ if (arc_ref.ilabel == 0) { // propagate nonemitting only...
+ Arc arc(arc_ref);
+ StateId next_lm_state = PropagateLm(lm_state, &arc);
+ PairId next_pair = ConstructPair(arc.nextstate, next_lm_state);
+ Token *new_tok = new Token(arc, tok);
+ if (new_tok->weight_.Value() > cutoff) { // prune
+ Token::TokenDelete(new_tok);
+ } else {
+ Elem *e_found = toks_.Insert(next_pair, new_tok);
+ if (e_found->val == new_tok) {
+ queue_.push_back(e_found);
+ } else {
+ if ( *(e_found->val) < *new_tok ) {
+ Token::TokenDelete(e_found->val);
+ e_found->val = new_tok;
+ queue_.push_back(e_found);
+ } else {
+ Token::TokenDelete(new_tok);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // HashList defined in ../util/hash-list.h. It actually allows us to maintain
+ // more than one list (e.g. for current and previous frames), but only one of
+ // them at a time can be indexed by PairId.
+ HashList<PairId, Token*> toks_;
+ const fst::Fst<fst::StdArc> &fst_;
+ fst::DeterministicOnDemandFst<fst::StdArc> *lm_diff_fst_;
+ BiglmFasterDecoderOptions opts_;
+ bool warned_noarc_;
+ std::vector<const Elem* > queue_; // temp variable used in ProcessNonemitting,
+ std::vector<BaseFloat> tmp_array_; // used in GetCutoff.
+ // make it class member to avoid internal new/delete.
+
+ // It might seem unclear why we call ClearToks(toks_.Clear()).
+ // There are two separate cleanup tasks we need to do at when we start a new file.
+ // one is to delete the Token objects in the list; the other is to delete
+ // the Elem objects. toks_.Clear() just clears them from the hash and gives ownership
+ // to the caller, who then has to call toks_.Delete(e) for each one. It was designed
+ // this way for convenience in propagating tokens from one frame to the next.
+ void ClearToks(Elem *list) {
+ for (Elem *e = list, *e_tail; e != NULL; e = e_tail) {
+ Token::TokenDelete(e->val);
+ e_tail = e->tail;
+ toks_.Delete(e);
+ }
+ }
+ KALDI_DISALLOW_COPY_AND_ASSIGN(BiglmFasterDecoder);
+};
+
+
+} // end namespace kaldi.
+
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/decodable-mapped.h b/runtime/onnxruntime/third_party/kaldi/decoder/decodable-mapped.h
new file mode 100644
index 000000000..daebfb50d
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/decodable-mapped.h
@@ -0,0 +1,69 @@
+// decoder/decodable-mapped.h
+
+// Copyright 2009-2011 Saarland University; Microsoft Corporation;
+// Lukas Burget
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_DECODER_DECODABLE_MAPPED_H_
+#define KALDI_DECODER_DECODABLE_MAPPED_H_
+
+#include <vector>
+
+#include "base/kaldi-common.h"
+#include "itf/decodable-itf.h"
+
+namespace kaldi {
+
+// The DecodableMapped object is initialized by a normal decodable object,
+// and a vector that maps indices. The "pdf index" into this decodable object
+// is the index into the vector, and the value it finds there is used
+// to index into the base decodable object.
+
+class DecodableMapped: public DecodableInterface {
+ public:
+ DecodableMapped(const std::vector<int32> &index_map, DecodableInterface *d):
+ index_map_(index_map), decodable_(d) { }
+
+ // Note, frames are numbered from zero. But state_index is numbered
+ // from one (this routine is called by FSTs).
+ virtual BaseFloat LogLikelihood(int32 frame, int32 state_index) {
+ KALDI_ASSERT(static_cast<size_t>(state_index) < index_map_.size());
+ return decodable_->LogLikelihood(frame, index_map_[state_index]);
+ }
+
+ // note: indices are assumed to be numbered from one, so
+ // NumIndices() will be the same as the largest index.
+ virtual int32 NumIndices() const { return static_cast<int32>(index_map_.size()) - 1; }
+
+ virtual bool IsLastFrame(int32 frame) const {
+ // We require all the decodables have the same #frames. We don't check this though.
+ return decodable_->IsLastFrame(frame);
+ }
+
+ private:
+ std::vector<int32> index_map_;
+ DecodableInterface *decodable_;
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(DecodableMapped);
+};
+
+
+
+} // namespace kaldi
+
+#endif // KALDI_DECODER_DECODABLE_MAPPED_H_
+
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/decodable-matrix.cc b/runtime/onnxruntime/third_party/kaldi/decoder/decodable-matrix.cc
new file mode 100644
index 000000000..5cbc0a595
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/decodable-matrix.cc
@@ -0,0 +1,112 @@
+// decoder/decodable-matrix.cc
+
+// Copyright 2018 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "decoder/decodable-matrix.h"
+
+namespace kaldi {
+
+DecodableMatrixMapped::DecodableMatrixMapped(
+ const TransitionInformation &tm,
+ const MatrixBase<BaseFloat> &likes,
+ int32 frame_offset):
+ trans_model_(tm),
+ tid_to_pdf_(trans_model_.TransitionIdToPdfArray()),
+ likes_(&likes), likes_to_delete_(NULL),
+ frame_offset_(frame_offset) {
+ stride_ = likes.Stride();
+ raw_data_ = likes.Data() - (stride_ * frame_offset);
+
+ if (likes.NumCols() != tm.NumPdfs())
+ KALDI_ERR << "Mismatch, matrix has "
+ << likes.NumCols() << " cols but transition-model has "
+ << tm.NumPdfs() << " pdf-ids.";
+}
+
+DecodableMatrixMapped::DecodableMatrixMapped(
+ const TransitionInformation &tm, const Matrix<BaseFloat> *likes,
+ int32 frame_offset):
+ trans_model_(tm),
+ tid_to_pdf_(trans_model_.TransitionIdToPdfArray()),
+ likes_(likes), likes_to_delete_(likes),
+ frame_offset_(frame_offset) {
+ stride_ = likes->Stride();
+ raw_data_ = likes->Data() - (stride_ * frame_offset_);
+ if (likes->NumCols() != tm.NumPdfs())
+ KALDI_ERR << "Mismatch, matrix has "
+ << likes->NumCols() << " cols but transition-model has "
+ << tm.NumPdfs() << " pdf-ids.";
+}
+
+
+BaseFloat DecodableMatrixMapped::LogLikelihood(int32 frame, int32 tid) {
+ KALDI_PARANOID_ASSERT(tid >= 1 && tid < tid_to_pdf_.size());
+ int32 pdf_id = tid_to_pdf_[tid];
+#ifdef KALDI_PARANOID
+ return (*likes_)(frame - frame_offset_, pdf_id);
+#else
+ return raw_data_[frame * stride_ + pdf_id];
+#endif
+}
+
+int32 DecodableMatrixMapped::NumFramesReady() const {
+ return frame_offset_ + likes_->NumRows();
+}
+
+bool DecodableMatrixMapped::IsLastFrame(int32 frame) const {
+ KALDI_ASSERT(frame < NumFramesReady());
+ return (frame == NumFramesReady() - 1);
+}
+
+// Indices are one-based! This is for compatibility with OpenFst.
+int32 DecodableMatrixMapped::NumIndices() const {
+ return trans_model_.NumTransitionIds();
+}
+
+DecodableMatrixMapped::~DecodableMatrixMapped() {
+ delete likes_to_delete_;
+}
+
+
+void DecodableMatrixMappedOffset::AcceptLoglikes(
+ Matrix<BaseFloat> *loglikes, int32 frames_to_discard) {
+ if (loglikes->NumRows() == 0) return;
+ KALDI_ASSERT(loglikes->NumCols() == trans_model_.NumPdfs());
+ KALDI_ASSERT(frames_to_discard <= loglikes_.NumRows() &&
+ frames_to_discard >= 0);
+ if (frames_to_discard == loglikes_.NumRows()) {
+ loglikes_.Swap(loglikes);
+ loglikes->Resize(0, 0);
+ } else {
+ int32 old_rows_kept = loglikes_.NumRows() - frames_to_discard,
+ new_num_rows = old_rows_kept + loglikes->NumRows();
+ Matrix<BaseFloat> new_loglikes(new_num_rows, loglikes->NumCols());
+ new_loglikes.RowRange(0, old_rows_kept).CopyFromMat(
+ loglikes_.RowRange(frames_to_discard, old_rows_kept));
+ new_loglikes.RowRange(old_rows_kept, loglikes->NumRows()).CopyFromMat(
+ *loglikes);
+ loglikes_.Swap(&new_loglikes);
+ }
+ frame_offset_ += frames_to_discard;
+ stride_ = loglikes_.Stride();
+ raw_data_ = loglikes_.Data() - (frame_offset_ * stride_);
+}
+
+
+
+} // end namespace kaldi.
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/decodable-matrix.h b/runtime/onnxruntime/third_party/kaldi/decoder/decodable-matrix.h
new file mode 100644
index 000000000..94e141d87
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/decodable-matrix.h
@@ -0,0 +1,253 @@
+// decoder/decodable-matrix.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_DECODER_DECODABLE_MATRIX_H_
+#define KALDI_DECODER_DECODABLE_MATRIX_H_
+
+#include <vector>
+
+#include "base/kaldi-common.h"
+#include "itf/decodable-itf.h"
+#include "itf/transition-information.h"
+#include "matrix/kaldi-matrix.h"
+
+namespace kaldi {
+
+
+class DecodableMatrixScaledMapped: public DecodableInterface {
+ public:
+ // This constructor creates an object that will not delete "likes" when done.
+ DecodableMatrixScaledMapped(const TransitionInformation &tm,
+ const Matrix<BaseFloat> &likes,
+ BaseFloat scale): trans_model_(tm), likes_(&likes),
+ tid_to_pdf_(trans_model_.TransitionIdToPdfArray()),
+ scale_(scale), delete_likes_(false) {
+ if (likes.NumCols() != tm.NumPdfs())
+ KALDI_ERR << "DecodableMatrixScaledMapped: mismatch, matrix has "
+ << likes.NumCols() << " cols but transition-model has "
+ << tm.NumPdfs() << " pdf-ids.";
+ }
+
+ // This constructor creates an object that will delete "likes"
+ // when done.
+ DecodableMatrixScaledMapped(const TransitionInformation &tm,
+ BaseFloat scale,
+ const Matrix<BaseFloat> *likes):
+ trans_model_(tm), likes_(likes),
+ tid_to_pdf_(trans_model_.TransitionIdToPdfArray()),
+ scale_(scale), delete_likes_(true) {
+ if (likes->NumCols() != tm.NumPdfs())
+ KALDI_ERR << "DecodableMatrixScaledMapped: mismatch, matrix has "
+ << likes->NumCols() << " cols but transition-model has "
+ << tm.NumPdfs() << " pdf-ids.";
+ }
+
+ virtual int32 NumFramesReady() const { return likes_->NumRows(); }
+
+ virtual bool IsLastFrame(int32 frame) const {
+ KALDI_ASSERT(frame < NumFramesReady());
+ return (frame == NumFramesReady() - 1);
+ }
+
+ // Note, frames are numbered from zero.
+ virtual BaseFloat LogLikelihood(int32 frame, int32 tid) {
+ KALDI_PARANOID_ASSERT(tid >= 1 && tid < tid_to_pdf_.size());
+ return scale_ * (*likes_)(frame, tid_to_pdf_[tid]);
+ }
+
+ // Indices are one-based! This is for compatibility with OpenFst.
+ virtual int32 NumIndices() const { return trans_model_.NumTransitionIds(); }
+
+ virtual ~DecodableMatrixScaledMapped() {
+ if (delete_likes_) delete likes_;
+ }
+ private:
+ const TransitionInformation &trans_model_; // for tid to pdf mapping
+ const Matrix<BaseFloat> *likes_;
+ const std::vector<int32> &tid_to_pdf_;
+ BaseFloat scale_;
+ bool delete_likes_;
+ KALDI_DISALLOW_COPY_AND_ASSIGN(DecodableMatrixScaledMapped);
+};
+
+/**
+ This is like DecodableMatrixScaledMapped, but it doesn't support an acoustic
+ scale, and it does support a frame offset, whereby you can state that the
+ first row of 'likes' is actually the n'th row of the matrix of available
+ log-likelihoods. It's useful if the neural net output comes in chunks for
+ different frame ranges.
+
+ Note: DecodableMatrixMappedOffset solves the same problem in a slightly
+ different way, where you use the same decodable object. This one, unlike
+ DecodableMatrixMappedOffset, is compatible with when the loglikes are in a
+ SubMatrix.
+ */
+class DecodableMatrixMapped: public DecodableInterface {
+ public:
+ // This constructor creates an object that will not delete "likes" when done.
+ // the frame_offset is the frame the row 0 of 'likes' corresponds to, would be
+ // greater than one if this is not the first chunk of likelihoods.
+ DecodableMatrixMapped(const TransitionInformation &tm,
+ const MatrixBase<BaseFloat> &likes,
+ int32 frame_offset = 0);
+
+ // This constructor creates an object that will delete "likes"
+ // when done.
+ DecodableMatrixMapped(const TransitionInformation &tm,
+ const Matrix<BaseFloat> *likes,
+ int32 frame_offset = 0);
+
+ virtual int32 NumFramesReady() const;
+
+ virtual bool IsLastFrame(int32 frame) const;
+
+ virtual BaseFloat LogLikelihood(int32 frame, int32 tid);
+
+ // Note: these indices are 1-based.
+ virtual int32 NumIndices() const;
+
+ virtual ~DecodableMatrixMapped();
+
+ private:
+ const TransitionInformation &trans_model_; // for tid to pdf mapping
+ const std::vector<int32>& tid_to_pdf_;
+ const MatrixBase<BaseFloat> *likes_;
+ const Matrix<BaseFloat> *likes_to_delete_;
+ int32 frame_offset_;
+
+ // raw_data_ and stride_ are a kind of fast look-aside for 'likes_', to be
+ // used when KALDI_PARANOID is false.
+ const BaseFloat *raw_data_;
+ int32 stride_;
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(DecodableMatrixMapped);
+};
+
+
+/**
+ This decodable class returns log-likes stored in a matrix; it supports
+ repeatedly writing to the matrix and setting a time-offset representing the
+ frame-index of the first row of the matrix. It's intended for use in
+ multi-threaded decoding; mutex and semaphores are not included. External
+ code will call SetLoglikes() each time more log-likelihods are available.
+ If you try to access a log-likelihood that's no longer available because
+ the frame index is less than the current offset, it is of course an error.
+
+ See also DecodableMatrixMapped, which supports the same type of thing but
+ with a different interface where you are expected to re-construct the
+ object each time you want to decode.
+*/
+class DecodableMatrixMappedOffset: public DecodableInterface {
+ public:
+ DecodableMatrixMappedOffset(const TransitionInformation &tm):
+ trans_model_(tm), tid_to_pdf_(trans_model_.TransitionIdToPdfArray()),
+ frame_offset_(0), input_is_finished_(false) { }
+
+ // this is not part of the generic Decodable interface.
+ int32 FirstAvailableFrame() const { return frame_offset_; }
+
+ // Logically, this function appends 'loglikes' (interpreted as newly available
+ // frames) to the log-likelihoods stored in the class.
+ //
+ // This function is destructive of the input "loglikes" because it may
+ // under some circumstances do a shallow copy using Swap(). This function
+ // appends loglikes to any existing likelihoods you've previously supplied.
+ void AcceptLoglikes(Matrix<BaseFloat> *loglikes,
+ int32 frames_to_discard);
+
+ void InputIsFinished() { input_is_finished_ = true; }
+
+ virtual int32 NumFramesReady() const {
+ return loglikes_.NumRows() + frame_offset_;
+ }
+
+ virtual bool IsLastFrame(int32 frame) const {
+ KALDI_ASSERT(frame < NumFramesReady());
+ return (frame == NumFramesReady() - 1 && input_is_finished_);
+ }
+
+ virtual BaseFloat LogLikelihood(int32 frame, int32 tid) {
+ KALDI_PARANOID_ASSERT(tid >= 1 && tid < tid_to_pdf_.size());
+ int32 pdf_id = tid_to_pdf_[tid];
+#ifdef KALDI_PARANOID
+ return loglikes_(frame - frame_offset_, pdf_id);
+#else
+ // This does no checking, so will be faster.
+ return raw_data_[frame * stride_ + pdf_id];
+#endif
+ }
+
+ virtual int32 NumIndices() const { return trans_model_.NumTransitionIds(); }
+
+ // nothing special to do in destructor.
+ virtual ~DecodableMatrixMappedOffset() { }
+ private:
+ const TransitionInformation &trans_model_; // for tid to pdf mapping
+ const std::vector<int32>& tid_to_pdf_;
+ Matrix<BaseFloat> loglikes_;
+ int32 frame_offset_;
+ bool input_is_finished_;
+
+ // 'raw_data_' and 'stride_' are intended as a fast look-aside which is an
+ // alternative to accessing data_. raw_data_ is a faked version of
+ // data_->Data() as if it started from frame zero rather than frame_offset_.
+ // This simplifies the code of LogLikelihood(), in cases where KALDI_PARANOID
+ // is not defined.
+ BaseFloat *raw_data_;
+ int32 stride_;
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(DecodableMatrixMappedOffset);
+};
+
+
+class DecodableMatrixScaled: public DecodableInterface {
+ public:
+ DecodableMatrixScaled(const Matrix<BaseFloat> &likes,
+ BaseFloat scale):
+ likes_(likes), scale_(scale) { }
+
+ virtual int32 NumFramesReady() const { return likes_.NumRows(); }
+
+ virtual bool IsLastFrame(int32 frame) const {
+ KALDI_ASSERT(frame < NumFramesReady());
+ return (frame == NumFramesReady() - 1);
+ }
+
+ // Note, frames are numbered from zero.
+ virtual BaseFloat LogLikelihood(int32 frame, int32 index) {
+ if (index > likes_.NumCols() || index <= 0 ||
+ frame < 0 || frame >= likes_.NumRows())
+ KALDI_ERR << "Invalid (frame, index - 1) = ("
+ << frame << ", " << index - 1 << ") for matrix of size "
+ << likes_.NumRows() << " x " << likes_.NumCols();
+ return scale_ * likes_(frame, index - 1);
+ }
+
+ // Indices are one-based! This is for compatibility with OpenFst.
+ virtual int32 NumIndices() const { return likes_.NumCols(); }
+
+ private:
+ const Matrix<BaseFloat> &likes_;
+ BaseFloat scale_;
+ KALDI_DISALLOW_COPY_AND_ASSIGN(DecodableMatrixScaled);
+};
+} // namespace kaldi
+
+#endif // KALDI_DECODER_DECODABLE_MATRIX_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/decodable-sum.h b/runtime/onnxruntime/third_party/kaldi/decoder/decodable-sum.h
new file mode 100644
index 000000000..e3ff60a6f
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/decodable-sum.h
@@ -0,0 +1,109 @@
+// decoder/decodable-sum.h
+
+// Copyright 2009-2011 Saarland University; Microsoft Corporation;
+// Lukas Burget, Pawel Swietojanski
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_DECODER_DECODABLE_SUM_H_
+#define KALDI_DECODER_DECODABLE_SUM_H_
+
+#include <vector>
+#include <utility>
+
+#include "base/kaldi-common.h"
+#include "itf/decodable-itf.h"
+
+namespace kaldi {
+
+// The DecodableSum object is a very simple object that just sums
+// scores over a number of Decodable objects. They must all have
+// the same dimensions.
+
+class DecodableSum: public DecodableInterface {
+ public:
+ // Does not take ownership of pointers! They are just
+ // pointers because they are non-const.
+ DecodableSum(DecodableInterface *d1, BaseFloat w1,
+ DecodableInterface *d2, BaseFloat w2) {
+ decodables_.push_back(std::make_pair(d1, w1));
+ decodables_.push_back(std::make_pair(d2, w2));
+ CheckSizes();
+ }
+
+ // Does not take ownership of pointers!
+ DecodableSum(
+ const std::vector<std::pair<DecodableInterface*, BaseFloat> > &decodables) :
+ decodables_(decodables) { CheckSizes(); }
+
+ void CheckSizes() const {
+ KALDI_ASSERT(decodables_.size() >= 1
+ && decodables_[0].first != NULL);
+ for (size_t i = 1; i < decodables_.size(); i++)
+ KALDI_ASSERT(decodables_[i].first != NULL &&
+ decodables_[i].first->NumIndices() ==
+ decodables_[0].first->NumIndices());
+ }
+
+ // Note, frames are numbered from zero. But state_index is numbered
+ // from one (this routine is called by FSTs).
+ virtual BaseFloat LogLikelihood(int32 frame, int32 state_index) {
+ BaseFloat sum = 0.0;
+ // int32 i=1;
+ for (std::vector<std::pair<DecodableInterface*, BaseFloat> >::iterator iter = decodables_.begin();
+ iter != decodables_.end();
+ ++iter) {
+ sum += iter->first->LogLikelihood(frame, state_index) * iter->second;
+ }
+ return sum;
+ }
+
+ virtual int32 NumIndices() const { return decodables_[0].first->NumIndices(); }
+
+ virtual bool IsLastFrame(int32 frame) const {
+ // We require all the decodables have the same #frames. We don't check this though.
+ return decodables_[0].first->IsLastFrame(frame);
+ }
+
+ private:
+ std::vector<std::pair<DecodableInterface*, BaseFloat> > decodables_;
+ KALDI_DISALLOW_COPY_AND_ASSIGN(DecodableSum);
+};
+
+class DecodableSumScaled : public DecodableSum {
+ public:
+ DecodableSumScaled(DecodableInterface *d1, BaseFloat w1,
+ DecodableInterface *d2, BaseFloat w2,
+ BaseFloat scale)
+ : DecodableSum(d1, w1, d2, w2), scale_(scale) {}
+
+ DecodableSumScaled(const std::vector<std::pair<DecodableInterface*, BaseFloat> > &decodables,
+ BaseFloat scale)
+ : DecodableSum(decodables), scale_(scale) {}
+
+ virtual BaseFloat LogLikelihood(int32 frame, int32 state_index) {
+ return scale_ * DecodableSum::LogLikelihood(frame, state_index);
+ }
+
+ private:
+ BaseFloat scale_;
+ KALDI_DISALLOW_COPY_AND_ASSIGN(DecodableSumScaled);
+};
+
+} // namespace kaldi
+
+#endif // KALDI_DECODER_DECODABLE_SUM_H_
+
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/decoder-wrappers.cc b/runtime/onnxruntime/third_party/kaldi/decoder/decoder-wrappers.cc
new file mode 100644
index 000000000..626a69387
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/decoder-wrappers.cc
@@ -0,0 +1,665 @@
+// decoder/decoder-wrappers.cc
+
+// Copyright 2014 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "decoder/decoder-wrappers.h"
+#include "decoder/faster-decoder.h"
+#include "decoder/lattice-faster-decoder.h"
+#include "decoder/grammar-fst.h"
+#include "lat/lattice-functions.h"
+
+namespace kaldi {
+
+
+
+
+
+DecodeUtteranceLatticeFasterClass::DecodeUtteranceLatticeFasterClass(
+ LatticeFasterDecoder *decoder,
+ DecodableInterface *decodable,
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ const std::string &utt,
+ BaseFloat acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignments_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_sum, // on success, adds likelihood to this.
+ int64 *frame_sum, // on success, adds #frames to this.
+ int32 *num_done, // on success (including partial decode), increments this.
+ int32 *num_err, // on failure, increments this.
+ int32 *num_partial): // If partial decode (final-state not reached), increments this.
+ decoder_(decoder), decodable_(decodable), trans_model_(&trans_model),
+ word_syms_(word_syms), utt_(utt), acoustic_scale_(acoustic_scale),
+ determinize_(determinize), allow_partial_(allow_partial),
+ alignments_writer_(alignments_writer),
+ words_writer_(words_writer),
+ compact_lattice_writer_(compact_lattice_writer),
+ lattice_writer_(lattice_writer),
+ like_sum_(like_sum), frame_sum_(frame_sum),
+ num_done_(num_done), num_err_(num_err),
+ num_partial_(num_partial),
+ computed_(false), success_(false), partial_(false),
+ clat_(NULL), lat_(NULL) { }
+
+
+void DecodeUtteranceLatticeFasterClass::operator () () {
+ // Decoding and lattice determinization happens here.
+ computed_ = true; // Just means this function was called-- a check on the
+ // calling code.
+ success_ = true;
+ using fst::VectorFst;
+ if (!decoder_->Decode(decodable_)) {
+ KALDI_WARN << "Failed to decode utterance with id " << utt_;
+ success_ = false;
+ }
+ if (!decoder_->ReachedFinal()) {
+ if (allow_partial_) {
+ KALDI_WARN << "Outputting partial output for utterance " << utt_
+ << " since no final-state reached\n";
+ partial_ = true;
+ } else {
+ KALDI_WARN << "Not producing output for utterance " << utt_
+ << " since no final-state reached and "
+ << "--allow-partial=false.\n";
+ success_ = false;
+ }
+ }
+ if (!success_) return;
+
+ // Get lattice, and do determinization if requested.
+ lat_ = new Lattice;
+ decoder_->GetRawLattice(lat_);
+ if (lat_->NumStates() == 0)
+ KALDI_ERR << "Unexpected problem getting lattice for utterance " << utt_;
+ fst::Connect(lat_);
+ if (determinize_) {
+ clat_ = new CompactLattice;
+ if (!DeterminizeLatticePhonePrunedWrapper(
+ *trans_model_,
+ lat_,
+ decoder_->GetOptions().lattice_beam,
+ clat_,
+ decoder_->GetOptions().det_opts))
+ KALDI_WARN << "Determinization finished earlier than the beam for "
+ << "utterance " << utt_;
+ delete lat_;
+ lat_ = NULL;
+ // We'll write the lattice without acoustic scaling.
+ if (acoustic_scale_ != 0.0)
+ fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale_), clat_);
+ } else {
+ // We'll write the lattice without acoustic scaling.
+ if (acoustic_scale_ != 0.0)
+ fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale_), lat_);
+ }
+}
+
+DecodeUtteranceLatticeFasterClass::~DecodeUtteranceLatticeFasterClass() {
+ if (!computed_)
+ KALDI_ERR << "Destructor called without operator (), error in calling code.";
+
+ if (!success_) {
+ if (num_err_ != NULL) (*num_err_)++;
+ } else { // successful decode.
+ // Getting the one-best output is lightweight enough that we can do it in
+ // the destructor (easier than adding more variables to the class, and
+ // will rarely slow down the main thread.)
+ double likelihood;
+ LatticeWeight weight;
+ int32 num_frames;
+ { // First do some stuff with word-level traceback...
+ // This is basically for diagnostics.
+ fst::VectorFst<LatticeArc> decoded;
+ decoder_->GetBestPath(&decoded);
+ if (decoded.NumStates() == 0) {
+ // Shouldn't really reach this point as already checked success.
+ KALDI_ERR << "Failed to get traceback for utterance " << utt_;
+ }
+ std::vector<int32> alignment;
+ std::vector<int32> words;
+ GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
+ num_frames = alignment.size();
+ if (words_writer_->IsOpen())
+ words_writer_->Write(utt_, words);
+ if (alignments_writer_->IsOpen())
+ alignments_writer_->Write(utt_, alignment);
+ if (word_syms_ != NULL) {
+ std::cerr << utt_ << ' ';
+ for (size_t i = 0; i < words.size(); i++) {
+ std::string s = word_syms_->Find(words[i]);
+ if (s == "")
+ KALDI_ERR << "Word-id " << words[i] << " not in symbol table.";
+ std::cerr << s << ' ';
+ }
+ std::cerr << '\n';
+ }
+ likelihood = -(weight.Value1() + weight.Value2());
+ }
+
+ // Ouptut the lattices.
+ if (determinize_) { // CompactLattice output.
+ KALDI_ASSERT(compact_lattice_writer_ != NULL && clat_ != NULL);
+ if (clat_->NumStates() == 0) {
+ KALDI_WARN << "Empty lattice for utterance " << utt_;
+ } else {
+ compact_lattice_writer_->Write(utt_, *clat_);
+ }
+ delete clat_;
+ clat_ = NULL;
+ } else {
+ KALDI_ASSERT(lattice_writer_ != NULL && lat_ != NULL);
+ if (lat_->NumStates() == 0) {
+ KALDI_WARN << "Empty lattice for utterance " << utt_;
+ } else {
+ lattice_writer_->Write(utt_, *lat_);
+ }
+ delete lat_;
+ lat_ = NULL;
+ }
+
+ // Print out logging information.
+ KALDI_LOG << "Log-like per frame for utterance " << utt_ << " is "
+ << (likelihood / num_frames) << " over "
+ << num_frames << " frames.";
+ KALDI_VLOG(2) << "Cost for utterance " << utt_ << " is "
+ << weight.Value1() << " + " << weight.Value2();
+
+ // Now output the various diagnostic variables.
+ if (like_sum_ != NULL) *like_sum_ += likelihood;
+ if (frame_sum_ != NULL) *frame_sum_ += num_frames;
+ if (num_done_ != NULL) (*num_done_)++;
+ if (partial_ && num_partial_ != NULL) (*num_partial_)++;
+ }
+ // We were given ownership of these two objects that were passed in in
+ // the initializer.
+ delete decoder_;
+ delete decodable_;
+}
+
+template <typename FST>
+bool DecodeUtteranceLatticeIncremental(
+ LatticeIncrementalDecoderTpl<FST> &decoder, // not const but is really an input.
+ DecodableInterface &decodable, // not const but is really an input.
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ std::string utt,
+ double acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignment_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_ptr) { // puts utterance's like in like_ptr on success.
+ using fst::VectorFst;
+ if (!decoder.Decode(&decodable)) {
+ KALDI_WARN << "Failed to decode utterance with id " << utt;
+ return false;
+ }
+ if (!decoder.ReachedFinal()) {
+ if (allow_partial) {
+ KALDI_WARN << "Outputting partial output for utterance " << utt
+ << " since no final-state reached\n";
+ } else {
+ KALDI_WARN << "Not producing output for utterance " << utt
+ << " since no final-state reached and "
+ << "--allow-partial=false.\n";
+ return false;
+ }
+ }
+
+ // Get lattice
+ CompactLattice clat = decoder.GetLattice(decoder.NumFramesDecoded(), true);
+ if (clat.NumStates() == 0)
+ KALDI_ERR << "Unexpected problem getting lattice for utterance " << utt;
+
+ double likelihood;
+ LatticeWeight weight;
+ int32 num_frames;
+ { // First do some stuff with word-level traceback...
+ CompactLattice decoded_clat;
+ CompactLatticeShortestPath(clat, &decoded_clat);
+ Lattice decoded;
+ fst::ConvertLattice(decoded_clat, &decoded);
+
+ if (decoded.Start() == fst::kNoStateId)
+ // Shouldn't really reach this point as already checked success.
+ KALDI_ERR << "Failed to get traceback for utterance " << utt;
+
+ std::vector<int32> alignment;
+ std::vector<int32> words;
+ GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
+ num_frames = alignment.size();
+ KALDI_ASSERT(num_frames == decoder.NumFramesDecoded());
+ if (words_writer->IsOpen())
+ words_writer->Write(utt, words);
+ if (alignment_writer->IsOpen())
+ alignment_writer->Write(utt, alignment);
+ if (word_syms != NULL) {
+ std::cerr << utt << ' ';
+ for (size_t i = 0; i < words.size(); i++) {
+ std::string s = word_syms->Find(words[i]);
+ if (s == "")
+ KALDI_ERR << "Word-id " << words[i] << " not in symbol table.";
+ std::cerr << s << ' ';
+ }
+ std::cerr << '\n';
+ }
+ likelihood = -(weight.Value1() + weight.Value2());
+ }
+
+ // We'll write the lattice without acoustic scaling.
+ if (acoustic_scale != 0.0)
+ fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &clat);
+ Connect(&clat);
+ compact_lattice_writer->Write(utt, clat);
+ KALDI_LOG << "Log-like per frame for utterance " << utt << " is "
+ << (likelihood / num_frames) << " over "
+ << num_frames << " frames.";
+ KALDI_VLOG(2) << "Cost for utterance " << utt << " is "
+ << weight.Value1() << " + " << weight.Value2();
+ *like_ptr = likelihood;
+ return true;
+}
+
+
+// Takes care of output. Returns true on success.
+template <typename FST>
+bool DecodeUtteranceLatticeFaster(
+ LatticeFasterDecoderTpl<FST> &decoder, // not const but is really an input.
+ DecodableInterface &decodable, // not const but is really an input.
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ std::string utt,
+ double acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignment_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_ptr) { // puts utterance's like in like_ptr on success.
+ using fst::VectorFst;
+
+ if (!decoder.Decode(&decodable)) {
+ KALDI_WARN << "Failed to decode utterance with id " << utt;
+ return false;
+ }
+ if (!decoder.ReachedFinal()) {
+ if (allow_partial) {
+ KALDI_WARN << "Outputting partial output for utterance " << utt
+ << " since no final-state reached\n";
+ } else {
+ KALDI_WARN << "Not producing output for utterance " << utt
+ << " since no final-state reached and "
+ << "--allow-partial=false.\n";
+ return false;
+ }
+ }
+
+ double likelihood;
+ LatticeWeight weight;
+ int32 num_frames;
+ { // First do some stuff with word-level traceback...
+ VectorFst<LatticeArc> decoded;
+ if (!decoder.GetBestPath(&decoded))
+ // Shouldn't really reach this point as already checked success.
+ KALDI_ERR << "Failed to get traceback for utterance " << utt;
+
+ std::vector<int32> alignment;
+ std::vector<int32> words;
+ GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
+ num_frames = alignment.size();
+ if (words_writer->IsOpen())
+ words_writer->Write(utt, words);
+ if (alignment_writer->IsOpen())
+ alignment_writer->Write(utt, alignment);
+ if (word_syms != NULL) {
+ std::cerr << utt << ' ';
+ for (size_t i = 0; i < words.size(); i++) {
+ std::string s = word_syms->Find(words[i]);
+ if (s == "")
+ KALDI_ERR << "Word-id " << words[i] << " not in symbol table.";
+ std::cerr << s << ' ';
+ }
+ std::cerr << '\n';
+ }
+ likelihood = -(weight.Value1() + weight.Value2());
+ }
+
+ // Get lattice, and do determinization if requested.
+ Lattice lat;
+ decoder.GetRawLattice(&lat);
+ if (lat.NumStates() == 0)
+ KALDI_ERR << "Unexpected problem getting lattice for utterance " << utt;
+ fst::Connect(&lat);
+ if (determinize) {
+ CompactLattice clat;
+ if (!DeterminizeLatticePhonePrunedWrapper(
+ trans_model,
+ &lat,
+ decoder.GetOptions().lattice_beam,
+ &clat,
+ decoder.GetOptions().det_opts))
+ KALDI_WARN << "Determinization finished earlier than the beam for "
+ << "utterance " << utt;
+ // We'll write the lattice without acoustic scaling.
+ if (acoustic_scale != 0.0)
+ fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &clat);
+ compact_lattice_writer->Write(utt, clat);
+ } else {
+ // We'll write the lattice without acoustic scaling.
+ if (acoustic_scale != 0.0)
+ fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &lat);
+ lattice_writer->Write(utt, lat);
+ }
+ KALDI_LOG << "Log-like per frame for utterance " << utt << " is "
+ << (likelihood / num_frames) << " over "
+ << num_frames << " frames.";
+ KALDI_VLOG(2) << "Cost for utterance " << utt << " is "
+ << weight.Value1() << " + " << weight.Value2();
+ *like_ptr = likelihood;
+ return true;
+}
+
+// Instantiate the template above for the two required FST types.
+template bool DecodeUtteranceLatticeIncremental(
+ LatticeIncrementalDecoderTpl<fst::Fst<fst::StdArc> > &decoder,
+ DecodableInterface &decodable,
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ std::string utt,
+ double acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignment_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_ptr);
+
+template bool DecodeUtteranceLatticeIncremental(
+ LatticeIncrementalDecoderTpl<fst::ConstGrammarFst > &decoder,
+ DecodableInterface &decodable,
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ std::string utt,
+ double acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignment_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_ptr);
+
+template bool DecodeUtteranceLatticeFaster(
+ LatticeFasterDecoderTpl<fst::Fst<fst::StdArc> > &decoder,
+ DecodableInterface &decodable,
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ std::string utt,
+ double acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignment_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_ptr);
+
+template bool DecodeUtteranceLatticeFaster(
+ LatticeFasterDecoderTpl<fst::ConstGrammarFst > &decoder,
+ DecodableInterface &decodable,
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ std::string utt,
+ double acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignment_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_ptr);
+
+
+// Takes care of output. Returns true on success.
+bool DecodeUtteranceLatticeSimple(
+ LatticeSimpleDecoder &decoder, // not const but is really an input.
+ DecodableInterface &decodable, // not const but is really an input.
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ std::string utt,
+ double acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignment_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_ptr) { // puts utterance's like in like_ptr on success.
+ using fst::VectorFst;
+
+ if (!decoder.Decode(&decodable)) {
+ KALDI_WARN << "Failed to decode utterance with id " << utt;
+ return false;
+ }
+ if (!decoder.ReachedFinal()) {
+ if (allow_partial) {
+ KALDI_WARN << "Outputting partial output for utterance " << utt
+ << " since no final-state reached\n";
+ } else {
+ KALDI_WARN << "Not producing output for utterance " << utt
+ << " since no final-state reached and "
+ << "--allow-partial=false.\n";
+ return false;
+ }
+ }
+
+ double likelihood;
+ LatticeWeight weight = LatticeWeight::Zero();
+ int32 num_frames;
+ { // First do some stuff with word-level traceback...
+ VectorFst<LatticeArc> decoded;
+ if (!decoder.GetBestPath(&decoded))
+ // Shouldn't really reach this point as already checked success.
+ KALDI_ERR << "Failed to get traceback for utterance " << utt;
+
+ std::vector<int32> alignment;
+ std::vector<int32> words;
+ GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
+ num_frames = alignment.size();
+ if (words_writer->IsOpen())
+ words_writer->Write(utt, words);
+ if (alignment_writer->IsOpen())
+ alignment_writer->Write(utt, alignment);
+ if (word_syms != NULL) {
+ std::cerr << utt << ' ';
+ for (size_t i = 0; i < words.size(); i++) {
+ std::string s = word_syms->Find(words[i]);
+ if (s == "")
+ KALDI_ERR << "Word-id " << words[i] << " not in symbol table.";
+ std::cerr << s << ' ';
+ }
+ std::cerr << '\n';
+ }
+ likelihood = -(weight.Value1() + weight.Value2());
+ }
+
+ // Get lattice, and do determinization if requested.
+ Lattice lat;
+ if (!decoder.GetRawLattice(&lat))
+ KALDI_ERR << "Unexpected problem getting lattice for utterance " << utt;
+ fst::Connect(&lat);
+ if (determinize) {
+ CompactLattice clat;
+ if (!DeterminizeLatticePhonePrunedWrapper(
+ trans_model,
+ &lat,
+ decoder.GetOptions().lattice_beam,
+ &clat,
+ decoder.GetOptions().det_opts))
+ KALDI_WARN << "Determinization finished earlier than the beam for "
+ << "utterance " << utt;
+ // We'll write the lattice without acoustic scaling.
+ if (acoustic_scale != 0.0)
+ fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &clat);
+ compact_lattice_writer->Write(utt, clat);
+ } else {
+ // We'll write the lattice without acoustic scaling.
+ if (acoustic_scale != 0.0)
+ fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &lat);
+ lattice_writer->Write(utt, lat);
+ }
+ KALDI_LOG << "Log-like per frame for utterance " << utt << " is "
+ << (likelihood / num_frames) << " over "
+ << num_frames << " frames.";
+ KALDI_VLOG(2) << "Cost for utterance " << utt << " is "
+ << weight.Value1() << " + " << weight.Value2();
+ *like_ptr = likelihood;
+ return true;
+}
+
+
+// see comment in header.
+void ModifyGraphForCarefulAlignment(
+ fst::VectorFst<fst::StdArc> *fst) {
+ typedef fst::StdArc Arc;
+ typedef Arc::StateId StateId;
+ typedef Arc::Label Label;
+ typedef Arc::Weight Weight;
+ StateId num_states = fst->NumStates();
+ if (num_states == 0) {
+ KALDI_WARN << "Empty FST input.";
+ return;
+ }
+ Weight zero = Weight::Zero();
+ // fst_rhs will be the right hand side of the Concat operation.
+ fst::VectorFst<fst::StdArc> fst_rhs(*fst);
+ // first remove the final-probs from fst_rhs.
+ for (StateId state = 0; state < num_states; state++)
+ fst_rhs.SetFinal(state, zero);
+ StateId pre_initial = fst_rhs.AddState();
+ Arc to_initial(0, 0, Weight::One(), fst_rhs.Start());
+ fst_rhs.AddArc(pre_initial, to_initial);
+ fst_rhs.SetStart(pre_initial);
+ // make the pre_initial state final with probability one;
+ // this is equivalent to keeping the final-probs of the first
+ // FST when we do concat (otherwise they would get deleted).
+ fst_rhs.SetFinal(pre_initial, Weight::One());
+ fst::VectorFst<fst::StdArc> fst_concat;
+ fst::Concat(fst, fst_rhs);
+}
+
+
+void AlignUtteranceWrapper(
+ const AlignConfig &config,
+ const std::string &utt,
+ BaseFloat acoustic_scale, // affects scores written to scores_writer, if
+ // present
+ fst::VectorFst<fst::StdArc> *fst, // non-const in case config.careful ==
+ // true.
+ DecodableInterface *decodable, // not const but is really an input.
+ Int32VectorWriter *alignment_writer,
+ BaseFloatWriter *scores_writer,
+ int32 *num_done,
+ int32 *num_error,
+ int32 *num_retried,
+ double *tot_like,
+ int64 *frame_count,
+ BaseFloatVectorWriter *per_frame_acwt_writer) {
+
+ if ((config.retry_beam != 0 && config.retry_beam <= config.beam) ||
+ config.beam <= 0.0) {
+ KALDI_ERR << "Beams do not make sense: beam " << config.beam
+ << ", retry-beam " << config.retry_beam;
+ }
+
+ if (fst->Start() == fst::kNoStateId) {
+ KALDI_WARN << "Empty decoding graph for " << utt;
+ if (num_error != NULL) (*num_error)++;
+ return;
+ }
+
+ if (config.careful)
+ ModifyGraphForCarefulAlignment(fst);
+
+ FasterDecoderOptions decode_opts;
+ decode_opts.beam = config.beam;
+
+ FasterDecoder decoder(*fst, decode_opts);
+ decoder.Decode(decodable);
+
+ bool ans = decoder.ReachedFinal(); // consider only final states.
+
+ if (!ans && config.retry_beam != 0.0) {
+ if (num_retried != NULL) (*num_retried)++;
+ KALDI_WARN << "Retrying utterance " << utt << " with beam "
+ << config.retry_beam;
+ decode_opts.beam = config.retry_beam;
+ decoder.SetOptions(decode_opts);
+ decoder.Decode(decodable);
+ ans = decoder.ReachedFinal();
+ }
+
+ if (!ans) { // Still did not reach final state.
+ KALDI_WARN << "Did not successfully decode file " << utt << ", len = "
+ << decodable->NumFramesReady();
+ if (num_error != NULL) (*num_error)++;
+ return;
+ }
+
+ fst::VectorFst<LatticeArc> decoded; // linear FST.
+ decoder.GetBestPath(&decoded);
+ if (decoded.NumStates() == 0) {
+ KALDI_WARN << "Error getting best path from decoder (likely a bug)";
+ if (num_error != NULL) (*num_error)++;
+ return;
+ }
+
+ std::vector<int32> alignment;
+ std::vector<int32> words;
+ LatticeWeight weight;
+
+ GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
+ BaseFloat like = -(weight.Value1()+weight.Value2()) / acoustic_scale;
+
+ if (num_done != NULL) (*num_done)++;
+ if (tot_like != NULL) (*tot_like) += like;
+ if (frame_count != NULL) (*frame_count) += decodable->NumFramesReady();
+
+ if (alignment_writer != NULL && alignment_writer->IsOpen())
+ alignment_writer->Write(utt, alignment);
+
+ if (scores_writer != NULL && scores_writer->IsOpen())
+ scores_writer->Write(utt, -(weight.Value1()+weight.Value2()));
+
+ Vector<BaseFloat> per_frame_loglikes;
+ if (per_frame_acwt_writer != NULL && per_frame_acwt_writer->IsOpen()) {
+ GetPerFrameAcousticCosts(decoded, &per_frame_loglikes);
+ per_frame_loglikes.Scale(-1 / acoustic_scale);
+ per_frame_acwt_writer->Write(utt, per_frame_loglikes);
+ }
+}
+
+} // end namespace kaldi.
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/decoder-wrappers.h b/runtime/onnxruntime/third_party/kaldi/decoder/decoder-wrappers.h
new file mode 100644
index 000000000..edea6cf9a
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/decoder-wrappers.h
@@ -0,0 +1,221 @@
+// decoder/decoder-wrappers.h
+
+// Copyright 2014 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_DECODER_DECODER_WRAPPERS_H_
+#define KALDI_DECODER_DECODER_WRAPPERS_H_
+
+#include "itf/options-itf.h"
+#include "decoder/lattice-faster-decoder.h"
+#include "decoder/lattice-incremental-decoder.h"
+#include "decoder/lattice-simple-decoder.h"
+
+// This header contains declarations from various convenience functions that are called
+// from binary-level programs such as gmm-decode-faster.cc, gmm-align-compiled.cc, and
+// so on.
+
+namespace kaldi {
+
+
+struct AlignConfig {
+ BaseFloat beam;
+ BaseFloat retry_beam;
+ bool careful;
+
+ AlignConfig(): beam(200.0), retry_beam(0.0), careful(false) { }
+
+ void Register(OptionsItf *opts) {
+ opts->Register("beam", &beam, "Decoding beam used in alignment");
+ opts->Register("retry-beam", &retry_beam,
+ "Decoding beam for second try at alignment");
+ opts->Register("careful", &careful,
+ "If true, do 'careful' alignment, which is better at detecting "
+ "alignment failure (involves loop to start of decoding graph).");
+ }
+};
+
+
+/// AlignUtteranceWapper is a wrapper for alignment code used in training, that
+/// is called from many different binaries, e.g. gmm-align, gmm-align-compiled,
+/// sgmm-align, etc. The writers for alignments and words will only be written
+/// to if they are open. The num_done, num_error, num_retried, tot_like and
+/// frame_count pointers will (if non-NULL) be incremented or added to, not set,
+/// by this function.
+void AlignUtteranceWrapper(
+ const AlignConfig &config,
+ const std::string &utt,
+ BaseFloat acoustic_scale, // affects scores written to scores_writer, if
+ // present
+ fst::VectorFst<fst::StdArc> *fst, // non-const in case config.careful ==
+ // true, we add loop.
+ DecodableInterface *decodable, // not const but is really an input.
+ Int32VectorWriter *alignment_writer,
+ BaseFloatWriter *scores_writer,
+ int32 *num_done,
+ int32 *num_error,
+ int32 *num_retried,
+ double *tot_like,
+ int64 *frame_count,
+ BaseFloatVectorWriter *per_frame_acwt_writer = NULL);
+
+
+
+/// This function modifies the decoding graph for what we call "careful
+/// alignment". The problem we are trying to solve is that if the decoding eats
+/// up the words in the graph too fast, it can get stuck at the end, and produce
+/// what looks like a valid alignment even though there was really a failure.
+/// So what we want to do is to introduce, after the final-states of the graph,
+/// a "blind alley" with no final-probs reachable, where the decoding can go to
+/// get lost. Our basic idea is to append the decoding-graph to itself using
+/// the fst Concat operation; but in order that there should be final-probs at the end of
+/// the first but not the second FST, we modify the right-hand argument to the
+/// Concat operation so that it has none of the original final-probs, and add
+/// a "pre-initial" state that is final.
+void ModifyGraphForCarefulAlignment(
+ fst::VectorFst<fst::StdArc> *fst);
+
+/// TODO
+template <typename FST>
+bool DecodeUtteranceLatticeIncremental(
+ LatticeIncrementalDecoderTpl<FST> &decoder, // not const but is really an input.
+ DecodableInterface &decodable, // not const but is really an input.
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ std::string utt,
+ double acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignments_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_ptr); // puts utterance's likelihood in like_ptr on success.
+
+
+/// This function DecodeUtteranceLatticeFaster is used in several decoders, and
+/// we have moved it here. Note: this is really "binary-level" code as it
+/// involves table readers and writers; we've just put it here as there is no
+/// other obvious place to put it. If determinize == false, it writes to
+/// lattice_writer, else to compact_lattice_writer. The writers for
+/// alignments and words will only be written to if they are open.
+///
+/// Caution: this will only link correctly if FST is either fst::Fst<fst::StdArc>,
+/// or fst::GrammarFst, as the template function is defined in the .cc file and
+/// only instantiated for those two types.
+template <typename FST>
+bool DecodeUtteranceLatticeFaster(
+ LatticeFasterDecoderTpl<FST> &decoder, // not const but is really an input.
+ DecodableInterface &decodable, // not const but is really an input.
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ std::string utt,
+ double acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignments_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_ptr); // puts utterance's likelihood in like_ptr on success.
+
+
+/// This class basically does the same job as the function
+/// DecodeUtteranceLatticeFaster, but in a way that allows us
+/// to build a multi-threaded command line program more easily.
+/// The main computation takes place in operator (), and the output
+/// happens in the destructor.
+class DecodeUtteranceLatticeFasterClass {
+ public:
+ // Initializer sets various variables.
+ // NOTE: we "take ownership" of "decoder" and "decodable". These
+ // are deleted by the destructor. On error, "num_err" is incremented.
+ DecodeUtteranceLatticeFasterClass(
+ LatticeFasterDecoder *decoder,
+ DecodableInterface *decodable,
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ const std::string &utt,
+ BaseFloat acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignments_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_sum, // on success, adds likelihood to this.
+ int64 *frame_sum, // on success, adds #frames to this.
+ int32 *num_done, // on success (including partial decode), increments this.
+ int32 *num_err, // on failure, increments this.
+ int32 *num_partial); // If partial decode (final-state not reached), increments this.
+ void operator () (); // The decoding happens here.
+ ~DecodeUtteranceLatticeFasterClass(); // Output happens here.
+ private:
+ // The following variables correspond to inputs:
+ LatticeFasterDecoder *decoder_;
+ DecodableInterface *decodable_;
+ const TransitionInformation *trans_model_;
+ const fst::SymbolTable *word_syms_;
+ std::string utt_;
+ BaseFloat acoustic_scale_;
+ bool determinize_;
+ bool allow_partial_;
+ Int32VectorWriter *alignments_writer_;
+ Int32VectorWriter *words_writer_;
+ CompactLatticeWriter *compact_lattice_writer_;
+ LatticeWriter *lattice_writer_;
+ double *like_sum_;
+ int64 *frame_sum_;
+ int32 *num_done_;
+ int32 *num_err_;
+ int32 *num_partial_;
+
+ // The following variables are stored by the computation.
+ bool computed_; // operator () was called.
+ bool success_; // decoding succeeded (possibly partial)
+ bool partial_; // decoding was partial.
+ CompactLattice *clat_; // Stored output, if determinize_ == true.
+ Lattice *lat_; // Stored output, if determinize_ == false.
+};
+
+// This function DecodeUtteranceLatticeSimple is used in several decoders, and
+// we have moved it here. Note: this is really "binary-level" code as it
+// involves table readers and writers; we've just put it here as there is no
+// other obvious place to put it. If determinize == false, it writes to
+// lattice_writer, else to compact_lattice_writer. The writers for
+// alignments and words will only be written to if they are open.
+bool DecodeUtteranceLatticeSimple(
+ LatticeSimpleDecoder &decoder, // not const but is really an input.
+ DecodableInterface &decodable, // not const but is really an input.
+ const TransitionInformation &trans_model,
+ const fst::SymbolTable *word_syms,
+ std::string utt,
+ double acoustic_scale,
+ bool determinize,
+ bool allow_partial,
+ Int32VectorWriter *alignments_writer,
+ Int32VectorWriter *words_writer,
+ CompactLatticeWriter *compact_lattice_writer,
+ LatticeWriter *lattice_writer,
+ double *like_ptr); // puts utterance's likelihood in like_ptr on success.
+
+
+
+} // end namespace kaldi.
+
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/faster-decoder.cc b/runtime/onnxruntime/third_party/kaldi/decoder/faster-decoder.cc
new file mode 100644
index 000000000..9e8775875
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/faster-decoder.cc
@@ -0,0 +1,351 @@
+// decoder/faster-decoder.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2012-2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "decoder/faster-decoder.h"
+
+namespace kaldi {
+
+
+FasterDecoder::FasterDecoder(const fst::Fst<fst::StdArc> &fst,
+ const FasterDecoderOptions &opts):
+ fst_(fst), config_(opts), num_frames_decoded_(-1) {
+ KALDI_ASSERT(config_.hash_ratio >= 1.0); // less doesn't make much sense.
+ KALDI_ASSERT(config_.max_active > 1);
+ KALDI_ASSERT(config_.min_active >= 0 && config_.min_active < config_.max_active);
+ toks_.SetSize(1000); // just so on the first frame we do something reasonable.
+}
+
+
+void FasterDecoder::InitDecoding() {
+ // clean up from last time:
+ ClearToks(toks_.Clear());
+ StateId start_state = fst_.Start();
+ KALDI_ASSERT(start_state != fst::kNoStateId);
+ Arc dummy_arc(0, 0, Weight::One(), start_state);
+ toks_.Insert(start_state, new Token(dummy_arc, NULL));
+ ProcessNonemitting(std::numeric_limits<float>::max());
+ num_frames_decoded_ = 0;
+}
+
+
+void FasterDecoder::Decode(DecodableInterface *decodable) {
+ InitDecoding();
+ AdvanceDecoding(decodable);
+}
+
+void FasterDecoder::AdvanceDecoding(DecodableInterface *decodable,
+ int32 max_num_frames) {
+ KALDI_ASSERT(num_frames_decoded_ >= 0 &&
+ "You must call InitDecoding() before AdvanceDecoding()");
+ int32 num_frames_ready = decodable->NumFramesReady();
+ // num_frames_ready must be >= num_frames_decoded, or else
+ // the number of frames ready must have decreased (which doesn't
+ // make sense) or the decodable object changed between calls
+ // (which isn't allowed).
+ KALDI_ASSERT(num_frames_ready >= num_frames_decoded_);
+ int32 target_frames_decoded = num_frames_ready;
+ if (max_num_frames >= 0)
+ target_frames_decoded = std::min(target_frames_decoded,
+ num_frames_decoded_ + max_num_frames);
+ while (num_frames_decoded_ < target_frames_decoded) {
+ // note: ProcessEmitting() increments num_frames_decoded_
+ double weight_cutoff = ProcessEmitting(decodable);
+ ProcessNonemitting(weight_cutoff);
+ }
+}
+
+
+bool FasterDecoder::ReachedFinal() const {
+ for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail) {
+ if (e->val->cost_ != std::numeric_limits<double>::infinity() &&
+ fst_.Final(e->key) != Weight::Zero())
+ return true;
+ }
+ return false;
+}
+
+bool FasterDecoder::GetBestPath(fst::MutableFst<LatticeArc> *fst_out,
+ bool use_final_probs) {
+ // GetBestPath gets the decoding output. If "use_final_probs" is true
+ // AND we reached a final state, it limits itself to final states;
+ // otherwise it gets the most likely token not taking into
+ // account final-probs. fst_out will be empty (Start() == kNoStateId) if
+ // nothing was available. It returns true if it got output (thus, fst_out
+ // will be nonempty).
+ fst_out->DeleteStates();
+ Token *best_tok = NULL;
+ bool is_final = ReachedFinal();
+ if (!is_final) {
+ for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail)
+ if (best_tok == NULL || *best_tok < *(e->val) )
+ best_tok = e->val;
+ } else {
+ double infinity = std::numeric_limits<double>::infinity(),
+ best_cost = infinity;
+ for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail) {
+ double this_cost = e->val->cost_ + fst_.Final(e->key).Value();
+ if (this_cost < best_cost && this_cost != infinity) {
+ best_cost = this_cost;
+ best_tok = e->val;
+ }
+ }
+ }
+ if (best_tok == NULL) return false; // No output.
+
+ std::vector<LatticeArc> arcs_reverse; // arcs in reverse order.
+
+ for (Token *tok = best_tok; tok != NULL; tok = tok->prev_) {
+ BaseFloat tot_cost = tok->cost_ -
+ (tok->prev_ ? tok->prev_->cost_ : 0.0),
+ graph_cost = tok->arc_.weight.Value(),
+ ac_cost = tot_cost - graph_cost;
+ LatticeArc l_arc(tok->arc_.ilabel,
+ tok->arc_.olabel,
+ LatticeWeight(graph_cost, ac_cost),
+ tok->arc_.nextstate);
+ arcs_reverse.push_back(l_arc);
+ }
+ KALDI_ASSERT(arcs_reverse.back().nextstate == fst_.Start());
+ arcs_reverse.pop_back(); // that was a "fake" token... gives no info.
+
+ StateId cur_state = fst_out->AddState();
+ fst_out->SetStart(cur_state);
+ for (ssize_t i = static_cast<ssize_t>(arcs_reverse.size())-1; i >= 0; i--) {
+ LatticeArc arc = arcs_reverse[i];
+ arc.nextstate = fst_out->AddState();
+ fst_out->AddArc(cur_state, arc);
+ cur_state = arc.nextstate;
+ }
+ if (is_final && use_final_probs) {
+ Weight final_weight = fst_.Final(best_tok->arc_.nextstate);
+ fst_out->SetFinal(cur_state, LatticeWeight(final_weight.Value(), 0.0));
+ } else {
+ fst_out->SetFinal(cur_state, LatticeWeight::One());
+ }
+ RemoveEpsLocal(fst_out);
+ return true;
+}
+
+
+// Gets the weight cutoff. Also counts the active tokens.
+double FasterDecoder::GetCutoff(Elem *list_head, size_t *tok_count,
+ BaseFloat *adaptive_beam, Elem **best_elem) {
+ double best_cost = std::numeric_limits<double>::infinity();
+ size_t count = 0;
+ if (config_.max_active == std::numeric_limits<int32>::max() &&
+ config_.min_active == 0) {
+ for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
+ double w = e->val->cost_;
+ if (w < best_cost) {
+ best_cost = w;
+ if (best_elem) *best_elem = e;
+ }
+ }
+ if (tok_count != NULL) *tok_count = count;
+ if (adaptive_beam != NULL) *adaptive_beam = config_.beam;
+ return best_cost + config_.beam;
+ } else {
+ tmp_array_.clear();
+ for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
+ double w = e->val->cost_;
+ tmp_array_.push_back(w);
+ if (w < best_cost) {
+ best_cost = w;
+ if (best_elem) *best_elem = e;
+ }
+ }
+ if (tok_count != NULL) *tok_count = count;
+ double beam_cutoff = best_cost + config_.beam,
+ min_active_cutoff = std::numeric_limits<double>::infinity(),
+ max_active_cutoff = std::numeric_limits<double>::infinity();
+
+ if (tmp_array_.size() > static_cast<size_t>(config_.max_active)) {
+ std::nth_element(tmp_array_.begin(),
+ tmp_array_.begin() + config_.max_active,
+ tmp_array_.end());
+ max_active_cutoff = tmp_array_[config_.max_active];
+ }
+ if (max_active_cutoff < beam_cutoff) { // max_active is tighter than beam.
+ if (adaptive_beam)
+ *adaptive_beam = max_active_cutoff - best_cost + config_.beam_delta;
+ return max_active_cutoff;
+ }
+ if (tmp_array_.size() > static_cast<size_t>(config_.min_active)) {
+ if (config_.min_active == 0) min_active_cutoff = best_cost;
+ else {
+ std::nth_element(tmp_array_.begin(),
+ tmp_array_.begin() + config_.min_active,
+ tmp_array_.size() > static_cast<size_t>(config_.max_active) ?
+ tmp_array_.begin() + config_.max_active :
+ tmp_array_.end());
+ min_active_cutoff = tmp_array_[config_.min_active];
+ }
+ }
+ if (min_active_cutoff > beam_cutoff) { // min_active is looser than beam.
+ if (adaptive_beam)
+ *adaptive_beam = min_active_cutoff - best_cost + config_.beam_delta;
+ return min_active_cutoff;
+ } else {
+ *adaptive_beam = config_.beam;
+ return beam_cutoff;
+ }
+ }
+}
+
+void FasterDecoder::PossiblyResizeHash(size_t num_toks) {
+ size_t new_sz = static_cast<size_t>(static_cast<BaseFloat>(num_toks)
+ * config_.hash_ratio);
+ if (new_sz > toks_.Size()) {
+ toks_.SetSize(new_sz);
+ }
+}
+
+// ProcessEmitting returns the likelihood cutoff used.
+double FasterDecoder::ProcessEmitting(DecodableInterface *decodable) {
+ int32 frame = num_frames_decoded_;
+ Elem *last_toks = toks_.Clear();
+ size_t tok_cnt;
+ BaseFloat adaptive_beam;
+ Elem *best_elem = NULL;
+ double weight_cutoff = GetCutoff(last_toks, &tok_cnt,
+ &adaptive_beam, &best_elem);
+ KALDI_VLOG(3) << tok_cnt << " tokens active.";
+ PossiblyResizeHash(tok_cnt); // This makes sure the hash is always big enough.
+
+ // This is the cutoff we use after adding in the log-likes (i.e.
+ // for the next frame). This is a bound on the cutoff we will use
+ // on the next frame.
+ double next_weight_cutoff = std::numeric_limits<double>::infinity();
+
+ // First process the best token to get a hopefully
+ // reasonably tight bound on the next cutoff.
+ if (best_elem) {
+ StateId state = best_elem->key;
+ Token *tok = best_elem->val;
+ for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0) { // we'd propagate..
+ BaseFloat ac_cost = - decodable->LogLikelihood(frame, arc.ilabel);
+ double new_weight = arc.weight.Value() + tok->cost_ + ac_cost;
+ if (new_weight + adaptive_beam < next_weight_cutoff)
+ next_weight_cutoff = new_weight + adaptive_beam;
+ }
+ }
+ }
+
+ // int32 n = 0, np = 0;
+
+ // the tokens are now owned here, in last_toks, and the hash is empty.
+ // 'owned' is a complex thing here; the point is we need to call TokenDelete
+ // on each elem 'e' to let toks_ know we're done with them.
+ for (Elem *e = last_toks, *e_tail; e != NULL; e = e_tail) { // loop this way
+ // n++;
+ // because we delete "e" as we go.
+ StateId state = e->key;
+ Token *tok = e->val;
+ if (tok->cost_ < weight_cutoff) { // not pruned.
+ // np++;
+ KALDI_ASSERT(state == tok->arc_.nextstate);
+ for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ Arc arc = aiter.Value();
+ if (arc.ilabel != 0) { // propagate..
+ BaseFloat ac_cost = - decodable->LogLikelihood(frame, arc.ilabel);
+ double new_weight = arc.weight.Value() + tok->cost_ + ac_cost;
+ if (new_weight < next_weight_cutoff) { // not pruned..
+ Token *new_tok = new Token(arc, ac_cost, tok);
+ Elem *e_found = toks_.Insert(arc.nextstate, new_tok);
+ if (new_weight + adaptive_beam < next_weight_cutoff)
+ next_weight_cutoff = new_weight + adaptive_beam;
+ if (e_found->val != new_tok) {
+ if (*(e_found->val) < *new_tok) {
+ Token::TokenDelete(e_found->val);
+ e_found->val = new_tok;
+ } else {
+ Token::TokenDelete(new_tok);
+ }
+ }
+ }
+ }
+ }
+ }
+ e_tail = e->tail;
+ Token::TokenDelete(e->val);
+ toks_.Delete(e);
+ }
+ num_frames_decoded_++;
+ return next_weight_cutoff;
+}
+
+// TODO: first time we go through this, could avoid using the queue.
+void FasterDecoder::ProcessNonemitting(double cutoff) {
+ // Processes nonemitting arcs for one frame.
+ KALDI_ASSERT(queue_.empty());
+ for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail)
+ queue_.push_back(e);
+ while (!queue_.empty()) {
+ const Elem* e = queue_.back();
+ queue_.pop_back();
+ StateId state = e->key;
+ Token *tok = e->val; // would segfault if state not
+ // in toks_ but this can't happen.
+ if (tok->cost_ > cutoff) { // Don't bother processing successors.
+ continue;
+ }
+ KALDI_ASSERT(tok != NULL && state == tok->arc_.nextstate);
+ for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel == 0) { // propagate nonemitting only...
+ Token *new_tok = new Token(arc, tok);
+ if (new_tok->cost_ > cutoff) { // prune
+ Token::TokenDelete(new_tok);
+ } else {
+ Elem *e_found = toks_.Insert(arc.nextstate, new_tok);
+ if (e_found->val == new_tok) {
+ queue_.push_back(e_found);
+ } else {
+ if (*(e_found->val) < *new_tok) {
+ Token::TokenDelete(e_found->val);
+ e_found->val = new_tok;
+ queue_.push_back(e_found);
+ } else {
+ Token::TokenDelete(new_tok);
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+void FasterDecoder::ClearToks(Elem *list) {
+ for (Elem *e = list, *e_tail; e != NULL; e = e_tail) {
+ Token::TokenDelete(e->val);
+ e_tail = e->tail;
+ toks_.Delete(e);
+ }
+}
+
+} // end namespace kaldi.
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/faster-decoder.h b/runtime/onnxruntime/third_party/kaldi/decoder/faster-decoder.h
new file mode 100644
index 000000000..88f78a615
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/faster-decoder.h
@@ -0,0 +1,195 @@
+// decoder/faster-decoder.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_DECODER_FASTER_DECODER_H_
+#define KALDI_DECODER_FASTER_DECODER_H_
+
+#include "util/stl-utils.h"
+#include "itf/options-itf.h"
+#include "util/hash-list.h"
+#include "fst/fstlib.h"
+#include "itf/decodable-itf.h"
+#include "lat/kaldi-lattice.h" // for CompactLatticeArc
+
+namespace kaldi {
+
+struct FasterDecoderOptions {
+ BaseFloat beam;
+ int32 max_active;
+ int32 min_active;
+ BaseFloat beam_delta;
+ BaseFloat hash_ratio;
+ FasterDecoderOptions(): beam(16.0),
+ max_active(std::numeric_limits<int32>::max()),
+ min_active(20), // This decoder mostly used for
+ // alignment, use small default.
+ beam_delta(0.5),
+ hash_ratio(2.0) { }
+ void Register(OptionsItf *opts, bool full) { /// if "full", use obscure
+ /// options too.
+ /// Depends on program.
+ opts->Register("beam", &beam, "Decoding beam. Larger->slower, more accurate.");
+ opts->Register("max-active", &max_active, "Decoder max active states. Larger->slower; "
+ "more accurate");
+ opts->Register("min-active", &min_active,
+ "Decoder min active states (don't prune if #active less than this).");
+ if (full) {
+ opts->Register("beam-delta", &beam_delta,
+ "Increment used in decoder [obscure setting]");
+ opts->Register("hash-ratio", &hash_ratio,
+ "Setting used in decoder to control hash behavior");
+ }
+ }
+};
+
+class FasterDecoder {
+ public:
+ typedef fst::StdArc Arc;
+ typedef Arc::Label Label;
+ typedef Arc::StateId StateId;
+ typedef Arc::Weight Weight;
+
+ FasterDecoder(const fst::Fst<fst::StdArc> &fst,
+ const FasterDecoderOptions &config);
+
+ void SetOptions(const FasterDecoderOptions &config) { config_ = config; }
+
+ ~FasterDecoder() { ClearToks(toks_.Clear()); }
+
+ void Decode(DecodableInterface *decodable);
+
+ /// Returns true if a final state was active on the last frame.
+ bool ReachedFinal() const;
+
+ /// GetBestPath gets the decoding traceback. If "use_final_probs" is true
+ /// AND we reached a final state, it limits itself to final states;
+ /// otherwise it gets the most likely token not taking into account
+ /// final-probs. Returns true if the output best path was not the empty
+ /// FST (will only return false in unusual circumstances where
+ /// no tokens survived).
+ bool GetBestPath(fst::MutableFst<LatticeArc> *fst_out,
+ bool use_final_probs = true);
+
+ /// As a new alternative to Decode(), you can call InitDecoding
+ /// and then (possibly multiple times) AdvanceDecoding().
+ void InitDecoding();
+
+
+ /// This will decode until there are no more frames ready in the decodable
+ /// object, but if max_num_frames is >= 0 it will decode no more than
+ /// that many frames.
+ void AdvanceDecoding(DecodableInterface *decodable,
+ int32 max_num_frames = -1);
+
+ /// Returns the number of frames already decoded.
+ int32 NumFramesDecoded() const { return num_frames_decoded_; }
+
+ protected:
+
+ class Token {
+ public:
+ Arc arc_; // contains only the graph part of the cost;
+ // we can work out the acoustic part from difference between
+ // "cost_" and prev->cost_.
+ Token *prev_;
+ int32 ref_count_;
+ // if you are looking for weight_ here, it was removed and now we just have
+ // cost_, which corresponds to ConvertToCost(weight_).
+ double cost_;
+ inline Token(const Arc &arc, BaseFloat ac_cost, Token *prev):
+ arc_(arc), prev_(prev), ref_count_(1) {
+ if (prev) {
+ prev->ref_count_++;
+ cost_ = prev->cost_ + arc.weight.Value() + ac_cost;
+ } else {
+ cost_ = arc.weight.Value() + ac_cost;
+ }
+ }
+ inline Token(const Arc &arc, Token *prev):
+ arc_(arc), prev_(prev), ref_count_(1) {
+ if (prev) {
+ prev->ref_count_++;
+ cost_ = prev->cost_ + arc.weight.Value();
+ } else {
+ cost_ = arc.weight.Value();
+ }
+ }
+ inline bool operator < (const Token &other) {
+ return cost_ > other.cost_;
+ }
+
+ inline static void TokenDelete(Token *tok) {
+ while (--tok->ref_count_ == 0) {
+ Token *prev = tok->prev_;
+ delete tok;
+ if (prev == NULL) return;
+ else tok = prev;
+ }
+#ifdef KALDI_PARANOID
+ KALDI_ASSERT(tok->ref_count_ > 0);
+#endif
+ }
+ };
+ typedef HashList<StateId, Token*>::Elem Elem;
+
+
+ /// Gets the weight cutoff. Also counts the active tokens.
+ double GetCutoff(Elem *list_head, size_t *tok_count,
+ BaseFloat *adaptive_beam, Elem **best_elem);
+
+ void PossiblyResizeHash(size_t num_toks);
+
+ // ProcessEmitting returns the likelihood cutoff used.
+ // It decodes the frame num_frames_decoded_ of the decodable object
+ // and then increments num_frames_decoded_
+ double ProcessEmitting(DecodableInterface *decodable);
+
+ // TODO: first time we go through this, could avoid using the queue.
+ void ProcessNonemitting(double cutoff);
+
+ // HashList defined in ../util/hash-list.h. It actually allows us to maintain
+ // more than one list (e.g. for current and previous frames), but only one of
+ // them at a time can be indexed by StateId.
+ HashList<StateId, Token*> toks_;
+ const fst::Fst<fst::StdArc> &fst_;
+ FasterDecoderOptions config_;
+ std::vector<const Elem* > queue_; // temp variable used in ProcessNonemitting,
+ std::vector<BaseFloat> tmp_array_; // used in GetCutoff.
+ // make it class member to avoid internal new/delete.
+
+ // Keep track of the number of frames decoded in the current file.
+ int32 num_frames_decoded_;
+
+ // It might seem unclear why we call ClearToks(toks_.Clear()).
+ // There are two separate cleanup tasks we need to do at when we start a new file.
+ // one is to delete the Token objects in the list; the other is to delete
+ // the Elem objects. toks_.Clear() just clears them from the hash and gives ownership
+ // to the caller, who then has to call toks_.Delete(e) for each one. It was designed
+ // this way for convenience in propagating tokens from one frame to the next.
+ void ClearToks(Elem *list);
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(FasterDecoder);
+};
+
+
+} // end namespace kaldi.
+
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/lattice-biglm-faster-decoder.h b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-biglm-faster-decoder.h
new file mode 100644
index 000000000..9f50739a0
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-biglm-faster-decoder.h
@@ -0,0 +1,886 @@
+// decoder/lattice-biglm-faster-decoder.h
+
+// Copyright 2009-2011 Microsoft Corporation, Mirko Hannemann,
+// Gilles Boulianne
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_DECODER_LATTICE_BIGLM_FASTER_DECODER_H_
+#define KALDI_DECODER_LATTICE_BIGLM_FASTER_DECODER_H_
+
+
+#include "util/stl-utils.h"
+#include "util/hash-list.h"
+#include "fst/fstlib.h"
+#include "itf/decodable-itf.h"
+#include "fstext/fstext-lib.h"
+#include "lat/kaldi-lattice.h"
+#include "decoder/lattice-faster-decoder.h" // for options.
+
+
+namespace kaldi {
+
+// The options are the same as for lattice-faster-decoder.h for now.
+typedef LatticeFasterDecoderConfig LatticeBiglmFasterDecoderConfig;
+
+/** This is as LatticeFasterDecoder, but does online composition between
+ HCLG and the "difference language model", which is a deterministic
+ FST that represents the difference between the language model you want
+ and the language model you compiled HCLG with. The class
+ DeterministicOnDemandFst follows through the epsilons in G for you
+ (assuming G is a standard backoff language model) and makes it look
+ like a determinized FST.
+*/
+
+class LatticeBiglmFasterDecoder {
+ public:
+ typedef fst::StdArc Arc;
+ typedef Arc::Label Label;
+ typedef Arc::StateId StateId;
+ // A PairId will be constructed as: (StateId in fst) + (StateId in lm_diff_fst) << 32;
+ typedef uint64 PairId;
+ typedef Arc::Weight Weight;
+ // instantiate this class once for each thing you have to decode.
+ LatticeBiglmFasterDecoder(
+ const fst::Fst<fst::StdArc> &fst,
+ const LatticeBiglmFasterDecoderConfig &config,
+ fst::DeterministicOnDemandFst<fst::StdArc> *lm_diff_fst):
+ fst_(fst), lm_diff_fst_(lm_diff_fst), config_(config),
+ warned_noarc_(false), num_toks_(0) {
+ config.Check();
+ KALDI_ASSERT(fst.Start() != fst::kNoStateId &&
+ lm_diff_fst->Start() != fst::kNoStateId);
+ toks_.SetSize(1000); // just so on the first frame we do something reasonable.
+ }
+ void SetOptions(const LatticeBiglmFasterDecoderConfig &config) { config_ = config; }
+ LatticeBiglmFasterDecoderConfig GetOptions() { return config_; }
+ ~LatticeBiglmFasterDecoder() {
+ DeleteElems(toks_.Clear());
+ ClearActiveTokens();
+ }
+
+ // Returns true if any kind of traceback is available (not necessarily from
+ // a final state).
+ bool Decode(DecodableInterface *decodable) {
+ // clean up from last time:
+ DeleteElems(toks_.Clear());
+ ClearActiveTokens();
+ warned_ = false;
+ final_active_ = false;
+ final_costs_.clear();
+ num_toks_ = 0;
+ PairId start_pair = ConstructPair(fst_.Start(), lm_diff_fst_->Start());
+ active_toks_.resize(1);
+ Token *start_tok = new Token(0.0, 0.0, NULL, NULL);
+ active_toks_[0].toks = start_tok;
+ toks_.Insert(start_pair, start_tok);
+ num_toks_++;
+ ProcessNonemitting(0);
+
+ // We use 1-based indexing for frames in this decoder (if you view it in
+ // terms of features), but note that the decodable object uses zero-based
+ // numbering, which we have to correct for when we call it.
+ for (int32 frame = 1; !decodable->IsLastFrame(frame-2); frame++) {
+ active_toks_.resize(frame+1); // new column
+
+ ProcessEmitting(decodable, frame);
+
+ ProcessNonemitting(frame);
+
+ if (decodable->IsLastFrame(frame-1))
+ PruneActiveTokensFinal(frame);
+ else if (frame % config_.prune_interval == 0)
+ PruneActiveTokens(frame, config_.lattice_beam * 0.1); // use larger delta.
+ }
+ // Returns true if we have any kind of traceback available (not necessarily
+ // to the end state; query ReachedFinal() for that).
+ return !final_costs_.empty();
+ }
+
+ /// says whether a final-state was active on the last frame. If it was not, the
+ /// lattice (or traceback) will end with states that are not final-states.
+ bool ReachedFinal() const { return final_active_; }
+
+
+ // Outputs an FST corresponding to the single best path
+ // through the lattice.
+ bool GetBestPath(fst::MutableFst<LatticeArc> *ofst,
+ bool use_final_probs = true) const {
+ fst::VectorFst<LatticeArc> fst;
+ if (!GetRawLattice(&fst, use_final_probs)) return false;
+ // std::cout << "Raw lattice is:\n";
+ // fst::FstPrinter<LatticeArc> fstprinter(fst, NULL, NULL, NULL, false, true);
+ // fstprinter.Print(&std::cout, "standard output");
+ ShortestPath(fst, ofst);
+ return true;
+ }
+
+ // Outputs an FST corresponding to the raw, state-level
+ // tracebacks.
+ bool GetRawLattice(fst::MutableFst<LatticeArc> *ofst,
+ bool use_final_probs = true) const {
+ typedef LatticeArc Arc;
+ typedef Arc::StateId StateId;
+ // A PairId will be constructed as: (StateId in fst) + (StateId in lm_diff_fst) << 32;
+ typedef uint64 PairId;
+ typedef Arc::Weight Weight;
+ typedef Arc::Label Label;
+ ofst->DeleteStates();
+ // num-frames plus one (since frames are one-based, and we have
+ // an extra frame for the start-state).
+ int32 num_frames = active_toks_.size() - 1;
+ KALDI_ASSERT(num_frames > 0);
+ unordered_map<Token*, StateId> tok_map(num_toks_/2 + 3); // bucket count
+ // First create all states.
+ for (int32 f = 0; f <= num_frames; f++) {
+ if (active_toks_[f].toks == NULL) {
+ KALDI_WARN << "GetRawLattice: no tokens active on frame " << f
+ << ": not producing lattice.\n";
+ return false;
+ }
+ for (Token *tok = active_toks_[f].toks; tok != NULL; tok = tok->next)
+ tok_map[tok] = ofst->AddState();
+ // The next statement sets the start state of the output FST.
+ // Because we always add new states to the head of the list
+ // active_toks_[f].toks, and the start state was the first one
+ // added, it will be the last one added to ofst.
+ if (f == 0 && ofst->NumStates() > 0)
+ ofst->SetStart(ofst->NumStates()-1);
+ }
+ KALDI_VLOG(3) << "init:" << num_toks_/2 + 3 << " buckets:"
+ << tok_map.bucket_count() << " load:" << tok_map.load_factor()
+ << " max:" << tok_map.max_load_factor();
+ // Now create all arcs.
+ StateId cur_state = 0; // we rely on the fact that we numbered these
+ // consecutively (AddState() returns the numbers in order..)
+ for (int32 f = 0; f <= num_frames; f++) {
+ for (Token *tok = active_toks_[f].toks; tok != NULL; tok = tok->next,
+ cur_state++) {
+ for (ForwardLink *l = tok->links;
+ l != NULL;
+ l = l->next) {
+ unordered_map<Token*, StateId>::const_iterator iter =
+ tok_map.find(l->next_tok);
+ StateId nextstate = iter->second;
+ KALDI_ASSERT(iter != tok_map.end());
+ Arc arc(l->ilabel, l->olabel,
+ Weight(l->graph_cost, l->acoustic_cost),
+ nextstate);
+ ofst->AddArc(cur_state, arc);
+ }
+ if (f == num_frames) {
+ if (use_final_probs && !final_costs_.empty()) {
+ std::map<Token*, BaseFloat>::const_iterator iter =
+ final_costs_.find(tok);
+ if (iter != final_costs_.end())
+ ofst->SetFinal(cur_state, LatticeWeight(iter->second, 0));
+ } else {
+ ofst->SetFinal(cur_state, LatticeWeight::One());
+ }
+ }
+ }
+ }
+ KALDI_ASSERT(cur_state == ofst->NumStates());
+ return (cur_state != 0);
+ }
+
+ // This function is now deprecated, since now we do determinization from
+ // outside the LatticeBiglmFasterDecoder class.
+ // Outputs an FST corresponding to the lattice-determinized
+ // lattice (one path per word sequence).
+ bool GetLattice(fst::MutableFst<CompactLatticeArc> *ofst,
+ bool use_final_probs = true) const {
+ Lattice raw_fst;
+ if (!GetRawLattice(&raw_fst, use_final_probs)) return false;
+ Invert(&raw_fst); // make it so word labels are on the input.
+ if (!TopSort(&raw_fst)) // topological sort makes lattice-determinization more efficient
+ KALDI_WARN << "Topological sorting of state-level lattice failed "
+ "(probably your lexicon has empty words or your LM has epsilon cycles; this "
+ " is a bad idea.)";
+ // (in phase where we get backward-costs).
+ fst::ILabelCompare<LatticeArc> ilabel_comp;
+ ArcSort(&raw_fst, ilabel_comp); // sort on ilabel; makes
+ // lattice-determinization more efficient.
+
+ fst::DeterminizeLatticePrunedOptions lat_opts;
+ lat_opts.max_mem = config_.det_opts.max_mem;
+
+ DeterminizeLatticePruned(raw_fst, config_.lattice_beam, ofst, lat_opts);
+ raw_fst.DeleteStates(); // Free memory-- raw_fst no longer needed.
+ Connect(ofst); // Remove unreachable states... there might be
+ // a small number of these, in some cases.
+ return true;
+ }
+
+ private:
+ inline PairId ConstructPair(StateId fst_state, StateId lm_state) {
+ return static_cast<PairId>(fst_state) + (static_cast<PairId>(lm_state) << 32);
+ }
+
+ static inline StateId PairToState(PairId state_pair) {
+ return static_cast<StateId>(static_cast<uint32>(state_pair));
+ }
+ static inline StateId PairToLmState(PairId state_pair) {
+ return static_cast<StateId>(static_cast<uint32>(state_pair >> 32));
+ }
+
+ struct Token;
+ // ForwardLinks are the links from a token to a token on the next frame.
+ // or sometimes on the current frame (for input-epsilon links).
+ struct ForwardLink {
+ Token *next_tok; // the next token [or NULL if represents final-state]
+ Label ilabel; // ilabel on link.
+ Label olabel; // olabel on link.
+ BaseFloat graph_cost; // graph cost of traversing link (contains LM, etc.)
+ BaseFloat acoustic_cost; // acoustic cost (pre-scaled) of traversing link
+ ForwardLink *next; // next in singly-linked list of forward links from a
+ // token.
+ inline ForwardLink(Token *next_tok, Label ilabel, Label olabel,
+ BaseFloat graph_cost, BaseFloat acoustic_cost,
+ ForwardLink *next):
+ next_tok(next_tok), ilabel(ilabel), olabel(olabel),
+ graph_cost(graph_cost), acoustic_cost(acoustic_cost),
+ next(next) { }
+ };
+
+ // Token is what's resident in a particular state at a particular time.
+ // In this decoder a Token actually contains *forward* links.
+ // When first created, a Token just has the (total) cost. We add forward
+ // links to it when we process the next frame.
+ struct Token {
+ BaseFloat tot_cost; // would equal weight.Value()... cost up to this point.
+ BaseFloat extra_cost; // >= 0. After calling PruneForwardLinks, this equals
+ // the minimum difference between the cost of the best path, and the cost of
+ // this is on, and the cost of the absolute best path, under the assumption
+ // that any of the currently active states at the decoding front may
+ // eventually succeed (e.g. if you were to take the currently active states
+ // one by one and compute this difference, and then take the minimum).
+
+ ForwardLink *links; // Head of singly linked list of ForwardLinks
+
+ Token *next; // Next in list of tokens for this frame.
+
+ inline Token(BaseFloat tot_cost, BaseFloat extra_cost, ForwardLink *links,
+ Token *next): tot_cost(tot_cost), extra_cost(extra_cost),
+ links(links), next(next) { }
+ inline void DeleteForwardLinks() {
+ ForwardLink *l = links, *m;
+ while (l != NULL) {
+ m = l->next;
+ delete l;
+ l = m;
+ }
+ links = NULL;
+ }
+ };
+
+ // head and tail of per-frame list of Tokens (list is in topological order),
+ // and something saying whether we ever pruned it using PruneForwardLinks.
+ struct TokenList {
+ Token *toks;
+ bool must_prune_forward_links;
+ bool must_prune_tokens;
+ TokenList(): toks(NULL), must_prune_forward_links(true),
+ must_prune_tokens(true) { }
+ };
+
+ typedef HashList<PairId, Token*>::Elem Elem;
+
+ void PossiblyResizeHash(size_t num_toks) {
+ size_t new_sz = static_cast<size_t>(static_cast<BaseFloat>(num_toks)
+ * config_.hash_ratio);
+ if (new_sz > toks_.Size()) {
+ toks_.SetSize(new_sz);
+ }
+ }
+
+ // FindOrAddToken either locates a token in hash of toks_,
+ // or if necessary inserts a new, empty token (i.e. with no forward links)
+ // for the current frame. [note: it's inserted if necessary into hash toks_
+ // and also into the singly linked list of tokens active on this frame
+ // (whose head is at active_toks_[frame]).
+ inline Elem *FindOrAddToken(PairId state_pair, int32 frame,
+ BaseFloat tot_cost, bool emitting, bool *changed) {
+ // Returns the Token pointer. Sets "changed" (if non-NULL) to true
+ // if the token was newly created or the cost changed.
+ KALDI_ASSERT(frame < active_toks_.size());
+ Token *&toks = active_toks_[frame].toks;
+ Elem *e_found = toks_.Insert(state_pair, NULL);
+ if (e_found->val == NULL) { // no such token presently.
+ const BaseFloat extra_cost = 0.0;
+ // tokens on the currently final frame have zero extra_cost
+ // as any of them could end up
+ // on the winning path.
+ Token *new_tok = new Token (tot_cost, extra_cost, NULL, toks);
+ // NULL: no forward links yet
+ toks = new_tok;
+ num_toks_++;
+ e_found->val = new_tok;
+ if (changed) *changed = true;
+ return e_found;
+ } else {
+ Token *tok = e_found->val; // There is an existing Token for this state.
+ if (tok->tot_cost > tot_cost) { // replace old token
+ tok->tot_cost = tot_cost;
+ // we don't allocate a new token, the old stays linked in active_toks_
+ // we only replace the tot_cost
+ // in the current frame, there are no forward links (and no extra_cost)
+ // only in ProcessNonemitting we have to delete forward links
+ // in case we visit a state for the second time
+ // those forward links, that lead to this replaced token before:
+ // they remain and will hopefully be pruned later (PruneForwardLinks...)
+ if (changed) *changed = true;
+ } else {
+ if (changed) *changed = false;
+ }
+ return e_found;
+ }
+ }
+
+ // prunes outgoing links for all tokens in active_toks_[frame]
+ // it's called by PruneActiveTokens
+ // all links, that have link_extra_cost > lattice_beam are pruned
+ void PruneForwardLinks(int32 frame, bool *extra_costs_changed,
+ bool *links_pruned,
+ BaseFloat delta) {
+ // delta is the amount by which the extra_costs must change
+ // If delta is larger, we'll tend to go back less far
+ // toward the beginning of the file.
+ // extra_costs_changed is set to true if extra_cost was changed for any token
+ // links_pruned is set to true if any link in any token was pruned
+
+ *extra_costs_changed = false;
+ *links_pruned = false;
+ KALDI_ASSERT(frame >= 0 && frame < active_toks_.size());
+ if (active_toks_[frame].toks == NULL ) { // empty list; should not happen.
+ if (!warned_) {
+ KALDI_WARN << "No tokens alive [doing pruning].. warning first "
+ "time only for each utterance\n";
+ warned_ = true;
+ }
+ }
+
+ // We have to iterate until there is no more change, because the links
+ // are not guaranteed to be in topological order.
+ bool changed = true; // difference new minus old extra cost >= delta ?
+ while (changed) {
+ changed = false;
+ for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
+ ForwardLink *link, *prev_link=NULL;
+ // will recompute tok_extra_cost for tok.
+ BaseFloat tok_extra_cost = std::numeric_limits<BaseFloat>::infinity();
+ // tok_extra_cost is the best (min) of link_extra_cost of outgoing links
+ for (link = tok->links; link != NULL; ) {
+ // See if we need to excise this link...
+ Token *next_tok = link->next_tok;
+ BaseFloat link_extra_cost = next_tok->extra_cost +
+ ((tok->tot_cost + link->acoustic_cost + link->graph_cost)
+ - next_tok->tot_cost); // difference in brackets is >= 0
+ // link_exta_cost is the difference in score between the best paths
+ // through link source state and through link destination state
+ KALDI_ASSERT(link_extra_cost == link_extra_cost); // check for NaN
+ if (link_extra_cost > config_.lattice_beam) { // excise link
+ ForwardLink *next_link = link->next;
+ if (prev_link != NULL) prev_link->next = next_link;
+ else tok->links = next_link;
+ delete link;
+ link = next_link; // advance link but leave prev_link the same.
+ *links_pruned = true;
+ } else { // keep the link and update the tok_extra_cost if needed.
+ if (link_extra_cost < 0.0) { // this is just a precaution.
+ if (link_extra_cost < -0.01)
+ KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
+ link_extra_cost = 0.0;
+ }
+ if (link_extra_cost < tok_extra_cost)
+ tok_extra_cost = link_extra_cost;
+ prev_link = link; // move to next link
+ link = link->next;
+ }
+ } // for all outgoing links
+ if (fabs(tok_extra_cost - tok->extra_cost) > delta)
+ changed = true; // difference new minus old is bigger than delta
+ tok->extra_cost = tok_extra_cost;
+ // will be +infinity or <= lattice_beam_.
+ // infinity indicates, that no forward link survived pruning
+ } // for all Token on active_toks_[frame]
+ if (changed) *extra_costs_changed = true;
+
+ // Note: it's theoretically possible that aggressive compiler
+ // optimizations could cause an infinite loop here for small delta and
+ // high-dynamic-range scores.
+ } // while changed
+ }
+
+ // PruneForwardLinksFinal is a version of PruneForwardLinks that we call
+ // on the final frame. If there are final tokens active, it uses
+ // the final-probs for pruning, otherwise it treats all tokens as final.
+ void PruneForwardLinksFinal(int32 frame) {
+ KALDI_ASSERT(static_cast<size_t>(frame+1) == active_toks_.size());
+ if (active_toks_[frame].toks == NULL ) // empty list; should not happen.
+ KALDI_WARN << "No tokens alive at end of file\n";
+
+ // First go through, working out the best token (do it in parallel
+ // including final-probs and not including final-probs; we'll take
+ // the one with final-probs if it's valid).
+ const BaseFloat infinity = std::numeric_limits<BaseFloat>::infinity();
+ BaseFloat best_cost_final = infinity,
+ best_cost_nofinal = infinity;
+ unordered_map<Token*, BaseFloat> tok_to_final_cost;
+ Elem *cur_toks = toks_.Clear(); // swapping prev_toks_ / cur_toks_
+ for (Elem *e = cur_toks, *e_tail; e != NULL; e = e_tail) {
+ PairId state_pair = e->key;
+ StateId state = PairToState(state_pair),
+ lm_state = PairToLmState(state_pair);
+ Token *tok = e->val;
+ BaseFloat final_cost = fst_.Final(state).Value() +
+ lm_diff_fst_->Final(lm_state).Value();
+ tok_to_final_cost[tok] = final_cost;
+ best_cost_final = std::min(best_cost_final, tok->tot_cost + final_cost);
+ best_cost_nofinal = std::min(best_cost_nofinal, tok->tot_cost);
+ e_tail = e->tail;
+ toks_.Delete(e);
+ }
+ final_active_ = (best_cost_final != infinity);
+
+ // Now go through tokens on this frame, pruning forward links... may have
+ // to iterate a few times until there is no more change, because the list is
+ // not in topological order.
+
+ bool changed = true;
+ BaseFloat delta = 1.0e-05;
+ while (changed) {
+ changed = false;
+ for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
+ ForwardLink *link, *prev_link=NULL;
+ // will recompute tok_extra_cost. It has a term in it that corresponds
+ // to the "final-prob", so instead of initializing tok_extra_cost to infinity
+ // below we set it to the difference between the (score+final_prob) of this token,
+ // and the best such (score+final_prob).
+ BaseFloat tok_extra_cost;
+ if (final_active_) {
+ BaseFloat final_cost = tok_to_final_cost[tok];
+ tok_extra_cost = (tok->tot_cost + final_cost) - best_cost_final;
+ } else
+ tok_extra_cost = tok->tot_cost - best_cost_nofinal;
+
+ for (link = tok->links; link != NULL; ) {
+ // See if we need to excise this link...
+ Token *next_tok = link->next_tok;
+ BaseFloat link_extra_cost = next_tok->extra_cost +
+ ((tok->tot_cost + link->acoustic_cost + link->graph_cost)
+ - next_tok->tot_cost);
+ if (link_extra_cost > config_.lattice_beam) { // excise link
+ ForwardLink *next_link = link->next;
+ if (prev_link != NULL) prev_link->next = next_link;
+ else tok->links = next_link;
+ delete link;
+ link = next_link; // advance link but leave prev_link the same.
+ } else { // keep the link and update the tok_extra_cost if needed.
+ if (link_extra_cost < 0.0) { // this is just a precaution.
+ if (link_extra_cost < -0.01)
+ KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
+ link_extra_cost = 0.0;
+ }
+ if (link_extra_cost < tok_extra_cost)
+ tok_extra_cost = link_extra_cost;
+ prev_link = link;
+ link = link->next;
+ }
+ }
+ // prune away tokens worse than lattice_beam above best path. This step
+ // was not necessary in the non-final case because then, this case
+ // showed up as having no forward links. Here, the tok_extra_cost has
+ // an extra component relating to the final-prob.
+ if (tok_extra_cost > config_.lattice_beam)
+ tok_extra_cost = infinity;
+ // to be pruned in PruneTokensForFrame
+
+ if (!ApproxEqual(tok->extra_cost, tok_extra_cost, delta))
+ changed = true;
+ tok->extra_cost = tok_extra_cost; // will be +infinity or <= lattice_beam_.
+ }
+ } // while changed
+
+ // Now put surviving Tokens in the final_costs_ hash, which is a class
+ // member (unlike tok_to_final_costs).
+ for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
+ if (tok->extra_cost != infinity) {
+ // If the token was not pruned away,
+ if (final_active_) {
+ BaseFloat final_cost = tok_to_final_cost[tok];
+ if (final_cost != infinity)
+ final_costs_[tok] = final_cost;
+ } else {
+ final_costs_[tok] = 0;
+ }
+ }
+ }
+ }
+
+ // Prune away any tokens on this frame that have no forward links.
+ // [we don't do this in PruneForwardLinks because it would give us
+ // a problem with dangling pointers].
+ // It's called by PruneActiveTokens if any forward links have been pruned
+ void PruneTokensForFrame(int32 frame) {
+ KALDI_ASSERT(frame >= 0 && frame < active_toks_.size());
+ Token *&toks = active_toks_[frame].toks;
+ if (toks == NULL)
+ KALDI_WARN << "No tokens alive [doing pruning]\n";
+ Token *tok, *next_tok, *prev_tok = NULL;
+ for (tok = toks; tok != NULL; tok = next_tok) {
+ next_tok = tok->next;
+ if (tok->extra_cost == std::numeric_limits<BaseFloat>::infinity()) {
+ // token is unreachable from end of graph; (no forward links survived)
+ // excise tok from list and delete tok.
+ if (prev_tok != NULL) prev_tok->next = tok->next;
+ else toks = tok->next;
+ delete tok;
+ num_toks_--;
+ } else { // fetch next Token
+ prev_tok = tok;
+ }
+ }
+ }
+
+ // Go backwards through still-alive tokens, pruning them. note: cur_frame is
+ // where hash toks_ are (so we do not want to mess with it because these tokens
+ // don't yet have forward pointers), but we do all previous frames, unless we
+ // know that we can safely ignore them because the frame after them was unchanged.
+ // delta controls when it considers a cost to have changed enough to continue
+ // going backward and propagating the change.
+ // for a larger delta, we will recurse less far back
+ void PruneActiveTokens(int32 cur_frame, BaseFloat delta) {
+ int32 num_toks_begin = num_toks_;
+ for (int32 frame = cur_frame-1; frame >= 0; frame--) {
+ // Reason why we need to prune forward links in this situation:
+ // (1) we have never pruned them (new TokenList)
+ // (2) we have not yet pruned the forward links to the next frame,
+ // after any of those tokens have changed their extra_cost.
+ if (active_toks_[frame].must_prune_forward_links) {
+ bool extra_costs_changed = false, links_pruned = false;
+ PruneForwardLinks(frame, &extra_costs_changed, &links_pruned, delta);
+ if (extra_costs_changed && frame > 0) // any token has changed extra_cost
+ active_toks_[frame-1].must_prune_forward_links = true;
+ if (links_pruned) // any link was pruned
+ active_toks_[frame].must_prune_tokens = true;
+ active_toks_[frame].must_prune_forward_links = false; // job done
+ }
+ if (frame+1 < cur_frame && // except for last frame (no forward links)
+ active_toks_[frame+1].must_prune_tokens) {
+ PruneTokensForFrame(frame+1);
+ active_toks_[frame+1].must_prune_tokens = false;
+ }
+ }
+ KALDI_VLOG(3) << "PruneActiveTokens: pruned tokens from " << num_toks_begin
+ << " to " << num_toks_;
+ }
+
+ // Version of PruneActiveTokens that we call on the final frame.
+ // Takes into account the final-prob of tokens.
+ void PruneActiveTokensFinal(int32 cur_frame) {
+ // returns true if there were final states active
+ // else returns false and treats all states as final while doing the pruning
+ // (this can be useful if you want partial lattice output,
+ // although it can be dangerous, depending what you want the lattices for).
+ // final_active_ and final_probs_ (a hash) are set internally
+ // by PruneForwardLinksFinal
+ int32 num_toks_begin = num_toks_;
+ PruneForwardLinksFinal(cur_frame); // prune final frame (with final-probs)
+ // sets final_active_ and final_probs_
+ for (int32 frame = cur_frame-1; frame >= 0; frame--) {
+ bool b1, b2; // values not used.
+ BaseFloat dontcare = 0.0; // delta of zero means we must always update
+ PruneForwardLinks(frame, &b1, &b2, dontcare);
+ PruneTokensForFrame(frame+1);
+ }
+ PruneTokensForFrame(0);
+ KALDI_VLOG(3) << "PruneActiveTokensFinal: pruned tokens from " << num_toks_begin
+ << " to " << num_toks_;
+ }
+
+ /// Gets the weight cutoff. Also counts the active tokens.
+ BaseFloat GetCutoff(Elem *list_head, size_t *tok_count,
+ BaseFloat *adaptive_beam, Elem **best_elem) {
+ BaseFloat best_weight = std::numeric_limits<BaseFloat>::infinity();
+ // positive == high cost == bad.
+ size_t count = 0;
+ if (config_.max_active == std::numeric_limits<int32>::max()) {
+ for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
+ BaseFloat w = static_cast<BaseFloat>(e->val->tot_cost);
+ if (w < best_weight) {
+ best_weight = w;
+ if (best_elem) *best_elem = e;
+ }
+ }
+ if (tok_count != NULL) *tok_count = count;
+ if (adaptive_beam != NULL) *adaptive_beam = config_.beam;
+ return best_weight + config_.beam;
+ } else {
+ tmp_array_.clear();
+ for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
+ BaseFloat w = e->val->tot_cost;
+ tmp_array_.push_back(w);
+ if (w < best_weight) {
+ best_weight = w;
+ if (best_elem) *best_elem = e;
+ }
+ }
+ if (tok_count != NULL) *tok_count = count;
+ if (tmp_array_.size() <= static_cast<size_t>(config_.max_active)) {
+ if (adaptive_beam) *adaptive_beam = config_.beam;
+ return best_weight + config_.beam;
+ } else {
+ // the lowest elements (lowest costs, highest likes)
+ // will be put in the left part of tmp_array.
+ std::nth_element(tmp_array_.begin(),
+ tmp_array_.begin()+config_.max_active,
+ tmp_array_.end());
+ // return the tighter of the two beams.
+ BaseFloat ans = std::min(best_weight + config_.beam,
+ *(tmp_array_.begin()+config_.max_active));
+ if (adaptive_beam)
+ *adaptive_beam = std::min(config_.beam,
+ ans - best_weight + config_.beam_delta);
+ return ans;
+ }
+ }
+ }
+
+ inline StateId PropagateLm(StateId lm_state,
+ Arc *arc) { // returns new LM state.
+ if (arc->olabel == 0) {
+ return lm_state; // no change in LM state if no word crossed.
+ } else { // Propagate in the LM-diff FST.
+ Arc lm_arc;
+ bool ans = lm_diff_fst_->GetArc(lm_state, arc->olabel, &lm_arc);
+ if (!ans) { // this case is unexpected for statistical LMs.
+ if (!warned_noarc_) {
+ warned_noarc_ = true;
+ KALDI_WARN << "No arc available in LM (unlikely to be correct "
+ "if a statistical language model); will not warn again";
+ }
+ arc->weight = Weight::Zero();
+ return lm_state; // doesn't really matter what we return here; will
+ // be pruned.
+ } else {
+ arc->weight = Times(arc->weight, lm_arc.weight);
+ arc->olabel = lm_arc.olabel; // probably will be the same.
+ return lm_arc.nextstate; // return the new LM state.
+ }
+ }
+ }
+
+ void ProcessEmitting(DecodableInterface *decodable, int32 frame) {
+ // Processes emitting arcs for one frame. Propagates from prev_toks_ to cur_toks_.
+ Elem *last_toks = toks_.Clear(); // swapping prev_toks_ / cur_toks_
+ Elem *best_elem = NULL;
+ BaseFloat adaptive_beam;
+ size_t tok_cnt;
+ BaseFloat cur_cutoff = GetCutoff(last_toks, &tok_cnt, &adaptive_beam, &best_elem);
+ PossiblyResizeHash(tok_cnt); // This makes sure the hash is always big enough.
+
+ BaseFloat next_cutoff = std::numeric_limits<BaseFloat>::infinity();
+ // pruning "online" before having seen all tokens
+
+ // First process the best token to get a hopefully
+ // reasonably tight bound on the next cutoff.
+ if (best_elem) {
+ PairId state_pair = best_elem->key;
+ StateId state = PairToState(state_pair), // state in "fst"
+ lm_state = PairToLmState(state_pair);
+ Token *tok = best_elem->val;
+ for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ Arc arc = aiter.Value();
+ if (arc.ilabel != 0) { // propagate..
+ PropagateLm(lm_state, &arc); // may affect "arc.weight".
+ // We don't need the return value (the new LM state).
+ arc.weight = Times(arc.weight,
+ Weight(-decodable->LogLikelihood(frame-1, arc.ilabel)));
+ BaseFloat new_weight = arc.weight.Value() + tok->tot_cost;
+ if (new_weight + adaptive_beam < next_cutoff)
+ next_cutoff = new_weight + adaptive_beam;
+ }
+ }
+ }
+
+ // the tokens are now owned here, in last_toks, and the hash is empty.
+ // 'owned' is a complex thing here; the point is we need to call DeleteElem
+ // on each elem 'e' to let toks_ know we're done with them.
+ for (Elem *e = last_toks, *e_tail; e != NULL; e = e_tail) {
+ // loop this way because we delete "e" as we go.
+ PairId state_pair = e->key;
+ StateId state = PairToState(state_pair),
+ lm_state = PairToLmState(state_pair);
+ Token *tok = e->val;
+ if (tok->tot_cost <= cur_cutoff) {
+ for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc_ref = aiter.Value();
+ if (arc_ref.ilabel != 0) { // propagate..
+ Arc arc(arc_ref);
+ StateId next_lm_state = PropagateLm(lm_state, &arc);
+ BaseFloat ac_cost = -decodable->LogLikelihood(frame-1, arc.ilabel),
+ graph_cost = arc.weight.Value(),
+ cur_cost = tok->tot_cost,
+ tot_cost = cur_cost + ac_cost + graph_cost;
+ if (tot_cost >= next_cutoff) continue;
+ else if (tot_cost + adaptive_beam < next_cutoff)
+ next_cutoff = tot_cost + adaptive_beam; // prune by best current token
+ PairId next_pair = ConstructPair(arc.nextstate, next_lm_state);
+ Elem *e_next = FindOrAddToken(next_pair, frame, tot_cost, true, NULL);
+ // true: emitting, NULL: no change indicator needed
+
+ // Add ForwardLink from tok to next_tok (put on head of list tok->links)
+ tok->links = new ForwardLink(e_next->val, arc.ilabel, arc.olabel,
+ graph_cost, ac_cost, tok->links);
+ }
+ } // for all arcs
+ }
+ e_tail = e->tail;
+ toks_.Delete(e); // delete Elem
+ }
+ }
+
+ void ProcessNonemitting(int32 frame) {
+ // note: "frame" is the same as emitting states just processed.
+
+ // Processes nonemitting arcs for one frame. Propagates within toks_.
+ // Note-- this queue structure is is not very optimal as
+ // it may cause us to process states unnecessarily (e.g. more than once),
+ // but in the baseline code, turning this vector into a set to fix this
+ // problem did not improve overall speed.
+
+ KALDI_ASSERT(queue_.empty());
+ BaseFloat best_cost = std::numeric_limits<BaseFloat>::infinity();
+ for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail) {
+ queue_.push_back(e);
+ // for pruning with current best token
+ best_cost = std::min(best_cost, static_cast<BaseFloat>(e->val->tot_cost));
+ }
+ if (queue_.empty()) {
+ if (!warned_) {
+ KALDI_ERR << "Error in ProcessNonemitting: no surviving tokens: frame is "
+ << frame;
+ warned_ = true;
+ }
+ }
+ BaseFloat cutoff = best_cost + config_.beam;
+
+ while (!queue_.empty()) {
+ const Elem *e = queue_.back();
+ queue_.pop_back();
+
+ PairId state_pair = e->key;
+ Token *tok = e->val; // would segfault if state not in
+ // toks_ but this can't happen.
+ BaseFloat cur_cost = tok->tot_cost;
+ if (cur_cost >= cutoff) // Don't bother processing successors.
+ continue;
+ StateId state = PairToState(state_pair),
+ lm_state = PairToLmState(state_pair);
+ // If "tok" has any existing forward links, delete them,
+ // because we're about to regenerate them. This is a kind
+ // of non-optimality (remember, this is the simple decoder),
+ // but since most states are emitting it's not a huge issue.
+ tok->DeleteForwardLinks(); // necessary when re-visiting
+ tok->links = NULL;
+ for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc_ref = aiter.Value();
+ if (arc_ref.ilabel == 0) { // propagate nonemitting only...
+ Arc arc(arc_ref);
+ StateId next_lm_state = PropagateLm(lm_state, &arc);
+ BaseFloat graph_cost = arc.weight.Value(),
+ tot_cost = cur_cost + graph_cost;
+ if (tot_cost < cutoff) {
+ bool changed;
+ PairId next_pair = ConstructPair(arc.nextstate, next_lm_state);
+ Elem *e_new = FindOrAddToken(next_pair, frame, tot_cost,
+ false, &changed); // false: non-emit
+
+ tok->links = new ForwardLink(e_new->val, 0, arc.olabel,
+ graph_cost, 0, tok->links);
+
+ // "changed" tells us whether the new token has a different
+ // cost from before, or is new [if so, add into queue].
+ if (changed) queue_.push_back(e_new);
+ }
+ }
+ } // for all arcs
+ } // while queue not empty
+ }
+
+
+ // HashList defined in ../util/hash-list.h. It actually allows us to maintain
+ // more than one list (e.g. for current and previous frames), but only one of
+ // them at a time can be indexed by StateId.
+ HashList<PairId, Token*> toks_;
+ std::vector<TokenList> active_toks_; // Lists of tokens, indexed by
+ // frame (members of TokenList are toks, must_prune_forward_links,
+ // must_prune_tokens).
+ std::vector<const Elem* > queue_; // temp variable used in ProcessNonemitting,
+ std::vector<BaseFloat> tmp_array_; // used in GetCutoff.
+ // make it class member to avoid internal new/delete.
+ const fst::Fst<fst::StdArc> &fst_;
+ fst::DeterministicOnDemandFst<fst::StdArc> *lm_diff_fst_;
+ LatticeBiglmFasterDecoderConfig config_;
+ bool warned_noarc_;
+ int32 num_toks_; // current total #toks allocated...
+ bool warned_;
+ bool final_active_; // use this to say whether we found active final tokens
+ // on the last frame.
+ std::map<Token*, BaseFloat> final_costs_; // A cache of final-costs
+ // of tokens on the last frame-- it's just convenient to store it this way.
+
+ // It might seem unclear why we call DeleteElems(toks_.Clear()).
+ // There are two separate cleanup tasks we need to do at when we start a new file.
+ // one is to delete the Token objects in the list; the other is to delete
+ // the Elem objects. toks_.Clear() just clears them from the hash and gives ownership
+ // to the caller, who then has to call toks_.Delete(e) for each one. It was designed
+ // this way for convenience in propagating tokens from one frame to the next.
+ void DeleteElems(Elem *list) {
+ for (Elem *e = list, *e_tail; e != NULL; e = e_tail) {
+ e_tail = e->tail;
+ toks_.Delete(e);
+ }
+ toks_.Clear();
+ }
+
+ void ClearActiveTokens() { // a cleanup routine, at utt end/begin
+ for (size_t i = 0; i < active_toks_.size(); i++) {
+ // Delete all tokens alive on this frame, and any forward
+ // links they may have.
+ for (Token *tok = active_toks_[i].toks; tok != NULL; ) {
+ tok->DeleteForwardLinks();
+ Token *next_tok = tok->next;
+ delete tok;
+ num_toks_--;
+ tok = next_tok;
+ }
+ }
+ active_toks_.clear();
+ KALDI_ASSERT(num_toks_ == 0);
+ }
+};
+
+} // end namespace kaldi.
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-decoder.cc b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-decoder.cc
new file mode 100644
index 000000000..6cd63d9aa
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-decoder.cc
@@ -0,0 +1,1061 @@
+// decoder/lattice-faster-decoder.cc
+
+// Copyright 2009-2012 Microsoft Corporation Mirko Hannemann
+// 2013-2018 Johns Hopkins University (Author: Daniel Povey)
+// 2014 Guoguo Chen
+// 2018 Zhehuai Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "decoder/lattice-faster-decoder.h"
+#include "lat/lattice-functions.h"
+
+namespace kaldi {
+int niter = 0;
+// instantiate this class once for each thing you have to decode.
+template <typename FST, typename Token>
+LatticeFasterDecoderTpl<FST, Token>::LatticeFasterDecoderTpl(
+ const FST &fst, const LatticeFasterDecoderConfig &config)
+ : fst_(&fst),
+ delete_fst_(false),
+ config_(config),
+ num_toks_(0),
+ token_pool_(config.memory_pool_tokens_block_size),
+ forward_link_pool_(config.memory_pool_links_block_size) {
+ config.Check();
+ toks_.SetSize(1000); // just so on the first frame we do something reasonable.
+}
+
+template <typename FST, typename Token>
+LatticeFasterDecoderTpl<FST, Token>::LatticeFasterDecoderTpl(
+ const LatticeFasterDecoderConfig &config, FST *fst)
+ : fst_(fst),
+ delete_fst_(true),
+ config_(config),
+ num_toks_(0),
+ token_pool_(config.memory_pool_tokens_block_size),
+ forward_link_pool_(config.memory_pool_links_block_size) {
+ config.Check();
+ toks_.SetSize(1000); // just so on the first frame we do something reasonable.
+}
+
+template <typename FST, typename Token>
+LatticeFasterDecoderTpl<FST, Token>::~LatticeFasterDecoderTpl() {
+ DeleteElems(toks_.Clear());
+ ClearActiveTokens();
+ if (delete_fst_) delete fst_;
+}
+
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::InitDecoding() {
+ // clean up from last time:
+ DeleteElems(toks_.Clear());
+ cost_offsets_.clear();
+ ClearActiveTokens();
+ warned_ = false;
+ num_toks_ = 0;
+ decoding_finalized_ = false;
+ final_costs_.clear();
+ StateId start_state = fst_->Start();
+ KALDI_ASSERT(start_state != fst::kNoStateId);
+ active_toks_.resize(1);
+ Token *start_tok =
+ new (token_pool_.Allocate()) Token(0.0, 0.0, NULL, NULL, NULL);
+ active_toks_[0].toks = start_tok;
+ toks_.Insert(start_state, start_tok);
+ num_toks_++;
+ ProcessNonemitting(config_.beam);
+}
+
+// Returns true if any kind of traceback is available (not necessarily from
+// a final state). It should only very rarely return false; this indicates
+// an unusual search error.
+template <typename FST, typename Token>
+bool LatticeFasterDecoderTpl<FST, Token>::Decode(DecodableInterface *decodable) {
+ InitDecoding();
+ // We use 1-based indexing for frames in this decoder (if you view it in
+ // terms of features), but note that the decodable object uses zero-based
+ // numbering, which we have to correct for when we call it.
+ AdvanceDecoding(decodable);
+ FinalizeDecoding();
+
+ // Returns true if we have any kind of traceback available (not necessarily
+ // to the end state; query ReachedFinal() for that).
+ return !active_toks_.empty() && active_toks_.back().toks != NULL;
+}
+
+
+// Outputs an FST corresponding to the single best path through the lattice.
+template <typename FST, typename Token>
+bool LatticeFasterDecoderTpl<FST, Token>::GetBestPath(Lattice *olat,
+ bool use_final_probs) const {
+ Lattice raw_lat;
+ GetRawLattice(&raw_lat, use_final_probs);
+ ShortestPath(raw_lat, olat);
+ return (olat->NumStates() != 0);
+}
+
+
+// Outputs an FST corresponding to the raw, state-level lattice
+template <typename FST, typename Token>
+bool LatticeFasterDecoderTpl<FST, Token>::GetRawLattice(
+ Lattice *ofst,
+ bool use_final_probs) const {
+ typedef LatticeArc Arc;
+ typedef Arc::StateId StateId;
+ typedef Arc::Weight Weight;
+ typedef Arc::Label Label;
+
+ // Note: you can't use the old interface (Decode()) if you want to
+ // get the lattice with use_final_probs = false. You'd have to do
+ // InitDecoding() and then AdvanceDecoding().
+ if (decoding_finalized_ && !use_final_probs)
+ KALDI_ERR << "You cannot call FinalizeDecoding() and then call "
+ << "GetRawLattice() with use_final_probs == false";
+
+ unordered_map<Token*, BaseFloat> final_costs_local;
+
+ const unordered_map<Token*, BaseFloat> &final_costs =
+ (decoding_finalized_ ? final_costs_ : final_costs_local);
+ if (!decoding_finalized_ && use_final_probs)
+ ComputeFinalCosts(&final_costs_local, NULL, NULL);
+
+ ofst->DeleteStates();
+ // num-frames plus one (since frames are one-based, and we have
+ // an extra frame for the start-state).
+ int32 num_frames = active_toks_.size() - 1;
+ KALDI_ASSERT(num_frames > 0);
+ const int32 bucket_count = num_toks_/2 + 3;
+ unordered_map<Token*, StateId> tok_map(bucket_count);
+ // First create all states.
+ std::vector<Token*> token_list;
+ for (int32 f = 0; f <= num_frames; f++) {
+ if (active_toks_[f].toks == NULL) {
+ KALDI_WARN << "GetRawLattice: no tokens active on frame " << f
+ << ": not producing lattice.\n";
+ return false;
+ }
+ TopSortTokens(active_toks_[f].toks, &token_list);
+ for (size_t i = 0; i < token_list.size(); i++)
+ if (token_list[i] != NULL)
+ tok_map[token_list[i]] = ofst->AddState();
+ }
+ // The next statement sets the start state of the output FST. Because we
+ // topologically sorted the tokens, state zero must be the start-state.
+ ofst->SetStart(0);
+
+ KALDI_VLOG(4) << "init:" << num_toks_/2 + 3 << " buckets:"
+ << tok_map.bucket_count() << " load:" << tok_map.load_factor()
+ << " max:" << tok_map.max_load_factor();
+ // Now create all arcs.
+ for (int32 f = 0; f <= num_frames; f++) {
+ for (Token *tok = active_toks_[f].toks; tok != NULL; tok = tok->next) {
+ StateId cur_state = tok_map[tok];
+ for (ForwardLinkT *l = tok->links;
+ l != NULL;
+ l = l->next) {
+ typename unordered_map<Token*, StateId>::const_iterator
+ iter = tok_map.find(l->next_tok);
+ StateId nextstate = iter->second;
+ KALDI_ASSERT(iter != tok_map.end());
+ BaseFloat cost_offset = 0.0;
+ if (l->ilabel != 0) { // emitting..
+ KALDI_ASSERT(f >= 0 && f < cost_offsets_.size());
+ cost_offset = cost_offsets_[f];
+ }
+ Arc arc(l->ilabel, l->olabel,
+ Weight(l->graph_cost, l->acoustic_cost - cost_offset),
+ nextstate);
+ ofst->AddArc(cur_state, arc);
+ }
+ if (f == num_frames) {
+ if (use_final_probs && !final_costs.empty()) {
+ typename unordered_map<Token*, BaseFloat>::const_iterator
+ iter = final_costs.find(tok);
+ if (iter != final_costs.end())
+ ofst->SetFinal(cur_state, LatticeWeight(iter->second, 0));
+ } else {
+ ofst->SetFinal(cur_state, LatticeWeight::One());
+ }
+ }
+ }
+ }
+ return (ofst->NumStates() > 0);
+}
+
+
+// This function is now deprecated, since now we do determinization from outside
+// the LatticeFasterDecoder class. Outputs an FST corresponding to the
+// lattice-determinized lattice (one path per word sequence).
+template <typename FST, typename Token>
+bool LatticeFasterDecoderTpl<FST, Token>::GetLattice(CompactLattice *ofst,
+ bool use_final_probs) const {
+ Lattice raw_fst;
+ GetRawLattice(&raw_fst, use_final_probs);
+ Invert(&raw_fst); // make it so word labels are on the input.
+ // (in phase where we get backward-costs).
+ fst::ILabelCompare<LatticeArc> ilabel_comp;
+ ArcSort(&raw_fst, ilabel_comp); // sort on ilabel; makes
+ // lattice-determinization more efficient.
+
+ fst::DeterminizeLatticePrunedOptions lat_opts;
+ lat_opts.max_mem = config_.det_opts.max_mem;
+
+ DeterminizeLatticePruned(raw_fst, config_.lattice_beam, ofst, lat_opts);
+ raw_fst.DeleteStates(); // Free memory-- raw_fst no longer needed.
+ Connect(ofst); // Remove unreachable states... there might be
+ // a small number of these, in some cases.
+ // Note: if something went wrong and the raw lattice was empty,
+ // we should still get to this point in the code without warnings or failures.
+ return (ofst->NumStates() != 0);
+}
+
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::PossiblyResizeHash(size_t num_toks) {
+ size_t new_sz = static_cast<size_t>(static_cast<BaseFloat>(num_toks)
+ * config_.hash_ratio);
+ if (new_sz > toks_.Size()) {
+ toks_.SetSize(new_sz);
+ }
+}
+
+/*
+ A note on the definition of extra_cost.
+
+ extra_cost is used in pruning tokens, to save memory.
+
+ extra_cost can be thought of as a beta (backward) cost assuming
+ we had set the betas on currently-active tokens to all be the negative
+ of the alphas for those tokens. (So all currently active tokens would
+ be on (tied) best paths).
+
+ We can use the extra_cost to accurately prune away tokens that we know will
+ never appear in the lattice. If the extra_cost is greater than the desired
+ lattice beam, the token would provably never appear in the lattice, so we can
+ prune away the token.
+
+ (Note: we don't update all the extra_costs every time we update a frame; we
+ only do it every 'config_.prune_interval' frames).
+ */
+
+// FindOrAddToken either locates a token in hash of toks_,
+// or if necessary inserts a new, empty token (i.e. with no forward links)
+// for the current frame. [note: it's inserted if necessary into hash toks_
+// and also into the singly linked list of tokens active on this frame
+// (whose head is at active_toks_[frame]).
+template <typename FST, typename Token>
+inline typename LatticeFasterDecoderTpl<FST, Token>::Elem*
+LatticeFasterDecoderTpl<FST, Token>::FindOrAddToken(
+ StateId state, int32 frame_plus_one, BaseFloat tot_cost,
+ Token *backpointer, bool *changed, StateId bias_lm_state) {
+ // Returns the Token pointer. Sets "changed" (if non-NULL) to true
+ // if the token was newly created or the cost changed.
+ KALDI_ASSERT(frame_plus_one < active_toks_.size());
+ Token *&toks = active_toks_[frame_plus_one].toks;
+ Elem *e_found = toks_.Insert(state, NULL);
+ if (e_found->val == NULL) { // no such token presently.
+ const BaseFloat extra_cost = 0.0;
+ // tokens on the currently final frame have zero extra_cost
+ // as any of them could end up
+ // on the winning path.
+ Token *new_tok = new (token_pool_.Allocate())
+ Token(tot_cost, extra_cost, NULL, toks, backpointer);
+ // NULL: no forward links yet
+ new_tok->bias_lm_state = bias_lm_state;
+ toks = new_tok;
+ num_toks_++;
+ e_found->val = new_tok;
+ if (changed) *changed = true;
+ return e_found;
+ } else {
+ Token *tok = e_found->val; // There is an existing Token for this state.
+ if (tok->tot_cost > tot_cost) { // replace old token
+ tok->bias_lm_state = bias_lm_state;
+ tok->tot_cost = tot_cost;
+ // SetBackpointer() just does tok->backpointer = backpointer in
+ // the case where Token == BackpointerToken, else nothing.
+ tok->SetBackpointer(backpointer);
+ // we don't allocate a new token, the old stays linked in active_toks_
+ // we only replace the tot_cost
+ // in the current frame, there are no forward links (and no extra_cost)
+ // only in ProcessNonemitting we have to delete forward links
+ // in case we visit a state for the second time
+ // those forward links, that lead to this replaced token before:
+ // they remain and will hopefully be pruned later (PruneForwardLinks...)
+ if (changed) *changed = true;
+ } else {
+ if (changed) *changed = false;
+ }
+ return e_found;
+ }
+}
+
+// prunes outgoing links for all tokens in active_toks_[frame]
+// it's called by PruneActiveTokens
+// all links, that have link_extra_cost > lattice_beam are pruned
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::PruneForwardLinks(
+ int32 frame_plus_one, bool *extra_costs_changed,
+ bool *links_pruned, BaseFloat delta) {
+ // delta is the amount by which the extra_costs must change
+ // If delta is larger, we'll tend to go back less far
+ // toward the beginning of the file.
+ // extra_costs_changed is set to true if extra_cost was changed for any token
+ // links_pruned is set to true if any link in any token was pruned
+
+ *extra_costs_changed = false;
+ *links_pruned = false;
+ KALDI_ASSERT(frame_plus_one >= 0 && frame_plus_one < active_toks_.size());
+ if (active_toks_[frame_plus_one].toks == NULL) { // empty list; should not happen.
+ if (!warned_) {
+ KALDI_WARN << "No tokens alive [doing pruning].. warning first "
+ "time only for each utterance\n";
+ warned_ = true;
+ }
+ }
+
+ // We have to iterate until there is no more change, because the links
+ // are not guaranteed to be in topological order.
+ bool changed = true; // difference new minus old extra cost >= delta ?
+ while (changed) {
+ changed = false;
+ for (Token *tok = active_toks_[frame_plus_one].toks;
+ tok != NULL; tok = tok->next) {
+ ForwardLinkT *link, *prev_link = NULL;
+ // will recompute tok_extra_cost for tok.
+ BaseFloat tok_extra_cost = std::numeric_limits<BaseFloat>::infinity();
+ // tok_extra_cost is the best (min) of link_extra_cost of outgoing links
+ for (link = tok->links; link != NULL; ) {
+ // See if we need to excise this link...
+ Token *next_tok = link->next_tok;
+ BaseFloat link_extra_cost = next_tok->extra_cost +
+ ((tok->tot_cost + link->acoustic_cost + link->graph_cost)
+ - next_tok->tot_cost); // difference in brackets is >= 0
+ // link_exta_cost is the difference in score between the best paths
+ // through link source state and through link destination state
+ KALDI_ASSERT(link_extra_cost == link_extra_cost); // check for NaN
+ if (link_extra_cost > config_.lattice_beam) { // excise link
+ ForwardLinkT *next_link = link->next;
+ if (prev_link != NULL) prev_link->next = next_link;
+ else tok->links = next_link;
+ forward_link_pool_.Free(link);
+ link = next_link; // advance link but leave prev_link the same.
+ *links_pruned = true;
+ } else { // keep the link and update the tok_extra_cost if needed.
+ if (link_extra_cost < 0.0) { // this is just a precaution.
+ //if (link_extra_cost < -0.01)
+ // KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
+ link_extra_cost = 0.0;
+ }
+ if (link_extra_cost < tok_extra_cost)
+ tok_extra_cost = link_extra_cost;
+ prev_link = link; // move to next link
+ link = link->next;
+ }
+ } // for all outgoing links
+ if (fabs(tok_extra_cost - tok->extra_cost) > delta)
+ changed = true; // difference new minus old is bigger than delta
+ tok->extra_cost = tok_extra_cost;
+ // will be +infinity or <= lattice_beam_.
+ // infinity indicates, that no forward link survived pruning
+ } // for all Token on active_toks_[frame]
+ if (changed) *extra_costs_changed = true;
+
+ // Note: it's theoretically possible that aggressive compiler
+ // optimizations could cause an infinite loop here for small delta and
+ // high-dynamic-range scores.
+ } // while changed
+}
+
+// PruneForwardLinksFinal is a version of PruneForwardLinks that we call
+// on the final frame. If there are final tokens active, it uses
+// the final-probs for pruning, otherwise it treats all tokens as final.
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::PruneForwardLinksFinal() {
+ KALDI_ASSERT(!active_toks_.empty());
+ int32 frame_plus_one = active_toks_.size() - 1;
+
+ if (active_toks_[frame_plus_one].toks == NULL) // empty list; should not happen.
+ KALDI_WARN << "No tokens alive at end of file";
+
+ typedef typename unordered_map<Token*, BaseFloat>::const_iterator IterType;
+ ComputeFinalCosts(&final_costs_, &final_relative_cost_, &final_best_cost_);
+ decoding_finalized_ = true;
+ // We call DeleteElems() as a nicety, not because it's really necessary;
+ // otherwise there would be a time, after calling PruneTokensForFrame() on the
+ // final frame, when toks_.GetList() or toks_.Clear() would contain pointers
+ // to nonexistent tokens.
+ DeleteElems(toks_.Clear());
+
+ // Now go through tokens on this frame, pruning forward links... may have to
+ // iterate a few times until there is no more change, because the list is not
+ // in topological order. This is a modified version of the code in
+ // PruneForwardLinks, but here we also take account of the final-probs.
+ bool changed = true;
+ BaseFloat delta = 1.0e-05;
+ while (changed) {
+ changed = false;
+ for (Token *tok = active_toks_[frame_plus_one].toks;
+ tok != NULL; tok = tok->next) {
+ ForwardLinkT *link, *prev_link = NULL;
+ // will recompute tok_extra_cost. It has a term in it that corresponds
+ // to the "final-prob", so instead of initializing tok_extra_cost to infinity
+ // below we set it to the difference between the (score+final_prob) of this token,
+ // and the best such (score+final_prob).
+ BaseFloat final_cost;
+ if (final_costs_.empty()) {
+ final_cost = 0.0;
+ } else {
+ IterType iter = final_costs_.find(tok);
+ if (iter != final_costs_.end())
+ final_cost = iter->second;
+ else
+ final_cost = std::numeric_limits<BaseFloat>::infinity();
+ }
+ BaseFloat tok_extra_cost = tok->tot_cost + final_cost - final_best_cost_;
+ // tok_extra_cost will be a "min" over either directly being final, or
+ // being indirectly final through other links, and the loop below may
+ // decrease its value:
+ for (link = tok->links; link != NULL; ) {
+ // See if we need to excise this link...
+ Token *next_tok = link->next_tok;
+ BaseFloat link_extra_cost = next_tok->extra_cost +
+ ((tok->tot_cost + link->acoustic_cost + link->graph_cost)
+ - next_tok->tot_cost);
+ if (link_extra_cost > config_.lattice_beam) { // excise link
+ ForwardLinkT *next_link = link->next;
+ if (prev_link != NULL) prev_link->next = next_link;
+ else tok->links = next_link;
+ forward_link_pool_.Free(link);
+ link = next_link; // advance link but leave prev_link the same.
+ } else { // keep the link and update the tok_extra_cost if needed.
+ if (link_extra_cost < 0.0) { // this is just a precaution.
+ //if (link_extra_cost < -0.01)
+ // KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
+ link_extra_cost = 0.0;
+ }
+ if (link_extra_cost < tok_extra_cost)
+ tok_extra_cost = link_extra_cost;
+ prev_link = link;
+ link = link->next;
+ }
+ }
+ // prune away tokens worse than lattice_beam above best path. This step
+ // was not necessary in the non-final case because then, this case
+ // showed up as having no forward links. Here, the tok_extra_cost has
+ // an extra component relating to the final-prob.
+ if (tok_extra_cost > config_.lattice_beam)
+ tok_extra_cost = std::numeric_limits<BaseFloat>::infinity();
+ // to be pruned in PruneTokensForFrame
+
+ if (!ApproxEqual(tok->extra_cost, tok_extra_cost, delta))
+ changed = true;
+ tok->extra_cost = tok_extra_cost; // will be +infinity or <= lattice_beam_.
+ }
+ } // while changed
+}
+
+template <typename FST, typename Token>
+BaseFloat LatticeFasterDecoderTpl<FST, Token>::FinalRelativeCost() const {
+ if (!decoding_finalized_) {
+ BaseFloat relative_cost;
+ ComputeFinalCosts(NULL, &relative_cost, NULL);
+ return relative_cost;
+ } else {
+ // we're not allowed to call that function if FinalizeDecoding() has
+ // been called; return a cached value.
+ return final_relative_cost_;
+ }
+}
+
+
+// Prune away any tokens on this frame that have no forward links.
+// [we don't do this in PruneForwardLinks because it would give us
+// a problem with dangling pointers].
+// It's called by PruneActiveTokens if any forward links have been pruned
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::PruneTokensForFrame(int32 frame_plus_one) {
+ KALDI_ASSERT(frame_plus_one >= 0 && frame_plus_one < active_toks_.size());
+ Token *&toks = active_toks_[frame_plus_one].toks;
+ if (toks == NULL)
+ KALDI_WARN << "No tokens alive [doing pruning]";
+ Token *tok, *next_tok, *prev_tok = NULL;
+ for (tok = toks; tok != NULL; tok = next_tok) {
+ next_tok = tok->next;
+ if (tok->extra_cost == std::numeric_limits<BaseFloat>::infinity()) {
+ // token is unreachable from end of graph; (no forward links survived)
+ // excise tok from list and delete tok.
+ if (prev_tok != NULL) prev_tok->next = tok->next;
+ else toks = tok->next;
+ token_pool_.Free(tok);
+ num_toks_--;
+ } else { // fetch next Token
+ prev_tok = tok;
+ }
+ }
+}
+
+// Go backwards through still-alive tokens, pruning them, starting not from
+// the current frame (where we want to keep all tokens) but from the frame before
+// that. We go backwards through the frames and stop when we reach a point
+// where the delta-costs are not changing (and the delta controls when we consider
+// a cost to have "not changed").
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::PruneActiveTokens(BaseFloat delta) {
+ int32 cur_frame_plus_one = NumFramesDecoded();
+ int32 num_toks_begin = num_toks_;
+ // The index "f" below represents a "frame plus one", i.e. you'd have to subtract
+ // one to get the corresponding index for the decodable object.
+ for (int32 f = cur_frame_plus_one - 1; f >= 0; f--) {
+ // Reason why we need to prune forward links in this situation:
+ // (1) we have never pruned them (new TokenList)
+ // (2) we have not yet pruned the forward links to the next f,
+ // after any of those tokens have changed their extra_cost.
+ if (active_toks_[f].must_prune_forward_links) {
+ bool extra_costs_changed = false, links_pruned = false;
+ PruneForwardLinks(f, &extra_costs_changed, &links_pruned, delta);
+ if (extra_costs_changed && f > 0) // any token has changed extra_cost
+ active_toks_[f-1].must_prune_forward_links = true;
+ if (links_pruned) // any link was pruned
+ active_toks_[f].must_prune_tokens = true;
+ active_toks_[f].must_prune_forward_links = false; // job done
+ }
+ if (f+1 < cur_frame_plus_one && // except for last f (no forward links)
+ active_toks_[f+1].must_prune_tokens) {
+ PruneTokensForFrame(f+1);
+ active_toks_[f+1].must_prune_tokens = false;
+ }
+ }
+ KALDI_VLOG(4) << "PruneActiveTokens: pruned tokens from " << num_toks_begin
+ << " to " << num_toks_;
+}
+
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::ComputeFinalCosts(
+ unordered_map<Token*, BaseFloat> *final_costs,
+ BaseFloat *final_relative_cost,
+ BaseFloat *final_best_cost) const {
+ KALDI_ASSERT(!decoding_finalized_);
+ if (final_costs != NULL)
+ final_costs->clear();
+ const Elem *final_toks = toks_.GetList();
+ BaseFloat infinity = std::numeric_limits<BaseFloat>::infinity();
+ BaseFloat best_cost = infinity,
+ best_cost_with_final = infinity;
+
+ while (final_toks != NULL) {
+ StateId state = final_toks->key;
+ Token *tok = final_toks->val;
+ const Elem *next = final_toks->tail;
+ BaseFloat final_cost = fst_->Final(state).Value();
+ BaseFloat cost = tok->tot_cost,
+ cost_with_final = cost + final_cost;
+ best_cost = std::min(cost, best_cost);
+ best_cost_with_final = std::min(cost_with_final, best_cost_with_final);
+ if (final_costs != NULL && final_cost != infinity)
+ (*final_costs)[tok] = final_cost;
+ final_toks = next;
+ }
+ if (final_relative_cost != NULL) {
+ if (best_cost == infinity && best_cost_with_final == infinity) {
+ // Likely this will only happen if there are no tokens surviving.
+ // This seems the least bad way to handle it.
+ *final_relative_cost = infinity;
+ } else {
+ *final_relative_cost = best_cost_with_final - best_cost;
+ }
+ }
+ if (final_best_cost != NULL) {
+ if (best_cost_with_final != infinity) { // final-state exists.
+ *final_best_cost = best_cost_with_final;
+ } else { // no final-state exists.
+ *final_best_cost = best_cost;
+ }
+ }
+}
+
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::AdvanceDecoding(DecodableInterface *decodable,
+ int32 max_num_frames) {
+ if (std::is_same<FST, fst::Fst<fst::StdArc> >::value) {
+ // if the type 'FST' is the FST base-class, then see if the FST type of fst_
+ // is actually VectorFst or ConstFst. If so, call the AdvanceDecoding()
+ // function after casting *this to the more specific type.
+ if (fst_->Type() == "const") {
+ LatticeFasterDecoderTpl<fst::ConstFst<fst::StdArc>, Token> *this_cast =
+ reinterpret_cast<LatticeFasterDecoderTpl<fst::ConstFst<fst::StdArc>, Token>* >(this);
+ this_cast->AdvanceDecoding(decodable, max_num_frames);
+ return;
+ } else if (fst_->Type() == "vector") {
+ LatticeFasterDecoderTpl<fst::VectorFst<fst::StdArc>, Token> *this_cast =
+ reinterpret_cast<LatticeFasterDecoderTpl<fst::VectorFst<fst::StdArc>, Token>* >(this);
+ this_cast->AdvanceDecoding(decodable, max_num_frames);
+ return;
+ }
+ }
+
+
+ KALDI_ASSERT(!active_toks_.empty() && !decoding_finalized_ &&
+ "You must call InitDecoding() before AdvanceDecoding");
+ int32 num_frames_ready = decodable->NumFramesReady();
+ // num_frames_ready must be >= num_frames_decoded, or else
+ // the number of frames ready must have decreased (which doesn't
+ // make sense) or the decodable object changed between calls
+ // (which isn't allowed).
+ KALDI_ASSERT(num_frames_ready >= NumFramesDecoded());
+ int32 target_frames_decoded = num_frames_ready;
+ if (max_num_frames >= 0)
+ target_frames_decoded = std::min(target_frames_decoded,
+ NumFramesDecoded() + max_num_frames);
+ while (NumFramesDecoded() < target_frames_decoded) {
+ if (NumFramesDecoded() % config_.prune_interval == 0) {
+ PruneActiveTokens(config_.lattice_beam * config_.prune_scale);
+ }
+ BaseFloat cost_cutoff = ProcessEmitting(decodable);
+ ProcessNonemitting(cost_cutoff);
+ }
+}
+
+// FinalizeDecoding() is a version of PruneActiveTokens that we call
+// (optionally) on the final frame. Takes into account the final-prob of
+// tokens. This function used to be called PruneActiveTokensFinal().
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::FinalizeDecoding() {
+ int32 final_frame_plus_one = NumFramesDecoded();
+ int32 num_toks_begin = num_toks_;
+ // PruneForwardLinksFinal() prunes final frame (with final-probs), and
+ // sets decoding_finalized_.
+ PruneForwardLinksFinal();
+ for (int32 f = final_frame_plus_one - 1; f >= 0; f--) {
+ bool b1, b2; // values not used.
+ BaseFloat dontcare = 0.0; // delta of zero means we must always update
+ PruneForwardLinks(f, &b1, &b2, dontcare);
+ PruneTokensForFrame(f + 1);
+ }
+ PruneTokensForFrame(0);
+ KALDI_VLOG(4) << "pruned tokens from " << num_toks_begin
+ << " to " << num_toks_;
+}
+
+/// Gets the weight cutoff. Also counts the active tokens.
+template <typename FST, typename Token>
+BaseFloat LatticeFasterDecoderTpl<FST, Token>::GetCutoff(Elem *list_head, size_t *tok_count,
+ BaseFloat *adaptive_beam, Elem **best_elem) {
+ BaseFloat best_weight = std::numeric_limits<BaseFloat>::infinity();
+ // positive == high cost == bad.
+ size_t count = 0;
+ if (config_.max_active == std::numeric_limits<int32>::max() &&
+ config_.min_active == 0) {
+ for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
+ BaseFloat w = static_cast<BaseFloat>(e->val->tot_cost);
+ if (w < best_weight) {
+ best_weight = w;
+ if (best_elem) *best_elem = e;
+ }
+ }
+ if (tok_count != NULL) *tok_count = count;
+ if (adaptive_beam != NULL) *adaptive_beam = config_.beam;
+ return best_weight + config_.beam;
+ } else {
+ tmp_array_.clear();
+ for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
+ BaseFloat w = e->val->tot_cost;
+ tmp_array_.push_back(w);
+ if (w < best_weight) {
+ best_weight = w;
+ if (best_elem) *best_elem = e;
+ }
+ }
+ if (tok_count != NULL) *tok_count = count;
+
+ BaseFloat beam_cutoff = best_weight + config_.beam,
+ min_active_cutoff = std::numeric_limits<BaseFloat>::infinity(),
+ max_active_cutoff = std::numeric_limits<BaseFloat>::infinity();
+
+ KALDI_VLOG(6) << "Number of tokens active on frame " << NumFramesDecoded()
+ << " is " << tmp_array_.size();
+
+ if (tmp_array_.size() > static_cast<size_t>(config_.max_active)) {
+ std::nth_element(tmp_array_.begin(),
+ tmp_array_.begin() + config_.max_active,
+ tmp_array_.end());
+ max_active_cutoff = tmp_array_[config_.max_active];
+ }
+ if (max_active_cutoff < beam_cutoff) { // max_active is tighter than beam.
+ if (adaptive_beam)
+ *adaptive_beam = max_active_cutoff - best_weight + config_.beam_delta;
+ return max_active_cutoff;
+ }
+ if (tmp_array_.size() > static_cast<size_t>(config_.min_active)) {
+ if (config_.min_active == 0) min_active_cutoff = best_weight;
+ else {
+ std::nth_element(tmp_array_.begin(),
+ tmp_array_.begin() + config_.min_active,
+ tmp_array_.size() > static_cast<size_t>(config_.max_active) ?
+ tmp_array_.begin() + config_.max_active :
+ tmp_array_.end());
+ min_active_cutoff = tmp_array_[config_.min_active];
+ }
+ }
+ if (min_active_cutoff > beam_cutoff) { // min_active is looser than beam.
+ if (adaptive_beam)
+ *adaptive_beam = min_active_cutoff - best_weight + config_.beam_delta;
+ return min_active_cutoff;
+ } else {
+ *adaptive_beam = config_.beam;
+ return beam_cutoff;
+ }
+ }
+}
+
+template <typename FST, typename Token>
+BaseFloat LatticeFasterDecoderTpl<FST, Token>::ProcessEmitting(
+ DecodableInterface *decodable) {
+ KALDI_ASSERT(active_toks_.size() > 0);
+ int32 frame = active_toks_.size() - 1; // frame is the frame-index
+ // (zero-based) used to get likelihoods
+ // from the decodable object.
+ active_toks_.resize(active_toks_.size() + 1);
+
+ Elem *final_toks = toks_.Clear(); // analogous to swapping prev_toks_ / cur_toks_
+ // in simple-decoder.h. Removes the Elems from
+ // being indexed in the hash in toks_.
+ Elem *best_elem = NULL;
+ BaseFloat adaptive_beam;
+ size_t tok_cnt;
+ BaseFloat cur_cutoff = GetCutoff(final_toks, &tok_cnt, &adaptive_beam, &best_elem);
+ KALDI_VLOG(6) << "Adaptive beam on frame " << NumFramesDecoded() << " is "
+ << adaptive_beam;
+
+ PossiblyResizeHash(tok_cnt); // This makes sure the hash is always big enough.
+
+ BaseFloat next_cutoff = std::numeric_limits<BaseFloat>::infinity();
+ // pruning "online" before having seen all tokens
+
+ BaseFloat cost_offset = 0.0; // Used to keep probabilities in a good
+ // dynamic range.
+
+
+ // First process the best token to get a hopefully
+ // reasonably tight bound on the next cutoff. The only
+ // products of the next block are "next_cutoff" and "cost_offset".
+ if (best_elem) {
+ StateId state = best_elem->key;
+ Token *tok = best_elem->val;
+ cost_offset = - tok->tot_cost;
+ for (fst::ArcIterator<FST> aiter(*fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0) { // propagate..
+ if (arc.nextstate == state) continue;
+ BaseFloat new_weight = arc.weight.Value() + cost_offset -
+ decodable->LogLikelihood(frame, arc.ilabel) + tok->tot_cost;
+
+ if (new_weight + adaptive_beam < next_cutoff)
+ next_cutoff = new_weight + adaptive_beam;
+ }
+ }
+ }
+
+ // Store the offset on the acoustic likelihoods that we're applying.
+ // Could just do cost_offsets_.push_back(cost_offset), but we
+ // do it this way as it's more robust to future code changes.
+ cost_offsets_.resize(frame + 1, 0.0);
+ cost_offsets_[frame] = cost_offset;
+
+ // the tokens are now owned here, in final_toks, and the hash is empty.
+ // 'owned' is a complex thing here; the point is we need to call DeleteElem
+ // on each elem 'e' to let toks_ know we're done with them.
+ for (Elem *e = final_toks, *e_tail; e != NULL; e = e_tail) {
+ // loop this way because we delete "e" as we go.
+ StateId state = e->key;
+ Token *tok = e->val;
+
+ if (tok->tot_cost <= cur_cutoff) {
+ for (fst::ArcIterator<FST> aiter(*fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0) { // propagate..
+ if (arc.nextstate == state) continue;
+ StateId new_bias_state = 0;
+ BaseFloat ac_cost = cost_offset -
+ decodable->LogLikelihood(frame, arc.ilabel),
+ graph_cost = arc.weight.Value(),
+ cur_cost = tok->tot_cost,
+ tot_cost = cur_cost + ac_cost + graph_cost;
+
+
+ if (bias_lm_) {
+ float bias_lm_score = 0.0f;
+ int frm = frame;
+ int stat = state;
+ int ilab = arc.ilabel-1;
+ if (arc.ilabel - 1 == 0) {
+ new_bias_state = tok->bias_lm_state;
+ } else {
+ bias_lm_score = bias_lm_->BiasLmScore(tok->bias_lm_state,
+ arc.ilabel - 1, new_bias_state);
+ }
+ graph_cost -= bias_lm_score;
+ tot_cost -= bias_lm_score;
+ }
+
+ if (tot_cost >= next_cutoff) {
+ continue;
+ } else if (tot_cost + adaptive_beam < next_cutoff) {
+ next_cutoff = tot_cost + adaptive_beam; // prune by best current token
+ }
+ // Note: the frame indexes into active_toks_ are one-based,
+ // hence the + 1.
+ Elem *e_next = FindOrAddToken(arc.nextstate,
+ frame + 1, tot_cost, tok, NULL, new_bias_state);
+ // NULL: no change indicator needed
+
+ // Add ForwardLink from tok to next_tok (put on head of list tok->links)
+ tok->links = new (forward_link_pool_.Allocate())
+ ForwardLinkT(e_next->val, arc.ilabel, arc.olabel, graph_cost,
+ ac_cost, tok->links);
+ }
+ } // for all arcs
+ }
+ e_tail = e->tail;
+ toks_.Delete(e); // delete Elem
+ }
+ return next_cutoff;
+}
+
+template <typename FST, typename Token>
+std::string LatticeFasterDecoderTpl<FST, Token>::GetTokResult(Token *tok) {
+ if (!tok) { return ""; }
+ std::string res;
+ ForwardLinkT* link;
+ std::vector<int> phn_id;
+ tok->GetLabelSeq(tok, phn_id);
+ for (int i = 0; i < phn_id.size(); i++) {
+ res = bias_lm_->GetPhoneLabel(phn_id[i]) + res;
+ }
+ return res;
+}
+
+// static inline
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::DeleteForwardLinks(Token *tok) {
+ ForwardLinkT *l = tok->links, *m;
+ while (l != NULL) {
+ m = l->next;
+ forward_link_pool_.Free(l);
+ l = m;
+ }
+ tok->links = NULL;
+}
+
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::ProcessNonemitting(BaseFloat cutoff) {
+ KALDI_ASSERT(!active_toks_.empty());
+ int32 frame = static_cast<int32>(active_toks_.size()) - 2;
+ // Note: "frame" is the time-index we just processed, or -1 if
+ // we are processing the nonemitting transitions before the
+ // first frame (called from InitDecoding()).
+
+ // Processes nonemitting arcs for one frame. Propagates within toks_.
+ // Note-- this queue structure is not very optimal as
+ // it may cause us to process states unnecessarily (e.g. more than once),
+ // but in the baseline code, turning this vector into a set to fix this
+ // problem did not improve overall speed.
+
+ KALDI_ASSERT(queue_.empty());
+
+ if (toks_.GetList() == NULL) {
+ if (!warned_) {
+ KALDI_WARN << "Error, no surviving tokens: frame is " << frame;
+ warned_ = true;
+ }
+ }
+
+ for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail) {
+ StateId state = e->key;
+ if (fst_->NumInputEpsilons(state) != 0)
+ queue_.push_back(e);
+ }
+
+ while (!queue_.empty()) {
+ const Elem *e = queue_.back();
+ queue_.pop_back();
+
+ StateId state = e->key;
+ Token *tok = e->val; // would segfault if e is a NULL pointer but this can't happen.
+ BaseFloat cur_cost = tok->tot_cost;
+ if (cur_cost >= cutoff) // Don't bother processing successors.
+ continue;
+ // If "tok" has any existing forward links, delete them,
+ // because we're about to regenerate them. This is a kind
+ // of non-optimality (remember, this is the simple decoder),
+ // but since most states are emitting it's not a huge issue.
+ DeleteForwardLinks(tok); // necessary when re-visiting
+ tok->links = NULL;
+ for (fst::ArcIterator<FST> aiter(*fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel == 0) { // propagate nonemitting only...
+ BaseFloat graph_cost = arc.weight.Value(),
+ tot_cost = cur_cost + graph_cost;
+ if (tot_cost < cutoff) {
+ bool changed;
+
+ Elem *e_new = FindOrAddToken(arc.nextstate, frame + 1, tot_cost,
+ tok, &changed);
+ if (bias_lm_ && changed) {
+ e_new->val->bias_lm_state = tok->bias_lm_state;
+ }
+
+ tok->links = new (forward_link_pool_.Allocate()) ForwardLinkT(
+ e_new->val, 0, arc.olabel, graph_cost, 0, tok->links);
+
+ // "changed" tells us whether the new token has a different
+ // cost from before, or is new [if so, add into queue].
+ if (changed && fst_->NumInputEpsilons(arc.nextstate) != 0)
+ queue_.push_back(e_new);
+ }
+ }
+ } // for all arcs
+ } // while queue not empty
+}
+
+
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::DeleteElems(Elem *list) {
+ for (Elem *e = list, *e_tail; e != NULL; e = e_tail) {
+ e_tail = e->tail;
+ toks_.Delete(e);
+ }
+}
+
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::ClearActiveTokens() { // a cleanup routine, at utt end/begin
+ for (size_t i = 0; i < active_toks_.size(); i++) {
+ // Delete all tokens alive on this frame, and any forward
+ // links they may have.
+ for (Token *tok = active_toks_[i].toks; tok != NULL; ) {
+ DeleteForwardLinks(tok);
+ Token *next_tok = tok->next;
+ token_pool_.Free(tok);
+ num_toks_--;
+ tok = next_tok;
+ }
+ }
+ active_toks_.clear();
+ KALDI_ASSERT(num_toks_ == 0);
+}
+
+// static
+template <typename FST, typename Token>
+void LatticeFasterDecoderTpl<FST, Token>::TopSortTokens(
+ Token *tok_list, std::vector<Token*> *topsorted_list) {
+ unordered_map<Token*, int32> token2pos;
+ typedef typename unordered_map<Token*, int32>::iterator IterType;
+ int32 num_toks = 0;
+ for (Token *tok = tok_list; tok != NULL; tok = tok->next)
+ num_toks++;
+ int32 cur_pos = 0;
+ // We assign the tokens numbers num_toks - 1, ... , 2, 1, 0.
+ // This is likely to be in closer to topological order than
+ // if we had given them ascending order, because of the way
+ // new tokens are put at the front of the list.
+ for (Token *tok = tok_list; tok != NULL; tok = tok->next)
+ token2pos[tok] = num_toks - ++cur_pos;
+
+ unordered_set<Token*> reprocess;
+
+ for (IterType iter = token2pos.begin(); iter != token2pos.end(); ++iter) {
+ Token *tok = iter->first;
+ int32 pos = iter->second;
+ for (ForwardLinkT *link = tok->links; link != NULL; link = link->next) {
+ if (link->ilabel == 0) {
+ // We only need to consider epsilon links, since non-epsilon links
+ // transition between frames and this function only needs to sort a list
+ // of tokens from a single frame.
+ IterType following_iter = token2pos.find(link->next_tok);
+ if (following_iter != token2pos.end()) { // another token on this frame,
+ // so must consider it.
+ int32 next_pos = following_iter->second;
+ if (next_pos < pos) { // reassign the position of the next Token.
+ following_iter->second = cur_pos++;
+ reprocess.insert(link->next_tok);
+ }
+ }
+ }
+ }
+ // In case we had previously assigned this token to be reprocessed, we can
+ // erase it from that set because it's "happy now" (we just processed it).
+ reprocess.erase(tok);
+ }
+
+ size_t max_loop = 1000000, loop_count; // max_loop is to detect epsilon cycles.
+ for (loop_count = 0;
+ !reprocess.empty() && loop_count < max_loop; ++loop_count) {
+ std::vector<Token*> reprocess_vec;
+ for (typename unordered_set<Token*>::iterator iter = reprocess.begin();
+ iter != reprocess.end(); ++iter)
+ reprocess_vec.push_back(*iter);
+ reprocess.clear();
+ for (typename std::vector<Token*>::iterator iter = reprocess_vec.begin();
+ iter != reprocess_vec.end(); ++iter) {
+ Token *tok = *iter;
+ int32 pos = token2pos[tok];
+ // Repeat the processing we did above (for comments, see above).
+ for (ForwardLinkT *link = tok->links; link != NULL; link = link->next) {
+ if (link->ilabel == 0) {
+ IterType following_iter = token2pos.find(link->next_tok);
+ if (following_iter != token2pos.end()) {
+ int32 next_pos = following_iter->second;
+ if (next_pos < pos) {
+ following_iter->second = cur_pos++;
+ reprocess.insert(link->next_tok);
+ }
+ }
+ }
+ }
+ }
+ }
+ KALDI_ASSERT(loop_count < max_loop && "Epsilon loops exist in your decoding "
+ "graph (this is not allowed!)");
+
+ topsorted_list->clear();
+ topsorted_list->resize(cur_pos, NULL); // create a list with NULLs in between.
+ for (IterType iter = token2pos.begin(); iter != token2pos.end(); ++iter)
+ (*topsorted_list)[iter->second] = iter->first;
+}
+
+// Instantiate the template for the combination of token types and FST types
+// that we'll need.
+template class LatticeFasterDecoderTpl<fst::Fst<fst::StdArc>, decoder::StdToken>;
+template class LatticeFasterDecoderTpl<fst::VectorFst<fst::StdArc>, decoder::StdToken >;
+template class LatticeFasterDecoderTpl<fst::ConstFst<fst::StdArc>, decoder::StdToken >;
+
+//template class LatticeFasterDecoderTpl<fst::ConstGrammarFst, decoder::StdToken>;
+//template class LatticeFasterDecoderTpl<fst::VectorGrammarFst, decoder::StdToken>;
+
+template class LatticeFasterDecoderTpl<fst::Fst<fst::StdArc> , decoder::BackpointerToken>;
+template class LatticeFasterDecoderTpl<fst::VectorFst<fst::StdArc>, decoder::BackpointerToken >;
+template class LatticeFasterDecoderTpl<fst::ConstFst<fst::StdArc>, decoder::BackpointerToken >;
+//template class LatticeFasterDecoderTpl<fst::ConstGrammarFst, decoder::BackpointerToken>;
+//template class LatticeFasterDecoderTpl<fst::VectorGrammarFst, decoder::BackpointerToken>;
+
+
+} // end namespace kaldi.
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-decoder.h b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-decoder.h
new file mode 100644
index 000000000..b752e1783
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-decoder.h
@@ -0,0 +1,597 @@
+// decoder/lattice-faster-decoder.h
+
+// Copyright 2009-2013 Microsoft Corporation; Mirko Hannemann;
+// 2013-2014 Johns Hopkins University (Author: Daniel Povey)
+// 2014 Guoguo Chen
+// 2018 Zhehuai Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_DECODER_LATTICE_FASTER_DECODER_H_
+#define KALDI_DECODER_LATTICE_FASTER_DECODER_H_
+
+//#include "decoder/grammar-fst.h"
+#include "fst/fstlib.h"
+#include "fst/memory.h"
+#include "fstext/fstext-lib.h"
+#include "itf/decodable-itf.h"
+#include "lat/determinize-lattice-pruned.h"
+#include "lat/kaldi-lattice.h"
+#include "util/hash-list.h"
+#include "util/stl-utils.h"
+#include "bias-lm.h"
+
+namespace kaldi {
+
+struct LatticeFasterDecoderConfig {
+ BaseFloat beam;
+ int32 max_active;
+ int32 min_active;
+ BaseFloat lattice_beam;
+ int32 prune_interval;
+ bool determinize_lattice; // not inspected by this class... used in
+ // command-line program.
+ BaseFloat beam_delta;
+ BaseFloat hash_ratio;
+ // Note: we don't make prune_scale configurable on the command line, it's not
+ // a very important parameter. It affects the algorithm that prunes the
+ // tokens as we go.
+ BaseFloat prune_scale;
+
+ // Number of elements in the block for Token and ForwardLink memory
+ // pool allocation.
+ int32 memory_pool_tokens_block_size;
+ int32 memory_pool_links_block_size;
+
+ // Most of the options inside det_opts are not actually queried by the
+ // LatticeFasterDecoder class itself, but by the code that calls it, for
+ // example in the function DecodeUtteranceLatticeFaster.
+ fst::DeterminizeLatticePhonePrunedOptions det_opts;
+
+ LatticeFasterDecoderConfig(float glob_beam, float lat_beam)
+ : beam(glob_beam),
+ max_active(std::numeric_limits<int32>::max()),
+ min_active(200),
+ lattice_beam(lat_beam),
+ prune_interval(25),
+ determinize_lattice(true),
+ beam_delta(0.5),
+ hash_ratio(2.0),
+ prune_scale(0.1),
+ memory_pool_tokens_block_size(1 << 8),
+ memory_pool_links_block_size(1 << 8) {}
+
+ LatticeFasterDecoderConfig()
+ : beam(3.0),
+ max_active(std::numeric_limits<int32>::max()),
+ min_active(200),
+ lattice_beam(3.0),
+ prune_interval(25),
+ determinize_lattice(true),
+ beam_delta(0.5),
+ hash_ratio(2.0),
+ prune_scale(0.1),
+ memory_pool_tokens_block_size(1 << 8),
+ memory_pool_links_block_size(1 << 8) {}
+ void Register(OptionsItf *opts) {
+ det_opts.Register(opts);
+ opts->Register("beam", &beam, "Decoding beam. Larger->slower, more accurate.");
+ opts->Register("max-active", &max_active, "Decoder max active states. Larger->slower; "
+ "more accurate");
+ opts->Register("min-active", &min_active, "Decoder minimum #active states.");
+ opts->Register("lattice-beam", &lattice_beam, "Lattice generation beam. Larger->slower, "
+ "and deeper lattices");
+ opts->Register("prune-interval", &prune_interval, "Interval (in frames) at "
+ "which to prune tokens");
+ opts->Register("determinize-lattice", &determinize_lattice, "If true, "
+ "determinize the lattice (lattice-determinization, keeping only "
+ "best pdf-sequence for each word-sequence).");
+ opts->Register("beam-delta", &beam_delta, "Increment used in decoding-- this "
+ "parameter is obscure and relates to a speedup in the way the "
+ "max-active constraint is applied. Larger is more accurate.");
+ opts->Register("hash-ratio", &hash_ratio, "Setting used in decoder to "
+ "control hash behavior");
+ opts->Register("memory-pool-tokens-block-size", &memory_pool_tokens_block_size,
+ "Memory pool block size suggestion for storing tokens (in elements). "
+ "Smaller uses less memory but increases cache misses.");
+ opts->Register("memory-pool-links-block-size", &memory_pool_links_block_size,
+ "Memory pool block size suggestion for storing links (in elements). "
+ "Smaller uses less memory but increases cache misses.");
+ }
+ void Check() const {
+ KALDI_ASSERT(beam > 0.0 && max_active > 1 && lattice_beam > 0.0
+ && min_active <= max_active
+ && prune_interval > 0 && beam_delta > 0.0 && hash_ratio >= 1.0
+ && prune_scale > 0.0 && prune_scale < 1.0);
+ }
+};
+
+namespace decoder {
+// We will template the decoder on the token type as well as the FST type; this
+// is a mechanism so that we can use the same underlying decoder code for
+// versions of the decoder that support quickly getting the best path
+// (LatticeFasterOnlineDecoder, see lattice-faster-online-decoder.h) and also
+// those that do not (LatticeFasterDecoder).
+
+
+// ForwardLinks are the links from a token to a token on the next frame.
+// or sometimes on the current frame (for input-epsilon links).
+template <typename Token>
+struct ForwardLink {
+ using Label = fst::StdArc::Label;
+
+ Token *next_tok; // the next token [or NULL if represents final-state]
+ Label ilabel; // ilabel on arc
+ Label olabel; // olabel on arc
+ BaseFloat graph_cost; // graph cost of traversing arc (contains LM, etc.)
+ BaseFloat acoustic_cost; // acoustic cost (pre-scaled) of traversing arc
+ ForwardLink *next; // next in singly-linked list of forward arcs (arcs
+ // in the state-level lattice) from a token.
+ inline ForwardLink(Token *next_tok, Label ilabel, Label olabel,
+ BaseFloat graph_cost, BaseFloat acoustic_cost,
+ ForwardLink *next):
+ next_tok(next_tok), ilabel(ilabel), olabel(olabel),
+ graph_cost(graph_cost), acoustic_cost(acoustic_cost),
+ next(next) { }
+};
+
+
+struct StdToken {
+ using ForwardLinkT = ForwardLink<StdToken>;
+ using Token = StdToken;
+
+ // Standard token type for LatticeFasterDecoder. Each active HCLG
+ // (decoding-graph) state on each frame has one token.
+
+ // tot_cost is the total (LM + acoustic) cost from the beginning of the
+ // utterance up to this point. (but see cost_offset_, which is subtracted
+ // to keep it in a good numerical range).
+ BaseFloat tot_cost;
+
+ // exta_cost is >= 0. After calling PruneForwardLinks, this equals the
+ // minimum difference between the cost of the best path that this link is a
+ // part of, and the cost of the absolute best path, under the assumption that
+ // any of the currently active states at the decoding front may eventually
+ // succeed (e.g. if you were to take the currently active states one by one
+ // and compute this difference, and then take the minimum).
+ BaseFloat extra_cost;
+ // 'links' is the head of singly-linked list of ForwardLinks, which is what we
+ // use for lattice generation.
+ ForwardLinkT *links;
+
+ //'next' is the next in the singly-linked list of tokens for this frame.
+ Token *next;
+
+ // bias_lm_state is used to record the state of tokens in the bias lm network
+ LatticeArc::StateId bias_lm_state;
+
+ // This function does nothing and should be optimized out; it's needed
+ // so we can share the regular LatticeFasterDecoderTpl code and the code
+ // for LatticeFasterOnlineDecoder that supports fast traceback.
+ inline void SetBackpointer (Token *backpointer) { }
+
+ // This constructor just ignores the 'backpointer' argument. That argument is
+ // needed so that we can use the same decoder code for LatticeFasterDecoderTpl
+ // and LatticeFasterOnlineDecoderTpl (which needs backpointers to support a
+ // fast way to obtain the best path).
+ inline StdToken(BaseFloat tot_cost, BaseFloat extra_cost, ForwardLinkT *links,
+ Token *next, Token *backpointer):
+ tot_cost(tot_cost), extra_cost(extra_cost), links(links), next(next), bias_lm_state(0) { }
+
+ inline void GetLabelSeq(Token *tok, std::vector<int> &phn_id) {}
+};
+
+struct BackpointerToken {
+ using ForwardLinkT = ForwardLink<BackpointerToken>;
+ using Token = BackpointerToken;
+
+ // BackpointerToken is like Token but also
+ // Standard token type for LatticeFasterDecoder. Each active HCLG
+ // (decoding-graph) state on each frame has one token.
+
+ // tot_cost is the total (LM + acoustic) cost from the beginning of the
+ // utterance up to this point. (but see cost_offset_, which is subtracted
+ // to keep it in a good numerical range).
+ BaseFloat tot_cost;
+
+ // exta_cost is >= 0. After calling PruneForwardLinks, this equals
+ // the minimum difference between the cost of the best path, and the cost of
+ // this is on, and the cost of the absolute best path, under the assumption
+ // that any of the currently active states at the decoding front may
+ // eventually succeed (e.g. if you were to take the currently active states
+ // one by one and compute this difference, and then take the minimum).
+ BaseFloat extra_cost;
+
+ // 'links' is the head of singly-linked list of ForwardLinks, which is what we
+ // use for lattice generation.
+ ForwardLinkT *links;
+
+ //'next' is the next in the singly-linked list of tokens for this frame.
+ BackpointerToken *next;
+
+ // Best preceding BackpointerToken (could be a on this frame, connected to
+ // this via an epsilon transition, or on a previous frame). This is only
+ // required for an efficient GetBestPath function in
+ // LatticeFasterOnlineDecoderTpl; it plays no part in the lattice generation
+ // (the "links" list is what stores the forward links, for that).
+ Token *backpointer;
+
+ // bias_lm_state is used to record the state of tokens in the bias lm network
+ LatticeArc::StateId bias_lm_state;
+
+ inline void SetBackpointer (Token *backpointer) {
+ this->backpointer = backpointer;
+ }
+
+ inline BackpointerToken(BaseFloat tot_cost, BaseFloat extra_cost, ForwardLinkT *links,
+ Token *next, Token *backpointer):
+ tot_cost(tot_cost), extra_cost(extra_cost), links(links), next(next),
+ backpointer(backpointer), bias_lm_state(0) { }
+
+ inline void GetLabelSeq(Token *token, std::vector<int> &phn_id) {
+ ForwardLinkT* link;
+ Token *tok = token;
+ while (tok && tok->backpointer) {
+ for (link = tok->backpointer->links; link != NULL; link = link->next) {
+ if (link->next_tok == tok) {
+ phn_id.push_back(link->ilabel - 1);
+ break;
+ }
+ }
+ tok = tok->backpointer;
+ }
+ }
+};
+
+} // namespace decoder
+
+
+/** This is the "normal" lattice-generating decoder.
+ See \ref lattices_generation \ref decoders_faster and \ref decoders_simple
+ for more information.
+
+ The decoder is templated on the FST type and the token type. The token type
+ will normally be StdToken, but also may be BackpointerToken which is to support
+ quick lookup of the current best path (see lattice-faster-online-decoder.h)
+
+ The FST you invoke this decoder which is expected to equal
+ Fst::Fst<fst::StdArc>, a.k.a. StdFst, or GrammarFst. If you invoke it with
+ FST == StdFst and it notices that the actual FST type is
+ fst::VectorFst<fst::StdArc> or fst::ConstFst<fst::StdArc>, the decoder object
+ will internally cast itself to one that is templated on those more specific
+ types; this is an optimization for speed.
+ */
+template <typename FST, typename Token = decoder::StdToken>
+class LatticeFasterDecoderTpl {
+ public:
+ using Arc = typename FST::Arc;
+ using Label = typename Arc::Label;
+ using StateId = typename Arc::StateId;
+ using Weight = typename Arc::Weight;
+ using ForwardLinkT = decoder::ForwardLink<Token>;
+
+ // Instantiate this class once for each thing you have to decode.
+ // This version of the constructor does not take ownership of
+ // 'fst'.
+ LatticeFasterDecoderTpl(const FST &fst,
+ const LatticeFasterDecoderConfig &config);
+
+ // This version of the constructor takes ownership of the fst, and will delete
+ // it when this object is destroyed.
+ LatticeFasterDecoderTpl(const LatticeFasterDecoderConfig &config,
+ FST *fst);
+ //LatticeFasterDecoderTpl() { }
+
+ void SetOptions(const LatticeFasterDecoderConfig &config) {
+ config_ = config;
+ }
+
+ const LatticeFasterDecoderConfig &GetOptions() const {
+ return config_;
+ }
+
+ ~LatticeFasterDecoderTpl();
+
+ /// Decodes until there are no more frames left in the "decodable" object..
+ /// note, this may block waiting for input if the "decodable" object blocks.
+ /// Returns true if any kind of traceback is available (not necessarily from a
+ /// final state).
+ bool Decode(DecodableInterface *decodable);
+
+
+ /// says whether a final-state was active on the last frame. If it was not, the
+ /// lattice (or traceback) will end with states that are not final-states.
+ bool ReachedFinal() const {
+ return FinalRelativeCost() != std::numeric_limits<BaseFloat>::infinity();
+ }
+
+ /// Outputs an FST corresponding to the single best path through the lattice.
+ /// Returns true if result is nonempty (using the return status is deprecated,
+ /// it will become void). If "use_final_probs" is true AND we reached the
+ /// final-state of the graph then it will include those as final-probs, else
+ /// it will treat all final-probs as one. Note: this just calls GetRawLattice()
+ /// and figures out the shortest path.
+ bool GetBestPath(Lattice *ofst,
+ bool use_final_probs = true) const;
+
+ /// Outputs an FST corresponding to the raw, state-level
+ /// tracebacks. Returns true if result is nonempty.
+ /// If "use_final_probs" is true AND we reached the final-state
+ /// of the graph then it will include those as final-probs, else
+ /// it will treat all final-probs as one.
+ /// The raw lattice will be topologically sorted.
+ ///
+ /// See also GetRawLatticePruned in lattice-faster-online-decoder.h,
+ /// which also supports a pruning beam, in case for some reason
+ /// you want it pruned tighter than the regular lattice beam.
+ /// We could put that here in future needed.
+ bool GetRawLattice(Lattice *ofst, bool use_final_probs = true) const;
+
+
+
+ /// [Deprecated, users should now use GetRawLattice and determinize it
+ /// themselves, e.g. using DeterminizeLatticePhonePrunedWrapper].
+ /// Outputs an FST corresponding to the lattice-determinized
+ /// lattice (one path per word sequence). Returns true if result is nonempty.
+ /// If "use_final_probs" is true AND we reached the final-state of the graph
+ /// then it will include those as final-probs, else it will treat all
+ /// final-probs as one.
+ bool GetLattice(CompactLattice *ofst,
+ bool use_final_probs = true) const;
+
+ /// InitDecoding initializes the decoding, and should only be used if you
+ /// intend to call AdvanceDecoding(). If you call Decode(), you don't need to
+ /// call this. You can also call InitDecoding if you have already decoded an
+ /// utterance and want to start with a new utterance.
+ void InitDecoding();
+
+ /// This will decode until there are no more frames ready in the decodable
+ /// object. You can keep calling it each time more frames become available.
+ /// If max_num_frames is specified, it specifies the maximum number of frames
+ /// the function will decode before returning.
+ void AdvanceDecoding(DecodableInterface *decodable,
+ int32 max_num_frames = -1);
+
+ /// This function may be optionally called after AdvanceDecoding(), when you
+ /// do not plan to decode any further. It does an extra pruning step that
+ /// will help to prune the lattices output by GetLattice and (particularly)
+ /// GetRawLattice more completely, particularly toward the end of the
+ /// utterance. If you call this, you cannot call AdvanceDecoding again (it
+ /// will fail), and you cannot call GetLattice() and related functions with
+ /// use_final_probs = false. Used to be called PruneActiveTokensFinal().
+ void FinalizeDecoding();
+
+ /// FinalRelativeCost() serves the same purpose as ReachedFinal(), but gives
+ /// more information. It returns the difference between the best (final-cost
+ /// plus cost) of any token on the final frame, and the best cost of any token
+ /// on the final frame. If it is infinity it means no final-states were
+ /// present on the final frame. It will usually be nonnegative. If it not
+ /// too positive (e.g. < 5 is my first guess, but this is not tested) you can
+ /// take it as a good indication that we reached the final-state with
+ /// reasonable likelihood.
+ BaseFloat FinalRelativeCost() const;
+
+
+ // Returns the number of frames decoded so far. The value returned changes
+ // whenever we call ProcessEmitting().
+ inline int32 NumFramesDecoded() const { return active_toks_.size() - 1; }
+
+ std::string GetTokResult(Token *tok);
+
+ void SetBiasLm(std::shared_ptr<funasr::BiasLm> &bias_lm) {
+ bias_lm_ = bias_lm;
+ }
+
+ void ClearBiasLm() {
+ bias_lm_.reset();
+ }
+
+ protected:
+ // we make things protected instead of private, as code in
+ // LatticeFasterOnlineDecoderTpl, which inherits from this, also uses the
+ // internals.
+
+ // Deletes the elements of the singly linked list tok->links.
+ void DeleteForwardLinks(Token *tok);
+
+ // head of per-frame list of Tokens (list is in topological order),
+ // and something saying whether we ever pruned it using PruneForwardLinks.
+ struct TokenList {
+ Token *toks;
+ bool must_prune_forward_links;
+ bool must_prune_tokens;
+ TokenList(): toks(NULL), must_prune_forward_links(true),
+ must_prune_tokens(true) { }
+ };
+
+ using Elem = typename HashList<StateId, Token*>::Elem;
+ // Equivalent to:
+ // struct Elem {
+ // StateId key;
+ // Token *val;
+ // Elem *tail;
+ // };
+
+ void PossiblyResizeHash(size_t num_toks);
+
+ // FindOrAddToken either locates a token in hash of toks_, or if necessary
+ // inserts a new, empty token (i.e. with no forward links) for the current
+ // frame. [note: it's inserted if necessary into hash toks_ and also into the
+ // singly linked list of tokens active on this frame (whose head is at
+ // active_toks_[frame]). The frame_plus_one argument is the acoustic frame
+ // index plus one, which is used to index into the active_toks_ array.
+ // Returns the Token pointer. Sets "changed" (if non-NULL) to true if the
+ // token was newly created or the cost changed.
+ // If Token == StdToken, the 'backpointer' argument has no purpose (and will
+ // hopefully be optimized out).
+ inline Elem *FindOrAddToken(StateId state, int32 frame_plus_one,
+ BaseFloat tot_cost, Token *backpointer,
+ bool *changed, StateId bias_lm_state = 0);
+
+ // prunes outgoing links for all tokens in active_toks_[frame]
+ // it's called by PruneActiveTokens
+ // all links, that have link_extra_cost > lattice_beam are pruned
+ // delta is the amount by which the extra_costs must change
+ // before we set *extra_costs_changed = true.
+ // If delta is larger, we'll tend to go back less far
+ // toward the beginning of the file.
+ // extra_costs_changed is set to true if extra_cost was changed for any token
+ // links_pruned is set to true if any link in any token was pruned
+ void PruneForwardLinks(int32 frame_plus_one, bool *extra_costs_changed,
+ bool *links_pruned,
+ BaseFloat delta);
+
+ // This function computes the final-costs for tokens active on the final
+ // frame. It outputs to final-costs, if non-NULL, a map from the Token*
+ // pointer to the final-prob of the corresponding state, for all Tokens
+ // that correspond to states that have final-probs. This map will be
+ // empty if there were no final-probs. It outputs to
+ // final_relative_cost, if non-NULL, the difference between the best
+ // forward-cost including the final-prob cost, and the best forward-cost
+ // without including the final-prob cost (this will usually be positive), or
+ // infinity if there were no final-probs. [c.f. FinalRelativeCost(), which
+ // outputs this quanitity]. It outputs to final_best_cost, if
+ // non-NULL, the lowest for any token t active on the final frame, of
+ // forward-cost[t] + final-cost[t], where final-cost[t] is the final-cost in
+ // the graph of the state corresponding to token t, or the best of
+ // forward-cost[t] if there were no final-probs active on the final frame.
+ // You cannot call this after FinalizeDecoding() has been called; in that
+ // case you should get the answer from class-member variables.
+ void ComputeFinalCosts(unordered_map<Token*, BaseFloat> *final_costs,
+ BaseFloat *final_relative_cost,
+ BaseFloat *final_best_cost) const;
+
+ // PruneForwardLinksFinal is a version of PruneForwardLinks that we call
+ // on the final frame. If there are final tokens active, it uses
+ // the final-probs for pruning, otherwise it treats all tokens as final.
+ void PruneForwardLinksFinal();
+
+ // Prune away any tokens on this frame that have no forward links.
+ // [we don't do this in PruneForwardLinks because it would give us
+ // a problem with dangling pointers].
+ // It's called by PruneActiveTokens if any forward links have been pruned
+ void PruneTokensForFrame(int32 frame_plus_one);
+
+
+ // Go backwards through still-alive tokens, pruning them if the
+ // forward+backward cost is more than lat_beam away from the best path. It's
+ // possible to prove that this is "correct" in the sense that we won't lose
+ // anything outside of lat_beam, regardless of what happens in the future.
+ // delta controls when it considers a cost to have changed enough to continue
+ // going backward and propagating the change. larger delta -> will recurse
+ // less far.
+ void PruneActiveTokens(BaseFloat delta);
+
+ /// Gets the weight cutoff. Also counts the active tokens.
+ BaseFloat GetCutoff(Elem *list_head, size_t *tok_count,
+ BaseFloat *adaptive_beam, Elem **best_elem);
+
+ /// Processes emitting arcs for one frame. Propagates from prev_toks_ to
+ /// cur_toks_. Returns the cost cutoff for subsequent ProcessNonemitting() to
+ /// use.
+ BaseFloat ProcessEmitting(DecodableInterface *decodable);
+
+ /// Processes nonemitting (epsilon) arcs for one frame. Called after
+ /// ProcessEmitting() on each frame. The cost cutoff is computed by the
+ /// preceding ProcessEmitting().
+ void ProcessNonemitting(BaseFloat cost_cutoff);
+
+ // HashList defined in ../util/hash-list.h. It actually allows us to maintain
+ // more than one list (e.g. for current and previous frames), but only one of
+ // them at a time can be indexed by StateId. It is indexed by frame-index
+ // plus one, where the frame-index is zero-based, as used in decodable object.
+ // That is, the emitting probs of frame t are accounted for in tokens at
+ // toks_[t+1]. The zeroth frame is for nonemitting transition at the start of
+ // the graph.
+ HashList<StateId, Token*> toks_;
+
+ std::vector<TokenList> active_toks_; // Lists of tokens, indexed by
+ // frame (members of TokenList are toks, must_prune_forward_links,
+ // must_prune_tokens).
+ std::vector<const Elem* > queue_; // temp variable used in ProcessNonemitting,
+ std::vector<BaseFloat> tmp_array_; // used in GetCutoff.
+
+ // fst_ is a pointer to the FST we are decoding from.
+ const FST *fst_;
+ // delete_fst_ is true if the pointer fst_ needs to be deleted when this
+ // object is destroyed.
+ bool delete_fst_;
+
+ std::vector<BaseFloat> cost_offsets_; // This contains, for each
+ // frame, an offset that was added to the acoustic log-likelihoods on that
+ // frame in order to keep everything in a nice dynamic range i.e. close to
+ // zero, to reduce roundoff errors.
+ LatticeFasterDecoderConfig config_;
+ int32 num_toks_; // current total #toks allocated...
+ bool warned_;
+
+ /// decoding_finalized_ is true if someone called FinalizeDecoding(). [note,
+ /// calling this is optional]. If true, it's forbidden to decode more. Also,
+ /// if this is set, then the output of ComputeFinalCosts() is in the next
+ /// three variables. The reason we need to do this is that after
+ /// FinalizeDecoding() calls PruneTokensForFrame() for the final frame, some
+ /// of the tokens on the last frame are freed, so we free the list from toks_
+ /// to avoid having dangling pointers hanging around.
+ bool decoding_finalized_;
+ /// For the meaning of the next 3 variables, see the comment for
+ /// decoding_finalized_ above., and ComputeFinalCosts().
+ unordered_map<Token*, BaseFloat> final_costs_;
+ BaseFloat final_relative_cost_;
+ BaseFloat final_best_cost_;
+
+ // Memory pools for storing tokens and forward links.
+ // We use it to decrease the work put on allocator and to move some of data
+ // together. Too small block sizes will result in more work to allocator but
+ // bigger ones increase the memory usage.
+ fst::MemoryPool<Token> token_pool_;
+ fst::MemoryPool<ForwardLinkT> forward_link_pool_;
+
+ // There are various cleanup tasks... the toks_ structure contains
+ // singly linked lists of Token pointers, where Elem is the list type.
+ // It also indexes them in a hash, indexed by state (this hash is only
+ // maintained for the most recent frame). toks_.Clear()
+ // deletes them from the hash and returns the list of Elems. The
+ // function DeleteElems calls toks_.Delete(elem) for each elem in
+ // the list, which returns ownership of the Elem to the toks_ structure
+ // for reuse, but does not delete the Token pointer. The Token pointers
+ // are reference-counted and are ultimately deleted in PruneTokensForFrame,
+ // but are also linked together on each frame by their own linked-list,
+ // using the "next" pointer. We delete them manually.
+ void DeleteElems(Elem *list);
+
+ // This function takes a singly linked list of tokens for a single frame, and
+ // outputs a list of them in topological order (it will crash if no such order
+ // can be found, which will typically be due to decoding graphs with epsilon
+ // cycles, which are not allowed). Note: the output list may contain NULLs,
+ // which the caller should pass over; it just happens to be more efficient for
+ // the algorithm to output a list that contains NULLs.
+ static void TopSortTokens(Token *tok_list,
+ std::vector<Token*> *topsorted_list);
+
+ void ClearActiveTokens();
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(LatticeFasterDecoderTpl);
+
+ std::shared_ptr<funasr::BiasLm> bias_lm_ = nullptr;
+};
+
+typedef LatticeFasterDecoderTpl<fst::StdFst, decoder::StdToken> LatticeFasterDecoder;
+
+
+
+} // end namespace kaldi.
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-online-decoder.cc b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-online-decoder.cc
new file mode 100644
index 000000000..b5261503c
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-online-decoder.cc
@@ -0,0 +1,285 @@
+// decoder/lattice-faster-online-decoder.cc
+
+// Copyright 2009-2012 Microsoft Corporation Mirko Hannemann
+// 2013-2014 Johns Hopkins University (Author: Daniel Povey)
+// 2014 Guoguo Chen
+// 2014 IMSL, PKU-HKUST (author: Wei Shi)
+// 2018 Zhehuai Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+// see note at the top of lattice-faster-decoder.cc, about how to maintain this
+// file in sync with lattice-faster-decoder.cc
+
+#include "decoder/lattice-faster-online-decoder.h"
+#include "lat/lattice-functions.h"
+
+namespace kaldi {
+
+template <typename FST>
+bool LatticeFasterOnlineDecoderTpl<FST>::TestGetBestPath(
+ bool use_final_probs) const {
+ Lattice lat1;
+ {
+ Lattice raw_lat;
+ this->GetRawLattice(&raw_lat, use_final_probs);
+ ShortestPath(raw_lat, &lat1);
+ }
+ Lattice lat2;
+ GetBestPath(&lat2, use_final_probs);
+ BaseFloat delta = 0.1;
+ int32 num_paths = 1;
+ if (!fst::RandEquivalent(lat1, lat2, num_paths, delta, rand())) {
+ KALDI_WARN << "Best-path test failed";
+ return false;
+ } else {
+ return true;
+ }
+}
+
+
+// Outputs an FST corresponding to the single best path through the lattice.
+template <typename FST>
+bool LatticeFasterOnlineDecoderTpl<FST>::GetBestPath(Lattice *olat,
+ bool use_final_probs) const {
+ olat->DeleteStates();
+ BaseFloat final_graph_cost;
+ BestPathIterator iter = BestPathEnd(use_final_probs, &final_graph_cost);
+ if (iter.Done())
+ return false; // would have printed warning.
+ StateId state = olat->AddState();
+ olat->SetFinal(state, LatticeWeight(final_graph_cost, 0.0));
+ while (!iter.Done()) {
+ LatticeArc arc;
+ iter = TraceBackBestPath(iter, &arc);
+ arc.nextstate = state;
+ StateId new_state = olat->AddState();
+ olat->AddArc(new_state, arc);
+ state = new_state;
+ }
+ olat->SetStart(state);
+ return true;
+}
+
+template <typename FST>
+typename LatticeFasterOnlineDecoderTpl<FST>::BestPathIterator LatticeFasterOnlineDecoderTpl<FST>::BestPathEnd(
+ bool use_final_probs,
+ BaseFloat *final_cost_out) const {
+ if (this->decoding_finalized_ && !use_final_probs)
+ KALDI_ERR << "You cannot call FinalizeDecoding() and then call "
+ << "BestPathEnd() with use_final_probs == false";
+ KALDI_ASSERT(this->NumFramesDecoded() > 0 &&
+ "You cannot call BestPathEnd if no frames were decoded.");
+
+ unordered_map<Token*, BaseFloat> final_costs_local;
+
+ const unordered_map<Token*, BaseFloat> &final_costs =
+ (this->decoding_finalized_ ? this->final_costs_ :final_costs_local);
+ if (!this->decoding_finalized_ && use_final_probs)
+ this->ComputeFinalCosts(&final_costs_local, NULL, NULL);
+
+ // Singly linked list of tokens on last frame (access list through "next"
+ // pointer).
+ BaseFloat best_cost = std::numeric_limits<BaseFloat>::infinity();
+ BaseFloat best_final_cost = 0;
+ Token *best_tok = NULL;
+ for (Token *tok = this->active_toks_.back().toks;
+ tok != NULL; tok = tok->next) {
+ BaseFloat cost = tok->tot_cost, final_cost = 0.0;
+ if (use_final_probs && !final_costs.empty()) {
+ // if we are instructed to use final-probs, and any final tokens were
+ // active on final frame, include the final-prob in the cost of the token.
+ typename unordered_map<Token*, BaseFloat>::const_iterator
+ iter = final_costs.find(tok);
+ if (iter != final_costs.end()) {
+ final_cost = iter->second;
+ cost += final_cost;
+ } else {
+ cost = std::numeric_limits<BaseFloat>::infinity();
+ }
+ }
+ if (cost < best_cost) {
+ best_cost = cost;
+ best_tok = tok;
+ best_final_cost = final_cost;
+ }
+ }
+ if (best_tok == NULL) { // this should not happen, and is likely a code error or
+ // caused by infinities in likelihoods, but I'm not making
+ // it a fatal error for now.
+ KALDI_WARN << "No final token found.";
+ }
+ if (final_cost_out)
+ *final_cost_out = best_final_cost;
+ return BestPathIterator(best_tok, this->NumFramesDecoded() - 1);
+}
+
+
+template <typename FST>
+typename LatticeFasterOnlineDecoderTpl<FST>::BestPathIterator LatticeFasterOnlineDecoderTpl<FST>::TraceBackBestPath(
+ BestPathIterator iter, LatticeArc *oarc) const {
+ KALDI_ASSERT(!iter.Done() && oarc != NULL);
+ Token *tok = static_cast<Token*>(iter.tok);
+ int32 cur_t = iter.frame, step_t = 0;
+ if (tok->backpointer != NULL) {
+ // retrieve the correct forward link(with the best link cost)
+ BaseFloat best_cost = std::numeric_limits<BaseFloat>::infinity();
+ ForwardLinkT *link;
+ for (link = tok->backpointer->links;
+ link != NULL; link = link->next) {
+ if (link->next_tok == tok) { // this is a link to "tok"
+ BaseFloat graph_cost = link->graph_cost,
+ acoustic_cost = link->acoustic_cost;
+ BaseFloat cost = graph_cost + acoustic_cost;
+ if (cost < best_cost) {
+ oarc->ilabel = link->ilabel;
+ oarc->olabel = link->olabel;
+ if (link->ilabel != 0) {
+ KALDI_ASSERT(static_cast<size_t>(cur_t) < this->cost_offsets_.size());
+ acoustic_cost -= this->cost_offsets_[cur_t];
+ step_t = -1;
+ } else {
+ step_t = 0;
+ }
+ oarc->weight = LatticeWeight(graph_cost, acoustic_cost);
+ best_cost = cost;
+ }
+ }
+ }
+ if (link == NULL &&
+ best_cost == std::numeric_limits<BaseFloat>::infinity()) { // Did not find correct link.
+ KALDI_ERR << "Error tracing best-path back (likely "
+ << "bug in token-pruning algorithm)";
+ }
+ } else {
+ oarc->ilabel = 0;
+ oarc->olabel = 0;
+ oarc->weight = LatticeWeight::One(); // zero costs.
+ }
+ return BestPathIterator(tok->backpointer, cur_t + step_t);
+}
+
+template <typename FST>
+bool LatticeFasterOnlineDecoderTpl<FST>::GetRawLatticePruned(
+ Lattice *ofst,
+ bool use_final_probs,
+ BaseFloat beam) const {
+ typedef LatticeArc Arc;
+ typedef Arc::StateId StateId;
+ typedef Arc::Weight Weight;
+ typedef Arc::Label Label;
+
+ // Note: you can't use the old interface (Decode()) if you want to
+ // get the lattice with use_final_probs = false. You'd have to do
+ // InitDecoding() and then AdvanceDecoding().
+ if (this->decoding_finalized_ && !use_final_probs)
+ KALDI_ERR << "You cannot call FinalizeDecoding() and then call "
+ << "GetRawLattice() with use_final_probs == false";
+
+ unordered_map<Token*, BaseFloat> final_costs_local;
+
+ const unordered_map<Token*, BaseFloat> &final_costs =
+ (this->decoding_finalized_ ? this->final_costs_ : final_costs_local);
+ if (!this->decoding_finalized_ && use_final_probs)
+ this->ComputeFinalCosts(&final_costs_local, NULL, NULL);
+
+ ofst->DeleteStates();
+ // num-frames plus one (since frames are one-based, and we have
+ // an extra frame for the start-state).
+ int32 num_frames = this->active_toks_.size() - 1;
+ KALDI_ASSERT(num_frames > 0);
+ for (int32 f = 0; f <= num_frames; f++) {
+ if (this->active_toks_[f].toks == NULL) {
+ KALDI_WARN << "No tokens active on frame " << f
+ << ": not producing lattice.\n";
+ return false;
+ }
+ }
+ unordered_map<Token*, StateId> tok_map;
+ std::queue<std::pair<Token*, int32> > tok_queue;
+ // First initialize the queue and states. Put the initial state on the queue;
+ // this is the last token in the list active_toks_[0].toks.
+ for (Token *tok = this->active_toks_[0].toks;
+ tok != NULL; tok = tok->next) {
+ if (tok->next == NULL) {
+ tok_map[tok] = ofst->AddState();
+ ofst->SetStart(tok_map[tok]);
+ std::pair<Token*, int32> tok_pair(tok, 0); // #frame = 0
+ tok_queue.push(tok_pair);
+ }
+ }
+
+ // Next create states for "good" tokens
+ while (!tok_queue.empty()) {
+ std::pair<Token*, int32> cur_tok_pair = tok_queue.front();
+ tok_queue.pop();
+ Token *cur_tok = cur_tok_pair.first;
+ int32 cur_frame = cur_tok_pair.second;
+ KALDI_ASSERT(cur_frame >= 0 &&
+ cur_frame <= this->cost_offsets_.size());
+
+ typename unordered_map<Token*, StateId>::const_iterator iter =
+ tok_map.find(cur_tok);
+ KALDI_ASSERT(iter != tok_map.end());
+ StateId cur_state = iter->second;
+
+ for (ForwardLinkT *l = cur_tok->links;
+ l != NULL;
+ l = l->next) {
+ Token *next_tok = l->next_tok;
+ if (next_tok->extra_cost < beam) {
+ // so both the current and the next token are good; create the arc
+ int32 next_frame = l->ilabel == 0 ? cur_frame : cur_frame + 1;
+ StateId nextstate;
+ if (tok_map.find(next_tok) == tok_map.end()) {
+ nextstate = tok_map[next_tok] = ofst->AddState();
+ tok_queue.push(std::pair<Token*, int32>(next_tok, next_frame));
+ } else {
+ nextstate = tok_map[next_tok];
+ }
+ BaseFloat cost_offset = (l->ilabel != 0 ?
+ this->cost_offsets_[cur_frame] : 0);
+ Arc arc(l->ilabel, l->olabel,
+ Weight(l->graph_cost, l->acoustic_cost - cost_offset),
+ nextstate);
+ ofst->AddArc(cur_state, arc);
+ }
+ }
+ if (cur_frame == num_frames) {
+ if (use_final_probs && !final_costs.empty()) {
+ typename unordered_map<Token*, BaseFloat>::const_iterator iter =
+ final_costs.find(cur_tok);
+ if (iter != final_costs.end())
+ ofst->SetFinal(cur_state, LatticeWeight(iter->second, 0));
+ } else {
+ ofst->SetFinal(cur_state, LatticeWeight::One());
+ }
+ }
+ }
+ return (ofst->NumStates() != 0);
+}
+
+
+
+// Instantiate the template for the FST types that we'll need.
+template class LatticeFasterOnlineDecoderTpl<fst::Fst<fst::StdArc> >;
+template class LatticeFasterOnlineDecoderTpl<fst::VectorFst<fst::StdArc> >;
+template class LatticeFasterOnlineDecoderTpl<fst::ConstFst<fst::StdArc> >;
+//template class LatticeFasterOnlineDecoderTpl<fst::ConstGrammarFst >;
+//template class LatticeFasterOnlineDecoderTpl<fst::VectorGrammarFst >;
+
+
+} // end namespace kaldi.
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-online-decoder.h b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-online-decoder.h
new file mode 100644
index 000000000..4040d8f2e
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-faster-online-decoder.h
@@ -0,0 +1,146 @@
+// decoder/lattice-faster-online-decoder.h
+
+// Copyright 2009-2013 Microsoft Corporation; Mirko Hannemann;
+// 2013-2014 Johns Hopkins University (Author: Daniel Povey)
+// 2014 Guoguo Chen
+// 2018 Zhehuai Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+// see note at the top of lattice-faster-decoder.h, about how to maintain this
+// file in sync with lattice-faster-decoder.h
+
+
+#ifndef KALDI_DECODER_LATTICE_FASTER_ONLINE_DECODER_H_
+#define KALDI_DECODER_LATTICE_FASTER_ONLINE_DECODER_H_
+
+#include "util/stl-utils.h"
+#include "util/hash-list.h"
+#include "fst/fstlib.h"
+#include "itf/decodable-itf.h"
+#include "fstext/fstext-lib.h"
+#include "lat/determinize-lattice-pruned.h"
+#include "lat/kaldi-lattice.h"
+#include "decoder/lattice-faster-decoder.h"
+
+namespace kaldi {
+
+
+
+/** LatticeFasterOnlineDecoderTpl is as LatticeFasterDecoderTpl but also
+ supports an efficient way to get the best path (see the function
+ BestPathEnd()), which is useful in endpointing and in situations where you
+ might want to frequently access the best path.
+
+ This is only templated on the FST type, since the Token type is required to
+ be BackpointerToken. Actually it only makes sense to instantiate
+ LatticeFasterDecoderTpl with Token == BackpointerToken if you do so indirectly via
+ this child class.
+ */
+template <typename FST>
+class LatticeFasterOnlineDecoderTpl:
+ public LatticeFasterDecoderTpl<FST, decoder::BackpointerToken> {
+ public:
+ using Arc = typename FST::Arc;
+ using Label = typename Arc::Label;
+ using StateId = typename Arc::StateId;
+ using Weight = typename Arc::Weight;
+ using Token = decoder::BackpointerToken;
+ using ForwardLinkT = decoder::ForwardLink<Token>;
+
+ // Instantiate this class once for each thing you have to decode.
+ // This version of the constructor does not take ownership of
+ // 'fst'.
+ LatticeFasterOnlineDecoderTpl(const FST &fst,
+ const LatticeFasterDecoderConfig &config):
+ LatticeFasterDecoderTpl<FST, Token>(fst, config) { }
+
+ // This version of the initializer takes ownership of 'fst', and will delete
+ // it when this object is destroyed.
+ LatticeFasterOnlineDecoderTpl(const LatticeFasterDecoderConfig &config, FST *fst):
+ LatticeFasterDecoderTpl<FST, Token>(config, fst) { }
+ //LatticeFasterOnlineDecoderTpl() {}
+
+ struct BestPathIterator {
+ void *tok;
+ int32 frame;
+ // note, "frame" is the frame-index of the frame you'll get the
+ // transition-id for next time, if you call TraceBackBestPath on this
+ // iterator (assuming it's not an epsilon transition). Note that this
+ // is one less than you might reasonably expect, e.g. it's -1 for
+ // the nonemitting transitions before the first frame.
+ BestPathIterator(void *t, int32 f): tok(t), frame(f) { }
+ bool Done() const { return tok == NULL; }
+ };
+
+
+ /// Outputs an FST corresponding to the single best path through the lattice.
+ /// This is quite efficient because it doesn't get the entire raw lattice and find
+ /// the best path through it; instead, it uses the BestPathEnd and BestPathIterator
+ /// so it basically traces it back through the lattice.
+ /// Returns true if result is nonempty (using the return status is deprecated,
+ /// it will become void). If "use_final_probs" is true AND we reached the
+ /// final-state of the graph then it will include those as final-probs, else
+ /// it will treat all final-probs as one.
+ bool GetBestPath(Lattice *ofst,
+ bool use_final_probs = true) const;
+
+
+ /// This function does a self-test of GetBestPath(). Returns true on
+ /// success; returns false and prints a warning on failure.
+ bool TestGetBestPath(bool use_final_probs = true) const;
+
+
+ /// This function returns an iterator that can be used to trace back
+ /// the best path. If use_final_probs == true and at least one final state
+ /// survived till the end, it will use the final-probs in working out the best
+ /// final Token, and will output the final cost to *final_cost (if non-NULL),
+ /// else it will use only the forward likelihood, and will put zero in
+ /// *final_cost (if non-NULL).
+ /// Requires that NumFramesDecoded() > 0.
+ BestPathIterator BestPathEnd(bool use_final_probs,
+ BaseFloat *final_cost = NULL) const;
+
+
+ /// This function can be used in conjunction with BestPathEnd() to trace back
+ /// the best path one link at a time (e.g. this can be useful in endpoint
+ /// detection). By "link" we mean a link in the graph; not all links cross
+ /// frame boundaries, but each time you see a nonzero ilabel you can interpret
+ /// that as a frame. The return value is the updated iterator. It outputs
+ /// the ilabel and olabel, and the (graph and acoustic) weight to the "arc" pointer,
+ /// while leaving its "nextstate" variable unchanged.
+ BestPathIterator TraceBackBestPath(
+ BestPathIterator iter, LatticeArc *arc) const;
+
+
+ /// Behaves the same as GetRawLattice but only processes tokens whose
+ /// extra_cost is smaller than the best-cost plus the specified beam.
+ /// It is only worthwhile to call this function if beam is less than
+ /// the lattice_beam specified in the config; otherwise, it would
+ /// return essentially the same thing as GetRawLattice, but more slowly.
+ bool GetRawLatticePruned(Lattice *ofst,
+ bool use_final_probs,
+ BaseFloat beam) const;
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(LatticeFasterOnlineDecoderTpl);
+};
+
+typedef LatticeFasterOnlineDecoderTpl<fst::StdFst> LatticeFasterOnlineDecoder;
+
+
+} // end namespace kaldi.
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-decoder.cc b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-decoder.cc
new file mode 100644
index 000000000..b02247474
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-decoder.cc
@@ -0,0 +1,1730 @@
+// decoder/lattice-incremental-decoder.cc
+
+// Copyright 2019 Zhehuai Chen, Daniel Povey
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "decoder/lattice-incremental-decoder.h"
+#include "lat/lattice-functions.h"
+#include "base/timer.h"
+
+namespace kaldi {
+
+// instantiate this class once for each thing you have to decode.
+template <typename FST, typename Token>
+LatticeIncrementalDecoderTpl<FST, Token>::LatticeIncrementalDecoderTpl(
+ const FST &fst, const TransitionInformation &trans_model,
+ const LatticeIncrementalDecoderConfig &config)
+ : fst_(&fst),
+ delete_fst_(false),
+ num_toks_(0),
+ config_(config),
+ determinizer_(trans_model, config) {
+ config.Check();
+ toks_.SetSize(1000); // just so on the first frame we do something reasonable.
+}
+
+template <typename FST, typename Token>
+LatticeIncrementalDecoderTpl<FST, Token>::LatticeIncrementalDecoderTpl(
+ const LatticeIncrementalDecoderConfig &config, FST *fst,
+ const TransitionInformation &trans_model)
+ : fst_(fst),
+ delete_fst_(true),
+ num_toks_(0),
+ config_(config),
+ determinizer_(trans_model, config) {
+ config.Check();
+ toks_.SetSize(1000); // just so on the first frame we do something reasonable.
+}
+
+template <typename FST, typename Token>
+LatticeIncrementalDecoderTpl<FST, Token>::~LatticeIncrementalDecoderTpl() {
+ DeleteElems(toks_.Clear());
+ ClearActiveTokens();
+ if (delete_fst_) delete fst_;
+}
+
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::InitDecoding() {
+ // clean up from last time:
+ DeleteElems(toks_.Clear());
+ cost_offsets_.clear();
+ ClearActiveTokens();
+ warned_ = false;
+ num_toks_ = 0;
+ decoding_finalized_ = false;
+ final_costs_.clear();
+ StateId start_state = fst_->Start();
+ KALDI_ASSERT(start_state != fst::kNoStateId);
+ active_toks_.resize(1);
+ Token *start_tok = new Token(0.0, 0.0, NULL, NULL, NULL);
+ active_toks_[0].toks = start_tok;
+ toks_.Insert(start_state, start_tok);
+ num_toks_++;
+
+ determinizer_.Init();
+ num_frames_in_lattice_ = 0;
+ token2label_map_.clear();
+ next_token_label_ = LatticeIncrementalDeterminizer::kTokenLabelOffset;
+ ProcessNonemitting(config_.beam);
+}
+
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::UpdateLatticeDeterminization() {
+ if (NumFramesDecoded() - num_frames_in_lattice_ <
+ config_.determinize_max_delay)
+ return;
+
+
+ /* Make sure the token-pruning is active. Note: PruneActiveTokens() has
+ internal logic that prevents it from doing unnecessary work if you
+ call it and then immediately call it again. */
+ PruneActiveTokens(config_.lattice_beam * config_.prune_scale);
+
+ int32 first = num_frames_in_lattice_ + config_.determinize_min_chunk_size,
+ last = NumFramesDecoded(),
+ fewest_tokens = std::numeric_limits<int32>::max(),
+ best_frame = -1;
+ for (int32 t = last; t >= first; t--) {
+ /* Make sure PruneActiveTokens() has computed num_toks for all these
+ frames... */
+ KALDI_ASSERT(active_toks_[t].num_toks != -1);
+ if (active_toks_[t].num_toks < fewest_tokens) {
+ // <= because we want the latest one in case of ties.
+ fewest_tokens = active_toks_[t].num_toks;
+ best_frame = t;
+ }
+ }
+ /* Skip this update if we have too many tokens, determinization will take too long,
+ postpone it to the next update */
+ if (fewest_tokens > config_.determinize_max_active)
+ return;
+
+ /* OK, determinize the chunk that spans from num_frames_in_lattice_ to
+ best_frame. */
+ bool use_final_probs = false;
+ GetLattice(best_frame, use_final_probs);
+ return;
+}
+// Returns true if any kind of traceback is available (not necessarily from
+// a final state). It should only very rarely return false; this indicates
+// an unusual search error.
+template <typename FST, typename Token>
+bool LatticeIncrementalDecoderTpl<FST, Token>::Decode(DecodableInterface *decodable) {
+ InitDecoding();
+
+ // We use 1-based indexing for frames in this decoder (if you view it in
+ // terms of features), but note that the decodable object uses zero-based
+ // numbering, which we have to correct for when we call it.
+
+ while (!decodable->IsLastFrame(NumFramesDecoded() - 1)) {
+ if (NumFramesDecoded() % config_.prune_interval == 0) {
+ PruneActiveTokens(config_.lattice_beam * config_.prune_scale);
+ }
+ UpdateLatticeDeterminization();
+
+ BaseFloat cost_cutoff = ProcessEmitting(decodable);
+ ProcessNonemitting(cost_cutoff);
+ }
+ Timer timer;
+ FinalizeDecoding();
+ bool use_final_probs = true;
+ GetLattice(NumFramesDecoded(), use_final_probs);
+ KALDI_VLOG(2) << "Delay time during and after FinalizeDecoding()"
+ << "(secs): " << timer.Elapsed();
+
+ // Returns true if we have any kind of traceback available (not necessarily
+ // to the end state; query ReachedFinal() for that).
+ return !active_toks_.empty() && active_toks_.back().toks != NULL;
+}
+
+
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::PossiblyResizeHash(size_t num_toks) {
+ size_t new_sz =
+ static_cast<size_t>(static_cast<BaseFloat>(num_toks) * config_.hash_ratio);
+ if (new_sz > toks_.Size()) {
+ toks_.SetSize(new_sz);
+ }
+}
+
+/*
+ A note on the definition of extra_cost.
+
+ extra_cost is used in pruning tokens, to save memory.
+
+ extra_cost can be thought of as a beta (backward) cost assuming
+ we had set the betas on currently-active tokens to all be the negative
+ of the alphas for those tokens. (So all currently active tokens would
+ be on (tied) best paths).
+
+
+ Define the 'forward cost' of a token as zero for any token on the frame
+ we're currently decoding; and for other frames, as the shortest-path cost
+ between that token and a token on the frame we're currently decoding.
+ (by "currently decoding" I mean the most recently processed frame).
+
+ Then define the extra_cost of a token (always >= 0) as the forward-cost of
+ the token minus the smallest forward-cost of any token on the same frame.
+
+ We can use the extra_cost to accurately prune away tokens that we know will
+ never appear in the lattice. If the extra_cost is greater than the desired
+ lattice beam, the token would provably never appear in the lattice, so we can
+ prune away the token.
+
+ The advantage of storing the extra_cost rather than the forward-cost, is that
+ it is less costly to keep the extra_cost up-to-date when we process new frames.
+ When we process a new frame, *all* the previous frames' forward-costs would change;
+ but in general the extra_cost will change only for a finite number of frames.
+ (Actually we don't update all the extra_costs every time we update a frame; we
+ only do it every 'config_.prune_interval' frames).
+ */
+
+// FindOrAddToken either locates a token in hash of toks_,
+// or if necessary inserts a new, empty token (i.e. with no forward links)
+// for the current frame. [note: it's inserted if necessary into hash toks_
+// and also into the singly linked list of tokens active on this frame
+// (whose head is at active_toks_[frame]).
+template <typename FST, typename Token>
+inline Token *LatticeIncrementalDecoderTpl<FST, Token>::FindOrAddToken(
+ StateId state, int32 frame_plus_one, BaseFloat tot_cost, Token *backpointer,
+ bool *changed) {
+ // Returns the Token pointer. Sets "changed" (if non-NULL) to true
+ // if the token was newly created or the cost changed.
+ KALDI_ASSERT(frame_plus_one < active_toks_.size());
+ Token *&toks = active_toks_[frame_plus_one].toks;
+ Elem *e_found = toks_.Find(state);
+ if (e_found == NULL) { // no such token presently.
+ const BaseFloat extra_cost = 0.0;
+ // tokens on the currently final frame have zero extra_cost
+ // as any of them could end up
+ // on the winning path.
+ Token *new_tok = new Token(tot_cost, extra_cost, NULL, toks, backpointer);
+ // NULL: no forward links yet
+ toks = new_tok;
+ num_toks_++;
+ toks_.Insert(state, new_tok);
+ if (changed) *changed = true;
+ return new_tok;
+ } else {
+ Token *tok = e_found->val; // There is an existing Token for this state.
+ if (tok->tot_cost > tot_cost) { // replace old token
+ tok->tot_cost = tot_cost;
+ // SetBackpointer() just does tok->backpointer = backpointer in
+ // the case where Token == BackpointerToken, else nothing.
+ tok->SetBackpointer(backpointer);
+ // we don't allocate a new token, the old stays linked in active_toks_
+ // we only replace the tot_cost
+ // in the current frame, there are no forward links (and no extra_cost)
+ // only in ProcessNonemitting we have to delete forward links
+ // in case we visit a state for the second time
+ // those forward links, that lead to this replaced token before:
+ // they remain and will hopefully be pruned later (PruneForwardLinks...)
+ if (changed) *changed = true;
+ } else {
+ if (changed) *changed = false;
+ }
+ return tok;
+ }
+}
+
+// prunes outgoing links for all tokens in active_toks_[frame]
+// it's called by PruneActiveTokens
+// all links, that have link_extra_cost > lattice_beam are pruned
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::PruneForwardLinks(
+ int32 frame_plus_one, bool *extra_costs_changed, bool *links_pruned,
+ BaseFloat delta) {
+ // delta is the amount by which the extra_costs must change
+ // If delta is larger, we'll tend to go back less far
+ // toward the beginning of the file.
+ // extra_costs_changed is set to true if extra_cost was changed for any token
+ // links_pruned is set to true if any link in any token was pruned
+
+ *extra_costs_changed = false;
+ *links_pruned = false;
+ KALDI_ASSERT(frame_plus_one >= 0 && frame_plus_one < active_toks_.size());
+ if (active_toks_[frame_plus_one].toks == NULL) { // empty list; should not happen.
+ if (!warned_) {
+ KALDI_WARN << "No tokens alive [doing pruning].. warning first "
+ "time only for each utterance\n";
+ warned_ = true;
+ }
+ }
+
+ // We have to iterate until there is no more change, because the links
+ // are not guaranteed to be in topological order.
+ bool changed = true; // difference new minus old extra cost >= delta ?
+ while (changed) {
+ changed = false;
+ for (Token *tok = active_toks_[frame_plus_one].toks; tok != NULL;
+ tok = tok->next) {
+ ForwardLinkT *link, *prev_link = NULL;
+ // will recompute tok_extra_cost for tok.
+ BaseFloat tok_extra_cost = std::numeric_limits<BaseFloat>::infinity();
+ // tok_extra_cost is the best (min) of link_extra_cost of outgoing links
+ for (link = tok->links; link != NULL;) {
+ // See if we need to excise this link...
+ Token *next_tok = link->next_tok;
+ BaseFloat link_extra_cost =
+ next_tok->extra_cost +
+ ((tok->tot_cost + link->acoustic_cost + link->graph_cost) -
+ next_tok->tot_cost); // difference in brackets is >= 0
+ // link_exta_cost is the difference in score between the best paths
+ // through link source state and through link destination state
+ KALDI_ASSERT(link_extra_cost == link_extra_cost); // check for NaN
+ if (link_extra_cost > config_.lattice_beam) { // excise link
+ ForwardLinkT *next_link = link->next;
+ if (prev_link != NULL)
+ prev_link->next = next_link;
+ else
+ tok->links = next_link;
+ delete link;
+ link = next_link; // advance link but leave prev_link the same.
+ *links_pruned = true;
+ } else { // keep the link and update the tok_extra_cost if needed.
+ if (link_extra_cost < 0.0) { // this is just a precaution.
+ if (link_extra_cost < -0.01)
+ KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
+ link_extra_cost = 0.0;
+ }
+ if (link_extra_cost < tok_extra_cost) tok_extra_cost = link_extra_cost;
+ prev_link = link; // move to next link
+ link = link->next;
+ }
+ } // for all outgoing links
+ if (fabs(tok_extra_cost - tok->extra_cost) > delta)
+ changed = true; // difference new minus old is bigger than delta
+ tok->extra_cost = tok_extra_cost;
+ // will be +infinity or <= lattice_beam_.
+ // infinity indicates, that no forward link survived pruning
+ } // for all Token on active_toks_[frame]
+ if (changed) *extra_costs_changed = true;
+
+ // Note: it's theoretically possible that aggressive compiler
+ // optimizations could cause an infinite loop here for small delta and
+ // high-dynamic-range scores.
+ } // while changed
+}
+
+// PruneForwardLinksFinal is a version of PruneForwardLinks that we call
+// on the final frame. If there are final tokens active, it uses
+// the final-probs for pruning, otherwise it treats all tokens as final.
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::PruneForwardLinksFinal() {
+ KALDI_ASSERT(!active_toks_.empty());
+ int32 frame_plus_one = active_toks_.size() - 1;
+
+ if (active_toks_[frame_plus_one].toks == NULL) // empty list; should not happen.
+ KALDI_WARN << "No tokens alive at end of file";
+
+ typedef typename unordered_map<Token *, BaseFloat>::const_iterator IterType;
+ ComputeFinalCosts(&final_costs_, &final_relative_cost_, &final_best_cost_);
+ decoding_finalized_ = true;
+ // We call DeleteElems() as a nicety, not because it's really necessary;
+ // otherwise there would be a time, after calling PruneTokensForFrame() on the
+ // final frame, when toks_.GetList() or toks_.Clear() would contain pointers
+ // to nonexistent tokens.
+ DeleteElems(toks_.Clear());
+
+ // Now go through tokens on this frame, pruning forward links... may have to
+ // iterate a few times until there is no more change, because the list is not
+ // in topological order. This is a modified version of the code in
+ // PruneForwardLinks, but here we also take account of the final-probs.
+ bool changed = true;
+ BaseFloat delta = 1.0e-05;
+ while (changed) {
+ changed = false;
+ for (Token *tok = active_toks_[frame_plus_one].toks; tok != NULL;
+ tok = tok->next) {
+ ForwardLinkT *link, *prev_link = NULL;
+ // will recompute tok_extra_cost. It has a term in it that corresponds
+ // to the "final-prob", so instead of initializing tok_extra_cost to infinity
+ // below we set it to the difference between the (score+final_prob) of this
+ // token,
+ // and the best such (score+final_prob).
+ BaseFloat final_cost;
+ if (final_costs_.empty()) {
+ final_cost = 0.0;
+ } else {
+ IterType iter = final_costs_.find(tok);
+ if (iter != final_costs_.end())
+ final_cost = iter->second;
+ else
+ final_cost = std::numeric_limits<BaseFloat>::infinity();
+ }
+ BaseFloat tok_extra_cost = tok->tot_cost + final_cost - final_best_cost_;
+ // tok_extra_cost will be a "min" over either directly being final, or
+ // being indirectly final through other links, and the loop below may
+ // decrease its value:
+ for (link = tok->links; link != NULL;) {
+ // See if we need to excise this link...
+ Token *next_tok = link->next_tok;
+ BaseFloat link_extra_cost =
+ next_tok->extra_cost +
+ ((tok->tot_cost + link->acoustic_cost + link->graph_cost) -
+ next_tok->tot_cost);
+ if (link_extra_cost > config_.lattice_beam) { // excise link
+ ForwardLinkT *next_link = link->next;
+ if (prev_link != NULL)
+ prev_link->next = next_link;
+ else
+ tok->links = next_link;
+ delete link;
+ link = next_link; // advance link but leave prev_link the same.
+ } else { // keep the link and update the tok_extra_cost if needed.
+ if (link_extra_cost < 0.0) { // this is just a precaution.
+ if (link_extra_cost < -0.01)
+ KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
+ link_extra_cost = 0.0;
+ }
+ if (link_extra_cost < tok_extra_cost) tok_extra_cost = link_extra_cost;
+ prev_link = link;
+ link = link->next;
+ }
+ }
+ // prune away tokens worse than lattice_beam above best path. This step
+ // was not necessary in the non-final case because then, this case
+ // showed up as having no forward links. Here, the tok_extra_cost has
+ // an extra component relating to the final-prob.
+ if (tok_extra_cost > config_.lattice_beam)
+ tok_extra_cost = std::numeric_limits<BaseFloat>::infinity();
+ // to be pruned in PruneTokensForFrame
+
+ if (!ApproxEqual(tok->extra_cost, tok_extra_cost, delta)) changed = true;
+ tok->extra_cost = tok_extra_cost; // will be +infinity or <= lattice_beam_.
+ }
+ } // while changed
+}
+
+template <typename FST, typename Token>
+BaseFloat LatticeIncrementalDecoderTpl<FST, Token>::FinalRelativeCost() const {
+ BaseFloat relative_cost;
+ ComputeFinalCosts(NULL, &relative_cost, NULL);
+ return relative_cost;
+}
+
+// Prune away any tokens on this frame that have no forward links.
+// [we don't do this in PruneForwardLinks because it would give us
+// a problem with dangling pointers].
+// It's called by PruneActiveTokens if any forward links have been pruned
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::PruneTokensForFrame(
+ int32 frame_plus_one) {
+ KALDI_ASSERT(frame_plus_one >= 0 && frame_plus_one < active_toks_.size());
+ Token *&toks = active_toks_[frame_plus_one].toks;
+ if (toks == NULL) KALDI_WARN << "No tokens alive [doing pruning]";
+ Token *tok, *next_tok, *prev_tok = NULL;
+ int32 num_toks = 0;
+ for (tok = toks; tok != NULL; tok = next_tok, num_toks++) {
+ next_tok = tok->next;
+ if (tok->extra_cost == std::numeric_limits<BaseFloat>::infinity()) {
+ // token is unreachable from end of graph; (no forward links survived)
+ // excise tok from list and delete tok.
+ if (prev_tok != NULL)
+ prev_tok->next = tok->next;
+ else
+ toks = tok->next;
+ delete tok;
+ num_toks_--;
+ } else { // fetch next Token
+ prev_tok = tok;
+ }
+ }
+ active_toks_[frame_plus_one].num_toks = num_toks;
+}
+
+// Go backwards through still-alive tokens, pruning them, starting not from
+// the current frame (where we want to keep all tokens) but from the frame before
+// that. We go backwards through the frames and stop when we reach a point
+// where the delta-costs are not changing (and the delta controls when we consider
+// a cost to have "not changed").
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::PruneActiveTokens(BaseFloat delta) {
+ int32 cur_frame_plus_one = NumFramesDecoded();
+ int32 num_toks_begin = num_toks_;
+
+ if (active_toks_[cur_frame_plus_one].num_toks == -1){
+ // The current frame's tokens don't get pruned so they don't get counted
+ // (the count is needed by the incremental determinization code).
+ // Fix this.
+ int this_frame_num_toks = 0;
+ for (Token *t = active_toks_[cur_frame_plus_one].toks; t != NULL; t = t->next)
+ this_frame_num_toks++;
+ active_toks_[cur_frame_plus_one].num_toks = this_frame_num_toks;
+ }
+
+ // The index "f" below represents a "frame plus one", i.e. you'd have to subtract
+ // one to get the corresponding index for the decodable object.
+ for (int32 f = cur_frame_plus_one - 1; f >= 0; f--) {
+ // Reason why we need to prune forward links in this situation:
+ // (1) we have never pruned them (new TokenList)
+ // (2) we have not yet pruned the forward links to the next f,
+ // after any of those tokens have changed their extra_cost.
+ if (active_toks_[f].must_prune_forward_links) {
+ bool extra_costs_changed = false, links_pruned = false;
+ PruneForwardLinks(f, &extra_costs_changed, &links_pruned, delta);
+ if (extra_costs_changed && f > 0) // any token has changed extra_cost
+ active_toks_[f - 1].must_prune_forward_links = true;
+ if (links_pruned) // any link was pruned
+ active_toks_[f].must_prune_tokens = true;
+ active_toks_[f].must_prune_forward_links = false; // job done
+ }
+ if (f + 1 < cur_frame_plus_one && // except for last f (no forward links)
+ active_toks_[f + 1].must_prune_tokens) {
+ PruneTokensForFrame(f + 1);
+ active_toks_[f + 1].must_prune_tokens = false;
+ }
+ }
+ KALDI_VLOG(4) << "pruned tokens from " << num_toks_begin
+ << " to " << num_toks_;
+}
+
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::ComputeFinalCosts(
+ unordered_map<Token *, BaseFloat> *final_costs, BaseFloat *final_relative_cost,
+ BaseFloat *final_best_cost) const {
+ if (decoding_finalized_) {
+ // If we finalized decoding, the list toks_ will no longer exist, so return
+ // something we already computed.
+ if (final_costs) *final_costs = final_costs_;
+ if (final_relative_cost) *final_relative_cost = final_relative_cost_;
+ if (final_best_cost) *final_best_cost = final_best_cost_;
+ return;
+ }
+ if (final_costs != NULL) final_costs->clear();
+ const Elem *final_toks = toks_.GetList();
+ BaseFloat infinity = std::numeric_limits<BaseFloat>::infinity();
+ BaseFloat best_cost = infinity, best_cost_with_final = infinity;
+
+ while (final_toks != NULL) {
+ StateId state = final_toks->key;
+ Token *tok = final_toks->val;
+ const Elem *next = final_toks->tail;
+ BaseFloat final_cost = fst_->Final(state).Value();
+ BaseFloat cost = tok->tot_cost, cost_with_final = cost + final_cost;
+ best_cost = std::min(cost, best_cost);
+ best_cost_with_final = std::min(cost_with_final, best_cost_with_final);
+ if (final_costs != NULL && final_cost != infinity)
+ (*final_costs)[tok] = final_cost;
+ final_toks = next;
+ }
+ if (final_relative_cost != NULL) {
+ if (best_cost == infinity && best_cost_with_final == infinity) {
+ // Likely this will only happen if there are no tokens surviving.
+ // This seems the least bad way to handle it.
+ *final_relative_cost = infinity;
+ } else {
+ *final_relative_cost = best_cost_with_final - best_cost;
+ }
+ }
+ if (final_best_cost != NULL) {
+ if (best_cost_with_final != infinity) { // final-state exists.
+ *final_best_cost = best_cost_with_final;
+ } else { // no final-state exists.
+ *final_best_cost = best_cost;
+ }
+ }
+}
+
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::AdvanceDecoding(
+ DecodableInterface *decodable, int32 max_num_frames) {
+ if (std::is_same<FST, fst::Fst<fst::StdArc> >::value) {
+ // if the type 'FST' is the FST base-class, then see if the FST type of fst_
+ // is actually VectorFst or ConstFst. If so, call the AdvanceDecoding()
+ // function after casting *this to the more specific type.
+ if (fst_->Type() == "const") {
+ LatticeIncrementalDecoderTpl<fst::ConstFst<fst::StdArc>, Token> *this_cast =
+ reinterpret_cast<
+ LatticeIncrementalDecoderTpl<fst::ConstFst<fst::StdArc>, Token> *>(
+ this);
+ this_cast->AdvanceDecoding(decodable, max_num_frames);
+ return;
+ } else if (fst_->Type() == "vector") {
+ LatticeIncrementalDecoderTpl<fst::VectorFst<fst::StdArc>, Token> *this_cast =
+ reinterpret_cast<
+ LatticeIncrementalDecoderTpl<fst::VectorFst<fst::StdArc>, Token> *>(
+ this);
+ this_cast->AdvanceDecoding(decodable, max_num_frames);
+ return;
+ }
+ }
+
+ KALDI_ASSERT(!active_toks_.empty() && !decoding_finalized_ &&
+ "You must call InitDecoding() before AdvanceDecoding");
+ int32 num_frames_ready = decodable->NumFramesReady();
+ // num_frames_ready must be >= num_frames_decoded, or else
+ // the number of frames ready must have decreased (which doesn't
+ // make sense) or the decodable object changed between calls
+ // (which isn't allowed).
+ KALDI_ASSERT(num_frames_ready >= NumFramesDecoded());
+ int32 target_frames_decoded = num_frames_ready;
+ if (max_num_frames >= 0)
+ target_frames_decoded =
+ std::min(target_frames_decoded, NumFramesDecoded() + max_num_frames);
+ while (NumFramesDecoded() < target_frames_decoded) {
+ if (NumFramesDecoded() % config_.prune_interval == 0) {
+ PruneActiveTokens(config_.lattice_beam * config_.prune_scale);
+ }
+ BaseFloat cost_cutoff = ProcessEmitting(decodable);
+ ProcessNonemitting(cost_cutoff);
+ }
+ UpdateLatticeDeterminization();
+}
+
+// FinalizeDecoding() is a version of PruneActiveTokens that we call
+// (optionally) on the final frame. Takes into account the final-prob of
+// tokens. This function used to be called PruneActiveTokensFinal().
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::FinalizeDecoding() {
+ int32 final_frame_plus_one = NumFramesDecoded();
+ int32 num_toks_begin = num_toks_;
+ // PruneForwardLinksFinal() prunes the final frame (with final-probs), and
+ // sets decoding_finalized_.
+ PruneForwardLinksFinal();
+ for (int32 f = final_frame_plus_one - 1; f >= 0; f--) {
+ bool b1, b2; // values not used.
+ BaseFloat dontcare = 0.0; // delta of zero means we must always update
+ PruneForwardLinks(f, &b1, &b2, dontcare);
+ PruneTokensForFrame(f + 1);
+ }
+ PruneTokensForFrame(0);
+ KALDI_VLOG(4) << "pruned tokens from " << num_toks_begin << " to " << num_toks_;
+}
+
+/// Gets the weight cutoff. Also counts the active tokens.
+template <typename FST, typename Token>
+BaseFloat LatticeIncrementalDecoderTpl<FST, Token>::GetCutoff(
+ Elem *list_head, size_t *tok_count, BaseFloat *adaptive_beam, Elem **best_elem) {
+ BaseFloat best_weight = std::numeric_limits<BaseFloat>::infinity();
+ // positive == high cost == bad.
+ size_t count = 0;
+ if (config_.max_active == std::numeric_limits<int32>::max() &&
+ config_.min_active == 0) {
+ for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
+ BaseFloat w = static_cast<BaseFloat>(e->val->tot_cost);
+ if (w < best_weight) {
+ best_weight = w;
+ if (best_elem) *best_elem = e;
+ }
+ }
+ if (tok_count != NULL) *tok_count = count;
+ if (adaptive_beam != NULL) *adaptive_beam = config_.beam;
+ return best_weight + config_.beam;
+ } else {
+ tmp_array_.clear();
+ for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
+ BaseFloat w = e->val->tot_cost;
+ tmp_array_.push_back(w);
+ if (w < best_weight) {
+ best_weight = w;
+ if (best_elem) *best_elem = e;
+ }
+ }
+ if (tok_count != NULL) *tok_count = count;
+
+ BaseFloat beam_cutoff = best_weight + config_.beam,
+ min_active_cutoff = std::numeric_limits<BaseFloat>::infinity(),
+ max_active_cutoff = std::numeric_limits<BaseFloat>::infinity();
+
+ KALDI_VLOG(6) << "Number of tokens active on frame " << NumFramesDecoded()
+ << " is " << tmp_array_.size();
+
+ if (tmp_array_.size() > static_cast<size_t>(config_.max_active)) {
+ std::nth_element(tmp_array_.begin(), tmp_array_.begin() + config_.max_active,
+ tmp_array_.end());
+ max_active_cutoff = tmp_array_[config_.max_active];
+ }
+ if (max_active_cutoff < beam_cutoff) { // max_active is tighter than beam.
+ if (adaptive_beam)
+ *adaptive_beam = max_active_cutoff - best_weight + config_.beam_delta;
+ return max_active_cutoff;
+ }
+ if (tmp_array_.size() > static_cast<size_t>(config_.min_active)) {
+ if (config_.min_active == 0)
+ min_active_cutoff = best_weight;
+ else {
+ std::nth_element(tmp_array_.begin(), tmp_array_.begin() + config_.min_active,
+ tmp_array_.size() > static_cast<size_t>(config_.max_active)
+ ? tmp_array_.begin() + config_.max_active
+ : tmp_array_.end());
+ min_active_cutoff = tmp_array_[config_.min_active];
+ }
+ }
+ if (min_active_cutoff > beam_cutoff) { // min_active is looser than beam.
+ if (adaptive_beam)
+ *adaptive_beam = min_active_cutoff - best_weight + config_.beam_delta;
+ return min_active_cutoff;
+ } else {
+ *adaptive_beam = config_.beam;
+ return beam_cutoff;
+ }
+ }
+}
+
+template <typename FST, typename Token>
+BaseFloat LatticeIncrementalDecoderTpl<FST, Token>::ProcessEmitting(
+ DecodableInterface *decodable) {
+ KALDI_ASSERT(active_toks_.size() > 0);
+ int32 frame = active_toks_.size() - 1; // frame is the frame-index
+ // (zero-based) used to get likelihoods
+ // from the decodable object.
+ active_toks_.resize(active_toks_.size() + 1);
+
+ Elem *final_toks = toks_.Clear(); // analogous to swapping prev_toks_ / cur_toks_
+ // in simple-decoder.h. Removes the Elems from
+ // being indexed in the hash in toks_.
+ Elem *best_elem = NULL;
+ BaseFloat adaptive_beam;
+ size_t tok_cnt;
+ BaseFloat cur_cutoff = GetCutoff(final_toks, &tok_cnt, &adaptive_beam, &best_elem);
+ KALDI_VLOG(6) << "Adaptive beam on frame " << NumFramesDecoded() << " is "
+ << adaptive_beam;
+
+ PossiblyResizeHash(tok_cnt); // This makes sure the hash is always big enough.
+
+ BaseFloat next_cutoff = std::numeric_limits<BaseFloat>::infinity();
+ // pruning "online" before having seen all tokens
+
+ BaseFloat cost_offset = 0.0; // Used to keep probabilities in a good
+ // dynamic range.
+
+ // First process the best token to get a hopefully
+ // reasonably tight bound on the next cutoff. The only
+ // products of the next block are "next_cutoff" and "cost_offset".
+ if (best_elem) {
+ StateId state = best_elem->key;
+ Token *tok = best_elem->val;
+ cost_offset = -tok->tot_cost;
+ for (fst::ArcIterator<FST> aiter(*fst_, state); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0) { // propagate..
+ BaseFloat new_weight = arc.weight.Value() + cost_offset -
+ decodable->LogLikelihood(frame, arc.ilabel) +
+ tok->tot_cost;
+ if (new_weight + adaptive_beam < next_cutoff)
+ next_cutoff = new_weight + adaptive_beam;
+ }
+ }
+ }
+
+ // Store the offset on the acoustic likelihoods that we're applying.
+ // Could just do cost_offsets_.push_back(cost_offset), but we
+ // do it this way as it's more robust to future code changes.
+ cost_offsets_.resize(frame + 1, 0.0);
+ cost_offsets_[frame] = cost_offset;
+
+ // the tokens are now owned here, in final_toks, and the hash is empty.
+ // 'owned' is a complex thing here; the point is we need to call DeleteElem
+ // on each elem 'e' to let toks_ know we're done with them.
+ for (Elem *e = final_toks, *e_tail; e != NULL; e = e_tail) {
+ // loop this way because we delete "e" as we go.
+ StateId state = e->key;
+ Token *tok = e->val;
+ if (tok->tot_cost <= cur_cutoff) {
+ for (fst::ArcIterator<FST> aiter(*fst_, state); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0) { // propagate..
+ BaseFloat ac_cost =
+ cost_offset - decodable->LogLikelihood(frame, arc.ilabel),
+ graph_cost = arc.weight.Value(), cur_cost = tok->tot_cost,
+ tot_cost = cur_cost + ac_cost + graph_cost;
+ if (tot_cost >= next_cutoff)
+ continue;
+ else if (tot_cost + adaptive_beam < next_cutoff)
+ next_cutoff = tot_cost + adaptive_beam; // prune by best current token
+ // Note: the frame indexes into active_toks_ are one-based,
+ // hence the + 1.
+ Token *next_tok =
+ FindOrAddToken(arc.nextstate, frame + 1, tot_cost, tok, NULL);
+ // NULL: no change indicator needed
+
+ // Add ForwardLink from tok to next_tok (put on head of list tok->links)
+ tok->links = new ForwardLinkT(next_tok, arc.ilabel, arc.olabel, graph_cost,
+ ac_cost, tok->links);
+ }
+ } // for all arcs
+ }
+ e_tail = e->tail;
+ toks_.Delete(e); // delete Elem
+ }
+ return next_cutoff;
+}
+
+// static inline
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::DeleteForwardLinks(Token *tok) {
+ ForwardLinkT *l = tok->links, *m;
+ while (l != NULL) {
+ m = l->next;
+ delete l;
+ l = m;
+ }
+ tok->links = NULL;
+}
+
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::ProcessNonemitting(BaseFloat cutoff) {
+ KALDI_ASSERT(!active_toks_.empty());
+ int32 frame = static_cast<int32>(active_toks_.size()) - 2;
+ // Note: "frame" is the time-index we just processed, or -1 if
+ // we are processing the nonemitting transitions before the
+ // first frame (called from InitDecoding()).
+
+ // Processes nonemitting arcs for one frame. Propagates within toks_.
+ // Note-- this queue structure is is not very optimal as
+ // it may cause us to process states unnecessarily (e.g. more than once),
+ // but in the baseline code, turning this vector into a set to fix this
+ // problem did not improve overall speed.
+
+ KALDI_ASSERT(queue_.empty());
+
+ if (toks_.GetList() == NULL) {
+ if (!warned_) {
+ KALDI_WARN << "Error, no surviving tokens: frame is " << frame;
+ warned_ = true;
+ }
+ }
+
+ for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail) {
+ StateId state = e->key;
+ if (fst_->NumInputEpsilons(state) != 0) queue_.push_back(state);
+ }
+
+ while (!queue_.empty()) {
+ StateId state = queue_.back();
+ queue_.pop_back();
+
+ Token *tok =
+ toks_.Find(state)
+ ->val; // would segfault if state not in toks_ but this can't happen.
+ BaseFloat cur_cost = tok->tot_cost;
+ if (cur_cost >= cutoff) // Don't bother processing successors.
+ continue;
+ // If "tok" has any existing forward links, delete them,
+ // because we're about to regenerate them. This is a kind
+ // of non-optimality (remember, this is the simple decoder),
+ // but since most states are emitting it's not a huge issue.
+ DeleteForwardLinks(tok); // necessary when re-visiting
+ tok->links = NULL;
+ for (fst::ArcIterator<FST> aiter(*fst_, state); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel == 0) { // propagate nonemitting only...
+ BaseFloat graph_cost = arc.weight.Value(), tot_cost = cur_cost + graph_cost;
+ if (tot_cost < cutoff) {
+ bool changed;
+
+ Token *new_tok =
+ FindOrAddToken(arc.nextstate, frame + 1, tot_cost, tok, &changed);
+
+ tok->links =
+ new ForwardLinkT(new_tok, 0, arc.olabel, graph_cost, 0, tok->links);
+
+ // "changed" tells us whether the new token has a different
+ // cost from before, or is new [if so, add into queue].
+ if (changed && fst_->NumInputEpsilons(arc.nextstate) != 0)
+ queue_.push_back(arc.nextstate);
+ }
+ }
+ } // for all arcs
+ } // while queue not empty
+}
+
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<FST, Token>::DeleteElems(Elem *list) {
+ for (Elem *e = list, *e_tail; e != NULL; e = e_tail) {
+ e_tail = e->tail;
+ toks_.Delete(e);
+ }
+}
+
+template <typename FST, typename Token>
+void LatticeIncrementalDecoderTpl<
+ FST, Token>::ClearActiveTokens() { // a cleanup routine, at utt end/begin
+ for (size_t i = 0; i < active_toks_.size(); i++) {
+ // Delete all tokens alive on this frame, and any forward
+ // links they may have.
+ for (Token *tok = active_toks_[i].toks; tok != NULL;) {
+ DeleteForwardLinks(tok);
+ Token *next_tok = tok->next;
+ delete tok;
+ num_toks_--;
+ tok = next_tok;
+ }
+ }
+ active_toks_.clear();
+ KALDI_ASSERT(num_toks_ == 0);
+}
+
+
+template <typename FST, typename Token>
+const CompactLattice& LatticeIncrementalDecoderTpl<FST, Token>::GetLattice(
+ int32 num_frames_to_include,
+ bool use_final_probs) {
+ KALDI_ASSERT(num_frames_to_include >= num_frames_in_lattice_ &&
+ num_frames_to_include <= NumFramesDecoded());
+
+
+ if (num_frames_in_lattice_ > 0 &&
+ determinizer_.GetLattice().NumStates() == 0) {
+ /* Something went wrong, lattice is empty and will continue to be empty.
+ User-level code should detect and deal with this.
+ */
+ num_frames_in_lattice_ = num_frames_to_include;
+ return determinizer_.GetLattice();
+ }
+
+ if (decoding_finalized_ && !use_final_probs) {
+ // This is not supported
+ KALDI_ERR << "You cannot get the lattice without final-probs after "
+ "calling FinalizeDecoding().";
+ }
+ if (use_final_probs && num_frames_to_include != NumFramesDecoded()) {
+ /* This is because we only remember the relation between HCLG states and
+ Tokens for the current frame; the Token does not have a `state` field. */
+ KALDI_ERR << "use-final-probs may no be true if you are not "
+ "getting a lattice for all frames decoded so far.";
+ }
+
+
+ if (num_frames_to_include > num_frames_in_lattice_) {
+ /* Make sure the token-pruning is up to date. If we just pruned the tokens,
+ this will do very little work. */
+ PruneActiveTokens(config_.lattice_beam * config_.prune_scale);
+
+ if (determinizer_.GetLattice().NumStates() == 0 ||
+ determinizer_.GetLattice().Final(0) != CompactLatticeWeight::Zero()) {
+ num_frames_in_lattice_ = 0;
+ determinizer_.Init();
+ }
+
+ Lattice chunk_lat;
+
+ unordered_map<Label, LatticeArc::StateId> token_label2state;
+ if (num_frames_in_lattice_ != 0) {
+ determinizer_.InitializeRawLatticeChunk(&chunk_lat,
+ &token_label2state);
+ }
+
+ // tok_map will map from Token* to state-id in chunk_lat.
+ // The cur and prev versions alternate on different frames.
+ unordered_map<Token*, StateId> &tok2state_map(temp_token_map_);
+ tok2state_map.clear();
+
+ unordered_map<Token*, Label> &next_token2label_map(token2label_map_temp_);
+ next_token2label_map.clear();
+
+ { // Deal with the last frame in the chunk, the one numbered `num_frames_to_include`.
+ // (Yes, this is backwards). We allocate token labels, and set tokens as
+ // final, but don't add any transitions. This may leave some states
+ // disconnected (e.g. due to chains of nonemitting arcs), but it's OK; we'll
+ // fix it when we generate the next chunk of lattice.
+ int32 frame = num_frames_to_include;
+ // Allocate state-ids for all tokens on this frame.
+
+ for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
+ /* If we included the final-costs at this stage, they will cause
+ non-final states to be pruned out from the end of the lattice. */
+ BaseFloat final_cost;
+ { // This block computes final_cost
+ if (decoding_finalized_) {
+ if (final_costs_.empty()) {
+ final_cost = 0.0; /* No final-state survived, so treat all as final
+ * with probability One(). */
+ } else {
+ auto iter = final_costs_.find(tok);
+ if (iter == final_costs_.end())
+ final_cost = std::numeric_limits<BaseFloat>::infinity();
+ else
+ final_cost = iter->second;
+ }
+ } else {
+ /* this is a `fake` final-cost used to guide pruning. It's as if we
+ set the betas (backward-probs) on the final frame to the
+ negatives of the corresponding alphas, so all tokens on the last
+ frae will be on a best path.. the extra_cost for each token
+ always corresponds to its alpha+beta on this assumption. We want
+ the final_cost here to correspond to the beta (backward-prob), so
+ we get that by final_cost = extra_cost - tot_cost.
+ [The tot_cost is the forward/alpha cost.]
+ */
+ final_cost = tok->extra_cost - tok->tot_cost;
+ }
+ }
+
+ StateId state = chunk_lat.AddState();
+ tok2state_map[tok] = state;
+ if (final_cost < std::numeric_limits<BaseFloat>::infinity()) {
+ next_token2label_map[tok] = AllocateNewTokenLabel();
+ StateId token_final_state = chunk_lat.AddState();
+ LatticeArc::Label ilabel = 0,
+ olabel = (next_token2label_map[tok] = AllocateNewTokenLabel());
+ chunk_lat.AddArc(state,
+ LatticeArc(ilabel, olabel,
+ LatticeWeight::One(),
+ token_final_state));
+ chunk_lat.SetFinal(token_final_state, LatticeWeight(final_cost, 0.0));
+ }
+ }
+ }
+
+ // Go in reverse order over the remaining frames so we can create arcs as we
+ // go, and their destination-states will already be in the map.
+ for (int32 frame = num_frames_to_include;
+ frame >= num_frames_in_lattice_; frame--) {
+ // The conditional below is needed for the last frame of the utterance.
+ BaseFloat cost_offset = (frame < cost_offsets_.size() ?
+ cost_offsets_[frame] : 0.0);
+
+ // For the first frame of the chunk, we need to make sure the states are
+ // the ones created by InitializeRawLatticeChunk() (where not pruned away).
+ if (frame == num_frames_in_lattice_ && num_frames_in_lattice_ != 0) {
+ for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
+ auto iter = token2label_map_.find(tok);
+ KALDI_ASSERT(iter != token2label_map_.end());
+ Label token_label = iter->second;
+ auto iter2 = token_label2state.find(token_label);
+ if (iter2 != token_label2state.end()) {
+ StateId state = iter2->second;
+ tok2state_map[tok] = state;
+ } else {
+ // Some states may have been pruned out, but we should still allocate
+ // them. They might have been part of chains of nonemitting arcs
+ // where the state became disconnected because the last chunk didn't
+ // include arcs starting at this frame.
+ StateId state = chunk_lat.AddState();
+ tok2state_map[tok] = state;
+ }
+ }
+ } else if (frame != num_frames_to_include) { // We already created states
+ // for the last frame.
+ for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
+ StateId state = chunk_lat.AddState();
+ tok2state_map[tok] = state;
+ }
+ }
+ for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
+ auto iter = tok2state_map.find(tok);
+ KALDI_ASSERT(iter != tok2state_map.end());
+ StateId cur_state = iter->second;
+ for (ForwardLinkT *l = tok->links; l != NULL; l = l->next) {
+ auto next_iter = tok2state_map.find(l->next_tok);
+ if (next_iter == tok2state_map.end()) {
+ // Emitting arcs from the last frame we're including -- ignore
+ // these.
+ KALDI_ASSERT(frame == num_frames_to_include);
+ continue;
+ }
+ StateId next_state = next_iter->second;
+ BaseFloat this_offset = (l->ilabel != 0 ? cost_offset : 0);
+ LatticeArc arc(l->ilabel, l->olabel,
+ LatticeWeight(l->graph_cost, l->acoustic_cost - this_offset),
+ next_state);
+ // Note: the epsilons get redundantly included at the end and beginning
+ // of successive chunks. These will get removed in the determinization.
+ chunk_lat.AddArc(cur_state, arc);
+ }
+ }
+ }
+ if (num_frames_in_lattice_ == 0) {
+ // This block locates the start token. NOTE: we use the fact that in the
+ // linked list of tokens, things are added at the head, so the start state
+ // must be at the tail. If this data structure is changed in future, we
+ // might need to explicitly store the start token as a class member.
+ Token *tok = active_toks_[0].toks;
+ if (tok == NULL) {
+ KALDI_WARN << "No tokens exist on start frame";
+ return determinizer_.GetLattice(); // will be empty.
+ }
+ while (tok->next != NULL)
+ tok = tok->next;
+ Token *start_token = tok;
+ auto iter = tok2state_map.find(start_token);
+ KALDI_ASSERT(iter != tok2state_map.end());
+ StateId start_state = iter->second;
+ chunk_lat.SetStart(start_state);
+ }
+ token2label_map_.swap(next_token2label_map);
+
+ // bool finished_before_beam =
+ determinizer_.AcceptRawLatticeChunk(&chunk_lat);
+ // We are ignoring the return status, which say whether it finished before the beam.
+
+ num_frames_in_lattice_ = num_frames_to_include;
+
+ if (determinizer_.GetLattice().NumStates() == 0)
+ return determinizer_.GetLattice(); // Something went wrong, lattice is empty.
+ }
+
+ unordered_map<Token*, BaseFloat> token2final_cost;
+ unordered_map<Label, BaseFloat> token_label2final_cost;
+ if (use_final_probs) {
+ ComputeFinalCosts(&token2final_cost, NULL, NULL);
+ for (const auto &p: token2final_cost) {
+ Token *tok = p.first;
+ BaseFloat cost = p.second;
+ auto iter = token2label_map_.find(tok);
+ if (iter != token2label_map_.end()) {
+ /* Some tokens may not have survived the pruned determinization. */
+ Label token_label = iter->second;
+ bool ret = token_label2final_cost.insert({token_label, cost}).second;
+ KALDI_ASSERT(ret); /* Make sure it was inserted. */
+ }
+ }
+ }
+ /* Note: these final-probs won't affect the next chunk, only the lattice
+ returned from GetLattice(). They are kind of temporaries. */
+ determinizer_.SetFinalCosts(token_label2final_cost.empty() ? NULL :
+ &token_label2final_cost);
+
+ return determinizer_.GetLattice();
+}
+
+
+template <typename FST, typename Token>
+int32 LatticeIncrementalDecoderTpl<FST, Token>::GetNumToksForFrame(int32 frame) {
+ int32 r = 0;
+ for (Token *tok = active_toks_[frame].toks; tok; tok = tok->next) r++;
+ return r;
+}
+
+
+
+/* This utility function adds an arc to a Lattice, but where the source is a
+ CompactLatticeArc. If the CompactLatticeArc has a string with length greater
+ than 1, this will require adding extra states to `lat`.
+ */
+static void AddCompactLatticeArcToLattice(
+ const CompactLatticeArc &clat_arc,
+ LatticeArc::StateId src_state,
+ Lattice *lat) {
+ const std::vector<int32> &string = clat_arc.weight.String();
+ size_t N = string.size();
+ if (N == 0) {
+ LatticeArc arc;
+ arc.ilabel = 0;
+ arc.olabel = clat_arc.ilabel;
+ arc.nextstate = clat_arc.nextstate;
+ arc.weight = clat_arc.weight.Weight();
+ lat->AddArc(src_state, arc);
+ } else {
+ LatticeArc::StateId cur_state = src_state;
+ for (size_t i = 0; i < N; i++) {
+ LatticeArc arc;
+ arc.ilabel = string[i];
+ arc.olabel = (i == 0 ? clat_arc.ilabel : 0);
+ arc.nextstate = (i + 1 == N ? clat_arc.nextstate : lat->AddState());
+ arc.weight = (i == 0 ? clat_arc.weight.Weight() : LatticeWeight::One());
+ lat->AddArc(cur_state, arc);
+ cur_state = arc.nextstate;
+ }
+ }
+}
+
+
+void LatticeIncrementalDeterminizer::Init() {
+ non_final_redet_states_.clear();
+ clat_.DeleteStates();
+ final_arcs_.clear();
+ forward_costs_.clear();
+ arcs_in_.clear();
+}
+
+CompactLattice::StateId LatticeIncrementalDeterminizer::AddStateToClat() {
+ CompactLattice::StateId ans = clat_.AddState();
+ forward_costs_.push_back(std::numeric_limits<BaseFloat>::infinity());
+ KALDI_ASSERT(forward_costs_.size() == ans + 1);
+ arcs_in_.resize(ans + 1);
+ return ans;
+}
+
+void LatticeIncrementalDeterminizer::AddArcToClat(
+ CompactLattice::StateId state,
+ const CompactLatticeArc &arc) {
+ BaseFloat forward_cost = forward_costs_[state] +
+ ConvertToCost(arc.weight);
+ if (forward_cost == std::numeric_limits<BaseFloat>::infinity())
+ return;
+ int32 arc_idx = clat_.NumArcs(state);
+ clat_.AddArc(state, arc);
+ arcs_in_[arc.nextstate].push_back({state, arc_idx});
+ if (forward_cost < forward_costs_[arc.nextstate])
+ forward_costs_[arc.nextstate] = forward_cost;
+}
+
+// See documentation in header
+void LatticeIncrementalDeterminizer::IdentifyTokenFinalStates(
+ const CompactLattice &chunk_clat,
+ std::unordered_map<CompactLattice::StateId, CompactLatticeArc::Label> *token_map) const {
+ token_map->clear();
+ using StateId = CompactLattice::StateId;
+ using Label = CompactLatticeArc::Label;
+
+ StateId num_states = chunk_clat.NumStates();
+ for (StateId state = 0; state < num_states; state++) {
+ for (fst::ArcIterator<CompactLattice> aiter(chunk_clat, state);
+ !aiter.Done(); aiter.Next()) {
+ const CompactLatticeArc &arc = aiter.Value();
+ if (arc.olabel >= kTokenLabelOffset && arc.olabel < kMaxTokenLabel) {
+ StateId nextstate = arc.nextstate;
+ auto r = token_map->insert({nextstate, arc.olabel});
+ // Check consistency of labels on incoming arcs
+ KALDI_ASSERT(r.first->second == arc.olabel);
+ }
+ }
+ }
+}
+
+
+
+
+void LatticeIncrementalDeterminizer::GetNonFinalRedetStates() {
+ using StateId = CompactLattice::StateId;
+ non_final_redet_states_.clear();
+ non_final_redet_states_.reserve(final_arcs_.size());
+
+ std::vector<StateId> state_queue;
+ for (const CompactLatticeArc &arc: final_arcs_) {
+ // Note: we abuse the .nextstate field to store the state which is really
+ // the source of that arc.
+ StateId redet_state = arc.nextstate;
+ if (forward_costs_[redet_state] != std::numeric_limits<BaseFloat>::infinity()) {
+ // if it is accessible..
+ if (non_final_redet_states_.insert(redet_state).second) {
+ // it was not already there
+ state_queue.push_back(redet_state);
+ }
+ }
+ }
+ // Add any states that are reachable from the states above.
+ while (!state_queue.empty()) {
+ StateId s = state_queue.back();
+ state_queue.pop_back();
+ for (fst::ArcIterator<CompactLattice> aiter(clat_, s); !aiter.Done();
+ aiter.Next()) {
+ const CompactLatticeArc &arc = aiter.Value();
+ StateId nextstate = arc.nextstate;
+ if (non_final_redet_states_.insert(nextstate).second)
+ state_queue.push_back(nextstate); // it was not already there
+ }
+ }
+}
+
+
+void LatticeIncrementalDeterminizer::InitializeRawLatticeChunk(
+ Lattice *olat,
+ unordered_map<Label, LatticeArc::StateId> *token_label2state) {
+ using namespace fst;
+
+ olat->DeleteStates();
+ LatticeArc::StateId start_state = olat->AddState();
+ olat->SetStart(start_state);
+ token_label2state->clear();
+
+ // redet_state_map maps from state-ids in clat_ to state-ids in olat. This
+ // will be the set of states from which the arcs to final-states in the
+ // canonical appended lattice leave (physically, these are in the .nextstate
+ // elements of arcs_, since we use that field for the source state), plus any
+ // states reachable from those states.
+ unordered_map<CompactLattice::StateId, LatticeArc::StateId> redet_state_map;
+
+ for (CompactLattice::StateId redet_state: non_final_redet_states_)
+ redet_state_map[redet_state] = olat->AddState();
+
+ // First, process any arcs leaving the non-final redeterminized states that
+ // are not to final-states. (What we mean by "not to final states" is, not to
+ // stats that are final in the `canonical appended lattice`.. they may
+ // actually be physically final in clat_, because we make clat_ what we want
+ // to return to the user.
+ for (CompactLattice::StateId redet_state: non_final_redet_states_) {
+ LatticeArc::StateId lat_state = redet_state_map[redet_state];
+
+ for (ArcIterator<CompactLattice> aiter(clat_, redet_state);
+ !aiter.Done(); aiter.Next()) {
+ const CompactLatticeArc &arc = aiter.Value();
+ CompactLattice::StateId nextstate = arc.nextstate;
+ LatticeArc::StateId lat_nextstate = olat->NumStates();
+ auto r = redet_state_map.insert({nextstate, lat_nextstate});
+ if (r.second) { // Was inserted.
+ LatticeArc::StateId s = olat->AddState();
+ KALDI_ASSERT(s == lat_nextstate);
+ } else {
+ // was not inserted -> was already there.
+ lat_nextstate = r.first->second;
+ }
+ CompactLatticeArc clat_arc(arc);
+ clat_arc.nextstate = lat_nextstate;
+ AddCompactLatticeArcToLattice(clat_arc, lat_state, olat);
+ }
+ clat_.DeleteArcs(redet_state);
+ clat_.SetFinal(redet_state, CompactLatticeWeight::Zero());
+ }
+
+ for (const CompactLatticeArc &arc: final_arcs_) {
+ // We abuse the `nextstate` field to store the source state.
+ CompactLattice::StateId src_state = arc.nextstate;
+ auto iter = redet_state_map.find(src_state);
+ if (forward_costs_[src_state] == std::numeric_limits<BaseFloat>::infinity())
+ continue; /* Unreachable state */
+ KALDI_ASSERT(iter != redet_state_map.end());
+ LatticeArc::StateId src_lat_state = iter->second;
+ Label token_label = arc.ilabel; // will be == arc.olabel.
+ KALDI_ASSERT(token_label >= kTokenLabelOffset &&
+ token_label < kMaxTokenLabel);
+ auto r = token_label2state->insert({token_label,
+ olat->NumStates()});
+ LatticeArc::StateId dest_lat_state = r.first->second;
+ if (r.second) { // was inserted
+ LatticeArc::StateId new_state = olat->AddState();
+ KALDI_ASSERT(new_state == dest_lat_state);
+ }
+ CompactLatticeArc new_arc;
+ new_arc.nextstate = dest_lat_state;
+ /* We convert the token-label to epsilon; it's not needed anymore. */
+ new_arc.ilabel = new_arc.olabel = 0;
+ new_arc.weight = arc.weight;
+ AddCompactLatticeArcToLattice(new_arc, src_lat_state, olat);
+ }
+
+ // Now deal with the initial-probs. Arcs from initial-states to
+ // redeterminized-states in the raw lattice have an olabel that identifies the
+ // id of that redeterminized-state in clat_, and a cost that is derived from
+ // its entry in forward_costs_. These forward-probs are used to get the
+ // pruned lattice determinization to behave correctly, and will be canceled
+ // out later on.
+ //
+ // In the paper this is the second-from-last bullet in Sec. 5.2. NOTE: in the
+ // paper we state that we only include such arcs for "each redeterminized
+ // state that is either initial in det(A) or that has an arc entering it from
+ // a state that is not a redeterminized state." In fact, we include these
+ // arcs for all redeterminized states. I realized that it won't make a
+ // difference to the outcome, and it's easier to do it this way.
+ for (CompactLattice::StateId state_id: non_final_redet_states_) {
+ BaseFloat forward_cost = forward_costs_[state_id];
+ LatticeArc arc;
+ arc.ilabel = 0;
+ // The olabel (which appears where the word-id would) is what
+ // we call a 'state-label'. It identifies a state in clat_.
+ arc.olabel = state_id + kStateLabelOffset;
+ // It doesn't matter what field we put forward_cost in (or whether we
+ // divide it among them both; the effect on pruning is the same, and
+ // we will cancel it out later anyway.
+ arc.weight = LatticeWeight(forward_cost, 0);
+ auto iter = redet_state_map.find(state_id);
+ KALDI_ASSERT(iter != redet_state_map.end());
+ arc.nextstate = iter->second;
+ olat->AddArc(start_state, arc);
+ }
+}
+
+void LatticeIncrementalDeterminizer::GetRawLatticeFinalCosts(
+ const Lattice &raw_fst,
+ std::unordered_map<Label, BaseFloat> *old_final_costs) {
+ LatticeArc::StateId raw_fst_num_states = raw_fst.NumStates();
+ for (LatticeArc::StateId s = 0; s < raw_fst_num_states; s++) {
+ for (fst::ArcIterator<Lattice> aiter(raw_fst, s); !aiter.Done();
+ aiter.Next()) {
+ const LatticeArc &value = aiter.Value();
+ if (value.olabel >= (Label)kTokenLabelOffset &&
+ value.olabel < (Label)kMaxTokenLabel) {
+ LatticeWeight final_weight = raw_fst.Final(value.nextstate);
+ if (final_weight != LatticeWeight::Zero() &&
+ final_weight.Value2() != 0) {
+ KALDI_ERR << "Label " << value.olabel << " from state " << s
+ << " looks like a token-label but its next-state "
+ << value.nextstate <<
+ " has unexpected final-weight " << final_weight.Value1() << ','
+ << final_weight.Value2();
+ }
+ auto r = old_final_costs->insert({value.olabel,
+ final_weight.Value1()});
+ if (!r.second && r.first->second != final_weight.Value1()) {
+ // For any given token-label, all arcs in raw_fst with that
+ // olabel should go to the same state, so this should be
+ // impossible.
+ KALDI_ERR << "Unexpected mismatch in final-costs for tokens, "
+ << r.first->second << " vs " << final_weight.Value1();
+ }
+ }
+ }
+ }
+}
+
+
+bool LatticeIncrementalDeterminizer::ProcessArcsFromChunkStartState(
+ const CompactLattice &chunk_clat,
+ std::unordered_map<CompactLattice::StateId, CompactLattice::StateId> *state_map) {
+ using StateId = CompactLattice::StateId;
+ StateId clat_num_states = clat_.NumStates();
+
+ // Process arcs leaving the start state of chunk_clat. These arcs will have
+ // state-labels on them (unless this is the first chunk).
+ // For destination-states of those arcs, work out which states in
+ // clat_ they correspond to and update their forward_costs.
+ for (fst::ArcIterator<CompactLattice> aiter(chunk_clat, chunk_clat.Start());
+ !aiter.Done(); aiter.Next()) {
+ const CompactLatticeArc &arc = aiter.Value();
+ Label label = arc.ilabel; // ilabel == olabel; would be the olabel
+ // in a Lattice.
+ if (!(label >= kStateLabelOffset &&
+ label - kStateLabelOffset < clat_num_states)) {
+ // The label was not a state-label. This should only be possible on the
+ // first chunk.
+ KALDI_ASSERT(state_map->empty());
+ return true; // this is the first chunk.
+ }
+ StateId clat_state = label - kStateLabelOffset;
+ StateId chunk_state = arc.nextstate;
+ auto p = state_map->insert({chunk_state, clat_state});
+ StateId dest_clat_state = p.first->second;
+ // We deleted all its arcs in InitializeRawLatticeChunk
+ KALDI_ASSERT(clat_.NumArcs(clat_state) == 0);
+ /*
+ In almost all cases, dest_clat_state and clat_state will be the same state;
+ but there may be situations where two arcs with different state-labels
+ left the start state and entered the same next-state in chunk_clat; and in
+ these cases, they will be different.
+
+ We didn't address this issue in the paper (or actually realize it could be
+ a problem). What we do is pick one of the clat_states as the "canonical"
+ one, and redirect all incoming transitions of the others to enter the
+ "canonical" one. (Search below for new_in_arc.nextstate =
+ dest_clat_state).
+ */
+ if (clat_state != dest_clat_state) {
+ // Check that the start state isn't getting merged with any other state.
+ // If this were possible, we'd need to deal with it specially, but it
+ // can't be, because to be merged, 2 states must have identical arcs
+ // leaving them with identical weights, so we'd need to have another state
+ // on frame 0 identical to the start state, which is not possible if the
+ // lattice is deterministic and epsilon-free.
+ KALDI_ASSERT(clat_state != 0 && dest_clat_state != 0);
+ }
+
+ // in_weight is an extra weight that we'll include on arcs entering this
+ // state from the previous chunk. We need to cancel out
+ // `forward_costs[clat_state]`, which was included in the corresponding arc
+ // in the raw lattice for pruning purposes; and we need to include the
+ // weight on the arc from the start-state of `chunk_clat` to this state.
+ CompactLatticeWeight extra_weight_in = arc.weight;
+ extra_weight_in.SetWeight(
+ fst::Times(extra_weight_in.Weight(),
+ LatticeWeight(-forward_costs_[clat_state], 0.0)));
+
+ // We don't allow state 0 to be a redeterminized-state; calling code assures
+ // this. Search for `determinizer_.GetLattice().Final(0) !=
+ // CompactLatticeWeight::Zero())` to find that calling code.
+ KALDI_ASSERT(clat_state != 0);
+
+ // Note: 0 is the start state of clat_. This was checked.
+ forward_costs_[clat_state] = (clat_state == 0 ? 0 :
+ std::numeric_limits<BaseFloat>::infinity());
+ std::vector<std::pair<StateId, int32> > arcs_in;
+ arcs_in.swap(arcs_in_[clat_state]);
+ for (auto p: arcs_in) {
+ // Note: we'll be doing `continue` below if this input arc came from
+ // another redeterminized-state, because we did DeleteArcs() for them in
+ // InitializeRawLatticeChunk(). Those arcs will be transferred
+ // from chunk_clat later on.
+ CompactLattice::StateId src_state = p.first;
+ int32 arc_pos = p.second;
+
+ if (arc_pos >= (int32)clat_.NumArcs(src_state))
+ continue;
+ fst::MutableArcIterator<CompactLattice> aiter(&clat_, src_state);
+ aiter.Seek(arc_pos);
+ if (aiter.Value().nextstate != clat_state)
+ continue; // This arc record has become invalidated.
+ CompactLatticeArc new_in_arc(aiter.Value());
+ // In most cases we will have dest_clat_state == clat_state, so the next
+ // line won't change the value of .nextstate
+ new_in_arc.nextstate = dest_clat_state;
+ new_in_arc.weight = fst::Times(new_in_arc.weight, extra_weight_in);
+ aiter.SetValue(new_in_arc);
+
+ BaseFloat new_forward_cost = forward_costs_[src_state] +
+ ConvertToCost(new_in_arc.weight);
+ if (new_forward_cost < forward_costs_[dest_clat_state])
+ forward_costs_[dest_clat_state] = new_forward_cost;
+ arcs_in_[dest_clat_state].push_back(p);
+ }
+ }
+ return false; // this is not the first chunk.
+}
+
+void LatticeIncrementalDeterminizer::TransferArcsToClat(
+ const CompactLattice &chunk_clat,
+ bool is_first_chunk,
+ const std::unordered_map<CompactLattice::StateId, CompactLattice::StateId> &state_map,
+ const std::unordered_map<CompactLattice::StateId, Label> &chunk_state_to_token,
+ const std::unordered_map<Label, BaseFloat> &old_final_costs) {
+ using StateId = CompactLattice::StateId;
+ StateId chunk_num_states = chunk_clat.NumStates();
+
+ // Now transfer arcs from chunk_clat to clat_.
+ for (StateId chunk_state = (is_first_chunk ? 0 : 1);
+ chunk_state < chunk_num_states; chunk_state++) {
+ auto iter = state_map.find(chunk_state);
+ if (iter == state_map.end()) {
+ KALDI_ASSERT(chunk_state_to_token.count(chunk_state) != 0);
+ // Don't process token-final states. Anyway they have no arcs leaving
+ // them.
+ continue;
+ }
+ StateId clat_state = iter->second;
+
+ // We know that this point that `clat_state` is not a token-final state
+ // (see glossary for definition) as if it were, we would have done
+ // `continue` above.
+ //
+ // Only in the last chunk of the lattice would be there be a final-prob on
+ // states that are not `token-final states`; these final-probs would
+ // normally all be Zero() at this point. So in almost all cases the following
+ // call will do nothing.
+ clat_.SetFinal(clat_state, chunk_clat.Final(chunk_state));
+
+ // Process arcs leaving this state.
+ for (fst::ArcIterator<CompactLattice> aiter(chunk_clat, chunk_state);
+ !aiter.Done(); aiter.Next()) {
+ CompactLatticeArc arc(aiter.Value());
+
+ auto next_iter = state_map.find(arc.nextstate);
+ if (next_iter != state_map.end()) {
+ // The normal case (when the .nextstate has a corresponding
+ // state in clat_) is very simple. Just copy the arc over.
+ arc.nextstate = next_iter->second;
+ KALDI_ASSERT(arc.ilabel < kTokenLabelOffset ||
+ arc.ilabel > kMaxTokenLabel);
+ AddArcToClat(clat_state, arc);
+ } else {
+ // This is the case when the arc is to a `token-final` state (see
+ // glossary.)
+
+ // TODO: remove the following slightly excessive assertion?
+ KALDI_ASSERT(chunk_clat.Final(arc.nextstate) != CompactLatticeWeight::Zero() &&
+ arc.olabel >= (Label)kTokenLabelOffset &&
+ arc.olabel < (Label)kMaxTokenLabel &&
+ chunk_state_to_token.count(arc.nextstate) != 0 &&
+ old_final_costs.count(arc.olabel) != 0);
+
+ // Include the final-cost of the next state (which should be final)
+ // in arc.weight.
+ arc.weight = fst::Times(arc.weight,
+ chunk_clat.Final(arc.nextstate));
+
+ auto cost_iter = old_final_costs.find(arc.olabel);
+ KALDI_ASSERT(cost_iter != old_final_costs.end());
+ BaseFloat old_final_cost = cost_iter->second;
+
+ // `arc` is going to become an element of final_arcs_. These
+ // contain information about transitions from states in clat_ to
+ // `token-final` states (i.e. states that have a token-label on the arc
+ // to them and that are final in the canonical compact lattice).
+ // We subtract the old_final_cost as it was just a temporary cost
+ // introduced for pruning purposes.
+ arc.weight.SetWeight(fst::Times(arc.weight.Weight(),
+ LatticeWeight{-old_final_cost, 0.0}));
+ // In a slight abuse of the Arc data structure, the nextstate is set to
+ // the source state. The label (ilabel == olabel) indicates the
+ // token it is associated with.
+ arc.nextstate = clat_state;
+ final_arcs_.push_back(arc);
+ }
+ }
+ }
+
+}
+
+bool LatticeIncrementalDeterminizer::AcceptRawLatticeChunk(
+ Lattice *raw_fst) {
+ using Label = CompactLatticeArc::Label;
+ using StateId = CompactLattice::StateId;
+
+ // old_final_costs is a map from a `token-label` (see glossary) to the
+ // associated final-prob in a final-state of `raw_fst`, that is associated
+ // with that Token. These are Tokens that were active at the end of the
+ // chunk. The final-probs may arise from beta (backward) costs, introduced
+ // for pruning purposes, and/or from final-probs in HCLG. Those costs will
+ // not be included in anything we store permamently in this class; they used
+ // only to guide pruned determinization, and we will use `old_final_costs`
+ // later to cancel them out.
+ std::unordered_map<Label, BaseFloat> old_final_costs;
+ GetRawLatticeFinalCosts(*raw_fst, &old_final_costs);
+
+ CompactLattice chunk_clat;
+ bool determinized_till_beam = DeterminizeLatticePhonePrunedWrapper(
+ trans_model_, raw_fst, config_.lattice_beam, &chunk_clat,
+ config_.det_opts);
+
+ TopSortCompactLatticeIfNeeded(&chunk_clat);
+
+ std::unordered_map<StateId, Label> chunk_state_to_token;
+ IdentifyTokenFinalStates(chunk_clat,
+ &chunk_state_to_token);
+
+ StateId chunk_num_states = chunk_clat.NumStates();
+ if (chunk_num_states == 0) {
+ // This will be an error but user-level calling code can detect it from the
+ // lattice being empty.
+ KALDI_WARN << "Empty lattice, something went wrong.";
+ clat_.DeleteStates();
+ return false;
+ }
+
+ StateId start_state = chunk_clat.Start(); // would be 0.
+ KALDI_ASSERT(start_state == 0);
+
+ // Process arcs leaving the start state of chunk_clat. Unless this is the
+ // first chunk in the lattice, all arcs leaving the start state of chunk_clat
+ // will have `state labels` on them (identifying redeterminized-states in
+ // clat_), and will transition to a state in `chunk_clat` that we can identify
+ // with that redeterminized-state.
+
+ // state_map maps from (non-initial, non-token-final state s in chunk_clat) to
+ // a state in clat_.
+ std::unordered_map<StateId, StateId> state_map;
+
+
+ bool is_first_chunk = ProcessArcsFromChunkStartState(chunk_clat, &state_map);
+
+ // Remove any existing arcs in clat_ that leave redeterminized-states, and
+ // make those states non-final. Below, we'll add arcs leaving those states
+ // (and possibly new final-probs.)
+ for (StateId clat_state: non_final_redet_states_) {
+ clat_.DeleteArcs(clat_state);
+ clat_.SetFinal(clat_state, CompactLatticeWeight::Zero());
+ }
+
+ // The previous final-arc info is no longer relevant; we'll recreate it below.
+ final_arcs_.clear();
+
+ // assume chunk_lat.Start() == 0; we asserted it above. Allocate state-ids
+ // for all remaining states in chunk_clat, except for token-final states.
+ for (StateId state = (is_first_chunk ? 0 : 1);
+ state < chunk_num_states; state++) {
+ if (chunk_state_to_token.count(state) != 0)
+ continue; // these `token-final` states don't get a state allocated.
+
+ StateId new_clat_state = clat_.NumStates();
+ if (state_map.insert({state, new_clat_state}).second) {
+ // If it was inserted then we need to actually allocate that state
+ StateId s = AddStateToClat();
+ KALDI_ASSERT(s == new_clat_state);
+ } // else do nothing; it would have been a redeterminized-state and no
+ } // allocation is needed since they already exist in clat_. and
+ // in state_map.
+
+ if (is_first_chunk) {
+ auto iter = state_map.find(start_state);
+ KALDI_ASSERT(iter != state_map.end());
+ CompactLattice::StateId clat_start_state = iter->second;
+ KALDI_ASSERT(clat_start_state == 0); // topological order.
+ clat_.SetStart(clat_start_state);
+ forward_costs_[clat_start_state] = 0.0;
+ }
+
+ TransferArcsToClat(chunk_clat, is_first_chunk,
+ state_map, chunk_state_to_token, old_final_costs);
+
+ GetNonFinalRedetStates();
+
+ return determinized_till_beam;
+}
+
+
+
+void LatticeIncrementalDeterminizer::SetFinalCosts(
+ const unordered_map<Label, BaseFloat> *token_label2final_cost) {
+ if (final_arcs_.empty()) {
+ KALDI_WARN << "SetFinalCosts() called when final_arcs_.empty()... possibly "
+ "means you are calling this after Finalize()? Not allowed: could "
+ "indicate a code error. Or possibly decoding failed somehow.";
+ }
+
+ /*
+ prefinal states a terminology that does not appear in the paper. What it
+ means is: the set of states that have an arc with a Token-label as the label
+ leaving them in the canonical appended lattice.
+ */
+ std::unordered_set<int32> &prefinal_states(temp_);
+ prefinal_states.clear();
+ for (const auto &arc: final_arcs_) {
+ /* Caution: `state` is actually the state the arc would
+ leave from in the canonical appended lattice; we just store
+ that in the .nextstate field. */
+ CompactLattice::StateId state = arc.nextstate;
+ prefinal_states.insert(state);
+ }
+
+ for (int32 state: prefinal_states)
+ clat_.SetFinal(state, CompactLatticeWeight::Zero());
+
+
+ for (const CompactLatticeArc &arc: final_arcs_) {
+ Label token_label = arc.ilabel;
+ /* Note: we store the source state in the .nextstate field. */
+ CompactLattice::StateId src_state = arc.nextstate;
+ BaseFloat graph_final_cost;
+ if (token_label2final_cost == NULL) {
+ graph_final_cost = 0.0;
+ } else {
+ auto iter = token_label2final_cost->find(token_label);
+ if (iter == token_label2final_cost->end())
+ continue;
+ else
+ graph_final_cost = iter->second;
+ }
+ /* It might seem odd to set a final-prob on the src-state of the arc..
+ the point is that the symbol on the arc is a token-label, which should not
+ appear in the lattice the user sees, so after that token-label is removed
+ the arc would just become a final-prob.
+ */
+ clat_.SetFinal(src_state,
+ fst::Plus(clat_.Final(src_state),
+ fst::Times(arc.weight,
+ CompactLatticeWeight(
+ LatticeWeight(graph_final_cost, 0), {}))));
+ }
+}
+
+
+
+
+// Instantiate the template for the combination of token types and FST types
+// that we'll need.
+template class LatticeIncrementalDecoderTpl<fst::Fst<fst::StdArc>, decoder::StdToken>;
+template class LatticeIncrementalDecoderTpl<fst::VectorFst<fst::StdArc>,
+ decoder::StdToken>;
+template class LatticeIncrementalDecoderTpl<fst::ConstFst<fst::StdArc>,
+ decoder::StdToken>;
+template class LatticeIncrementalDecoderTpl<fst::ConstGrammarFst ,
+ decoder::StdToken>;
+template class LatticeIncrementalDecoderTpl<fst::VectorGrammarFst,
+ decoder::StdToken>;
+
+template class LatticeIncrementalDecoderTpl<fst::Fst<fst::StdArc>,
+ decoder::BackpointerToken>;
+template class LatticeIncrementalDecoderTpl<fst::VectorFst<fst::StdArc>,
+ decoder::BackpointerToken>;
+template class LatticeIncrementalDecoderTpl<fst::ConstFst<fst::StdArc>,
+ decoder::BackpointerToken>;
+template class LatticeIncrementalDecoderTpl<fst::ConstGrammarFst,
+ decoder::BackpointerToken>;
+template class LatticeIncrementalDecoderTpl<fst::VectorGrammarFst,
+ decoder::BackpointerToken>;
+
+} // end namespace kaldi.
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-decoder.h b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-decoder.h
new file mode 100644
index 000000000..575a926aa
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-decoder.h
@@ -0,0 +1,734 @@
+// decoder/lattice-incremental-decoder.h
+
+// Copyright 2019 Zhehuai Chen, Daniel Povey
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_DECODER_LATTICE_INCREMENTAL_DECODER_H_
+#define KALDI_DECODER_LATTICE_INCREMENTAL_DECODER_H_
+
+#include "util/stl-utils.h"
+#include "util/hash-list.h"
+#include "fst/fstlib.h"
+#include "itf/decodable-itf.h"
+#include "fstext/fstext-lib.h"
+#include "lat/determinize-lattice-pruned.h"
+#include "lat/kaldi-lattice.h"
+#include "decoder/grammar-fst.h"
+#include "decoder/lattice-faster-decoder.h"
+
+namespace kaldi {
+/**
+ The normal decoder, lattice-faster-decoder.h, sometimes has an issue when
+ doing real-time applications with long utterances, that each time you get the
+ lattice the lattice determinization can take a considerable amount of time;
+ this introduces latency. This version of the decoder spreads the work of
+ lattice determinization out throughout the decoding process.
+
+ NOTE:
+
+ Please see https://www.danielpovey.com/files/ *TBD* .pdf for a technical
+ explanation of what is going on here.
+
+ GLOSSARY OF TERMS:
+ chunk: We do the determinization on chunks of frames; these
+ may coincide with the chunks on which the user calls
+ AdvanceDecoding(). The basic idea is to extract chunks
+ of the raw lattice and determinize them individually, but
+ it gets much more complicated than that. The chunks
+ should normally be at least as long as a word (let's say,
+ at least 20 frames), or the overhead of this algorithm
+ might become excessive and affect RTF.
+
+ raw lattice chunk: A chunk of raw (i.e. undeterminized) lattice
+ that we will determinize. In the paper this corresponds
+ to the FST B that is described in Section 5.2.
+
+ token_label, state_label / token-label, state-label:
+
+ In the paper these are both referred to as `state labels` (these are
+ special, large integer id's that refer to states in the undeterminized
+ lattice and in the the determinized lattice); but we use two separate
+ terms here, for more clarity, when referring to the undeterminized
+ vs. determinized lattice.
+
+ token_label conceptually refers to states in the
+ raw lattice, but we don't materialize the entire
+ raw lattice as a physical FST and and these tokens
+ are actually tokens (template type Token) held by
+ the decoder
+
+ state_label when used in this code refers specifically
+ to labels that identify states in the determinized
+ lattice (i.e. state indexes in lat_).
+
+ token-final state
+ A state in a raw lattice or in a determinized chunk that has an arc
+ entering it that has a `token-label` on it (as defined above).
+ These states will have nonzero final-probs.
+
+ redeterminized-non-splice-state, aka ns_redet:
+ A redeterminized state which is not also a splice state;
+ refer to the paper for explanation. In the already-determinized
+ part this means a redeterminized state which is not final.
+
+ canonical appended lattice: This is the appended compact lattice
+ that we conceptually have (i.e. what we described in the paper).
+ The difference from the "actual appended lattice" stored
+ in LatticeIncrementalDeterminizer::clat_ is that the
+ actual appended lattice has all its final-arcs replaced with
+ final-probs, and we keep the real final-arcs "on the side" in a
+ separate data structure. The final-probs in clat_ aren't
+ necessarily related to the costs on the final-arcs; instead
+ they can have arbitrary values passed in by the user (e.g.
+ if we want to include final-probs). This means that the
+ clat_ can be returned without modification to the user who wants
+ a partially determinized result.
+
+ final-arc: An arc in the canonical appended CompactLattice which
+ goes to a final-state. These arcs will have `state-labels` as
+ their labels.
+
+ */
+struct LatticeIncrementalDecoderConfig {
+ // All the configuration values until det_opts are the same as in
+ // LatticeFasterDecoder. For clarity we repeat them rather than inheriting.
+ BaseFloat beam;
+ int32 max_active;
+ int32 min_active;
+ BaseFloat lattice_beam;
+ int32 prune_interval;
+ BaseFloat beam_delta; // has nothing to do with beam_ratio
+ BaseFloat hash_ratio;
+ BaseFloat prune_scale; // Note: we don't make this configurable on the command line,
+ // it's not a very important parameter. It affects the
+ // algorithm that prunes the tokens as we go.
+ // Most of the options inside det_opts are not actually queried by the
+ // LatticeIncrementalDecoder class itself, but by the code that calls it, for
+ // example in the function DecodeUtteranceLatticeIncremental.
+ fst::DeterminizeLatticePhonePrunedOptions det_opts;
+
+ // The configuration values from this point on are specific to the
+ // incremental determinization. See where they are registered for
+ // explanation.
+ // Caution: these are only inspected in UpdateLatticeDeterminization().
+ // If you call
+ int32 determinize_max_delay;
+ int32 determinize_min_chunk_size;
+ int32 determinize_max_active;
+
+
+ LatticeIncrementalDecoderConfig()
+ : beam(16.0),
+ max_active(std::numeric_limits<int32>::max()),
+ min_active(200),
+ lattice_beam(10.0),
+ prune_interval(25),
+ beam_delta(0.5),
+ hash_ratio(2.0),
+ prune_scale(0.01),
+ determinize_max_delay(60),
+ determinize_min_chunk_size(20),
+ determinize_max_active(200) {
+ det_opts.minimize = false;
+ }
+ void Register(OptionsItf *opts) {
+ det_opts.Register(opts);
+ opts->Register("beam", &beam, "Decoding beam. Larger->slower, more accurate.");
+ opts->Register("max-active", &max_active,
+ "Decoder max active states. Larger->slower; "
+ "more accurate");
+ opts->Register("min-active", &min_active, "Decoder minimum #active states.");
+ opts->Register("lattice-beam", &lattice_beam,
+ "Lattice generation beam. Larger->slower, "
+ "and deeper lattices");
+ opts->Register("prune-interval", &prune_interval,
+ "Interval (in frames) at "
+ "which to prune tokens");
+ opts->Register("beam-delta", &beam_delta,
+ "Increment used in decoding-- this "
+ "parameter is obscure and relates to a speedup in the way the "
+ "max-active constraint is applied. Larger is more accurate.");
+ opts->Register("hash-ratio", &hash_ratio,
+ "Setting used in decoder to "
+ "control hash behavior");
+ opts->Register("determinize-max-delay", &determinize_max_delay,
+ "Maximum frames of delay between decoding a frame and "
+ "determinizing it");
+ opts->Register("determinize-min-chunk-size", &determinize_min_chunk_size,
+ "Minimum chunk size used in determinization");
+ opts->Register("determinize-max-active", &determinize_max_active,
+ "Maximum number of active tokens to update determinization");
+
+ }
+ void Check() const {
+ if (!(beam > 0.0 && max_active > 1 && lattice_beam > 0.0 &&
+ min_active <= max_active && prune_interval > 0 &&
+ beam_delta > 0.0 && hash_ratio >= 1.0 &&
+ prune_scale > 0.0 && prune_scale < 1.0 &&
+ determinize_max_delay > determinize_min_chunk_size &&
+ determinize_min_chunk_size > 0 &&
+ determinize_max_active >= 0))
+ KALDI_ERR << "Invalid options given to decoder";
+ /* Minimization of the chunks is not compatible withour algorithm (or at
+ least, would require additional complexity to implement.) */
+ if (det_opts.minimize || !det_opts.word_determinize)
+ KALDI_ERR << "Invalid determinization options given to decoder.";
+ }
+};
+
+
+
+/**
+ This class is used inside LatticeIncrementalDecoderTpl; it handles
+ some of the details of incremental determinization.
+ https://www.danielpovey.com/files/ *TBD*.pdf for the paper.
+
+*/
+class LatticeIncrementalDeterminizer {
+ public:
+ using Label = typename LatticeArc::Label; /* Actualy the same labels appear
+ in both lattice and compact
+ lattice, so we don't use the
+ specific type all the time but
+ just say 'Label' */
+ LatticeIncrementalDeterminizer(
+ const TransitionInformation &trans_model,
+ const LatticeIncrementalDecoderConfig &config):
+ trans_model_(trans_model), config_(config) { }
+
+ // Resets the lattice determinization data for new utterance
+ void Init();
+
+ // Returns the current determinized lattice.
+ const CompactLattice &GetDeterminizedLattice() const { return clat_; }
+
+ /**
+ Starts the process of creating a raw lattice chunk. (Search the glossary
+ for "raw lattice chunk"). This just sets up the initial states and
+ redeterminized-states in the chunk. Relates to sec. 5.2 in the paper,
+ specifically the initial-state i and the redeterminized-states.
+
+ After calling this, the caller would add the remaining arcs and states
+ to `olat` and then call AcceptRawLatticeChunk() with the result.
+
+ @param [out] olat The lattice to be (partially) created
+
+ @param [out] token_label2state This function outputs to here
+ a map from `token-label` to the state we created for
+ it in *olat. See glossary for `token-label`.
+ The keys actually correspond to the .nextstate fields
+ in the arcs in final_arcs_; values are states in `olat`.
+ See the last bullet point before Sec. 5.3 in the paper.
+ */
+ void InitializeRawLatticeChunk(
+ Lattice *olat,
+ unordered_map<Label, LatticeArc::StateId> *token_label2state);
+
+ /**
+ This function accepts the raw FST (state-level lattice) corresponding to a
+ single chunk of the lattice, determinizes it and appends it to this->clat_.
+ Unless this was the
+
+ Note: final-probs in `raw_fst` are treated specially: they are used to
+ guide the pruned determinization, but when you call GetLattice() it will be
+ -- except for pruning effects-- as if all nonzero final-probs in `raw_fst`
+ were: One() if final_costs == NULL; else the value present in `final_costs`.
+
+ @param [in] raw_fst (Consumed destructively). The input
+ raw (state-level) lattice. Would correspond to the
+ FST A in the paper if first_frame == 0, and B
+ otherwise.
+
+ @return returns false if determinization finished earlier than the beam
+ or the determinized lattice was empty; true otherwise.
+
+ NOTE: if this is not the final chunk, you will probably want to call
+ SetFinalCosts() directly after calling this.
+ */
+ bool AcceptRawLatticeChunk(Lattice *raw_fst);
+
+ /*
+ Sets final-probs in `clat_`. Must only be called if the final chunk
+ has not been processed. (The final chunk is whenever GetLattice() is
+ called with finalize == true).
+
+ The reason this is a separate function from AcceptRawLatticeChunk() is that
+ there may be situations where a user wants to get the latice with
+ final-probs in it, after previously getting it without final-probs; or
+ vice versa. By final-probs, we mean the Final() probabilities in the
+ HCLG (decoding graph; this->fst_).
+
+ @param [in] token_label2final_cost A map from the token-label
+ corresponding to Tokens active on the final frame of the
+ lattice in the object, to the final-cost we want to use for
+ those tokens. If NULL, it means all Tokens should be treated
+ as final with probability One(). If non-NULL, and a particular
+ token-label is not a key of this map, it means that Token
+ corresponded to a state that was not final in HCLG; and
+ such tokens will be treated as non-final. However,
+ if this would result in no states in the lattice being final,
+ we will treat all Tokens as final with probability One(),
+ a warning will be printed (this should not happen.)
+ */
+ void SetFinalCosts(const unordered_map<Label, BaseFloat> *token_label2final_cost = NULL);
+
+ const CompactLattice &GetLattice() { return clat_; }
+
+ // kStateLabelOffset is what we add to state-ids in clat_ to produce labels
+ // to identify them in the raw lattice chunk
+ // kTokenLabelOffset is where we start allocating labels corresponding to Tokens
+ // (these correspond with raw lattice states);
+ enum { kStateLabelOffset = (int)1e8, kTokenLabelOffset = (int)2e8, kMaxTokenLabel = (int)3e8 };
+
+ private:
+
+ // [called from AcceptRawLatticeChunk()]
+ // Gets the final costs from token-final states in the raw lattice (see
+ // glossary for definition). These final costs will be subtracted after
+ // determinization; in the normal case they are `temporaries` used to guide
+ // pruning. NOTE: the index of the array is not the FST state that is final,
+ // but the label on arcs entering it (these will be `token-labels`). Each
+ // token-final state will have the same label on all arcs entering it.
+ //
+ // `old_final_costs` is assumed to be empty at entry.
+ void GetRawLatticeFinalCosts(const Lattice &raw_fst,
+ std::unordered_map<Label, BaseFloat> *old_final_costs);
+
+ // Sets up non_final_redet_states_. See documentation for that variable.
+ void GetNonFinalRedetStates();
+
+ /** [called from AcceptRawLatticeChunk()] Processes arcs that leave the
+ start-state of `chunk_clat` (if this is not the first chunk); does nothing
+ if this is the first chunk. This includes using the `state-labels` to
+ work out which states in clat_ these states correspond to, and writing
+ that mapping to `state_map`.
+
+ Also modifies forward_costs_, because it has to do a kind of reweighting
+ of the clat states that are the values it puts in `state_map`, to take
+ account of the probabilities on the arcs from the start state of
+ chunk_clat to the states corresponding to those redeterminized-states
+ (i.e. the states in clat corresponding to the values it puts in
+ `*state_map`). It also modifies arcs_in_, mostly because there
+ are rare cases when we end up `merging` sets of those redeterminized-states,
+ because the determinization process mapped them to a single state,
+ and that means we need to reroute the arcs into members of that
+ set into one single member (which will appear as a value in
+ `*state_map`).
+
+ @param [in] chunk_clat The determinized chunk of lattice we are
+ processing
+ @param [out] state_map Mapping from states in chunk_clat to
+ the state in clat_ they correspond to.
+ @return Returns true if this is the first chunk.
+ */
+ bool ProcessArcsFromChunkStartState(
+ const CompactLattice &chunk_clat,
+ std::unordered_map<CompactLattice::StateId, CompactLattice::StateId> *state_map);
+
+ /**
+ This function, called from AcceptRawLatticeChunk(), transfers arcs from
+ `chunk_clat` to clat_. For those arcs that have `token-labels` on them,
+ they don't get written to clat_ but instead are stored in the arcs_ array.
+
+ @param [in] chunk_clat The determinized lattice for the chunk
+ we are processing; this is the source of the arcs
+ we are moving.
+ @param [in] is_first_chunk True if this is the first chunk in the
+ utterance; it's needed because if it is, we
+ will also transfer arcs from the start state of
+ chunk_clat.
+ @param [in] state_map Map from state-ids in chunk_clat to state-ids
+ in clat_.
+ @param [in] chunk_state_to_token Map from `token-final states`
+ (see glossary) in chunk_clat, to the token-label
+ on arcs entering those states.
+ @param [in] old_final_costs Map from token-label to the
+ final-costs that were on the corresponding
+ token-final states in the undeterminized lattice;
+ these final-costs need to be removed when
+ we record the weights in final_arcs_, because
+ they were just temporary.
+ */
+ void TransferArcsToClat(
+ const CompactLattice &chunk_clat,
+ bool is_first_chunk,
+ const std::unordered_map<CompactLattice::StateId, CompactLattice::StateId> &state_map,
+ const std::unordered_map<CompactLattice::StateId, Label> &chunk_state_to_token,
+ const std::unordered_map<Label, BaseFloat> &old_final_costs);
+
+
+
+ /**
+ Adds one arc to `clat_`. It's like clat_.AddArc(state, arc), except
+ it also modifies arcs_in_ and forward_costs_.
+ */
+ void AddArcToClat(CompactLattice::StateId state,
+ const CompactLatticeArc &arc);
+ CompactLattice::StateId AddStateToClat();
+
+
+ // Identifies token-final states in `chunk_clat`; see glossary above for
+ // definition of `token-final`. This function outputs a map from such states
+ // in chunk_clat, to the `token-label` on arcs entering them. (It is not
+ // possible that the same state would have multiple arcs entering it with
+ // different token-labels, or some arcs entering with one token-label and some
+ // another, or be both initial and have such arcs; this is true due to how we
+ // construct the raw lattice.)
+ void IdentifyTokenFinalStates(
+ const CompactLattice &chunk_clat,
+ std::unordered_map<CompactLattice::StateId, CompactLatticeArc::Label> *token_map) const;
+
+ // trans_model_ is needed by DeterminizeLatticePhonePrunedWrapper() which this
+ // class calls.
+ const TransitionInformation &trans_model_;
+ // config_ is needed by DeterminizeLatticePhonePrunedWrapper() which this
+ // class calls.
+ const LatticeIncrementalDecoderConfig &config_;
+
+
+ // Contains the set of redeterminized-states which are not final in the
+ // canonical appended lattice. Since the final ones don't physically appear
+ // in clat_, this means the set of redeterminized-states which are physically
+ // in clat_. In code terms, this means set of .first elements in final_arcs,
+ // plus whatever other states in clat_ are reachable from such states.
+ std::unordered_set<CompactLattice::StateId> non_final_redet_states_;
+
+
+ // clat_ is the appended lattice (containing all chunks processed so
+ // far), except its `final-arcs` (i.e. arcs which in the canonical
+ // lattice would go to final-states) are not present (they are stored
+ // separately in final_arcs_) and states which in the canonical lattice
+ // should have final-arcs leaving them will instead have a final-prob.
+ CompactLattice clat_;
+
+
+ // arcs_in_ is indexed by (state-id in clat_), and is a list of
+ // arcs that come into this state, in the form (prev-state,
+ // arc-index). CAUTION: not all these input-arc records will always
+ // be valid (some may be out-of-date, and may refer to an out-of-range
+ // arc or an arc that does not point to this state). But all
+ // input arcs will always be listed.
+ std::vector<std::vector<std::pair<CompactLattice::StateId, int32> > > arcs_in_;
+
+ // final_arcs_ contains arcs which would appear in the canonical appended
+ // lattice but for implementation reasons are not physically present in clat_.
+ // These are arcs to final states in the canonical appended lattice. The
+ // .first elements are the source states in clat_ (these will all be elements
+ // of non_final_redet_states_); the .nextstate elements of the arcs does not
+ // contain a physical state, but contain state-labels allocated by
+ // AllocateNewStateLabel().
+ std::vector<CompactLatticeArc> final_arcs_;
+
+ // forward_costs_, indexed by the state-id in clat_, stores the alpha
+ // (forward) costs, i.e. the minimum cost from the start state to each state
+ // in clat_. This is relevant for pruned determinization. The BaseFloat can
+ // be thought of as the sum of a Value1() + Value2() in a LatticeWeight.
+ std::vector<BaseFloat> forward_costs_;
+
+ // temporary used in a function, kept here to avoid excessive reallocation.
+ std::unordered_set<int32> temp_;
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(LatticeIncrementalDeterminizer);
+};
+
+
+/** This is an extention to the "normal" lattice-generating decoder.
+ See \ref lattices_generation \ref decoders_faster and \ref decoders_simple
+ for more information.
+
+ The main difference is the incremental determinization which will be
+ discussed in the function GetLattice(). This means that the work of determinizatin
+ isn't done all at once at the end of the file, but incrementally while decoding.
+ See the comment at the top of this file for more explanation.
+
+ The decoder is templated on the FST type and the token type. The token type
+ will normally be StdToken, but also may be BackpointerToken which is to support
+ quick lookup of the current best path (see lattice-faster-online-decoder.h)
+
+ The FST you invoke this decoder with is expected to be of type
+ Fst::Fst<fst::StdArc>, a.k.a. StdFst, or GrammarFst. If you invoke it with
+ FST == StdFst and it notices that the actual FST type is
+ fst::VectorFst<fst::StdArc> or fst::ConstFst<fst::StdArc>, the decoder object
+ will internally cast itself to one that is templated on those more specific
+ types; this is an optimization for speed.
+ */
+template <typename FST, typename Token = decoder::StdToken>
+class LatticeIncrementalDecoderTpl {
+ public:
+ using Arc = typename FST::Arc;
+ using Label = typename Arc::Label;
+ using StateId = typename Arc::StateId;
+ using Weight = typename Arc::Weight;
+ using ForwardLinkT = decoder::ForwardLink<Token>;
+
+ // Instantiate this class once for each thing you have to decode.
+ // This version of the constructor does not take ownership of
+ // 'fst'.
+ LatticeIncrementalDecoderTpl(const FST &fst, const TransitionInformation &trans_model,
+ const LatticeIncrementalDecoderConfig &config);
+
+ // This version of the constructor takes ownership of the fst, and will delete
+ // it when this object is destroyed.
+ LatticeIncrementalDecoderTpl(const LatticeIncrementalDecoderConfig &config,
+ FST *fst, const TransitionInformation &trans_model);
+
+ void SetOptions(const LatticeIncrementalDecoderConfig &config) { config_ = config; }
+
+ const LatticeIncrementalDecoderConfig &GetOptions() const { return config_; }
+
+ ~LatticeIncrementalDecoderTpl();
+
+ /**
+ CAUTION: it's unlikely that you will ever want to call this function. In a
+ scenario where you have the entire file and just want to decode it, there
+ is no point using this decoder.
+
+ An example of how to do decoding together with incremental
+ determinization. It decodes until there are no more frames left in the
+ "decodable" object.
+
+ In this example, config_.determinize_max_delay, config_.determinize_min_chunk_size
+ and config_.determinize_max_active are used to determine the time to
+ call GetLattice().
+
+ Users will probably want to use appropriate combinations of
+ AdvanceDecoding() and GetLattice() to build their application; this just
+ gives you some idea how.
+
+ The function returns true if any kind of traceback is available (not
+ necessarily from a final state).
+ */
+ bool Decode(DecodableInterface *decodable);
+
+ /// says whether a final-state was active on the last frame. If it was not,
+ /// the lattice (or traceback) will end with states that are not final-states.
+ bool ReachedFinal() const {
+ return FinalRelativeCost() != std::numeric_limits<BaseFloat>::infinity();
+ }
+
+ /**
+ This decoder has no GetBestPath() function.
+ If you need that functionality you should probably use lattice-incremental-online-decoder.h,
+ which makes it very efficient to obtain the best path. */
+
+ /**
+ This GetLattice() function returns the lattice containing
+ `num_frames_to_decode` frames; this will be all frames decoded so
+ far, if you let num_frames_to_decode == NumFramesDecoded(),
+ but it will generally be better to make it a few frames less than
+ that to avoid the lattice having too many active states at
+ the end.
+
+ @param [in] num_frames_to_include The number of frames that you want
+ to be included in the lattice. Must be >=
+ NumFramesInLattice() and <= NumFramesDecoded().
+
+ @param [in] use_final_probs True if you want the final-probs
+ of HCLG to be included in the output lattice. Must not
+ be set to true if num_frames_to_include !=
+ NumFramesDecoded(). Must be set to true if you have
+ previously called FinalizeDecoding().
+
+ (If no state was final on frame `num_frames_to_include`, the
+ final-probs won't be included regardless of
+ `use_final_probs`; you can test whether this
+ was the case by calling ReachedFinal().
+
+ @return clat The CompactLattice representing what has been decoded
+ up until `num_frames_to_include` (e.g., LatticeStateTimes()
+ on this lattice would return `num_frames_to_include`).
+
+ See also UpdateLatticeDeterminizaton(). Caution: this const ref
+ is only valid until the next time you call AdvanceDecoding() or
+ GetLattice().
+
+ CAUTION: the lattice may contain disconnnected states; you should
+ call Connect() on the output before writing it out.
+ */
+ const CompactLattice &GetLattice(int32 num_frames_to_include,
+ bool use_final_probs = false);
+
+ /*
+ Returns the number of frames in the currently-determinized part of the
+ lattice which will be a number in [0, NumFramesDecoded()]. It will
+ be the largest number that GetLattice() was called with, but note
+ that GetLattice() may be called from UpdateLatticeDeterminization().
+
+ Made available in case the user wants to give that same number to
+ GetLattice().
+ */
+ int NumFramesInLattice() const { return num_frames_in_lattice_; }
+
+ /**
+ InitDecoding initializes the decoding, and should only be used if you
+ intend to call AdvanceDecoding(). If you call Decode(), you don't need to
+ call this. You can also call InitDecoding if you have already decoded an
+ utterance and want to start with a new utterance.
+ */
+ void InitDecoding();
+
+ /**
+ This will decode until there are no more frames ready in the decodable
+ object. You can keep calling it each time more frames become available
+ (this is the normal pattern in a real-time/online decoding scenario).
+ If max_num_frames is specified, it specifies the maximum number of frames
+ the function will decode before returning.
+ */
+ void AdvanceDecoding(DecodableInterface *decodable, int32 max_num_frames = -1);
+
+
+ /** FinalRelativeCost() serves the same purpose as ReachedFinal(), but gives
+ more information. It returns the difference between the best (final-cost
+ plus cost) of any token on the final frame, and the best cost of any token
+ on the final frame. If it is infinity it means no final-states were
+ present on the final frame. It will usually be nonnegative. If it not
+ too positive (e.g. < 5 is my first guess, but this is not tested) you can
+ take it as a good indication that we reached the final-state with
+ reasonable likelihood. */
+ BaseFloat FinalRelativeCost() const;
+
+ /** Returns the number of frames decoded so far. */
+ inline int32 NumFramesDecoded() const { return active_toks_.size() - 1; }
+
+ /**
+ Finalizes the decoding, doing an extra pruning step on the last frame
+ that uses the final-probs. May be called only once.
+ */
+ void FinalizeDecoding();
+
+ protected:
+ /* Some protected things are needed in LatticeIncrementalOnlineDecoderTpl. */
+
+ /** NOTE: for parts the internal implementation that are shared with LatticeFasterDecoer,
+ we have removed the comments.*/
+ inline static void DeleteForwardLinks(Token *tok);
+ struct TokenList {
+ Token *toks;
+ bool must_prune_forward_links;
+ bool must_prune_tokens;
+ int32 num_toks; /* Note: you can only trust `num_toks` if must_prune_tokens
+ * == false, because it is only set in
+ * PruneTokensForFrame(). */
+ TokenList()
+ : toks(NULL), must_prune_forward_links(true), must_prune_tokens(true),
+ num_toks(-1) {}
+ };
+ using Elem = typename HashList<StateId, Token *>::Elem;
+ void PossiblyResizeHash(size_t num_toks);
+ inline Token *FindOrAddToken(StateId state, int32 frame_plus_one,
+ BaseFloat tot_cost, Token *backpointer, bool *changed);
+ void PruneForwardLinks(int32 frame_plus_one, bool *extra_costs_changed,
+ bool *links_pruned, BaseFloat delta);
+ void ComputeFinalCosts(unordered_map<Token *, BaseFloat> *final_costs,
+ BaseFloat *final_relative_cost,
+ BaseFloat *final_best_cost) const;
+ void PruneForwardLinksFinal();
+ void PruneTokensForFrame(int32 frame_plus_one);
+ void PruneActiveTokens(BaseFloat delta);
+ BaseFloat GetCutoff(Elem *list_head, size_t *tok_count, BaseFloat *adaptive_beam,
+ Elem **best_elem);
+ BaseFloat ProcessEmitting(DecodableInterface *decodable);
+ void ProcessNonemitting(BaseFloat cost_cutoff);
+
+ HashList<StateId, Token *> toks_;
+ std::vector<TokenList> active_toks_; // indexed by frame.
+ std::vector<StateId> queue_; // temp variable used in ProcessNonemitting,
+ std::vector<BaseFloat> tmp_array_; // used in GetCutoff.
+ const FST *fst_;
+ bool delete_fst_;
+ std::vector<BaseFloat> cost_offsets_;
+ int32 num_toks_;
+ bool warned_;
+ bool decoding_finalized_;
+
+ unordered_map<Token *, BaseFloat> final_costs_;
+ BaseFloat final_relative_cost_;
+ BaseFloat final_best_cost_;
+
+ /***********************
+ Variables below this point relate to the incremental
+ determinization.
+ *********************/
+ LatticeIncrementalDecoderConfig config_;
+ /** Much of the the incremental determinization algorithm is encapsulated in
+ the determinize_ object. */
+ LatticeIncrementalDeterminizer determinizer_;
+
+
+ /* Just a temporary used in a function; stored here to avoid reallocation. */
+ unordered_map<Token*, StateId> temp_token_map_;
+
+ /** num_frames_in_lattice_ is the highest `num_frames_to_include_` argument
+ for any prior call to GetLattice(). */
+ int32 num_frames_in_lattice_;
+
+ // A map from Token to its token_label. Will contain an entry for
+ // each Token in active_toks_[num_frames_in_lattice_].
+ unordered_map<Token*, Label> token2label_map_;
+
+ // A temporary used in a function, kept here to avoid reallocation.
+ unordered_map<Token*, Label> token2label_map_temp_;
+
+ // we allocate a unique id for each Token
+ Label next_token_label_;
+
+ inline Label AllocateNewTokenLabel() { return next_token_label_++; }
+
+
+ // There are various cleanup tasks... the the toks_ structure contains
+ // singly linked lists of Token pointers, where Elem is the list type.
+ // It also indexes them in a hash, indexed by state (this hash is only
+ // maintained for the most recent frame). toks_.Clear()
+ // deletes them from the hash and returns the list of Elems. The
+ // function DeleteElems calls toks_.Delete(elem) for each elem in
+ // the list, which returns ownership of the Elem to the toks_ structure
+ // for reuse, but does not delete the Token pointer. The Token pointers
+ // are reference-counted and are ultimately deleted in PruneTokensForFrame,
+ // but are also linked together on each frame by their own linked-list,
+ // using the "next" pointer. We delete them manually.
+ void DeleteElems(Elem *list);
+
+ void ClearActiveTokens();
+
+
+ // Returns the number of active tokens on frame `frame`. Can be used as part
+ // of a heuristic to decide which frame to determinize until, if you are not
+ // at the end of an utterance.
+ int32 GetNumToksForFrame(int32 frame);
+
+ /**
+ UpdateLatticeDeterminization() ensures the work of determinization is kept
+ up to date so that when you do need the lattice you can get it fast. It
+ uses the configuration values `determinize_max_delay`, `determinize_min_chunk_size`
+ and `determinize_max_active`, to decide whether and when to call
+ GetLattice(). You can safely call this as often as you want (e.g. after
+ each time you call AdvanceDecoding(); it won't do subtantially more work if
+ it is called frequently.
+ */
+ void UpdateLatticeDeterminization();
+
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(LatticeIncrementalDecoderTpl);
+};
+
+typedef LatticeIncrementalDecoderTpl<fst::StdFst, decoder::StdToken>
+ LatticeIncrementalDecoder;
+
+
+} // end namespace kaldi.
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-online-decoder.cc b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-online-decoder.cc
new file mode 100644
index 000000000..cacac2c08
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-online-decoder.cc
@@ -0,0 +1,158 @@
+// decoder/lattice-incremental-online-decoder.cc
+
+// Copyright 2019 Zhehuai Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+// see note at the top of lattice-faster-decoder.cc, about how to maintain this
+// file in sync with lattice-faster-decoder.cc
+
+#include "decoder/lattice-incremental-decoder.h"
+#include "decoder/lattice-incremental-online-decoder.h"
+#include "lat/lattice-functions.h"
+#include "base/timer.h"
+
+namespace kaldi {
+
+// Outputs an FST corresponding to the single best path through the lattice.
+template <typename FST>
+bool LatticeIncrementalOnlineDecoderTpl<FST>::GetBestPath(Lattice *olat,
+ bool use_final_probs) const {
+ olat->DeleteStates();
+ BaseFloat final_graph_cost;
+ BestPathIterator iter = BestPathEnd(use_final_probs, &final_graph_cost);
+ if (iter.Done())
+ return false; // would have printed warning.
+ StateId state = olat->AddState();
+ olat->SetFinal(state, LatticeWeight(final_graph_cost, 0.0));
+ while (!iter.Done()) {
+ LatticeArc arc;
+ iter = TraceBackBestPath(iter, &arc);
+ arc.nextstate = state;
+ StateId new_state = olat->AddState();
+ olat->AddArc(new_state, arc);
+ state = new_state;
+ }
+ olat->SetStart(state);
+ return true;
+}
+
+template <typename FST>
+typename LatticeIncrementalOnlineDecoderTpl<FST>::BestPathIterator LatticeIncrementalOnlineDecoderTpl<FST>::BestPathEnd(
+ bool use_final_probs,
+ BaseFloat *final_cost_out) const {
+ if (this->decoding_finalized_ && !use_final_probs)
+ KALDI_ERR << "You cannot call FinalizeDecoding() and then call "
+ << "BestPathEnd() with use_final_probs == false";
+ KALDI_ASSERT(this->NumFramesDecoded() > 0 &&
+ "You cannot call BestPathEnd if no frames were decoded.");
+
+ unordered_map<Token*, BaseFloat> final_costs_local;
+
+ const unordered_map<Token*, BaseFloat> &final_costs =
+ (this->decoding_finalized_ ? this->final_costs_ :final_costs_local);
+ if (!this->decoding_finalized_ && use_final_probs)
+ this->ComputeFinalCosts(&final_costs_local, NULL, NULL);
+
+ // Singly linked list of tokens on last frame (access list through "next"
+ // pointer).
+ BaseFloat best_cost = std::numeric_limits<BaseFloat>::infinity();
+ BaseFloat best_final_cost = 0;
+ Token *best_tok = NULL;
+ for (Token *tok = this->active_toks_.back().toks;
+ tok != NULL; tok = tok->next) {
+ BaseFloat cost = tok->tot_cost, final_cost = 0.0;
+ if (use_final_probs && !final_costs.empty()) {
+ // if we are instructed to use final-probs, and any final tokens were
+ // active on final frame, include the final-prob in the cost of the token.
+ typename unordered_map<Token*, BaseFloat>::const_iterator
+ iter = final_costs.find(tok);
+ if (iter != final_costs.end()) {
+ final_cost = iter->second;
+ cost += final_cost;
+ } else {
+ cost = std::numeric_limits<BaseFloat>::infinity();
+ }
+ }
+ if (cost < best_cost) {
+ best_cost = cost;
+ best_tok = tok;
+ best_final_cost = final_cost;
+ }
+ }
+ if (best_tok == NULL) { // this should not happen, and is likely a code error or
+ // caused by infinities in likelihoods, but I'm not making
+ // it a fatal error for now.
+ KALDI_WARN << "No final token found.";
+ }
+ if (final_cost_out != NULL)
+ *final_cost_out = best_final_cost;
+ return BestPathIterator(best_tok, this->NumFramesDecoded() - 1);
+}
+
+
+template <typename FST>
+typename LatticeIncrementalOnlineDecoderTpl<FST>::BestPathIterator LatticeIncrementalOnlineDecoderTpl<FST>::TraceBackBestPath(
+ BestPathIterator iter, LatticeArc *oarc) const {
+ KALDI_ASSERT(!iter.Done() && oarc != NULL);
+ Token *tok = static_cast<Token*>(iter.tok);
+ int32 cur_t = iter.frame, step_t = 0;
+ if (tok->backpointer != NULL) {
+ // retrieve the correct forward link(with the best link cost)
+ BaseFloat best_cost = std::numeric_limits<BaseFloat>::infinity();
+ ForwardLinkT *link;
+ for (link = tok->backpointer->links;
+ link != NULL; link = link->next) {
+ if (link->next_tok == tok) { // this is the a to "tok"
+ BaseFloat graph_cost = link->graph_cost,
+ acoustic_cost = link->acoustic_cost;
+ BaseFloat cost = graph_cost + acoustic_cost;
+ if (cost < best_cost) {
+ oarc->ilabel = link->ilabel;
+ oarc->olabel = link->olabel;
+ if (link->ilabel != 0) {
+ KALDI_ASSERT(static_cast<size_t>(cur_t) < this->cost_offsets_.size());
+ acoustic_cost -= this->cost_offsets_[cur_t];
+ step_t = -1;
+ } else {
+ step_t = 0;
+ }
+ oarc->weight = LatticeWeight(graph_cost, acoustic_cost);
+ best_cost = cost;
+ }
+ }
+ }
+ if (link == NULL &&
+ best_cost == std::numeric_limits<BaseFloat>::infinity()) { // Did not find correct link.
+ KALDI_ERR << "Error tracing best-path back (likely "
+ << "bug in token-pruning algorithm)";
+ }
+ } else {
+ oarc->ilabel = 0;
+ oarc->olabel = 0;
+ oarc->weight = LatticeWeight::One(); // zero costs.
+ }
+ return BestPathIterator(tok->backpointer, cur_t + step_t);
+}
+
+// Instantiate the template for the FST types that we'll need.
+template class LatticeIncrementalOnlineDecoderTpl<fst::Fst<fst::StdArc> >;
+template class LatticeIncrementalOnlineDecoderTpl<fst::VectorFst<fst::StdArc> >;
+template class LatticeIncrementalOnlineDecoderTpl<fst::ConstFst<fst::StdArc> >;
+template class LatticeIncrementalOnlineDecoderTpl<fst::ConstGrammarFst >;
+template class LatticeIncrementalOnlineDecoderTpl<fst::VectorGrammarFst >;
+
+} // end namespace kaldi.
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-online-decoder.h b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-online-decoder.h
new file mode 100644
index 000000000..c82abed4e
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-incremental-online-decoder.h
@@ -0,0 +1,132 @@
+// decoder/lattice-incremental-online-decoder.h
+
+// Copyright 2019 Zhehuai Chen
+//
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+// see note at the top of lattice-faster-decoder.h, about how to maintain this
+// file in sync with lattice-faster-decoder.h
+
+
+#ifndef KALDI_DECODER_LATTICE_INCREMENTAL_ONLINE_DECODER_H_
+#define KALDI_DECODER_LATTICE_INCREMENTAL_ONLINE_DECODER_H_
+
+#include "util/stl-utils.h"
+#include "util/hash-list.h"
+#include "fst/fstlib.h"
+#include "itf/decodable-itf.h"
+#include "fstext/fstext-lib.h"
+#include "lat/determinize-lattice-pruned.h"
+#include "lat/kaldi-lattice.h"
+#include "decoder/lattice-incremental-decoder.h"
+
+namespace kaldi {
+
+
+
+/** LatticeIncrementalOnlineDecoderTpl is as LatticeIncrementalDecoderTpl but also
+ supports an efficient way to get the best path (see the function
+ BestPathEnd()), which is useful in endpointing and in situations where you
+ might want to frequently access the best path.
+
+ This is only templated on the FST type, since the Token type is required to
+ be BackpointerToken. Actually it only makes sense to instantiate
+ LatticeIncrementalDecoderTpl with Token == BackpointerToken if you do so indirectly via
+ this child class.
+ */
+template <typename FST>
+class LatticeIncrementalOnlineDecoderTpl:
+ public LatticeIncrementalDecoderTpl<FST, decoder::BackpointerToken> {
+ public:
+ using Arc = typename FST::Arc;
+ using Label = typename Arc::Label;
+ using StateId = typename Arc::StateId;
+ using Weight = typename Arc::Weight;
+ using Token = decoder::BackpointerToken;
+ using ForwardLinkT = decoder::ForwardLink<Token>;
+
+ // Instantiate this class once for each thing you have to decode.
+ // This version of the constructor does not take ownership of
+ // 'fst'.
+ LatticeIncrementalOnlineDecoderTpl(const FST &fst,
+ const TransitionInformation &trans_model,
+ const LatticeIncrementalDecoderConfig &config):
+ LatticeIncrementalDecoderTpl<FST, Token>(fst, trans_model, config) { }
+
+ // This version of the initializer takes ownership of 'fst', and will delete
+ // it when this object is destroyed.
+ LatticeIncrementalOnlineDecoderTpl(const LatticeIncrementalDecoderConfig &config,
+ FST *fst,
+ const TransitionInformation &trans_model):
+ LatticeIncrementalDecoderTpl<FST, Token>(config, fst, trans_model) { }
+
+
+ struct BestPathIterator {
+ void *tok;
+ int32 frame;
+ // note, "frame" is the frame-index of the frame you'll get the
+ // transition-id for next time, if you call TraceBackBestPath on this
+ // iterator (assuming it's not an epsilon transition). Note that this
+ // is one less than you might reasonably expect, e.g. it's -1 for
+ // the nonemitting transitions before the first frame.
+ BestPathIterator(void *t, int32 f): tok(t), frame(f) { }
+ bool Done() { return tok == NULL; }
+ };
+
+
+ /// Outputs an FST corresponding to the single best path through the lattice.
+ /// This is quite efficient because it doesn't get the entire raw lattice and find
+ /// the best path through it; instead, it uses the BestPathEnd and BestPathIterator
+ /// so it basically traces it back through the lattice.
+ /// Returns true if result is nonempty (using the return status is deprecated,
+ /// it will become void). If "use_final_probs" is true AND we reached the
+ /// final-state of the graph then it will include those as final-probs, else
+ /// it will treat all final-probs as one.
+ bool GetBestPath(Lattice *ofst,
+ bool use_final_probs = true) const;
+
+
+
+ /// This function returns an iterator that can be used to trace back
+ /// the best path. If use_final_probs == true and at least one final state
+ /// survived till the end, it will use the final-probs in working out the best
+ /// final Token, and will output the final cost to *final_cost (if non-NULL),
+ /// else it will use only the forward likelihood, and will put zero in
+ /// *final_cost (if non-NULL).
+ /// Requires that NumFramesDecoded() > 0.
+ BestPathIterator BestPathEnd(bool use_final_probs,
+ BaseFloat *final_cost = NULL) const;
+
+
+ /// This function can be used in conjunction with BestPathEnd() to trace back
+ /// the best path one link at a time (e.g. this can be useful in endpoint
+ /// detection). By "link" we mean a link in the graph; not all links cross
+ /// frame boundaries, but each time you see a nonzero ilabel you can interpret
+ /// that as a frame. The return value is the updated iterator. It outputs
+ /// the ilabel and olabel, and the (graph and acoustic) weight to the "arc" pointer,
+ /// while leaving its "nextstate" variable unchanged.
+ BestPathIterator TraceBackBestPath(
+ BestPathIterator iter, LatticeArc *arc) const;
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(LatticeIncrementalOnlineDecoderTpl);
+};
+
+typedef LatticeIncrementalOnlineDecoderTpl<fst::StdFst> LatticeIncrementalOnlineDecoder;
+
+
+} // end namespace kaldi.
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/lattice-simple-decoder.cc b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-simple-decoder.cc
new file mode 100644
index 000000000..cc8712e85
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-simple-decoder.cc
@@ -0,0 +1,666 @@
+// decoder/lattice-simple-decoder.cc
+
+// Copyright 2009-2012 Microsoft Corporation
+// 2013-2014 Johns Hopkins University (Author: Daniel Povey)
+// 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "decoder/lattice-simple-decoder.h"
+
+namespace kaldi {
+
+
+void LatticeSimpleDecoder::InitDecoding() {
+ // clean up from last time:
+ cur_toks_.clear();
+ prev_toks_.clear();
+ ClearActiveTokens();
+ warned_ = false;
+ decoding_finalized_ = false;
+ final_costs_.clear();
+ num_toks_ = 0;
+ StateId start_state = fst_.Start();
+ KALDI_ASSERT(start_state != fst::kNoStateId);
+ active_toks_.resize(1);
+ Token *start_tok = new Token(0.0, 0.0, NULL, NULL);
+ active_toks_[0].toks = start_tok;
+ cur_toks_[start_state] = start_tok;
+ num_toks_++;
+ ProcessNonemitting();
+}
+
+bool LatticeSimpleDecoder::Decode(DecodableInterface *decodable) {
+ InitDecoding();
+
+ while (!decodable->IsLastFrame(NumFramesDecoded() - 1)) {
+ if (NumFramesDecoded() % config_.prune_interval == 0)
+ PruneActiveTokens(config_.lattice_beam * config_.prune_scale);
+ ProcessEmitting(decodable);
+ // Important to call PruneCurrentTokens before ProcessNonemitting, or we
+ // would get dangling forward pointers. Anyway, ProcessNonemitting uses the
+ // beam.
+ PruneCurrentTokens(config_.beam, &cur_toks_);
+ ProcessNonemitting();
+ }
+ FinalizeDecoding();
+
+ // Returns true if we have any kind of traceback available (not necessarily
+ // to the end state; query ReachedFinal() for that).
+ return !final_costs_.empty();
+}
+
+// Outputs an FST corresponding to the single best path
+// through the lattice.
+bool LatticeSimpleDecoder::GetBestPath(Lattice *ofst,
+ bool use_final_probs) const {
+ fst::VectorFst<LatticeArc> fst;
+ GetRawLattice(&fst, use_final_probs);
+ ShortestPath(fst, ofst);
+ return (ofst->NumStates() > 0);
+}
+
+// Outputs an FST corresponding to the raw, state-level
+// tracebacks.
+bool LatticeSimpleDecoder::GetRawLattice(Lattice *ofst,
+ bool use_final_probs) const {
+ typedef LatticeArc Arc;
+ typedef Arc::StateId StateId;
+ typedef Arc::Weight Weight;
+ typedef Arc::Label Label;
+
+ // Note: you can't use the old interface (Decode()) if you want to
+ // get the lattice with use_final_probs = false. You'd have to do
+ // InitDecoding() and then AdvanceDecoding().
+ if (decoding_finalized_ && !use_final_probs)
+ KALDI_ERR << "You cannot call FinalizeDecoding() and then call "
+ << "GetRawLattice() with use_final_probs == false";
+
+ unordered_map<Token*, BaseFloat> final_costs_local;
+
+ const unordered_map<Token*, BaseFloat> &final_costs =
+ (decoding_finalized_ ? final_costs_ : final_costs_local);
+
+ if (!decoding_finalized_ && use_final_probs)
+ ComputeFinalCosts(&final_costs_local, NULL, NULL);
+
+ ofst->DeleteStates();
+ int32 num_frames = NumFramesDecoded();
+ KALDI_ASSERT(num_frames > 0);
+ const int32 bucket_count = num_toks_/2 + 3;
+ unordered_map<Token*, StateId> tok_map(bucket_count);
+ // First create all states.
+ for (int32 f = 0; f <= num_frames; f++) {
+ if (active_toks_[f].toks == NULL) {
+ KALDI_WARN << "GetRawLattice: no tokens active on frame " << f
+ << ": not producing lattice.\n";
+ return false;
+ }
+ for (Token *tok = active_toks_[f].toks; tok != NULL; tok = tok->next)
+ tok_map[tok] = ofst->AddState();
+ // The next statement sets the start state of the output FST.
+ // Because we always add new states to the head of the list
+ // active_toks_[f].toks, and the start state was the first one
+ // added, it will be the last one added to ofst.
+ if (f == 0 && ofst->NumStates() > 0)
+ ofst->SetStart(ofst->NumStates()-1);
+ }
+ StateId cur_state = 0; // we rely on the fact that we numbered these
+ // consecutively (AddState() returns the numbers in order..)
+ for (int32 f = 0; f <= num_frames; f++) {
+ for (Token *tok = active_toks_[f].toks; tok != NULL; tok = tok->next,
+ cur_state++) {
+ for (ForwardLink *l = tok->links;
+ l != NULL;
+ l = l->next) {
+ unordered_map<Token*, StateId>::const_iterator iter =
+ tok_map.find(l->next_tok);
+ StateId nextstate = iter->second;
+ KALDI_ASSERT(iter != tok_map.end());
+ Arc arc(l->ilabel, l->olabel,
+ Weight(l->graph_cost, l->acoustic_cost),
+ nextstate);
+ ofst->AddArc(cur_state, arc);
+ }
+ if (f == num_frames) {
+ if (use_final_probs && !final_costs.empty()) {
+ unordered_map<Token*, BaseFloat>::const_iterator iter =
+ final_costs.find(tok);
+ if (iter != final_costs.end())
+ ofst->SetFinal(cur_state, LatticeWeight(iter->second, 0));
+ } else {
+ ofst->SetFinal(cur_state, LatticeWeight::One());
+ }
+ }
+ }
+ }
+ KALDI_ASSERT(cur_state == ofst->NumStates());
+ return (cur_state != 0);
+}
+
+// This function is now deprecated, since now we do determinization from outside
+// the LatticeSimpleDecoder class.
+// Outputs an FST corresponding to the lattice-determinized
+// lattice (one path per word sequence).
+bool LatticeSimpleDecoder::GetLattice(
+ CompactLattice *ofst,
+ bool use_final_probs) const {
+ Lattice raw_fst;
+ GetRawLattice(&raw_fst, use_final_probs);
+ Invert(&raw_fst); // make it so word labels are on the input.
+ if (!TopSort(&raw_fst)) // topological sort makes lattice-determinization more efficient
+ KALDI_WARN << "Topological sorting of state-level lattice failed "
+ "(probably your lexicon has empty words or your LM has epsilon cycles; this "
+ " is a bad idea.)";
+ // (in phase where we get backward-costs).
+ fst::ILabelCompare<LatticeArc> ilabel_comp;
+ ArcSort(&raw_fst, ilabel_comp); // sort on ilabel; makes
+ // lattice-determinization more efficient.
+
+ fst::DeterminizeLatticePrunedOptions lat_opts;
+ lat_opts.max_mem = config_.det_opts.max_mem;
+
+ DeterminizeLatticePruned(raw_fst, config_.lattice_beam, ofst, lat_opts);
+ raw_fst.DeleteStates(); // Free memory-- raw_fst no longer needed.
+ Connect(ofst); // Remove unreachable states... there might be
+ // a small number of these, in some cases.
+ // Note: if something went wrong and the raw lattice was empty,
+ // we should still get to this point in the code without warnings or failures.
+ return (ofst->NumStates() != 0);
+}
+
+
+
+// FindOrAddToken either locates a token in cur_toks_, or if necessary inserts a new,
+// empty token (i.e. with no forward links) for the current frame. [note: it's
+// inserted if necessary into cur_toks_ and also into the singly linked list
+// of tokens active on this frame (whose head is at active_toks_[frame]).
+//
+// Returns the Token pointer. Sets "changed" (if non-NULL) to true
+// if the token was newly created or the cost changed.
+inline LatticeSimpleDecoder::Token *LatticeSimpleDecoder::FindOrAddToken(
+ StateId state, int32 frame, BaseFloat tot_cost,
+ bool emitting, bool *changed) {
+ KALDI_ASSERT(frame < active_toks_.size());
+ Token *&toks = active_toks_[frame].toks;
+
+ unordered_map<StateId, Token*>::iterator find_iter = cur_toks_.find(state);
+ if (find_iter == cur_toks_.end()) { // no such token presently.
+ // Create one.
+ const BaseFloat extra_cost = 0.0;
+ // tokens on the currently final frame have zero extra_cost
+ // as any of them could end up
+ // on the winning path.
+ Token *new_tok = new Token (tot_cost, extra_cost, NULL, toks);
+ toks = new_tok;
+ num_toks_++;
+ cur_toks_[state] = new_tok;
+ if (changed) *changed = true;
+ return new_tok;
+ } else {
+ Token *tok = find_iter->second; // There is an existing Token for this state.
+ if (tok->tot_cost > tot_cost) {
+ tok->tot_cost = tot_cost;
+ if (changed) *changed = true;
+ } else {
+ if (changed) *changed = false;
+ }
+ return tok;
+ }
+}
+
+// delta is the amount by which the extra_costs must
+// change before it sets "extra_costs_changed" to true. If delta is larger,
+// we'll tend to go back less far toward the beginning of the file.
+void LatticeSimpleDecoder::PruneForwardLinks(
+ int32 frame, bool *extra_costs_changed,
+ bool *links_pruned, BaseFloat delta) {
+ // We have to iterate until there is no more change, because the links
+ // are not guaranteed to be in topological order.
+
+ *extra_costs_changed = false;
+ *links_pruned = false;
+ KALDI_ASSERT(frame >= 0 && frame < active_toks_.size());
+ if (active_toks_[frame].toks == NULL ) { // empty list; this should
+ // not happen.
+ if (!warned_) {
+ KALDI_WARN << "No tokens alive [doing pruning].. warning first "
+ "time only for each utterance\n";
+ warned_ = true;
+ }
+ }
+
+ bool changed = true;
+ while (changed) {
+ changed = false;
+ for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
+ ForwardLink *link, *prev_link = NULL;
+ // will recompute tok_extra_cost.
+ BaseFloat tok_extra_cost = std::numeric_limits<BaseFloat>::infinity();
+ for (link = tok->links; link != NULL; ) {
+ // See if we need to excise this link...
+ Token *next_tok = link->next_tok;
+ BaseFloat link_extra_cost = next_tok->extra_cost +
+ ((tok->tot_cost + link->acoustic_cost + link->graph_cost)
+ - next_tok->tot_cost);
+ KALDI_ASSERT(link_extra_cost == link_extra_cost); // check for NaN
+ if (link_extra_cost > config_.lattice_beam) { // excise link
+ ForwardLink *next_link = link->next;
+ if (prev_link != NULL) prev_link->next = next_link;
+ else tok->links = next_link;
+ delete link;
+ link = next_link; // advance link but leave prev_link the same.
+ *links_pruned = true;
+ } else { // keep the link and update the tok_extra_cost if needed.
+ if (link_extra_cost < 0.0) { // this is just a precaution.
+ if (link_extra_cost < -0.01)
+ KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
+ link_extra_cost = 0.0;
+ }
+ if (link_extra_cost < tok_extra_cost)
+ tok_extra_cost = link_extra_cost;
+ prev_link = link;
+ link = link->next;
+ }
+ }
+ if (fabs(tok_extra_cost - tok->extra_cost) > delta)
+ changed = true;
+ tok->extra_cost = tok_extra_cost; // will be +infinity or <= lattice_beam_.
+ }
+ if (changed) *extra_costs_changed = true;
+
+ // Note: it's theoretically possible that aggressive compiler
+ // optimizations could cause an infinite loop here for small delta and
+ // high-dynamic-range scores.
+ }
+}
+
+
+void LatticeSimpleDecoder::ComputeFinalCosts(
+ unordered_map<Token*, BaseFloat> *final_costs,
+ BaseFloat *final_relative_cost,
+ BaseFloat *final_best_cost) const {
+ KALDI_ASSERT(!decoding_finalized_);
+ if (final_costs != NULL)
+ final_costs->clear();
+
+ BaseFloat infinity = std::numeric_limits<BaseFloat>::infinity();
+ BaseFloat best_cost = infinity,
+ best_cost_with_final = infinity;
+
+ for (unordered_map<StateId, Token*>::const_iterator iter = cur_toks_.begin();
+ iter != cur_toks_.end(); ++iter) {
+ StateId state = iter->first;
+ Token *tok = iter->second;
+ BaseFloat final_cost = fst_.Final(state).Value();
+ BaseFloat cost = tok->tot_cost,
+ cost_with_final = cost + final_cost;
+ best_cost = std::min(cost, best_cost);
+ best_cost_with_final = std::min(cost_with_final, best_cost_with_final);
+ if (final_costs != NULL && final_cost != infinity)
+ (*final_costs)[tok] = final_cost;
+ }
+ if (final_relative_cost != NULL) {
+ if (best_cost == infinity && best_cost_with_final == infinity) {
+ // Likely this will only happen if there are no tokens surviving.
+ // This seems the least bad way to handle it.
+ *final_relative_cost = infinity;
+ } else {
+ *final_relative_cost = best_cost_with_final - best_cost;
+ }
+ }
+ if (final_best_cost != NULL) {
+ if (best_cost_with_final != infinity) { // final-state exists.
+ *final_best_cost = best_cost_with_final;
+ } else { // no final-state exists.
+ *final_best_cost = best_cost;
+ }
+ }
+}
+
+
+// PruneForwardLinksFinal is a version of PruneForwardLinks that we call
+// on the final frame. If there are final tokens active, it uses the final-probs
+// for pruning, otherwise it treats all tokens as final.
+void LatticeSimpleDecoder::PruneForwardLinksFinal() {
+ KALDI_ASSERT(!active_toks_.empty());
+ int32 frame_plus_one = active_toks_.size() - 1;
+
+ if (active_toks_[frame_plus_one].toks == NULL) // empty list; should not happen.
+ KALDI_WARN << "No tokens alive at end of file\n";
+
+ typedef unordered_map<Token*, BaseFloat>::const_iterator IterType;
+ ComputeFinalCosts(&final_costs_, &final_relative_cost_, &final_best_cost_);
+ decoding_finalized_ = true;
+ // We're about to delete some of the tokens active on the final frame, so we
+ // clear cur_toks_ because otherwise it would then contain dangling pointers.
+ cur_toks_.clear();
+
+ // Now go through tokens on this frame, pruning forward links... may have to
+ // iterate a few times until there is no more change, because the list is not
+ // in topological order. This is a modified version of the code in
+ // PruneForwardLinks, but here we also take account of the final-probs.
+ bool changed = true;
+ BaseFloat delta = 1.0e-05;
+ while (changed) {
+ changed = false;
+ for (Token *tok = active_toks_[frame_plus_one].toks;
+ tok != NULL; tok = tok->next) {
+ ForwardLink *link, *prev_link=NULL;
+ // will recompute tok_extra_cost. It has a term in it that corresponds
+ // to the "final-prob", so instead of initializing tok_extra_cost to infinity
+ // below we set it to the difference between the (score+final_prob) of this token,
+ // and the best such (score+final_prob).
+
+ BaseFloat final_cost;
+ if (final_costs_.empty()) {
+ final_cost = 0.0;
+ } else {
+ IterType iter = final_costs_.find(tok);
+ if (iter != final_costs_.end())
+ final_cost = iter->second;
+ else
+ final_cost = std::numeric_limits<BaseFloat>::infinity();
+ }
+ BaseFloat tok_extra_cost = tok->tot_cost + final_cost - final_best_cost_;
+ // tok_extra_cost will be a "min" over either directly being final, or
+ // being indirectly final through other links, and the loop below may
+ // decrease its value:
+ for (link = tok->links; link != NULL; ) {
+ // See if we need to excise this link...
+ Token *next_tok = link->next_tok;
+ BaseFloat link_extra_cost = next_tok->extra_cost +
+ ((tok->tot_cost + link->acoustic_cost + link->graph_cost)
+ - next_tok->tot_cost);
+ if (link_extra_cost > config_.lattice_beam) { // excise link
+ ForwardLink *next_link = link->next;
+ if (prev_link != NULL) prev_link->next = next_link;
+ else tok->links = next_link;
+ delete link;
+ link = next_link; // advance link but leave prev_link the same.
+ } else { // keep the link and update the tok_extra_cost if needed.
+ if (link_extra_cost < 0.0) { // this is just a precaution.
+ if (link_extra_cost < -0.01)
+ KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
+ link_extra_cost = 0.0;
+ }
+ if (link_extra_cost < tok_extra_cost)
+ tok_extra_cost = link_extra_cost;
+ prev_link = link;
+ link = link->next;
+ }
+ }
+ // prune away tokens worse than lattice_beam above best path. This step
+ // was not necessary in the non-final case because then, this case
+ // showed up as having no forward links. Here, the tok_extra_cost has
+ // an extra component relating to the final-prob.
+ if (tok_extra_cost > config_.lattice_beam)
+ tok_extra_cost = std::numeric_limits<BaseFloat>::infinity();
+ // to be pruned in PruneTokensForFrame
+
+ if (!ApproxEqual(tok->extra_cost, tok_extra_cost, delta))
+ changed = true;
+ tok->extra_cost = tok_extra_cost; // will be +infinity or <= lattice_beam_.
+ }
+ } // while changed
+}
+
+BaseFloat LatticeSimpleDecoder::FinalRelativeCost() const {
+ if (!decoding_finalized_) {
+ BaseFloat relative_cost;
+ ComputeFinalCosts(NULL, &relative_cost, NULL);
+ return relative_cost;
+ } else {
+ // we're not allowed to call that function if FinalizeDecoding() has
+ // been called; return a cached value.
+ return final_relative_cost_;
+ }
+}
+
+// Prune away any tokens on this frame that have no forward links. [we don't do
+// this in PruneForwardLinks because it would give us a problem with dangling
+// pointers].
+void LatticeSimpleDecoder::PruneTokensForFrame(int32 frame) {
+ KALDI_ASSERT(frame >= 0 && frame < active_toks_.size());
+ Token *&toks = active_toks_[frame].toks;
+ if (toks == NULL)
+ KALDI_WARN << "No tokens alive [doing pruning]";
+ Token *tok, *next_tok, *prev_tok = NULL;
+ for (tok = toks; tok != NULL; tok = next_tok) {
+ next_tok = tok->next;
+ if (tok->extra_cost == std::numeric_limits<BaseFloat>::infinity()) {
+ // Next token is unreachable from end of graph; excise tok from list
+ // and delete tok.
+ if (prev_tok != NULL) prev_tok->next = tok->next;
+ else toks = tok->next;
+ delete tok;
+ num_toks_--;
+ } else {
+ prev_tok = tok;
+ }
+ }
+}
+
+// Go backwards through still-alive tokens, pruning them, starting not from
+// the current frame (where we want to keep all tokens) but from the frame before
+// that. We go backwards through the frames and stop when we reach a point
+// where the delta-costs are not changing (and the delta controls when we consider
+// a cost to have "not changed").
+void LatticeSimpleDecoder::PruneActiveTokens(BaseFloat delta) {
+ int32 cur_frame_plus_one = NumFramesDecoded();
+ int32 num_toks_begin = num_toks_;
+ // The index "f" below represents a "frame plus one", i.e. you'd have to subtract
+ // one to get the corresponding index for the decodable object.
+ for (int32 f = cur_frame_plus_one - 1; f >= 0; f--) {
+ // Reason why we need to prune forward links in this situation:
+ // (1) we have never pruned them
+ // (2) we never pruned the forward links on the next frame, which
+ //
+ if (active_toks_[f].must_prune_forward_links) {
+ bool extra_costs_changed = false, links_pruned = false;
+ PruneForwardLinks(f, &extra_costs_changed, &links_pruned, delta);
+ if (extra_costs_changed && f > 0)
+ active_toks_[f-1].must_prune_forward_links = true;
+ if (links_pruned)
+ active_toks_[f].must_prune_tokens = true;
+ active_toks_[f].must_prune_forward_links = false;
+ }
+ if (f+1 < cur_frame_plus_one &&
+ active_toks_[f+1].must_prune_tokens) {
+ PruneTokensForFrame(f+1);
+ active_toks_[f+1].must_prune_tokens = false;
+ }
+ }
+ KALDI_VLOG(3) << "PruneActiveTokens: pruned tokens from " << num_toks_begin
+ << " to " << num_toks_;
+}
+
+
+// FinalizeDecoding() is a version of PruneActiveTokens that we call
+// (optionally) on the final frame. Takes into account the final-prob of
+// tokens. This function used to be called PruneActiveTokensFinal().
+void LatticeSimpleDecoder::FinalizeDecoding() {
+ int32 final_frame_plus_one = NumFramesDecoded();
+ int32 num_toks_begin = num_toks_;
+ PruneForwardLinksFinal();
+ for (int32 f = final_frame_plus_one - 1; f >= 0; f--) {
+ bool b1, b2; // values not used.
+ BaseFloat dontcare = 0.0;
+ PruneForwardLinks(f, &b1, &b2, dontcare);
+ PruneTokensForFrame(f + 1);
+ }
+ PruneTokensForFrame(0);
+ KALDI_VLOG(3) << "pruned tokens from " << num_toks_begin
+ << " to " << num_toks_;
+}
+
+void LatticeSimpleDecoder::ProcessEmitting(DecodableInterface *decodable) {
+ int32 frame = active_toks_.size() - 1; // frame is the frame-index
+ // (zero-based) used to get likelihoods
+ // from the decodable object.
+ active_toks_.resize(active_toks_.size() + 1);
+ prev_toks_.clear();
+ cur_toks_.swap(prev_toks_);
+
+ // Processes emitting arcs for one frame. Propagates from
+ // prev_toks_ to cur_toks_.
+ BaseFloat cutoff = std::numeric_limits<BaseFloat>::infinity();
+ for (unordered_map<StateId, Token*>::iterator iter = prev_toks_.begin();
+ iter != prev_toks_.end();
+ ++iter) {
+ StateId state = iter->first;
+ Token *tok = iter->second;
+ for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0) { // propagate..
+ BaseFloat ac_cost = -decodable->LogLikelihood(frame, arc.ilabel),
+ graph_cost = arc.weight.Value(),
+ cur_cost = tok->tot_cost,
+ tot_cost = cur_cost + ac_cost + graph_cost;
+ if (tot_cost >= cutoff) continue;
+ else if (tot_cost + config_.beam < cutoff)
+ cutoff = tot_cost + config_.beam;
+ // AddToken adds the next_tok to cur_toks_ (if not already present).
+ Token *next_tok = FindOrAddToken(arc.nextstate, frame + 1, tot_cost,
+ true, NULL);
+
+ // Add ForwardLink from tok to next_tok (put on head of list tok->links)
+ tok->links = new ForwardLink(next_tok, arc.ilabel, arc.olabel,
+ graph_cost, ac_cost, tok->links);
+ }
+ }
+ }
+}
+
+void LatticeSimpleDecoder::ProcessNonemitting() {
+ KALDI_ASSERT(!active_toks_.empty());
+ int32 frame = static_cast<int32>(active_toks_.size()) - 2;
+ // Note: "frame" is the time-index we just processed, or -1 if
+ // we are processing the nonemitting transitions before the
+ // first frame (called from InitDecoding()).
+
+ // Processes nonemitting arcs for one frame. Propagates within
+ // cur_toks_. Note-- this queue structure is is not very optimal as
+ // it may cause us to process states unnecessarily (e.g. more than once),
+ // but in the baseline code, turning this vector into a set to fix this
+ // problem did not improve overall speed.
+ std::vector<StateId> queue;
+ BaseFloat best_cost = std::numeric_limits<BaseFloat>::infinity();
+ for (unordered_map<StateId, Token*>::iterator iter = cur_toks_.begin();
+ iter != cur_toks_.end();
+ ++iter) {
+ StateId state = iter->first;
+ if (fst_.NumInputEpsilons(state) != 0)
+ queue.push_back(state);
+ best_cost = std::min(best_cost, iter->second->tot_cost);
+ }
+ if (queue.empty()) {
+ if (!warned_) {
+ KALDI_ERR << "Error in ProcessEmitting: no surviving tokens: frame is "
+ << frame;
+ warned_ = true;
+ }
+ }
+ BaseFloat cutoff = best_cost + config_.beam;
+
+ while (!queue.empty()) {
+ StateId state = queue.back();
+ queue.pop_back();
+ Token *tok = cur_toks_[state];
+ // If "tok" has any existing forward links, delete them,
+ // because we're about to regenerate them. This is a kind
+ // of non-optimality (remember, this is the simple decoder),
+ // but since most states are emitting it's not a huge issue.
+ tok->DeleteForwardLinks();
+ tok->links = NULL;
+ for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel == 0) { // propagate nonemitting only...
+ BaseFloat graph_cost = arc.weight.Value(),
+ cur_cost = tok->tot_cost,
+ tot_cost = cur_cost + graph_cost;
+ if (tot_cost < cutoff) {
+ bool changed;
+ Token *new_tok = FindOrAddToken(arc.nextstate, frame + 1, tot_cost,
+ false, &changed);
+
+ tok->links = new ForwardLink(new_tok, 0, arc.olabel,
+ graph_cost, 0, tok->links);
+
+ // "changed" tells us whether the new token has a different
+ // cost from before, or is new [if so, add into queue].
+ if (changed && fst_.NumInputEpsilons(arc.nextstate) != 0)
+ queue.push_back(arc.nextstate);
+ }
+ }
+ }
+ }
+}
+
+void LatticeSimpleDecoder::ClearActiveTokens() { // a cleanup routine, at utt end/begin
+ for (size_t i = 0; i < active_toks_.size(); i++) {
+ // Delete all tokens alive on this frame, and any forward
+ // links they may have.
+ for (Token *tok = active_toks_[i].toks; tok != NULL; ) {
+ tok->DeleteForwardLinks();
+ Token *next_tok = tok->next;
+ delete tok;
+ num_toks_--;
+ tok = next_tok;
+ }
+ }
+ active_toks_.clear();
+ KALDI_ASSERT(num_toks_ == 0);
+}
+
+// PruneCurrentTokens deletes the tokens from the "toks" map, but not
+// from the active_toks_ list, which could cause dangling forward pointers
+// (will delete it during regular pruning operation).
+void LatticeSimpleDecoder::PruneCurrentTokens(BaseFloat beam, unordered_map<StateId, Token*> *toks) {
+ if (toks->empty()) {
+ KALDI_VLOG(2) << "No tokens to prune.\n";
+ return;
+ }
+ BaseFloat best_cost = 1.0e+10; // positive == high cost == bad.
+ for (unordered_map<StateId, Token*>::iterator iter = toks->begin();
+ iter != toks->end(); ++iter) {
+ best_cost =
+ std::min(best_cost,
+ static_cast<BaseFloat>(iter->second->tot_cost));
+ }
+ std::vector<StateId> retained;
+ BaseFloat cutoff = best_cost + beam;
+ for (unordered_map<StateId, Token*>::iterator iter = toks->begin();
+ iter != toks->end(); ++iter) {
+ if (iter->second->tot_cost < cutoff)
+ retained.push_back(iter->first);
+ }
+ unordered_map<StateId, Token*> tmp;
+ for (size_t i = 0; i < retained.size(); i++) {
+ tmp[retained[i]] = (*toks)[retained[i]];
+ }
+ KALDI_VLOG(2) << "Pruned to "<<(retained.size())<<" toks.\n";
+ tmp.swap(*toks);
+}
+
+
+} // end namespace kaldi.
+
+
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/lattice-simple-decoder.h b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-simple-decoder.h
new file mode 100644
index 000000000..dd8de81e1
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/lattice-simple-decoder.h
@@ -0,0 +1,318 @@
+// decoder/lattice-simple-decoder.h
+
+// Copyright 2009-2012 Microsoft Corporation
+// 2012-2014 Johns Hopkins University (Author: Daniel Povey)
+// 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_DECODER_LATTICE_SIMPLE_DECODER_H_
+#define KALDI_DECODER_LATTICE_SIMPLE_DECODER_H_
+
+
+#include "util/stl-utils.h"
+#include "fst/fstlib.h"
+#include "itf/decodable-itf.h"
+#include "fstext/fstext-lib.h"
+#include "lat/determinize-lattice-pruned.h"
+#include "lat/kaldi-lattice.h"
+
+#include <algorithm>
+
+namespace kaldi {
+
+struct LatticeSimpleDecoderConfig {
+ BaseFloat beam;
+ BaseFloat lattice_beam;
+ int32 prune_interval;
+ bool determinize_lattice; // not inspected by this class... used in
+ // command-line program.
+ bool prune_lattice;
+ BaseFloat beam_ratio;
+ BaseFloat prune_scale; // Note: we don't make this configurable on the command line,
+ // it's not a very important parameter. It affects the
+ // algorithm that prunes the tokens as we go.
+ fst::DeterminizeLatticePhonePrunedOptions det_opts;
+
+ LatticeSimpleDecoderConfig(): beam(16.0),
+ lattice_beam(10.0),
+ prune_interval(25),
+ determinize_lattice(true),
+ beam_ratio(0.9),
+ prune_scale(0.1) { }
+ void Register(OptionsItf *opts) {
+ det_opts.Register(opts);
+ opts->Register("beam", &beam, "Decoding beam.");
+ opts->Register("lattice-beam", &lattice_beam, "Lattice generation beam");
+ opts->Register("prune-interval", &prune_interval, "Interval (in frames) at "
+ "which to prune tokens");
+ opts->Register("determinize-lattice", &determinize_lattice, "If true, "
+ "determinize the lattice (in a special sense, keeping only "
+ "best pdf-sequence for each word-sequence).");
+ }
+ void Check() const {
+ KALDI_ASSERT(beam > 0.0 && lattice_beam > 0.0 && prune_interval > 0);
+ }
+};
+
+
+/** Simplest possible decoder, included largely for didactic purposes and as a
+ means to debug more highly optimized decoders. See \ref decoders_simple
+ for more information.
+ */
+class LatticeSimpleDecoder {
+ public:
+ typedef fst::StdArc Arc;
+ typedef Arc::Label Label;
+ typedef Arc::StateId StateId;
+ typedef Arc::Weight Weight;
+ // instantiate this class once for each thing you have to decode.
+ LatticeSimpleDecoder(const fst::Fst<fst::StdArc> &fst,
+ const LatticeSimpleDecoderConfig &config):
+ fst_(fst), config_(config), num_toks_(0) { config.Check(); }
+
+ ~LatticeSimpleDecoder() { ClearActiveTokens(); }
+
+ const LatticeSimpleDecoderConfig &GetOptions() const {
+ return config_;
+ }
+
+ // Returns true if any kind of traceback is available (not necessarily from
+ // a final state).
+ bool Decode(DecodableInterface *decodable);
+
+
+ /// says whether a final-state was active on the last frame. If it was not, the
+ /// lattice (or traceback) will end with states that are not final-states.
+ bool ReachedFinal() const {
+ return FinalRelativeCost() != std::numeric_limits<BaseFloat>::infinity();
+ }
+
+ /// InitDecoding initializes the decoding, and should only be used if you
+ /// intend to call AdvanceDecoding(). If you call Decode(), you don't need
+ /// to call this. You can call InitDecoding if you have already decoded an
+ /// utterance and want to start with a new utterance.
+ void InitDecoding();
+
+ /// This function may be optionally called after AdvanceDecoding(), when you
+ /// do not plan to decode any further. It does an extra pruning step that
+ /// will help to prune the lattices output by GetLattice and (particularly)
+ /// GetRawLattice more accurately, particularly toward the end of the
+ /// utterance. It does this by using the final-probs in pruning (if any
+ /// final-state survived); it also does a final pruning step that visits all
+ /// states (the pruning that is done during decoding may fail to prune states
+ /// that are within kPruningScale = 0.1 outside of the beam). If you call
+ /// this, you cannot call AdvanceDecoding again (it will fail), and you
+ /// cannot call GetLattice() and related functions with use_final_probs =
+ /// false.
+ /// Used to be called PruneActiveTokensFinal().
+ void FinalizeDecoding();
+
+ /// FinalRelativeCost() serves the same purpose as ReachedFinal(), but gives
+ /// more information. It returns the difference between the best (final-cost
+ /// plus cost) of any token on the final frame, and the best cost of any token
+ /// on the final frame. If it is infinity it means no final-states were
+ /// present on the final frame. It will usually be nonnegative. If it not
+ /// too positive (e.g. < 5 is my first guess, but this is not tested) you can
+ /// take it as a good indication that we reached the final-state with
+ /// reasonable likelihood.
+ BaseFloat FinalRelativeCost() const;
+
+ // Outputs an FST corresponding to the single best path
+ // through the lattice. Returns true if result is nonempty
+ // (using the return status is deprecated, it will become void).
+ // If "use_final_probs" is true AND we reached the final-state
+ // of the graph then it will include those as final-probs, else
+ // it will treat all final-probs as one.
+ bool GetBestPath(Lattice *lat,
+ bool use_final_probs = true) const;
+
+ // Outputs an FST corresponding to the raw, state-level
+ // tracebacks. Returns true if result is nonempty
+ // (using the return status is deprecated, it will become void).
+ // If "use_final_probs" is true AND we reached the final-state
+ // of the graph then it will include those as final-probs, else
+ // it will treat all final-probs as one.
+ bool GetRawLattice(Lattice *lat,
+ bool use_final_probs = true) const;
+
+ // This function is now deprecated, since now we do determinization from
+ // outside the LatticeTrackingDecoder class.
+ // Outputs an FST corresponding to the lattice-determinized
+ // lattice (one path per word sequence). [will become deprecated,
+ // users should determinize themselves.]
+ bool GetLattice(CompactLattice *clat,
+ bool use_final_probs = true) const;
+
+ inline int32 NumFramesDecoded() const { return active_toks_.size() - 1; }
+ private:
+ struct Token;
+ // ForwardLinks are the links from a token to a token on the next frame.
+ // or sometimes on the current frame (for input-epsilon links).
+ struct ForwardLink {
+ Token *next_tok; // the next token [or NULL if represents final-state]
+ Label ilabel; // ilabel on link.
+ Label olabel; // olabel on link.
+ BaseFloat graph_cost; // graph cost of traversing link (contains LM, etc.)
+ BaseFloat acoustic_cost; // acoustic cost (pre-scaled) of traversing link
+ ForwardLink *next; // next in singly-linked list of forward links from a
+ // token.
+ ForwardLink(Token *next_tok, Label ilabel, Label olabel,
+ BaseFloat graph_cost, BaseFloat acoustic_cost,
+ ForwardLink *next):
+ next_tok(next_tok), ilabel(ilabel), olabel(olabel),
+ graph_cost(graph_cost), acoustic_cost(acoustic_cost),
+ next(next) { }
+ };
+
+ // Token is what's resident in a particular state at a particular time.
+ // In this decoder a Token actually contains *forward* links.
+ // When first created, a Token just has the (total) cost. We add forward
+ // links from it when we process the next frame.
+ struct Token {
+ BaseFloat tot_cost; // would equal weight.Value()... cost up to this point.
+ BaseFloat extra_cost; // >= 0. After calling PruneForwardLinks, this equals
+ // the minimum difference between the cost of the best path this is on,
+ // and the cost of the absolute best path, under the assumption
+ // that any of the currently active states at the decoding front may
+ // eventually succeed (e.g. if you were to take the currently active states
+ // one by one and compute this difference, and then take the minimum).
+
+ ForwardLink *links; // Head of singly linked list of ForwardLinks
+
+ Token *next; // Next in list of tokens for this frame.
+
+ Token(BaseFloat tot_cost, BaseFloat extra_cost, ForwardLink *links,
+ Token *next): tot_cost(tot_cost), extra_cost(extra_cost), links(links),
+ next(next) { }
+ Token() {}
+ void DeleteForwardLinks() {
+ ForwardLink *l = links, *m;
+ while (l != NULL) {
+ m = l->next;
+ delete l;
+ l = m;
+ }
+ links = NULL;
+ }
+ };
+
+ // head and tail of per-frame list of Tokens (list is in topological order),
+ // and something saying whether we ever pruned it using PruneForwardLinks.
+ struct TokenList {
+ Token *toks;
+ bool must_prune_forward_links;
+ bool must_prune_tokens;
+ TokenList(): toks(NULL), must_prune_forward_links(true),
+ must_prune_tokens(true) { }
+ };
+
+
+ // FindOrAddToken either locates a token in cur_toks_, or if necessary inserts a new,
+ // empty token (i.e. with no forward links) for the current frame. [note: it's
+ // inserted if necessary into cur_toks_ and also into the singly linked list
+ // of tokens active on this frame (whose head is at active_toks_[frame]).
+ //
+ // Returns the Token pointer. Sets "changed" (if non-NULL) to true
+ // if the token was newly created or the cost changed.
+ inline Token *FindOrAddToken(StateId state, int32 frame_plus_one,
+ BaseFloat tot_cost, bool emitting, bool *changed);
+
+ // delta is the amount by which the extra_costs must
+ // change before it sets "extra_costs_changed" to true. If delta is larger,
+ // we'll tend to go back less far toward the beginning of the file.
+ void PruneForwardLinks(int32 frame, bool *extra_costs_changed,
+ bool *links_pruned,
+ BaseFloat delta);
+
+ // PruneForwardLinksFinal is a version of PruneForwardLinks that we call
+ // on the final frame. If there are final tokens active, it uses the final-probs
+ // for pruning, otherwise it treats all tokens as final.
+ void PruneForwardLinksFinal();
+
+ // Prune away any tokens on this frame that have no forward links. [we don't do
+ // this in PruneForwardLinks because it would give us a problem with dangling
+ // pointers].
+ void PruneTokensForFrame(int32 frame);
+
+ // Go backwards through still-alive tokens, pruning them if the
+ // forward+backward cost is more than lat_beam away from the best path. It's
+ // possible to prove that this is "correct" in the sense that we won't lose
+ // anything outside of lat_beam, regardless of what happens in the future.
+ // delta controls when it considers a cost to have changed enough to continue
+ // going backward and propagating the change. larger delta -> will recurse
+ // less far.
+ void PruneActiveTokens(BaseFloat delta);
+
+ void ProcessEmitting(DecodableInterface *decodable);
+
+ void ProcessNonemitting();
+
+ void ClearActiveTokens(); // a cleanup routine, at utt end/begin
+
+ // This function computes the final-costs for tokens active on the final
+ // frame. It outputs to final-costs, if non-NULL, a map from the Token*
+ // pointer to the final-prob of the corresponding state, or zero for all states if
+ // none were final. It outputs to final_relative_cost, if non-NULL, the
+ // difference between the best forward-cost including the final-prob cost, and
+ // the best forward-cost without including the final-prob cost (this will
+ // usually be positive), or infinity if there were no final-probs. It outputs
+ // to final_best_cost, if non-NULL, the lowest for any token t active on the
+ // final frame, of t + final-cost[t], where final-cost[t] is the final-cost
+ // in the graph of the state corresponding to token t, or zero if there
+ // were no final-probs active on the final frame.
+ // You cannot call this after FinalizeDecoding() has been called; in that
+ // case you should get the answer from class-member variables.
+ void ComputeFinalCosts(unordered_map<Token*, BaseFloat> *final_costs,
+ BaseFloat *final_relative_cost,
+ BaseFloat *final_best_cost) const;
+
+
+ // PruneCurrentTokens deletes the tokens from the "toks" map, but not
+ // from the active_toks_ list, which could cause dangling forward pointers
+ // (will delete it during regular pruning operation).
+ void PruneCurrentTokens(BaseFloat beam, unordered_map<StateId, Token*> *toks);
+
+ unordered_map<StateId, Token*> cur_toks_;
+ unordered_map<StateId, Token*> prev_toks_;
+ std::vector<TokenList> active_toks_; // Lists of tokens, indexed by
+ // frame_plus_one
+ const fst::Fst<fst::StdArc> &fst_;
+ LatticeSimpleDecoderConfig config_;
+ int32 num_toks_; // current total #toks allocated...
+ bool warned_;
+
+
+ /// decoding_finalized_ is true if someone called FinalizeDecoding(). [note,
+ /// calling this is optional]. If true, it's forbidden to decode more. Also,
+ /// if this is set, then the output of ComputeFinalCosts() is in the next
+ /// three variables. The reason we need to do this is that after
+ /// FinalizeDecoding() calls PruneTokensForFrame() for the final frame, some
+ /// of the tokens on the last frame are freed, so we free the list from
+ /// cur_toks_ to avoid having dangling pointers hanging around.
+ bool decoding_finalized_;
+ /// For the meaning of the next 3 variables, see the comment for
+ /// decoding_finalized_ above., and ComputeFinalCosts().
+ unordered_map<Token*, BaseFloat> final_costs_;
+ BaseFloat final_relative_cost_;
+ BaseFloat final_best_cost_;
+};
+
+
+} // end namespace kaldi.
+
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/simple-decoder.cc b/runtime/onnxruntime/third_party/kaldi/decoder/simple-decoder.cc
new file mode 100644
index 000000000..f6d799aa8
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/simple-decoder.cc
@@ -0,0 +1,293 @@
+// decoder/simple-decoder.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2012-2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "decoder/simple-decoder.h"
+#include "fstext/remove-eps-local.h"
+#include <algorithm>
+
+namespace kaldi {
+
+SimpleDecoder::~SimpleDecoder() {
+ ClearToks(cur_toks_);
+ ClearToks(prev_toks_);
+}
+
+
+bool SimpleDecoder::Decode(DecodableInterface *decodable) {
+ InitDecoding();
+ AdvanceDecoding(decodable);
+ return (!cur_toks_.empty());
+}
+
+void SimpleDecoder::InitDecoding() {
+ // clean up from last time:
+ ClearToks(cur_toks_);
+ ClearToks(prev_toks_);
+ // initialize decoding:
+ StateId start_state = fst_.Start();
+ KALDI_ASSERT(start_state != fst::kNoStateId);
+ StdArc dummy_arc(0, 0, StdWeight::One(), start_state);
+ cur_toks_[start_state] = new Token(dummy_arc, 0.0, NULL);
+ num_frames_decoded_ = 0;
+ ProcessNonemitting();
+}
+
+void SimpleDecoder::AdvanceDecoding(DecodableInterface *decodable,
+ int32 max_num_frames) {
+ KALDI_ASSERT(num_frames_decoded_ >= 0 &&
+ "You must call InitDecoding() before AdvanceDecoding()");
+ int32 num_frames_ready = decodable->NumFramesReady();
+ // num_frames_ready must be >= num_frames_decoded, or else
+ // the number of frames ready must have decreased (which doesn't
+ // make sense) or the decodable object changed between calls
+ // (which isn't allowed).
+ KALDI_ASSERT(num_frames_ready >= num_frames_decoded_);
+ int32 target_frames_decoded = num_frames_ready;
+ if (max_num_frames >= 0)
+ target_frames_decoded = std::min(target_frames_decoded,
+ num_frames_decoded_ + max_num_frames);
+ while (num_frames_decoded_ < target_frames_decoded) {
+ // note: ProcessEmitting() increments num_frames_decoded_
+ ClearToks(prev_toks_);
+ cur_toks_.swap(prev_toks_);
+ ProcessEmitting(decodable);
+ ProcessNonemitting();
+ PruneToks(beam_, &cur_toks_);
+ }
+}
+
+bool SimpleDecoder::ReachedFinal() const {
+ for (unordered_map<StateId, Token*>::const_iterator iter = cur_toks_.begin();
+ iter != cur_toks_.end();
+ ++iter) {
+ if (iter->second->cost_ != std::numeric_limits<BaseFloat>::infinity() &&
+ fst_.Final(iter->first) != StdWeight::Zero())
+ return true;
+ }
+ return false;
+}
+
+BaseFloat SimpleDecoder::FinalRelativeCost() const {
+ // as a special case, if there are no active tokens at all (e.g. some kind of
+ // pruning failure), return infinity.
+ double infinity = std::numeric_limits<double>::infinity();
+ if (cur_toks_.empty())
+ return infinity;
+ double best_cost = infinity,
+ best_cost_with_final = infinity;
+ for (unordered_map<StateId, Token*>::const_iterator iter = cur_toks_.begin();
+ iter != cur_toks_.end();
+ ++iter) {
+ // Note: Plus is taking the minimum cost, since we're in the tropical
+ // semiring.
+ best_cost = std::min(best_cost, iter->second->cost_);
+ best_cost_with_final = std::min(best_cost_with_final,
+ iter->second->cost_ +
+ fst_.Final(iter->first).Value());
+ }
+ BaseFloat extra_cost = best_cost_with_final - best_cost;
+ if (extra_cost != extra_cost) { // NaN. This shouldn't happen; it indicates some
+ // kind of error, most likely.
+ KALDI_WARN << "Found NaN (likely search failure in decoding)";
+ return infinity;
+ }
+ // Note: extra_cost will be infinity if no states were final.
+ return extra_cost;
+}
+
+// Outputs an FST corresponding to the single best path
+// through the lattice.
+bool SimpleDecoder::GetBestPath(Lattice *fst_out, bool use_final_probs) const {
+ fst_out->DeleteStates();
+ Token *best_tok = NULL;
+ bool is_final = ReachedFinal();
+ if (!is_final) {
+ for (unordered_map<StateId, Token*>::const_iterator iter = cur_toks_.begin();
+ iter != cur_toks_.end();
+ ++iter)
+ if (best_tok == NULL || *best_tok < *(iter->second) )
+ best_tok = iter->second;
+ } else {
+ double infinity =std::numeric_limits<double>::infinity(),
+ best_cost = infinity;
+ for (unordered_map<StateId, Token*>::const_iterator iter = cur_toks_.begin();
+ iter != cur_toks_.end();
+ ++iter) {
+ double this_cost = iter->second->cost_ + fst_.Final(iter->first).Value();
+ if (this_cost != infinity && this_cost < best_cost) {
+ best_cost = this_cost;
+ best_tok = iter->second;
+ }
+ }
+ }
+ if (best_tok == NULL) return false; // No output.
+
+ std::vector<LatticeArc> arcs_reverse; // arcs in reverse order.
+ for (Token *tok = best_tok; tok != NULL; tok = tok->prev_)
+ arcs_reverse.push_back(tok->arc_);
+ KALDI_ASSERT(arcs_reverse.back().nextstate == fst_.Start());
+ arcs_reverse.pop_back(); // that was a "fake" token... gives no info.
+
+ StateId cur_state = fst_out->AddState();
+ fst_out->SetStart(cur_state);
+ for (ssize_t i = static_cast<ssize_t>(arcs_reverse.size())-1; i >= 0; i--) {
+ LatticeArc arc = arcs_reverse[i];
+ arc.nextstate = fst_out->AddState();
+ fst_out->AddArc(cur_state, arc);
+ cur_state = arc.nextstate;
+ }
+ if (is_final && use_final_probs)
+ fst_out->SetFinal(cur_state,
+ LatticeWeight(fst_.Final(best_tok->arc_.nextstate).Value(),
+ 0.0));
+ else
+ fst_out->SetFinal(cur_state, LatticeWeight::One());
+ fst::RemoveEpsLocal(fst_out);
+ return true;
+}
+
+
+void SimpleDecoder::ProcessEmitting(DecodableInterface *decodable) {
+ int32 frame = num_frames_decoded_;
+ // Processes emitting arcs for one frame. Propagates from
+ // prev_toks_ to cur_toks_.
+ double cutoff = std::numeric_limits<BaseFloat>::infinity();
+ for (unordered_map<StateId, Token*>::iterator iter = prev_toks_.begin();
+ iter != prev_toks_.end();
+ ++iter) {
+ StateId state = iter->first;
+ Token *tok = iter->second;
+ KALDI_ASSERT(state == tok->arc_.nextstate);
+ for (fst::ArcIterator<fst::Fst<StdArc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const StdArc &arc = aiter.Value();
+ if (arc.ilabel != 0) { // propagate..
+ BaseFloat acoustic_cost = -decodable->LogLikelihood(frame, arc.ilabel);
+ double total_cost = tok->cost_ + arc.weight.Value() + acoustic_cost;
+
+ if (total_cost >= cutoff) continue;
+ if (total_cost + beam_ < cutoff)
+ cutoff = total_cost + beam_;
+ Token *new_tok = new Token(arc, acoustic_cost, tok);
+ unordered_map<StateId, Token*>::iterator find_iter
+ = cur_toks_.find(arc.nextstate);
+ if (find_iter == cur_toks_.end()) {
+ cur_toks_[arc.nextstate] = new_tok;
+ } else {
+ if ( *(find_iter->second) < *new_tok ) {
+ Token::TokenDelete(find_iter->second);
+ find_iter->second = new_tok;
+ } else {
+ Token::TokenDelete(new_tok);
+ }
+ }
+ }
+ }
+ }
+ num_frames_decoded_++;
+}
+
+void SimpleDecoder::ProcessNonemitting() {
+ // Processes nonemitting arcs for one frame. Propagates within
+ // cur_toks_.
+ std::vector<StateId> queue;
+ double infinity = std::numeric_limits<double>::infinity();
+ double best_cost = infinity;
+ for (unordered_map<StateId, Token*>::iterator iter = cur_toks_.begin();
+ iter != cur_toks_.end();
+ ++iter) {
+ queue.push_back(iter->first);
+ best_cost = std::min(best_cost, iter->second->cost_);
+ }
+ double cutoff = best_cost + beam_;
+
+ while (!queue.empty()) {
+ StateId state = queue.back();
+ queue.pop_back();
+ Token *tok = cur_toks_[state];
+ KALDI_ASSERT(tok != NULL && state == tok->arc_.nextstate);
+ for (fst::ArcIterator<fst::Fst<StdArc> > aiter(fst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const StdArc &arc = aiter.Value();
+ if (arc.ilabel == 0) { // propagate nonemitting only...
+ const BaseFloat acoustic_cost = 0.0;
+ Token *new_tok = new Token(arc, acoustic_cost, tok);
+ if (new_tok->cost_ > cutoff) {
+ Token::TokenDelete(new_tok);
+ } else {
+ unordered_map<StateId, Token*>::iterator find_iter
+ = cur_toks_.find(arc.nextstate);
+ if (find_iter == cur_toks_.end()) {
+ cur_toks_[arc.nextstate] = new_tok;
+ queue.push_back(arc.nextstate);
+ } else {
+ if ( *(find_iter->second) < *new_tok ) {
+ Token::TokenDelete(find_iter->second);
+ find_iter->second = new_tok;
+ queue.push_back(arc.nextstate);
+ } else {
+ Token::TokenDelete(new_tok);
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+// static
+void SimpleDecoder::ClearToks(unordered_map<StateId, Token*> &toks) {
+ for (unordered_map<StateId, Token*>::iterator iter = toks.begin();
+ iter != toks.end(); ++iter) {
+ Token::TokenDelete(iter->second);
+ }
+ toks.clear();
+}
+
+// static
+void SimpleDecoder::PruneToks(BaseFloat beam, unordered_map<StateId, Token*> *toks) {
+ if (toks->empty()) {
+ KALDI_VLOG(2) << "No tokens to prune.\n";
+ return;
+ }
+ double best_cost = std::numeric_limits<double>::infinity();
+ for (unordered_map<StateId, Token*>::iterator iter = toks->begin();
+ iter != toks->end(); ++iter)
+ best_cost = std::min(best_cost, iter->second->cost_);
+ std::vector<StateId> retained;
+ double cutoff = best_cost + beam;
+ for (unordered_map<StateId, Token*>::iterator iter = toks->begin();
+ iter != toks->end(); ++iter) {
+ if (iter->second->cost_ < cutoff)
+ retained.push_back(iter->first);
+ else
+ Token::TokenDelete(iter->second);
+ }
+ unordered_map<StateId, Token*> tmp;
+ for (size_t i = 0; i < retained.size(); i++) {
+ tmp[retained[i]] = (*toks)[retained[i]];
+ }
+ KALDI_VLOG(2) << "Pruned to " << (retained.size()) << " toks.\n";
+ tmp.swap(*toks);
+}
+
+} // end namespace kaldi.
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/simple-decoder.h b/runtime/onnxruntime/third_party/kaldi/decoder/simple-decoder.h
new file mode 100644
index 000000000..cd3a690bf
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/simple-decoder.h
@@ -0,0 +1,156 @@
+// decoder/simple-decoder.h
+
+// Copyright 2009-2013 Microsoft Corporation; Lukas Burget;
+// Saarland University (author: Arnab Ghoshal);
+// Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_DECODER_SIMPLE_DECODER_H_
+#define KALDI_DECODER_SIMPLE_DECODER_H_
+
+
+#include "util/stl-utils.h"
+#include "fst/fstlib.h"
+#include "lat/kaldi-lattice.h"
+#include "itf/decodable-itf.h"
+
+namespace kaldi {
+
+/** Simplest possible decoder, included largely for didactic purposes and as a
+ means to debug more highly optimized decoders. See \ref decoders_simple
+ for more information.
+ */
+class SimpleDecoder {
+ public:
+ typedef fst::StdArc StdArc;
+ typedef StdArc::Weight StdWeight;
+ typedef StdArc::Label Label;
+ typedef StdArc::StateId StateId;
+
+ SimpleDecoder(const fst::Fst<fst::StdArc> &fst, BaseFloat beam): fst_(fst), beam_(beam) { }
+
+ ~SimpleDecoder();
+
+ /// Decode this utterance.
+ /// Returns true if any tokens reached the end of the file (regardless of
+ /// whether they are in a final state); query ReachedFinal() after Decode()
+ /// to see whether we reached a final state.
+ bool Decode(DecodableInterface *decodable);
+
+ bool ReachedFinal() const;
+
+ // GetBestPath gets the decoding traceback. If "use_final_probs" is true
+ // AND we reached a final state, it limits itself to final states;
+ // otherwise it gets the most likely token not taking into account final-probs.
+ // fst_out will be empty (Start() == kNoStateId) if nothing was available due to
+ // search error.
+ // If Decode() returned true, it is safe to assume GetBestPath will return true.
+ // It returns true if the output lattice was nonempty (i.e. had states in it);
+ // using the return value is deprecated.
+ bool GetBestPath(Lattice *fst_out, bool use_final_probs = true) const;
+
+ /// *** The next functions are from the "new interface". ***
+
+ /// FinalRelativeCost() serves the same function as ReachedFinal(), but gives
+ /// more information. It returns the difference between the best (final-cost plus
+ /// cost) of any token on the final frame, and the best cost of any token
+ /// on the final frame. If it is infinity it means no final-states were present
+ /// on the final frame. It will usually be nonnegative.
+ BaseFloat FinalRelativeCost() const;
+
+ /// InitDecoding initializes the decoding, and should only be used if you
+ /// intend to call AdvanceDecoding(). If you call Decode(), you don't need
+ /// to call this. You can call InitDecoding if you have already decoded an
+ /// utterance and want to start with a new utterance.
+ void InitDecoding();
+
+ /// This will decode until there are no more frames ready in the decodable
+ /// object, but if max_num_frames is >= 0 it will decode no more than
+ /// that many frames. If it returns false, then no tokens are alive,
+ /// which is a kind of error state.
+ void AdvanceDecoding(DecodableInterface *decodable,
+ int32 max_num_frames = -1);
+
+ /// Returns the number of frames already decoded.
+ int32 NumFramesDecoded() const { return num_frames_decoded_; }
+
+ private:
+
+ class Token {
+ public:
+ LatticeArc arc_; // We use LatticeArc so that we can separately
+ // store the acoustic and graph cost, in case
+ // we need to produce lattice-formatted output.
+ Token *prev_;
+ int32 ref_count_;
+ double cost_; // accumulated total cost up to this point.
+ Token(const StdArc &arc,
+ BaseFloat acoustic_cost,
+ Token *prev): prev_(prev), ref_count_(1) {
+ arc_.ilabel = arc.ilabel;
+ arc_.olabel = arc.olabel;
+ arc_.weight = LatticeWeight(arc.weight.Value(), acoustic_cost);
+ arc_.nextstate = arc.nextstate;
+ if (prev) {
+ prev->ref_count_++;
+ cost_ = prev->cost_ + (arc.weight.Value() + acoustic_cost);
+ } else {
+ cost_ = arc.weight.Value() + acoustic_cost;
+ }
+ }
+ bool operator < (const Token &other) {
+ return cost_ > other.cost_;
+ }
+
+ static void TokenDelete(Token *tok) {
+ while (--tok->ref_count_ == 0) {
+ Token *prev = tok->prev_;
+ delete tok;
+ if (prev == NULL) return;
+ else tok = prev;
+ }
+#ifdef KALDI_PARANOID
+ KALDI_ASSERT(tok->ref_count_ > 0);
+#endif
+ }
+ };
+
+ // ProcessEmitting decodes the frame num_frames_decoded_ of the
+ // decodable object, then increments num_frames_decoded_.
+ void ProcessEmitting(DecodableInterface *decodable);
+
+ void ProcessNonemitting();
+
+ unordered_map<StateId, Token*> cur_toks_;
+ unordered_map<StateId, Token*> prev_toks_;
+ const fst::Fst<fst::StdArc> &fst_;
+ BaseFloat beam_;
+ // Keep track of the number of frames decoded in the current file.
+ int32 num_frames_decoded_;
+
+ static void ClearToks(unordered_map<StateId, Token*> &toks);
+
+ static void PruneToks(BaseFloat beam, unordered_map<StateId, Token*> *toks);
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(SimpleDecoder);
+};
+
+
+} // end namespace kaldi.
+
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/training-graph-compiler.cc b/runtime/onnxruntime/third_party/kaldi/decoder/training-graph-compiler.cc
new file mode 100644
index 000000000..f610ce51c
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/training-graph-compiler.cc
@@ -0,0 +1,182 @@
+// decoder/training-graph-compiler.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2018 Johns Hopkins University (author: Daniel Povey)
+// 2021 Xiaomi Corporation (Author: Junbo Zhang)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#include "decoder/training-graph-compiler.h"
+#include "hmm/hmm-utils.h" // for GetHTransducer
+
+namespace kaldi {
+
+
+TrainingGraphCompiler::TrainingGraphCompiler(const TransitionModel &trans_model,
+ const ContextDependency &ctx_dep, // Does not maintain reference to this.
+ fst::VectorFst<fst::StdArc> *lex_fst,
+ const std::vector<int32> &disambig_syms,
+ const TrainingGraphCompilerOptions &opts):
+ trans_model_(trans_model), ctx_dep_(ctx_dep), lex_fst_(lex_fst),
+ disambig_syms_(disambig_syms), opts_(opts) {
+ using namespace fst;
+ const std::vector<int32> &phone_syms = trans_model_.GetPhones(); // needed to create context fst.
+
+ KALDI_ASSERT(!phone_syms.empty());
+ KALDI_ASSERT(IsSortedAndUniq(phone_syms));
+ SortAndUniq(&disambig_syms_);
+ for (int32 i = 0; i < disambig_syms_.size(); i++)
+ if (std::binary_search(phone_syms.begin(), phone_syms.end(),
+ disambig_syms_[i]))
+ KALDI_ERR << "Disambiguation symbol " << disambig_syms_[i]
+ << " is also a phone.";
+
+ subsequential_symbol_ = 1 + phone_syms.back();
+ if (!disambig_syms_.empty() && subsequential_symbol_ <= disambig_syms_.back())
+ subsequential_symbol_ = 1 + disambig_syms_.back();
+
+ if (lex_fst == NULL) return;
+
+ {
+ int32 N = ctx_dep.ContextWidth(),
+ P = ctx_dep.CentralPosition();
+ if (P != N-1)
+ AddSubsequentialLoop(subsequential_symbol_, lex_fst_); // This is needed for
+ // systems with right-context or we will not successfully compose
+ // with C.
+ }
+
+ { // make sure lexicon is olabel sorted.
+ fst::OLabelCompare<fst::StdArc> olabel_comp;
+ fst::ArcSort(lex_fst_, olabel_comp);
+ }
+}
+
+bool TrainingGraphCompiler::CompileGraphFromText(
+ const std::vector<int32> &transcript,
+ fst::VectorFst<fst::StdArc> *out_fst) {
+ using namespace fst;
+ VectorFst<StdArc> word_fst;
+ MakeLinearAcceptor(transcript, &word_fst);
+ return CompileGraph(word_fst, out_fst);
+}
+
+bool TrainingGraphCompiler::CompileGraphFromLG(const fst::VectorFst<fst::StdArc> &phone2word_fst,
+ fst::VectorFst<fst::StdArc> *out_fst) {
+ using namespace fst;
+
+ KALDI_ASSERT(phone2word_fst.Start() != kNoStateId);
+
+ const std::vector<int32> &phone_syms = trans_model_.GetPhones(); // needed to create context fst.
+
+ // inv_cfst will be expanded on the fly, as needed.
+ InverseContextFst inv_cfst(subsequential_symbol_,
+ phone_syms,
+ disambig_syms_,
+ ctx_dep_.ContextWidth(),
+ ctx_dep_.CentralPosition());
+
+
+ VectorFst<StdArc> ctx2word_fst;
+ ComposeDeterministicOnDemandInverse(phone2word_fst, &inv_cfst, &ctx2word_fst);
+ // now ctx2word_fst is C * LG, assuming phone2word_fst is written as LG.
+ KALDI_ASSERT(ctx2word_fst.Start() != kNoStateId);
+
+ HTransducerConfig h_cfg;
+ h_cfg.transition_scale = opts_.transition_scale;
+
+ std::vector<int32> disambig_syms_h; // disambiguation symbols on
+ // input side of H.
+ VectorFst<StdArc> *H = GetHTransducer(inv_cfst.IlabelInfo(),
+ ctx_dep_,
+ trans_model_,
+ h_cfg,
+ &disambig_syms_h);
+
+ VectorFst<StdArc> &trans2word_fst = *out_fst; // transition-id to word.
+ TableCompose(*H, ctx2word_fst, &trans2word_fst);
+
+ KALDI_ASSERT(trans2word_fst.Start() != kNoStateId);
+
+ // Epsilon-removal and determinization combined. This will fail if not determinizable.
+ DeterminizeStarInLog(&trans2word_fst);
+
+ if (!disambig_syms_h.empty()) {
+ RemoveSomeInputSymbols(disambig_syms_h, &trans2word_fst);
+ // we elect not to remove epsilons after this phase, as it is
+ // a little slow.
+ if (opts_.rm_eps)
+ RemoveEpsLocal(&trans2word_fst);
+ }
+
+
+ // Encoded minimization.
+ MinimizeEncoded(&trans2word_fst);
+
+ std::vector<int32> disambig;
+ bool check_no_self_loops = true;
+ AddSelfLoops(trans_model_,
+ disambig,
+ opts_.self_loop_scale,
+ opts_.reorder,
+ check_no_self_loops,
+ &trans2word_fst);
+
+ delete H;
+ return true;
+}
+
+bool TrainingGraphCompiler::CompileGraph(const fst::VectorFst<fst::StdArc> &word_fst,
+ fst::VectorFst<fst::StdArc> *out_fst) {
+ using namespace fst;
+ KALDI_ASSERT(lex_fst_ !=NULL);
+ KALDI_ASSERT(out_fst != NULL);
+
+ VectorFst<StdArc> phone2word_fst;
+ // TableCompose more efficient than compose.
+ TableCompose(*lex_fst_, word_fst, &phone2word_fst, &lex_cache_);
+ return CompileGraphFromLG(phone2word_fst, out_fst);
+}
+
+bool TrainingGraphCompiler::CompileGraphsFromText(
+ const std::vector<std::vector<int32> > &transcripts,
+ std::vector<fst::VectorFst<fst::StdArc>*> *out_fsts) {
+ using namespace fst;
+ std::vector<const VectorFst<StdArc>* > word_fsts(transcripts.size());
+ for (size_t i = 0; i < transcripts.size(); i++) {
+ VectorFst<StdArc> *word_fst = new VectorFst<StdArc>();
+ MakeLinearAcceptor(transcripts[i], word_fst);
+ word_fsts[i] = word_fst;
+ }
+ bool ans = CompileGraphs(word_fsts, out_fsts);
+ for (size_t i = 0; i < transcripts.size(); i++)
+ delete word_fsts[i];
+ return ans;
+}
+
+bool TrainingGraphCompiler::CompileGraphs(
+ const std::vector<const fst::VectorFst<fst::StdArc>* > &word_fsts,
+ std::vector<fst::VectorFst<fst::StdArc>* > *out_fsts) {
+ out_fsts->resize(word_fsts.size(), NULL);
+ for (size_t i = 0; i < word_fsts.size(); i++) {
+ fst::VectorFst<fst::StdArc> trans2word_fst;
+ if (!CompileGraph(*(word_fsts[i]), &trans2word_fst)) return false;
+ (*out_fsts)[i] = trans2word_fst.Copy();
+ }
+ return true;
+}
+
+
+} // end namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/decoder/training-graph-compiler.h b/runtime/onnxruntime/third_party/kaldi/decoder/training-graph-compiler.h
new file mode 100644
index 000000000..f6128d82b
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/decoder/training-graph-compiler.h
@@ -0,0 +1,117 @@
+// decoder/training-graph-compiler.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2018 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#ifndef KALDI_DECODER_TRAINING_GRAPH_COMPILER_H_
+#define KALDI_DECODER_TRAINING_GRAPH_COMPILER_H_
+
+#include "base/kaldi-common.h"
+#include "hmm/transition-model.h"
+#include "fst/fstlib.h"
+#include "fstext/fstext-lib.h"
+#include "tree/context-dep.h"
+
+
+namespace kaldi {
+
+struct TrainingGraphCompilerOptions {
+
+ BaseFloat transition_scale;
+ BaseFloat self_loop_scale;
+ bool rm_eps;
+ bool reorder; // (Dan-style graphs)
+
+ explicit TrainingGraphCompilerOptions(BaseFloat transition_scale = 1.0,
+ BaseFloat self_loop_scale = 1.0,
+ bool b = true) :
+ transition_scale(transition_scale),
+ self_loop_scale(self_loop_scale),
+ rm_eps(false),
+ reorder(b) { }
+
+ void Register(OptionsItf *opts) {
+ opts->Register("transition-scale", &transition_scale, "Scale of transition "
+ "probabilities (excluding self-loops)");
+ opts->Register("self-loop-scale", &self_loop_scale, "Scale of self-loop vs. "
+ "non-self-loop probability mass ");
+ opts->Register("reorder", &reorder, "Reorder transition ids for greater decoding efficiency.");
+ opts->Register("rm-eps", &rm_eps, "Remove [most] epsilons before minimization (only applicable "
+ "if disambig symbols present)");
+ }
+};
+
+
+class TrainingGraphCompiler {
+ public:
+ TrainingGraphCompiler(const TransitionModel &trans_model, // Maintains reference to this object.
+ const ContextDependency &ctx_dep, // And this.
+ fst::VectorFst<fst::StdArc> *lex_fst, // Takes ownership of this object.
+ // It should not contain disambiguation symbols or subsequential symbol,
+ // but it should contain optional silence.
+ const std::vector<int32> &disambig_syms, // disambig symbols in phone symbol table.
+ const TrainingGraphCompilerOptions &opts);
+
+
+ // CompileGraph compiles a single training graph its input is a
+ // weighted acceptor (G) at the word level, its output is HCLG.
+ // Note: G could actually be a transducer, it would also work.
+ // This function is not const for technical reasons involving the cache.
+ // if not for "table_compose" we could make it const.
+ bool CompileGraph(const fst::VectorFst<fst::StdArc> &word_grammar,
+ fst::VectorFst<fst::StdArc> *out_fst);
+
+ // Same as `CompileGraph`, but uses an external LG fst.
+ bool CompileGraphFromLG(const fst::VectorFst<fst::StdArc> &phone2word_fst,
+ fst::VectorFst<fst::StdArc> * out_fst);
+
+ // CompileGraphs allows you to compile a number of graphs at the same
+ // time. This consumes more memory but is faster.
+ bool CompileGraphs(
+ const std::vector<const fst::VectorFst<fst::StdArc> *> &word_fsts,
+ std::vector<fst::VectorFst<fst::StdArc> *> *out_fsts);
+
+ // This version creates an FST from the text and calls CompileGraph.
+ bool CompileGraphFromText(const std::vector<int32> &transcript,
+ fst::VectorFst<fst::StdArc> *out_fst);
+
+ // This function creates FSTs from the text and calls CompileGraphs.
+ bool CompileGraphsFromText(
+ const std::vector<std::vector<int32> > &word_grammar,
+ std::vector<fst::VectorFst<fst::StdArc> *> *out_fsts);
+
+
+ ~TrainingGraphCompiler() { delete lex_fst_; }
+ private:
+ const TransitionModel &trans_model_;
+ const ContextDependency &ctx_dep_;
+ fst::VectorFst<fst::StdArc> *lex_fst_; // lexicon FST (an input; we take
+ // ownership as we need to modify it).
+ std::vector<int32> disambig_syms_; // disambig symbols (if any) in the phone
+ int32 subsequential_symbol_; // search in ../fstext/context-fst.h for more info.
+ // symbol table.
+ fst::TableComposeCache<fst::Fst<fst::StdArc> > lex_cache_; // stores matcher..
+ // this is one of Dan's extensions.
+
+ TrainingGraphCompilerOptions opts_;
+};
+
+
+
+} // end namespace kaldi.
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/Makefile b/runtime/onnxruntime/third_party/kaldi/fstbin/Makefile
new file mode 100644
index 000000000..a22c014a7
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/Makefile
@@ -0,0 +1,31 @@
+
+# make "all" the target.
+all:
+
+# Disable linking math libs because not needed here. Just for compilation speed.
+# no, it's now needed for context-fst-test.
+# MATHLIB = NONE
+
+EXTRA_CXXFLAGS = -Wno-sign-compare
+
+include ../kaldi.mk
+
+BINFILES = fstdeterminizestar \
+ fstrmsymbols fstisstochastic fstminimizeencoded fstmakecontextfst \
+ fstmakecontextsyms fstaddsubsequentialloop fstaddselfloops \
+ fstrmepslocal fstcomposecontext fsttablecompose fstrand \
+ fstdeterminizelog fstphicompose fstcopy \
+ fstpushspecial fsts-to-transcripts fsts-project fsts-union \
+ fsts-concat make-grammar-fst
+
+OBJFILES =
+
+TESTFILES =
+
+# actually, this library is currently empty. Everything is a header.
+LIBFILE =
+
+ADDLIBS = ../decoder/kaldi-decoder.a ../fstext/kaldi-fstext.a \
+ ../util/kaldi-util.a ../matrix/kaldi-matrix.a ../base/kaldi-base.a
+
+include ../makefiles/default_rules.mk
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstaddselfloops.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstaddselfloops.cc
new file mode 100644
index 000000000..a84b316d4
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstaddselfloops.cc
@@ -0,0 +1,93 @@
+// fstbin/fstaddselfloops.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "fst/fstlib.h"
+#include "fstext/determinize-star.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+#include "util/parse-options.h"
+#include "util/simple-io-funcs.h"
+/* some test examples:
+ pushd ~/tmpdir
+ ( echo 3; echo 4) > in.list
+ ( echo 5; echo 6) > out.list
+ ( echo "0 0 0 0"; echo "0 0" ) | fstcompile | fstaddselfloops in.list out.list | fstprint
+ ( echo "0 1 0 1"; echo " 0 2 1 0"; echo "1 0"; echo "2 0"; ) | fstcompile | fstaddselfloops in.list out.list | fstprint
+*/
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Adds self-loops to states of an FST to propagate disambiguation symbols through it\n"
+ "They are added on each final state and each state with non-epsilon output symbols\n"
+ "on at least one arc out of the state. Useful in conjunction with predeterminize\n"
+ "\n"
+ "Usage: fstaddselfloops in-disambig-list out-disambig-list [in.fst [out.fst] ]\n"
+ "E.g: fstaddselfloops in.list out.list < in.fst > withloops.fst\n"
+ "in.list and out.list are lists of integers, one per line, of the\n"
+ "same length.\n";
+
+ ParseOptions po(usage);
+ po.Read(argc, argv);
+
+ if (po.NumArgs() < 2 || po.NumArgs() > 4) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string disambig_in_rxfilename = po.GetArg(1),
+ disambig_out_rxfilename = po.GetArg(2),
+ fst_in_filename = po.GetOptArg(3),
+ fst_out_filename = po.GetOptArg(4);
+
+ VectorFst<StdArc> *fst = ReadFstKaldi(fst_in_filename);
+
+ std::vector<int32> disambig_in;
+ if (!ReadIntegerVectorSimple(disambig_in_rxfilename, &disambig_in))
+ KALDI_ERR << "fstaddselfloops: Could not read disambiguation symbols from "
+ << kaldi::PrintableRxfilename(disambig_in_rxfilename);
+
+ std::vector<int32> disambig_out;
+ if (!ReadIntegerVectorSimple(disambig_out_rxfilename, &disambig_out))
+ KALDI_ERR << "fstaddselfloops: Could not read disambiguation symbols from "
+ << kaldi::PrintableRxfilename(disambig_out_rxfilename);
+
+ if (disambig_in.size() != disambig_out.size())
+ KALDI_ERR << "fstaddselfloops: mismatch in size of disambiguation symbols";
+
+ AddSelfLoops(fst, disambig_in, disambig_out);
+
+ WriteFstKaldi(*fst, fst_out_filename);
+
+ delete fst;
+
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+ return 0;
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstaddsubsequentialloop.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstaddsubsequentialloop.cc
new file mode 100644
index 000000000..7f8133400
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstaddsubsequentialloop.cc
@@ -0,0 +1,85 @@
+// fstbin/fstaddsubsequentialloop.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/kaldi-io.h"
+#include "util/parse-options.h"
+#include "util/text-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/context-fst.h"
+#include "fstext/kaldi-fst-io.h"
+
+
+
+/* some test examples:
+ ( echo "0 0 0 0"; echo "0 0" ) | fstcompile | fstaddsubsequentialloop 1 | fstprint
+ ( echo "0 1 0 0"; echo " 0 2 0 0"; echo "1 0"; echo "2 0"; ) | fstcompile | fstaddsubsequentialloop 1 | fstprint
+*/
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Minimizes FST after encoding [this algorithm applicable to all FSTs in tropical semiring]\n"
+ "\n"
+ "Usage: fstaddsubsequentialloop subseq_sym [in.fst [out.fst] ]\n"
+ "E.g.: fstaddsubsequentialloop 52 < LG.fst > LG_sub.fst\n";
+
+ float delta = kDelta;
+ ParseOptions po(usage);
+ po.Register("delta", &delta,
+ "Delta likelihood used for quantization of weights");
+ po.Read(argc, argv);
+
+ if (po.NumArgs() < 1 || po.NumArgs() > 3) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ int32 subseq_sym;
+ if (!ConvertStringToInteger(po.GetArg(1), &subseq_sym))
+ KALDI_ERR << "Invalid subsequential symbol "<<po.GetArg(1);
+
+ std::string fst_in_filename = po.GetOptArg(2);
+
+ std::string fst_out_filename = po.GetOptArg(3);
+
+ VectorFst<StdArc> *fst = ReadFstKaldi(fst_in_filename);
+
+ int32 h = HighestNumberedInputSymbol(*fst);
+ if (subseq_sym <= h) {
+ std::cerr << "fstaddsubsequentialloop.cc: subseq symbol does not seem right, "<<subseq_sym<<" <= "<<h<<'\n';
+ }
+
+ AddSubsequentialLoop(subseq_sym, fst);
+
+ WriteFstKaldi(*fst, fst_out_filename);
+ delete fst;
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstcomposecontext.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstcomposecontext.cc
new file mode 100644
index 000000000..8f9d270ee
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstcomposecontext.cc
@@ -0,0 +1,183 @@
+// fstbin/fstcomposecontext.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/context-fst.h"
+#include "fstext/grammar-context-fst.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+/*
+ A couple of test examples:
+
+ pushd ~/tmpdir
+ # (1) with no disambig syms.
+ ( echo "0 1 1 1"; echo "1 2 2 2"; echo "2 3 3 3"; echo "3 0" ) | fstcompile | fstcomposecontext ilabels.sym > tmp.fst
+ ( echo "<eps> 0"; echo "a 1"; echo "b 2"; echo "c 3" ) > phones.txt
+ fstmakecontextsyms phones.txt ilabels.sym > context.txt
+ fstprint --isymbols=context.txt --osymbols=phones.txt tmp.fst
+ # and the result is:
+
+WARNING (fstcomposecontext[5.4]:main():fstcomposecontext.cc:130) Disambiguation symbols list is empty; this likely indicates an error in data preparation.
+0 1 <eps> a
+1 2 <eps>/a/b b
+2 3 a/b/c c
+3 4 b/c/<eps> <eps>
+4
+
+
+ # (2) with disambig syms:
+ ( echo 4; echo 5) > disambig.list
+ ( echo "<eps> 0"; echo "a 1"; echo "b 2"; echo "c 3"; echo "#0 4"; echo "#1 5") > phones.txt
+ ( echo "0 1 1 1"; echo "1 2 2 2"; echo " 2 3 4 4"; echo "3 4 3 3"; echo "4 5 5 5"; echo "5 0" ) | fstcompile > in.fst
+ fstcomposecontext --read-disambig-syms=disambig.list ilabels.sym in.fst tmp.fst
+ fstmakecontextsyms phones.txt ilabels.sym > context.txt
+ cp phones.txt phones_disambig.txt; ( echo "#0 4"; echo "#1 5" ) >> phones_disambig.txt
+ fstprint --isymbols=context.txt --osymbols=phones_disambig.txt tmp.fst
+
+0 1 #-1 a
+1 2 <eps>/a/b b
+2 3 #0 #0
+3 4 a/b/c c
+4 5 #1 #1
+5 6 b/c/<eps> <eps>
+
+*/
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+ /*
+ # fstcomposecontext composes efficiently with a context fst
+ # that it generates. Without --disambig-syms specified, it
+ # assumes that all input symbols of in.fst are phones.
+ # It adds the subsequential symbol itself (it does not
+ # appear in the output so doesn't need to be specified by the user).
+ # the disambig.list is a list of disambiguation symbols on the LHS
+ # of in.fst. The symbols on the LHS of out.fst are indexes into
+ # the ilabels.list file, which is a kaldi-format file containing a
+ # vector<vector<int32> >, which specifies what the labels mean in
+ # terms of windows of symbols.
+ fstcomposecontext ilabels.sym [ in.fst [ out.fst ] ]
+ --disambig-syms=disambig.list
+ --context-size=3
+ --central-position=1
+ --binary=false
+ */
+
+ const char *usage =
+ "Composes on the left with a dynamically created context FST\n"
+ "\n"
+ "Usage: fstcomposecontext <ilabels-output-file> [<in.fst> [<out.fst>] ]\n"
+ "E.g: fstcomposecontext ilabels.sym < LG.fst > CLG.fst\n";
+
+
+ ParseOptions po(usage);
+ bool binary = true;
+ std::string disambig_rxfilename,
+ disambig_wxfilename;
+ int32 context_width = 3, central_position = 1;
+ int32 nonterm_phones_offset = -1;
+ po.Register("binary", &binary,
+ "If true, output ilabels-output-file in binary format");
+ po.Register("read-disambig-syms", &disambig_rxfilename,
+ "List of disambiguation symbols on input of in.fst");
+ po.Register("write-disambig-syms", &disambig_wxfilename,
+ "List of disambiguation symbols on input of out.fst");
+ po.Register("context-size", &context_width, "Size of phone context window");
+ po.Register("central-position", &central_position,
+ "Designated central position in context window");
+ po.Register("nonterm-phones-offset", &nonterm_phones_offset,
+ "The integer id of #nonterm_bos in your phones.txt, if present "
+ "(only relevant for grammar-FST construction, see "
+ "doc/grammar.dox");
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() < 1 || po.NumArgs() > 3) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string ilabels_out_filename = po.GetArg(1),
+ fst_in_filename = po.GetOptArg(2),
+ fst_out_filename = po.GetOptArg(3);
+
+ VectorFst<StdArc> *fst = ReadFstKaldi(fst_in_filename);
+
+ if ( (disambig_wxfilename != "") && (disambig_rxfilename == "") )
+ KALDI_ERR << "fstcomposecontext: cannot specify --write-disambig-syms if "
+ "not specifying --read-disambig-syms\n";
+
+ std::vector<int32> disambig_in;
+ if (disambig_rxfilename != "")
+ if (!ReadIntegerVectorSimple(disambig_rxfilename, &disambig_in))
+ KALDI_ERR << "fstcomposecontext: Could not read disambiguation symbols from "
+ << PrintableRxfilename(disambig_rxfilename);
+
+ if (disambig_in.empty()) {
+ KALDI_WARN << "Disambiguation symbols list is empty; this likely "
+ << "indicates an error in data preparation.";
+ }
+
+ std::vector<std::vector<int32> > ilabels;
+ VectorFst<StdArc> composed_fst;
+
+ // Work gets done here (see context-fst.h)
+ if (nonterm_phones_offset < 0) {
+ // The normal case.
+ ComposeContext(disambig_in, context_width, central_position,
+ fst, &composed_fst, &ilabels);
+ } else {
+ // The grammar-FST case. See ../doc/grammar.dox for an intro.
+ if (context_width != 2 || central_position != 1) {
+ KALDI_ERR << "Grammar-fst graph creation only supports models with left-"
+ "biphone context. (--nonterm-phones-offset option was supplied).";
+ }
+ ComposeContextLeftBiphone(nonterm_phones_offset, disambig_in,
+ *fst, &composed_fst, &ilabels);
+ }
+ WriteILabelInfo(Output(ilabels_out_filename, binary).Stream(),
+ binary, ilabels);
+
+ if (disambig_wxfilename != "") {
+ std::vector<int32> disambig_out;
+ for (size_t i = 0; i < ilabels.size(); i++)
+ if (ilabels[i].size() == 1 && ilabels[i][0] <= 0)
+ disambig_out.push_back(static_cast<int32>(i));
+ if (!WriteIntegerVectorSimple(disambig_wxfilename, disambig_out)) {
+ std::cerr << "fstcomposecontext: Could not write disambiguation symbols to "
+ << PrintableWxfilename(disambig_wxfilename) << '\n';
+ return 1;
+ }
+ }
+
+ WriteFstKaldi(composed_fst, fst_out_filename);
+ delete fst;
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstcopy.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstcopy.cc
new file mode 100644
index 000000000..a22b148d6
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstcopy.cc
@@ -0,0 +1,78 @@
+// fstbin/fstcopy.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/table-matcher.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+/*
+Test:
+the command below should print out something similar to the given
+input. and if you remove ,t from the output side it should print something
+binary.
+cat <<EOF | fstcopy ark,t:- ark,t:-
+foo
+0 1 9 9
+1 0.0
+
+EOF
+
+*/
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Copy tables/archives of FSTs, indexed by a string (e.g. utterance-id)\n"
+ "\n"
+ "Usage: fstcopy <fst-rspecifier> <fst-wspecifier>\n";
+
+ ParseOptions po(usage);
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() != 2) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fst_rspecifier = po.GetArg(1),
+ fst_wspecifier = po.GetArg(2);
+
+ SequentialTableReader<VectorFstHolder> fst_reader(fst_rspecifier);
+ TableWriter<VectorFstHolder> fst_writer(fst_wspecifier);
+ int32 n_done = 0;
+
+ for (; !fst_reader.Done(); fst_reader.Next(), n_done++)
+ fst_writer.Write(fst_reader.Key(), fst_reader.Value());
+
+ KALDI_LOG << "Copied " << n_done << " FSTs.";
+ return (n_done != 0 ? 0 : 1);
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstdeterminizelog.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstdeterminizelog.cc
new file mode 100644
index 000000000..f44624180
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstdeterminizelog.cc
@@ -0,0 +1,65 @@
+// fstbin/fstdeterminizelog.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/kaldi-io.h"
+#include "util/parse-options.h"
+#include "util/text-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Determinizes in the log semiring\n"
+ "\n"
+ "Usage: fstdeterminizelog [in.fst [out.fst] ]\n"
+ "\n"
+ "See also fstdeterminizestar\n";
+
+ ParseOptions po(usage);
+ po.Read(argc, argv);
+
+ if (po.NumArgs() > 2) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fst_in_filename = po.GetOptArg(1),
+ fst_out_filename = po.GetOptArg(2);
+
+ VectorFst<StdArc> *fst = ReadFstKaldi(fst_in_filename);
+
+ DeterminizeInLog(fst);
+
+ WriteFstKaldi(*fst, fst_out_filename);
+ delete fst;
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstdeterminizestar.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstdeterminizestar.cc
new file mode 100644
index 000000000..82cc7f6cf
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstdeterminizestar.cc
@@ -0,0 +1,119 @@
+// fstbin/fstdeterminizestar.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "fst/fstlib.h"
+#include "fstext/determinize-star.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+#include "util/parse-options.h"
+
+#if !defined(_MSC_VER) && !defined(__APPLE__)
+#include <signal.h> // Comment this line and the call to signal below if
+// it causes compilation problems. It is only to enable a debugging procedure
+// when determinization does not terminate. We are disabling this code if
+// compiling on Windows because signal.h is not available there, and on
+// MacOS due to a problem with <signal.h> in the initial release of Sierra.
+#endif
+
+/* some test examples:
+ ( echo "0 0 0 0"; echo "0 0" ) | fstcompile | fstdeterminizestar | fstprint
+ ( echo "0 0 1 0"; echo "0 0" ) | fstcompile | fstdeterminizestar | fstprint
+ ( echo "0 0 1 0"; echo "0 1 1 0"; echo "0 0" ) | fstcompile | fstdeterminizestar | fstprint
+ # this last one fails [correctly]:
+ ( echo "0 0 0 1"; echo "0 0" ) | fstcompile | fstdeterminizestar | fstprint
+
+ cd ~/tmpdir
+ while true; do
+ fstrand > 1.fst
+ fstpredeterminize out.lst 1.fst | fstdeterminizestar | fstrmsymbols out.lst > 2.fst
+ fstequivalent --random=true 1.fst 2.fst || echo "Test failed"
+ echo -n "."
+ done
+
+ Test of debugging [with non-determinizable input]:
+ ( echo " 0 0 1 0 1.0"; echo "0 1 1 0"; echo "1 1 1 0 0"; echo "0 2 2 0"; echo "2"; echo "1" ) | fstcompile | fstdeterminizestar
+ kill -SIGUSR1 [the process-id of fstdeterminizestar]
+ # prints out a bunch of debugging output showing the mess it got itself into.
+*/
+
+
+bool debug_location = false;
+void signal_handler(int) {
+ debug_location = true;
+}
+
+
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Removes epsilons and determinizes in one step\n"
+ "\n"
+ "Usage: fstdeterminizestar [in.fst [out.fst] ]\n"
+ "\n"
+ "See also: fstdeterminizelog, lattice-determinize\n";
+
+ float delta = kDelta;
+ int max_states = -1;
+ bool use_log = false;
+ ParseOptions po(usage);
+ po.Register("use-log", &use_log, "Determinize in log semiring.");
+ po.Register("delta", &delta, "Delta value used to determine equivalence of weights.");
+ po.Register("max-states", &max_states, "Maximum number of states in determinized FST before it will abort.");
+ po.Read(argc, argv);
+
+ if (po.NumArgs() > 2) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fst_in_str = po.GetOptArg(1),
+ fst_out_str = po.GetOptArg(2);
+
+ // This enables us to get traceback info from determinization that is
+ // not seeming to terminate.
+#if !defined(_MSC_VER) && !defined(__APPLE__)
+ signal(SIGUSR1, signal_handler);
+#endif
+ // Normal case: just files.
+ VectorFst<StdArc> *fst = ReadFstKaldi(fst_in_str);
+
+ ArcSort(fst, ILabelCompare<StdArc>()); // improves speed.
+ if (use_log) {
+ DeterminizeStarInLog(fst, delta, &debug_location, max_states);
+ } else {
+ VectorFst<StdArc> det_fst;
+ DeterminizeStar(*fst, &det_fst, delta, &debug_location, max_states);
+ *fst = det_fst; // will do shallow copy and then det_fst goes
+ // out of scope anyway.
+ }
+ WriteFstKaldi(*fst, fst_out_str);
+ delete fst;
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstisstochastic.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstisstochastic.cc
new file mode 100644
index 000000000..3e0f1651b
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstisstochastic.cc
@@ -0,0 +1,85 @@
+// fstbin/fstisstochastic.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/kaldi-io.h"
+#include "util/parse-options.h"
+#include "fst/fstlib.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+// e.g. of test:
+// echo " 0 0" | fstcompile | fstisstochastic
+// should return 0 and print "0 0" [meaning, min and
+// max weight are one = exp(0)]
+// echo " 0 1" | fstcompile | fstisstochastic
+// should return 1, not stochastic, and print 1 1
+// (echo "0 0 0 0 0.693147 "; echo "0 1 0 0 0.693147 "; echo "1 0" ) | fstcompile | fstisstochastic
+// should return 0, stochastic; it prints "0 -1.78e-07" for me
+// (echo "0 0 0 0 0.693147 "; echo "0 1 0 0 0.693147 "; echo "1 0" ) | fstcompile | fstisstochastic --test-in-log=false
+// should return 1, not stochastic in tropical; it prints "0 0.693147" for me
+// (echo "0 0 0 0 0 "; echo "0 1 0 0 0 "; echo "1 0" ) | fstcompile | fstisstochastic --test-in-log=false
+// should return 0, stochastic in tropical; it prints "0 0" for me
+// (echo "0 0 0 0 0.693147 "; echo "0 1 0 0 0.693147 "; echo "1 0" ) | fstcompile | fstisstochastic --test-in-log=false --delta=1
+// returns 0 even though not stochastic because we gave it an absurdly large delta.
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Checks whether an FST is stochastic and exits with success if so.\n"
+ "Prints out maximum error (in log units).\n"
+ "\n"
+ "Usage: fstisstochastic [ in.fst ]\n";
+
+ float delta = 0.01;
+ bool test_in_log = true;
+
+ ParseOptions po(usage);
+ po.Register("delta", &delta, "Maximum error to accept.");
+ po.Register("test-in-log", &test_in_log, "Test stochasticity in log semiring.");
+ po.Read(argc, argv);
+
+ if (po.NumArgs() > 1) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fst_in_filename = po.GetOptArg(1);
+
+ Fst<StdArc> *fst = ReadFstKaldiGeneric(fst_in_filename);
+
+ bool ans;
+ StdArc::Weight min, max;
+ if (test_in_log) ans = IsStochasticFstInLog(*fst, delta, &min, &max);
+ else ans = IsStochasticFst(*fst, delta, &min, &max);
+
+ std::cout << min.Value() << " " << max.Value() << '\n';
+ delete fst;
+ if (ans) return 0; // success;
+ else return 1;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstmakecontextfst.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstmakecontextfst.cc
new file mode 100644
index 000000000..818bf00f5
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstmakecontextfst.cc
@@ -0,0 +1,143 @@
+// fstbin/fstmakecontextfst.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/kaldi-io.h"
+#include "util/common-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/context-fst.h"
+#include "fstext/kaldi-fst-io.h"
+
+
+/* for example of testing setup, see fstmakecontextsymbols.cc */
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Constructs a context FST with a specified context-width and context-position.\n"
+ "Outputs the context FST, and a file in Kaldi format that describes what the\n"
+ "input labels mean. Note: this is very inefficient if there are a lot of phones,\n"
+ "better to use fstcomposecontext instead\n"
+ "\n"
+ "Usage: fstmakecontextfst <phones-symbol-table> <subsequential-symbol> <ilabels-output-file> [<out-fst>]\n"
+ "E.g.: fstmakecontextfst phones.txt 42 ilabels.sym > C.fst\n";
+
+ bool binary = true; // binary output to ilabels_output_file.
+ std::string disambig_rxfilename, disambig_wxfilename;
+ int32 context_width = 3, central_position = 1;
+
+ ParseOptions po(usage);
+ po.Register("read-disambig-syms", &disambig_rxfilename,
+ "List of disambiguation symbols to read");
+ po.Register("write-disambig-syms", &disambig_wxfilename,
+ "List of disambiguation symbols to write");
+ po.Register("context-size", &context_width, "Size of phonetic context window");
+ po.Register("central-position", &central_position,
+ "Designated central position in context window");
+ po.Register("binary", &binary,
+ "Write ilabels output file in binary Kaldi format");
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() < 3 || po.NumArgs() > 4) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string phones_symtab_filename = po.GetArg(1);
+ int32 subseq_sym;
+ if (!ConvertStringToInteger(po.GetArg(2), &subseq_sym))
+ KALDI_ERR << "Invalid subsequential symbol " << po.GetArg(2);
+ std::string ilabels_out_filename = po.GetArg(3);
+ std::string fst_out_filename = po.GetOptArg(4);
+
+
+ std::vector<kaldi::int32> phone_syms;
+ {
+ fst::SymbolTable *phones_symtab = NULL;
+ { // read phone symbol table.
+ std::ifstream is(phones_symtab_filename.c_str());
+ phones_symtab = fst::SymbolTable::ReadText(is, phones_symtab_filename);
+ if (!phones_symtab) KALDI_ERR << "Could not read phones symbol-table file "<<phones_symtab_filename;
+ }
+ GetSymbols(*phones_symtab,
+ false, // don't include eps,
+ &phone_syms);
+ delete phones_symtab;
+ }
+
+ if ( (disambig_wxfilename != "") && (disambig_rxfilename == "") )
+ KALDI_ERR << "fstmakecontextfst: cannot specify --write-disambig-syms if "
+ "not specifying --read-disambig-syms\n";
+
+ std::vector<int32> disambig_in;
+ if (disambig_rxfilename != "") {
+ if (!ReadIntegerVectorSimple(disambig_rxfilename, &disambig_in))
+ KALDI_ERR << "fstcomposecontext: Could not read disambiguation symbols from "
+ << PrintableRxfilename(disambig_rxfilename);
+ }
+
+ if (std::binary_search(phone_syms.begin(), phone_syms.end(), subseq_sym)
+ || std::binary_search(disambig_in.begin(), disambig_in.end(), subseq_sym))
+ KALDI_ERR << "Invalid subsequential symbol " << subseq_sym
+ << ", already a phone or disambiguation symbol.";
+
+ // 'loop_fst' will be an acceptor FST with single (initial and final) state, with
+ // a loop for each phone and disambiguation symbol.
+ StdVectorFst loop_fst;
+ loop_fst.AddState(); // Add state zero.
+ loop_fst.SetStart(0);
+ loop_fst.SetFinal(0, TropicalWeight::One());
+ for (size_t i = 0; i < phone_syms.size(); i++) {
+ int32 sym = phone_syms[i];
+ loop_fst.AddArc(0, StdArc(sym, sym, TropicalWeight::One(), 0));
+ }
+
+ std::vector<std::vector<int32> > ilabels;
+ VectorFst<StdArc> context_fst;
+
+ ComposeContext(disambig_in, context_width, central_position,
+ &loop_fst, &context_fst, &ilabels, true);
+
+ WriteFstKaldi(context_fst, fst_out_filename);
+
+ WriteILabelInfo(Output(ilabels_out_filename, binary).Stream(),
+ binary, ilabels);
+
+ if (disambig_wxfilename != "") {
+ std::vector<int32> disambig_out;
+ for (size_t i = 0; i < ilabels.size(); i++)
+ if (ilabels[i].size() == 1 && ilabels[i][0] <= 0)
+ disambig_out.push_back(static_cast<int32>(i));
+ if (!WriteIntegerVectorSimple(disambig_wxfilename, disambig_out))
+ KALDI_ERR << "fstcomposecontext: Could not write disambiguation symbols to "
+ << PrintableWxfilename(disambig_wxfilename);
+ }
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstmakecontextsyms.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstmakecontextsyms.cc
new file mode 100644
index 000000000..c9d493975
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstmakecontextsyms.cc
@@ -0,0 +1,122 @@
+// fstbin/fstmakecontextsyms.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "tree/context-dep.h"
+#include "util/common-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/context-fst.h"
+
+
+/*
+ Test for this and makecontextfst:
+ mkdir -p ~/tmpdir
+ pushd ~/tmpdir
+ (echo "<eps> 0"; echo "a 1"; echo "b 2"; echo "#0 3"; echo "#1 4"; echo "#$ 5" ) > phones.txt
+ ( echo 3; echo 4 ) > disambig.list
+ fstmakecontextfst --read-disambig-syms=disambig.list <(grep -v '#' phones.txt) 5 ilabels.int > C.fst
+ fstmakecontextsyms phones.txt ilabels.int > context_syms.txt
+ fstprint --isymbols=context_syms.txt --osymbols=phones.txt C.fst > C.txt
+
+ fstrandgen C.fst | fstprint --isymbols=context_syms.txt --osymbols=phones.txt
+
+ Example output:
+
+ fstrandgen C.fst | fstprint --isymbols=context_syms.txt --osymbols=phones.txt
+0 1 #-1 b
+1 2 <eps>/b/<eps> #$
+2 3 #1 #1
+3 4 #0 #0
+4 5 #0 #0
+5 6 #0 #0
+6 7 #0 #0
+7 8 #0 #0
+8 9 #1 #1
+9
+*/
+
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ typedef fst::StdArc::Label Label;
+ const char *usage = "Create input symbols for CLG\n"
+ "Usage: fstmakecontextsyms phones-symtab ilabels_input_file [output-symtab.txt]\n"
+ "E.g.: fstmakecontextsyms phones.txt ilabels.sym > context_symbols.txt\n";
+
+ ParseOptions po(usage);
+
+ std::string disambig_list_file = "",
+ phone_separator = "/",
+ initial_disambig = "#-1";
+
+ po.Register("phone-separator", &phone_separator,
+ "Separator for phones in phone-in-context symbols.");
+ po.Register("initial-disambig", &initial_disambig,
+ "Name for special disambiguation symbol that occurs at start "
+ "of context-dependent phone sequences");
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() < 2 || po.NumArgs() > 3) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string phones_symtab_filename = po.GetArg(1),
+ ilabel_info_filename = po.GetArg(2),
+ clg_symtab_filename = po.GetOptArg(3);
+
+ std::vector<std::vector<kaldi::int32> > ilabel_info;
+ {
+ bool binary;
+ Input ki(ilabel_info_filename, &binary);
+ ReadILabelInfo(ki.Stream(),
+ binary, &ilabel_info);
+ }
+
+ fst::SymbolTable *phones_symtab = NULL;
+ { // read phone symbol table.
+ std::ifstream is(phones_symtab_filename.c_str());
+ phones_symtab = fst::SymbolTable::ReadText(is, phones_symtab_filename);
+ if (!phones_symtab) KALDI_ERR << "Could not read phones symbol-table file "<<phones_symtab_filename;
+ }
+
+ fst::SymbolTable *clg_symtab =
+ CreateILabelInfoSymbolTable(ilabel_info,
+ *phones_symtab,
+ phone_separator,
+ initial_disambig);
+
+ if (clg_symtab_filename == "") {
+ if (!clg_symtab->WriteText(std::cout))
+ KALDI_ERR << "Cannot write symbol table to standard output.";
+ } else {
+ if (!clg_symtab->WriteText(clg_symtab_filename))
+ KALDI_ERR << "Cannot open symbol table file "<<clg_symtab_filename<<" for writing.";
+ }
+ delete clg_symtab;
+ delete phones_symtab;
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstminimizeencoded.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstminimizeencoded.cc
new file mode 100644
index 000000000..1346c063e
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstminimizeencoded.cc
@@ -0,0 +1,73 @@
+// fstbin/fstminimizeencoded.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/kaldi-io.h"
+#include "util/parse-options.h"
+#include "util/text-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/determinize-star.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+/* some test examples:
+ ( echo "0 0 0 0"; echo "0 0" ) | fstcompile | fstminimizeencoded | fstprint
+ ( echo "0 1 0 0"; echo " 0 2 0 0"; echo "1 0"; echo "2 0"; ) | fstcompile | fstminimizeencoded | fstprint
+*/
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Minimizes FST after encoding [similar to fstminimize, but no weight-pushing]\n"
+ "\n"
+ "Usage: fstminimizeencoded [in.fst [out.fst] ]\n";
+
+ float delta = kDelta;
+ ParseOptions po(usage);
+ po.Register("delta", &delta, "Delta likelihood used for quantization of weights");
+ po.Read(argc, argv);
+
+ if (po.NumArgs() > 2) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fst_in_filename = po.GetOptArg(1),
+ fst_out_filename = po.GetOptArg(2);
+
+ VectorFst<StdArc> *fst = ReadFstKaldi(fst_in_filename);
+
+ MinimizeEncoded(fst, delta);
+
+ WriteFstKaldi(*fst, fst_out_filename);
+
+ delete fst;
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+ return 0;
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstphicompose.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstphicompose.cc
new file mode 100644
index 000000000..13ffcf39c
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstphicompose.cc
@@ -0,0 +1,183 @@
+// fstbin/fstphicompose.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/table-matcher.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+/*
+The following commands represent a basic test of this program.
+
+cat <<EOF | fstcompile > a.fst
+0 1 10 10
+0 1 11 11
+1
+EOF
+
+cat <<EOF | fstcompile > g.fst
+0 1 10 10 2.0
+0 2 100 100 6.6
+2 1 10 10 0.0
+2 1 11 11 1.0
+1
+EOF
+fstcompose a.fst g.fst | fstprint
+# gives, as expected:
+# 0 1 10 10 2
+# 1
+fstphicompose 100 a.fst g.fst | fstprint
+# gives, again correctly:
+#0 1 10 10 2
+#0 1 11 11 7.5999999
+#1
+
+Next, test that it's working as desired for final-probs,
+i.e. it takes the backoff arc when looking for a final-prob,
+only if no final-prob present at current state.
+
+cat <<EOF | fstcompile > a.fst
+0 1 10 10
+0 1 11 11
+1
+EOF
+cat <<EOF | fstcompile > g.fst
+0 1 10 10 2.0
+0 3 11 11 2.0
+1 2 100 110 6.6
+3 10.0
+3 2 100 110 0.0
+2
+EOF
+fstphicompose 100 a.fst g.fst | fstprint
+# output is:
+#0 1 10 10 2
+#0 2 11 11 2
+#1 6.5999999
+#2 10
+
+*/
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+ /*
+ fstphicompose does composition, but treats the second FST
+ specially (basically, like a backoff LM); whenever the
+ composition algorithm fails to find a match for a label
+ in the second FST, if it sees a phi transition it will
+ take it instead, and look for a match at the destination.
+ phi is the label on the input side of the backoff arc of
+ the LM (the label on the output side doesn't matter).
+
+ Also modifies the second fst so that it treats final-probs
+ "correctly", i.e. takes the failure transition when looking
+ for a final-prob. This would not work if there were
+ epsilons.
+ */
+
+ const char *usage =
+ "Composition, where the right FST has \"failure\" (phi) transitions\n"
+ "that are only taken where there was no match of a \"real\" label\n"
+ "You supply the label corresponding to phi.\n"
+ "\n"
+ "Usage: fstphicompose phi-label (fst1-rxfilename|fst1-rspecifier) "
+ "(fst2-rxfilename|fst2-rspecifier) [(out-rxfilename|out-rspecifier)]\n"
+ "E.g.: fstphicompose 54 a.fst b.fst c.fst\n"
+ "or: fstphicompose 11 ark:a.fsts G.fst ark:b.fsts\n";
+
+ ParseOptions po(usage);
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() < 3 || po.NumArgs() > 4) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string
+ phi_str = po.GetArg(1),
+ fst1_in_str = po.GetArg(2),
+ fst2_in_str = po.GetArg(3),
+ fst_out_str = po.GetOptArg(4);
+
+ bool is_table_1 =
+ (ClassifyRspecifier(fst1_in_str, NULL, NULL) != kNoRspecifier),
+ is_table_2 =
+ (ClassifyRspecifier(fst2_in_str, NULL, NULL) != kNoRspecifier),
+ is_table_out =
+ (ClassifyWspecifier(fst_out_str, NULL, NULL, NULL) != kNoWspecifier);
+
+ int32 phi_label;
+ if (!ConvertStringToInteger(phi_str, &phi_label)
+ || phi_label <= 0)
+ KALDI_ERR << "Invalid first argument (phi label), expect positive integer.";
+
+ if (is_table_out != (is_table_1 || is_table_2))
+ KALDI_ERR << "Incompatible combination of archives and files";
+
+ if (!is_table_1 && !is_table_2) { // Only dealing with files...
+ VectorFst<StdArc> *fst1 = ReadFstKaldi(fst1_in_str);
+
+ VectorFst<StdArc> *fst2 = ReadFstKaldi(fst2_in_str);
+
+ PropagateFinal(phi_label, fst2); // makes it work correctly
+ // w.r.t. final-probs.
+
+ VectorFst<StdArc> composed_fst;
+
+ PhiCompose(*fst1, *fst2, phi_label, &composed_fst);
+
+ delete fst1;
+ delete fst2;
+
+ WriteFstKaldi(composed_fst, fst_out_str);
+ return 0;
+ } else if (is_table_1 && !is_table_2) {
+
+ VectorFst<StdArc> *fst2 = ReadFstKaldi(fst2_in_str);
+ PropagateFinal(phi_label, fst2); // makes it work correctly
+ // w.r.t. final-probs.
+ SequentialTableReader<VectorFstHolder> fst1_reader(fst1_in_str);
+ TableWriter<VectorFstHolder> fst_writer(fst_out_str);
+ int32 n_done = 0;
+ for (; !fst1_reader.Done(); fst1_reader.Next(), n_done++) {
+ VectorFst<StdArc> fst1(fst1_reader.Value());
+ VectorFst<StdArc> fst_out;
+ PhiCompose(fst1, *fst2, phi_label, &fst_out);
+ fst_writer.Write(fst1_reader.Key(), fst_out);
+ }
+ KALDI_LOG << "Composed " << n_done << " FSTs.";
+ return (n_done != 0 ? 0 : 1);
+ } else {
+ KALDI_ERR << "The combination of tables/non-tables that you "
+ << "supplied is not currently supported. Either implement this, "
+ << "ask the maintainers to implement it, or call this program "
+ << "differently.";
+ }
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstpushspecial.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstpushspecial.cc
new file mode 100644
index 000000000..b7428f2b9
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstpushspecial.cc
@@ -0,0 +1,72 @@
+// fstbin/fstpushspecial.cc
+
+// Copyright 2012 Daniel Povey
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/kaldi-io.h"
+#include "util/parse-options.h"
+#include "util/text-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/push-special.h"
+#include "fstext/kaldi-fst-io.h"
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Pushes weights in an FST such that all the states\n"
+ "in the FST have arcs and final-probs with weights that\n"
+ "sum to the same amount (viewed as being in the log semiring).\n"
+ "Thus, the \"extra weight\" is distributed throughout the FST.\n"
+ "Tolerance parameter --delta controls how exact this is, and the\n"
+ "speed.\n"
+ "\n"
+ "Usage: fstpushspecial [options] [in.fst [out.fst] ]\n";
+
+ BaseFloat delta = kDelta;
+ ParseOptions po(usage);
+ po.Register("delta", &delta, "Delta cost: after pushing, all states will "
+ "have a total weight that differs from the average by no more "
+ "than this.");
+ po.Read(argc, argv);
+
+ if (po.NumArgs() > 2) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fst_in_filename = po.GetOptArg(1),
+ fst_out_filename = po.GetOptArg(2);
+
+ VectorFst<StdArc> *fst = ReadFstKaldi(fst_in_filename);
+
+ PushSpecial(fst, delta);
+
+ WriteFstKaldi(*fst, fst_out_filename);
+ delete fst;
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstrand.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstrand.cc
new file mode 100644
index 000000000..f0bc39380
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstrand.cc
@@ -0,0 +1,67 @@
+// fstbin/fstrand.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/kaldi-io.h"
+#include "util/parse-options.h"
+#include "util/text-utils.h"
+#include "fstext/rand-fst.h"
+#include "time.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Generate random FST\n"
+ "\n"
+ "Usage: fstrand [out.fst]\n";
+
+ srand(time(NULL));
+ RandFstOptions opts;
+
+
+ kaldi::ParseOptions po(usage);
+ po.Register("allow-empty", &opts.allow_empty,
+ "If true, we may generate an empty FST.");
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() > 1) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fst_out_filename = po.GetOptArg(1);
+
+ VectorFst <StdArc> *rand_fst = RandFst<StdArc>(opts);
+
+ WriteFstKaldi(*rand_fst, fst_out_filename);
+ delete rand_fst;
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstrmepslocal.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstrmepslocal.cc
new file mode 100644
index 000000000..3aedd6dd7
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstrmepslocal.cc
@@ -0,0 +1,101 @@
+// fstbin/fstrmepslocal.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/kaldi-io.h"
+#include "util/parse-options.h"
+#include "util/text-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/determinize-star.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+
+/*
+ A test example:
+ ( echo "0 1 1 0"; echo "1 2 0 2"; echo "2 0"; ) | fstcompile | fstrmepslocal | fstprint
+# prints:
+# 0 1 1 2
+# 1
+ ( echo "0 1 0 0"; echo "0 0"; echo "1 0" ) | fstcompile | fstrmepslocal | fstprint
+# 0
+ ( echo "0 1 0 0"; echo "0 0"; echo "1 0" ) | fstcompile | fstrmepslocal | fstprint
+ ( echo "0 1 0 0"; echo "0 0"; echo "1 0" ) | fstcompile | fstrmepslocal --use-log=true | fstprint
+# 0 -0.693147182
+
+*/
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Removes some (but not all) epsilons in an algorithm that will always reduce the number of\n"
+ "arcs+states. Option to preserves equivalence in tropical or log semiring, and\n"
+ "if in tropical, stochasticit in either log or tropical.\n"
+ "\n"
+ "Usage: fstrmepslocal [in.fst [out.fst] ]\n";
+
+ ParseOptions po(usage);
+ bool use_log = false;
+ bool stochastic_in_log = true;
+ po.Register("use-log", &use_log,
+ "Preserve equivalence in log semiring [false->tropical]\n");
+ po.Register("stochastic-in-log", &stochastic_in_log,
+ "Preserve stochasticity in log semiring [false->tropical]\n");
+ po.Read(argc, argv);
+
+ if (po.NumArgs() > 2) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fst_in_filename = po.GetOptArg(1),
+ fst_out_filename = po.GetOptArg(2);
+
+ VectorFst<StdArc> *fst = ReadFstKaldi(fst_in_filename);
+
+ if (!use_log && stochastic_in_log) {
+ RemoveEpsLocalSpecial(fst);
+ } else if (use_log && !stochastic_in_log) {
+ std::cerr << "fstrmsymbols: invalid combination of flags\n";
+ return 1;
+ } else if (use_log) {
+ VectorFst<LogArc> log_fst;
+ Cast(*fst, &log_fst);
+ delete fst;
+ RemoveEpsLocal(&log_fst);
+ fst = new VectorFst<StdArc>;
+ Cast(log_fst, fst);
+ } else {
+ RemoveEpsLocal(fst);
+ }
+
+ WriteFstKaldi(*fst, fst_out_filename);
+ delete fst;
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fstrmsymbols.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fstrmsymbols.cc
new file mode 100644
index 000000000..a365b016e
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fstrmsymbols.cc
@@ -0,0 +1,193 @@
+// fstbin/fstrmsymbols.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/determinize-star.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+namespace fst {
+// we can move these functions elsewhere later, if they are needed in other
+// places.
+
+template<class Arc, class I>
+void RemoveArcsWithSomeInputSymbols(const std::vector<I> &symbols_in,
+ VectorFst<Arc> *fst) {
+ typedef typename Arc::StateId StateId;
+
+ kaldi::ConstIntegerSet<I> symbol_set(symbols_in);
+
+ StateId num_states = fst->NumStates();
+ StateId dead_state = fst->AddState();
+ for (StateId s = 0; s < num_states; s++) {
+ for (MutableArcIterator<VectorFst<Arc> > iter(fst, s);
+ !iter.Done(); iter.Next()) {
+ if (symbol_set.count(iter.Value().ilabel) != 0) {
+ Arc arc = iter.Value();
+ arc.nextstate = dead_state;
+ iter.SetValue(arc);
+ }
+ }
+ }
+ // Connect() will actually remove the arcs, and the dead state.
+ Connect(fst);
+ if (fst->NumStates() == 0)
+ KALDI_WARN << "After Connect(), fst was empty.";
+}
+
+template<class Arc, class I>
+void PenalizeArcsWithSomeInputSymbols(const std::vector<I> &symbols_in,
+ float penalty,
+ VectorFst<Arc> *fst) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Label Label;
+ typedef typename Arc::Weight Weight;
+
+ Weight penalty_weight(penalty);
+
+ kaldi::ConstIntegerSet<I> symbol_set(symbols_in);
+
+ StateId num_states = fst->NumStates();
+ for (StateId s = 0; s < num_states; s++) {
+ for (MutableArcIterator<VectorFst<Arc> > iter(fst, s);
+ !iter.Done(); iter.Next()) {
+ if (symbol_set.count(iter.Value().ilabel) != 0) {
+ Arc arc = iter.Value();
+ arc.weight = Times(arc.weight, penalty_weight);
+ iter.SetValue(arc);
+ }
+ }
+ }
+}
+
+}
+
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ bool apply_to_output = false;
+ bool remove_arcs = false;
+ float penalty = -std::numeric_limits<BaseFloat>::infinity();
+
+ const char *usage =
+ "With no options, replaces a subset of symbols with epsilon, wherever\n"
+ "they appear on the input side of an FST."
+ "With --remove-arcs=true, will remove arcs that contain these symbols\n"
+ "on the input\n"
+ "With --penalty=<float>, will add the specified penalty to the\n"
+ "cost of any arc that has one of the given symbols on its input side\n"
+ "In all cases, the option --apply-to-output=true (or for\n"
+ "back-compatibility, --remove-from-output=true) makes this apply\n"
+ "to the output side.\n"
+ "\n"
+ "Usage: fstrmsymbols [options] <in-disambig-list> [<in.fst> [<out.fst>]]\n"
+ "E.g: fstrmsymbols in.list < in.fst > out.fst\n"
+ "<in-disambig-list> is an rxfilename specifying a file containing list of integers\n"
+ "representing symbols, in text form, one per line.\n";
+
+ ParseOptions po(usage);
+ po.Register("remove-from-output", &apply_to_output, "If true, this applies to symbols "
+ "on the output, not the input, side. (For back compatibility; use "
+ "--apply-to-output insead)");
+ po.Register("apply-to-output", &apply_to_output, "If true, this applies to symbols "
+ "on the output, not the input, side.");
+ po.Register("remove-arcs", &remove_arcs, "If true, instead of converting the symbol "
+ "to <eps>, remove the arcs.");
+ po.Register("penalty", &penalty, "If specified, instead of converting "
+ "the symbol to <eps>, penalize the arc it is on by adding this "
+ "value to its cost.");
+
+
+ po.Read(argc, argv);
+
+ if (remove_arcs &&
+ penalty != -std::numeric_limits<BaseFloat>::infinity())
+ KALDI_ERR << "--remove-arc and --penalty options are mutually exclusive";
+
+ if (po.NumArgs() < 1 || po.NumArgs() > 3) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string disambig_rxfilename = po.GetArg(1),
+ fst_rxfilename = po.GetOptArg(2),
+ fst_wxfilename = po.GetOptArg(3);
+
+ VectorFst<StdArc> *fst = CastOrConvertToVectorFst(
+ ReadFstKaldiGeneric(fst_rxfilename));
+
+ std::vector<int32> disambig_in;
+ if (!ReadIntegerVectorSimple(disambig_rxfilename, &disambig_in))
+ KALDI_ERR << "fstrmsymbols: Could not read disambiguation symbols from "
+ << (disambig_rxfilename == "" ? "standard input" : disambig_rxfilename);
+
+ if (apply_to_output) Invert(fst);
+ if (remove_arcs) {
+ RemoveArcsWithSomeInputSymbols(disambig_in, fst);
+ } else if (penalty != -std::numeric_limits<BaseFloat>::infinity()) {
+ PenalizeArcsWithSomeInputSymbols(disambig_in, penalty, fst);
+ } else {
+ RemoveSomeInputSymbols(disambig_in, fst);
+ }
+ if (apply_to_output) Invert(fst);
+
+ WriteFstKaldi(*fst, fst_wxfilename);
+
+ delete fst;
+ return 0;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
+
+/* some test examples:
+
+ ( echo "0 0 1 1"; echo " 0 0 3 2"; echo "0 0"; ) | fstcompile | fstrmsymbols "echo 3; echo 4|" | fstprint
+ # should produce:
+ # 0 0 1 1
+ # 0 0 0 2
+ # 0
+
+ ( echo "0 0 1 1"; echo " 0 0 3 2"; echo "0 0"; ) | fstcompile | fstrmsymbols --apply-to-output=true "echo 2; echo 3|" | fstprint
+ # should produce:
+ # 0 0 1 1
+ # 0 0 3 0
+ # 0
+
+
+ ( echo "0 0 1 1"; echo " 0 0 3 2"; echo "0 0"; ) | fstcompile | fstrmsymbols --remove-arcs=true "echo 3; echo 4|" | fstprint
+ # should produce:
+ # 0 0 1 1
+ # 0
+
+ ( echo "0 0 1 1"; echo " 0 0 3 2"; echo "0 0"; ) | fstcompile | fstrmsymbols --penalty=2 "echo 3; echo 4; echo 5|" | fstprint
+# should produce:
+ # 0 0 1 1
+ # 0 0 3 2 2
+ # 0
+
+*/
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-concat.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-concat.cc
new file mode 100644
index 000000000..2a217eda7
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-concat.cc
@@ -0,0 +1,112 @@
+// fstbin/fsts-concat.cc
+
+// Copyright 2016 Johns Hopkins University (Authors: Jan "Yenda" Trmal)
+// 2018 Soapbox Labs (Author: Karel Vesely)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ typedef kaldi::int32 int32;
+ typedef kaldi::uint64 uint64;
+
+ const char *usage =
+ "Reads kaldi archives with FSTs. Concatenates the fsts from all the rspecifiers.\n"
+ "The fsts to concatenate must have same key. The sequencing is given by the position of arguments.\n"
+ "\n"
+ "Usage: fsts-concat [options] <fsts-rspecifier1> <fsts-rspecifier2> ... <fsts-wspecifier>\n"
+ " e.g.: fsts-concat scp:fsts1.scp scp:fsts2.scp ... ark:fsts_out.ark\n"
+ "\n"
+ "see also: fstconcat (from the OpenFst toolkit)\n";
+
+ ParseOptions po(usage);
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() < 3) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fsts_rspecifier = po.GetArg(1),
+ fsts_wspecifier = po.GetArg(po.NumArgs());
+
+ SequentialTableReader<VectorFstHolder> fst_reader(fsts_rspecifier);
+ std::vector<RandomAccessTableReader<VectorFstHolder>*> fst_readers;
+ TableWriter<VectorFstHolder> fst_writer(fsts_wspecifier);
+
+ for (int32 i = 2; i < po.NumArgs(); i++)
+ fst_readers.push_back(new RandomAccessTableReader<VectorFstHolder>(po.GetArg(i)));
+ const int32 num_fst_readers = fst_readers.size();
+
+ int32 n_done = 0,
+ n_skipped = 0;
+
+ for (; !fst_reader.Done(); fst_reader.Next()) {
+ std::string key = fst_reader.Key();
+
+ // Check that the key exists in all 'fst_readers'.
+ bool skip_key = false;
+ for (int32 i = 0; i < num_fst_readers; i++) {
+ if (!fst_readers[i]->HasKey(key)) {
+ KALDI_WARN << "Skipping '" << key << "'"
+ << " due to missing the fst in " << (i+2) << "th <rspecifier> : "
+ << "'" << po.GetArg(i+2) << "'";
+ skip_key = true;
+ }
+ }
+ if (skip_key) {
+ n_skipped++;
+ continue;
+ }
+
+ // Concatenate!
+ VectorFst<StdArc> fst_out = fst_readers.back()->Value(key);
+ // Loop from (last-1) to first, as 'prepending' the fsts is faster,
+ // see: http://www.openfst.org/twiki/bin/view/FST/ConcatDoc
+ for (int32 i = num_fst_readers-2; i >= 0; i--) {
+ fst::Concat(fst_readers[i]->Value(key), &fst_out);
+ }
+ // Finally, prepend the fst from the 'Sequential' reader.
+ fst::Concat(fst_reader.Value(), &fst_out);
+
+ // Write the output.
+ fst_writer.Write(key, fst_out);
+ n_done++;
+ }
+
+ // Cleanup.
+ for (int32 i = 0; i < num_fst_readers; i++)
+ delete fst_readers[i];
+ fst_readers.clear();
+
+ KALDI_LOG << "Produced " << n_done << " FSTs by concatenating " << po.NumArgs()-1
+ << " streams " << "(" << n_skipped << " keys skipped).";
+ return (n_done != 0 ? 0 : 1);
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-project.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-project.cc
new file mode 100644
index 000000000..015f14317
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-project.cc
@@ -0,0 +1,82 @@
+// fstbin/fsts-project.cc
+
+// Copyright 2016 Johns Hopkins University (Authors: Jan "Yenda" Trmal)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ typedef kaldi::int32 int32;
+ typedef kaldi::uint64 uint64;
+
+ const char *usage =
+ "Reads kaldi archive of FSTs; for each element, performs the project\n"
+ "operation either on input (default) or on the output (if the option\n"
+ "--project-output is true).\n"
+ "\n"
+ "Usage: fsts-project [options] <fsts-rspecifier> <fsts-wspecifier>\n"
+ " e.g.: fsts-project ark:train.fsts ark,t:train.fsts\n"
+ "\n"
+ "see also: fstproject (from the OpenFst toolkit)\n";
+
+ ParseOptions po(usage);
+
+ bool project_output = false;
+
+ po.Register("project-output", &project_output,
+ "If true, project output vs input");
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() != 2) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fsts_rspecifier = po.GetArg(1),
+ fsts_wspecifier = po.GetArg(2);
+
+
+ SequentialTableReader<VectorFstHolder> fst_reader(fsts_rspecifier);
+ TableWriter<VectorFstHolder> fst_writer(fsts_wspecifier);
+
+ int32 n_done = 0;
+ for (; !fst_reader.Done(); fst_reader.Next()) {
+ std::string key = fst_reader.Key();
+ VectorFst<StdArc> fst(fst_reader.Value());
+
+ Project(&fst, project_output ? PROJECT_OUTPUT : PROJECT_INPUT);
+
+ fst_writer.Write(key, fst);
+ n_done++;
+ }
+
+ KALDI_LOG << "Projected " << n_done << " FSTs";
+ return (n_done != 0 ? 0 : 1);
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-to-transcripts.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-to-transcripts.cc
new file mode 100644
index 000000000..ae74d5de6
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-to-transcripts.cc
@@ -0,0 +1,103 @@
+// fstbin/fsts-to-transcripts.cc
+
+// Copyright 2012-2013 Johns Hopkins University (Authors: Guoguo Chen,
+// Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ typedef kaldi::int32 int32;
+ typedef kaldi::uint64 uint64;
+
+ const char *usage =
+ "Reads a table of FSTs; for each element, finds the best path and \n"
+ "prints out the output-symbol sequence (if --output-side=true), or \n"
+ "input-symbol sequence otherwise.\n"
+ "\n"
+ "Usage:\n"
+ " fsts-to-transcripts [options] <fsts-rspecifier>"
+ " <transcriptions-wspecifier>\n"
+ "e.g.:\n"
+ " fsts-to-transcripts ark:train.fsts ark,t:train.text\n";
+
+ ParseOptions po(usage);
+
+ bool output_side = true;
+
+ po.Register("output-side", &output_side, "If true, extract the symbols on "
+ "the output side of the FSTs, else the input side.");
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() != 2) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fst_rspecifier = po.GetArg(1),
+ transcript_wspecifier = po.GetArg(2);
+
+
+ SequentialTableReader<VectorFstHolder> fst_reader(fst_rspecifier);
+ Int32VectorWriter transcript_writer(transcript_wspecifier);
+
+ int32 n_done = 0, n_err = 0;
+ for (; !fst_reader.Done(); fst_reader.Next()) {
+ std::string key = fst_reader.Key();
+ const VectorFst<StdArc> &fst = fst_reader.Value();
+
+
+ VectorFst<StdArc> shortest_path;
+ ShortestPath(fst, &shortest_path); // the OpenFst algorithm ShortestPath.
+
+ if (shortest_path.NumStates() == 0) {
+ KALDI_WARN << "Input FST (after shortest path) was empty. Producing "
+ << "no output for key " << key;
+ n_err++;
+ continue;
+ }
+
+ std::vector<int32> transcript;
+ bool ans;
+ if (output_side) ans = fst::GetLinearSymbolSequence<StdArc, int32>(
+ shortest_path, NULL, &transcript, NULL);
+ else
+ ans = fst::GetLinearSymbolSequence<StdArc, int32>(
+ shortest_path, &transcript, NULL, NULL);
+ if (!ans) {
+ KALDI_ERR << "GetLinearSymbolSequence returned false (code error);";
+ }
+ transcript_writer.Write(key, transcript);
+ n_done++;
+ }
+
+ KALDI_LOG << "Converted " << n_done << " FSTs, " << n_err << " with errors";
+ return (n_done != 0 ? 0 : 1);
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-union.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-union.cc
new file mode 100644
index 000000000..ed68cea76
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fsts-union.cc
@@ -0,0 +1,100 @@
+// fstbin/fsts-union.cc
+
+// Copyright 2016 Johns Hopkins University (Authors: Jan "Yenda" Trmal)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ typedef kaldi::int32 int32;
+ typedef kaldi::uint64 uint64;
+
+ const char *usage =
+ "Reads a kaldi archive of FSTs. Performs the FST operation union on\n"
+ "all fsts sharing the same key. Assumes the archive is sorted by key.\n"
+ "\n"
+ "Usage: fsts-union [options] <fsts-rspecifier> <fsts-wspecifier>\n"
+ " e.g.: fsts-union ark:keywords_tmp.fsts ark,t:keywords.fsts\n"
+ "\n"
+ "see also: fstunion (from the OpenFst toolkit)\n";
+
+ ParseOptions po(usage);
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() != 2) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fsts_rspecifier = po.GetArg(1),
+ fsts_wspecifier = po.GetArg(2);
+
+
+ SequentialTableReader<VectorFstHolder> fst_reader(fsts_rspecifier);
+ TableWriter<VectorFstHolder> fst_writer(fsts_wspecifier);
+
+ int32 n_out_done = 0,
+ n_in_done = 0;
+ std::string res_key = "";
+ VectorFst<StdArc> res_fst;
+
+ for (; !fst_reader.Done(); fst_reader.Next()) {
+ std::string key = fst_reader.Key();
+ VectorFst<StdArc> fst(fst_reader.Value());
+
+ n_in_done++;
+ if (key == res_key) {
+ fst::Union(&res_fst, fst);
+ } else {
+ if (res_key != "") {
+ VectorFst<StdArc> out_fst;
+ fst::Determinize(res_fst, &out_fst);
+ fst::Minimize(&out_fst);
+ fst::RmEpsilon(&out_fst);
+ fst_writer.Write(res_key, out_fst);
+ n_out_done++;
+ }
+ res_fst = fst;
+ res_key = key;
+ }
+ }
+ if (res_key != "") {
+ VectorFst<StdArc> out_fst;
+ fst::Determinize(res_fst, &out_fst);
+ fst::Minimize(&out_fst);
+ fst::RmEpsilon(&out_fst);
+ fst_writer.Write(res_key, out_fst);
+ n_out_done++;
+ }
+
+ KALDI_LOG << "Applied fst union on " << n_in_done
+ << " FSTs, produced " << n_out_done << " FSTs";
+ return (n_out_done != 0 ? 0 : 1);
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/fsttablecompose.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/fsttablecompose.cc
new file mode 100644
index 000000000..6652a8c90
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/fsttablecompose.cc
@@ -0,0 +1,202 @@
+// fstbin/fsttablecompose.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+//#include "util/common-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/table-matcher.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/kaldi-fst-io.h"
+#include "util/parse-options.h"
+
+/*
+ cd ~/tmpdir
+ while true; do
+ fstrand | fstarcsort --sort_type=olabel > 1.fst; fstrand | fstarcsort > 2.fst
+ fstcompose 1.fst 2.fst > 3a.fst
+ fsttablecompose 1.fst 2.fst > 3b.fst
+ fstequivalent --random=true 3a.fst 3b.fst || echo "Test failed"
+ echo -n "."
+ done
+
+*/
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+ /*
+ fsttablecompose should always give equivalent results to compose,
+ but it is more efficient for certain kinds of inputs.
+ In particular, it is useful when, say, the left FST has states
+ that typically either have epsilon olabels, or
+ one transition out for each of the possible symbols (as the
+ olabel). The same with the input symbols of the right-hand FST
+ is possible.
+ */
+
+ const char *usage =
+ "Composition algorithm [between two FSTs of standard type, in tropical\n"
+ "semiring] that is more efficient for certain cases-- in particular,\n"
+ "where one of the FSTs (the left one, if --match-side=left) has large\n"
+ "out-degree\n"
+ "\n"
+ "Usage: fsttablecompose (fst1-rxfilename|fst1-rspecifier) "
+ "(fst2-rxfilename|fst2-rspecifier) [(out-rxfilename|out-rspecifier)]\n";
+
+ ParseOptions po(usage);
+
+ TableComposeOptions opts;
+ std::string match_side = "left";
+ std::string compose_filter = "sequence";
+
+ po.Register("connect", &opts.connect, "If true, trim FST before output.");
+ po.Register("match-side", &match_side, "Side of composition to do table "
+ "match, one of: \"left\" or \"right\".");
+ po.Register("compose-filter", &compose_filter, "Composition filter to use, "
+ "one of: \"alt_sequence\", \"auto\", \"match\", \"sequence\"");
+
+ po.Read(argc, argv);
+
+ if (match_side == "left") {
+ opts.table_match_type = MATCH_OUTPUT;
+ } else if (match_side == "right") {
+ opts.table_match_type = MATCH_INPUT;
+ } else {
+ KALDI_ERR << "Invalid match-side option: " << match_side;
+ }
+
+ if (compose_filter == "alt_sequence") {
+ opts.filter_type = ALT_SEQUENCE_FILTER;
+ } else if (compose_filter == "auto") {
+ opts.filter_type = AUTO_FILTER;
+ } else if (compose_filter == "match") {
+ opts.filter_type = MATCH_FILTER;
+ } else if (compose_filter == "sequence") {
+ opts.filter_type = SEQUENCE_FILTER;
+ } else {
+ KALDI_ERR << "Invalid compose-filter option: " << compose_filter;
+ }
+
+ if (po.NumArgs() < 2 || po.NumArgs() > 3) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ std::string fst1_in_str = po.GetArg(1),
+ fst2_in_str = po.GetArg(2),
+ fst_out_str = po.GetOptArg(3);
+
+
+ //// Note: the "table" in is_table_1 and similar variables has nothing
+ //// to do with the "table" in "fsttablecompose"; is_table_1 relates to
+ //// whether we are dealing with a single FST or a whole set of FSTs.
+ //bool is_table_1 =
+ // (ClassifyRspecifier(fst1_in_str, NULL, NULL) != kNoRspecifier),
+ // is_table_2 =
+ // (ClassifyRspecifier(fst2_in_str, NULL, NULL) != kNoRspecifier),
+ // is_table_out =
+ // (ClassifyWspecifier(fst_out_str, NULL, NULL, NULL) != kNoWspecifier);
+ //if (is_table_out != (is_table_1 || is_table_2))
+ // KALDI_ERR << "Incompatible combination of archives and files";
+ //
+ //if (!is_table_1 && !is_table_2) { // Only dealing with files...
+ VectorFst<StdArc> *fst1 = ReadFstKaldi(fst1_in_str);
+
+ VectorFst<StdArc> *fst2 = ReadFstKaldi(fst2_in_str);
+
+ // Checks if <fst1> is olabel sorted and <fst2> is ilabel sorted.
+ if (fst1->Properties(fst::kOLabelSorted, true) == 0) {
+ KALDI_WARN << "The first FST is not olabel sorted.";
+ }
+ if (fst2->Properties(fst::kILabelSorted, true) == 0) {
+ KALDI_WARN << "The second FST is not ilabel sorted.";
+ }
+
+ VectorFst<StdArc> composed_fst;
+
+ TableCompose(*fst1, *fst2, &composed_fst, opts);
+
+ delete fst1;
+ delete fst2;
+
+ WriteFstKaldi(composed_fst, fst_out_str);
+ return 0;
+ //} else if (!is_table_1 && is_table_2
+ // && opts.table_match_type == MATCH_OUTPUT) {
+ // // second arg is an archive, and match-side=left (default).
+ // TableComposeCache<Fst<StdArc> > cache(opts);
+ // VectorFst<StdArc> *fst1 = ReadFstKaldi(fst1_in_str);
+ // SequentialTableReader<VectorFstHolder> fst2_reader(fst2_in_str);
+ // TableWriter<VectorFstHolder> fst_writer(fst_out_str);
+ // int32 n_done = 0;
+
+ // // Checks if <fst1> is olabel sorted.
+ // if (fst1->Properties(fst::kOLabelSorted, true) == 0) {
+ // KALDI_WARN << "The first FST is not olabel sorted.";
+ // }
+ // for (; !fst2_reader.Done(); fst2_reader.Next(), n_done++) {
+ // VectorFst<StdArc> fst2(fst2_reader.Value());
+ // VectorFst<StdArc> fst_out;
+ // TableCompose(*fst1, fst2, &fst_out, &cache);
+ // fst_writer.Write(fst2_reader.Key(), fst_out);
+ // }
+ // KALDI_LOG << "Composed " << n_done << " FSTs.";
+ // return (n_done != 0 ? 0 : 1);
+ //} else if (is_table_1 && is_table_2) {
+ // SequentialTableReader<VectorFstHolder> fst1_reader(fst1_in_str);
+ // RandomAccessTableReader<VectorFstHolder> fst2_reader(fst2_in_str);
+ // TableWriter<VectorFstHolder> fst_writer(fst_out_str);
+ // int32 n_done = 0, n_err = 0;
+ // for (; !fst1_reader.Done(); fst1_reader.Next()) {
+ // std::string key = fst1_reader.Key();
+ // if (!fst2_reader.HasKey(key)) {
+ // KALDI_WARN << "No such key " << key << " in second table.";
+ // n_err++;
+ // } else {
+ // const VectorFst<StdArc> &fst1(fst1_reader.Value()),
+ // &fst2(fst2_reader.Value(key));
+ // VectorFst<StdArc> result;
+ // TableCompose(fst1, fst2, &result, opts);
+ // if (result.NumStates() == 0) {
+ // KALDI_WARN << "Empty output for key " << key;
+ // n_err++;
+ // } else {
+ // fst_writer.Write(key, result);
+ // n_done++;
+ // }
+ // }
+ // }
+ // KALDI_LOG << "Successfully composed " << n_done << " FSTs, errors or "
+ // << "empty output on " << n_err;
+ //} else {
+ // KALDI_ERR << "The combination of tables/non-tables and match-type that you "
+ // << "supplied is not currently supported. Either implement this, "
+ // << "ask the maintainers to implement it, or call this program "
+ // << "differently.";
+ //}
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstbin/make-grammar-fst.cc b/runtime/onnxruntime/third_party/kaldi/fstbin/make-grammar-fst.cc
new file mode 100644
index 000000000..564f25531
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstbin/make-grammar-fst.cc
@@ -0,0 +1,167 @@
+// fstbin/make-grammar-fst.cc
+
+// Copyright 2018 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fst/fstlib.h"
+#include "fstext/table-matcher.h"
+#include "fstext/kaldi-fst-io.h"
+#include "decoder/grammar-fst.h"
+
+template<typename FST>
+void MakeGrammarFst(kaldi::ParseOptions po,
+ int32 nonterm_phones_offset,
+ bool write_as_grammar){
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ std::string fst_out_str = po.GetArg(po.NumArgs());
+ std::string top_fst_str = po.GetArg(1);
+
+ ConstFst<StdArc> *top_tmp_fst = ConstFst<StdArc>::Read(top_fst_str);
+ std::shared_ptr<FST> top_fst(new FST(*top_tmp_fst));
+
+ std::vector<std::pair<int32, std::shared_ptr<FST> > > pairs;
+
+ int32 num_pairs = (po.NumArgs() - 2) / 2;
+ for (int32 i = 1; i <= num_pairs; i++) {
+ int32 nonterminal;
+ std::string nonterm_str = po.GetArg(2*i);
+ if (!ConvertStringToInteger(nonterm_str, &nonterminal) ||
+ nonterminal <= 0)
+ KALDI_ERR << "Expected positive integer as nonterminal, got: "
+ << nonterm_str;
+ std::string fst_str = po.GetArg(2*i + 1);
+
+ ConstFst<StdArc> *tmp_fst = ConstFst<StdArc>::Read(fst_str);
+ std::shared_ptr<FST> this_fst(new FST(*tmp_fst));
+
+ pairs.push_back(std::pair<int32, std::shared_ptr<FST> >(
+ nonterminal, this_fst));
+ };
+
+ GrammarFstTpl<FST> *grammar_fst = new GrammarFstTpl<FST>(nonterm_phones_offset,
+ top_fst,
+ pairs);
+
+ if (write_as_grammar) {
+ bool binary = true; // GrammarFst does not support non-binary write.
+ WriteKaldiObject(*grammar_fst, fst_out_str, binary);
+ } else {
+ VectorFst<StdArc> vfst;
+ CopyToVectorFst<FST>(grammar_fst, &vfst);
+ ConstFst<StdArc> cfst(vfst);
+ // We don't have a wrapper in kaldi-fst-io.h for writing type
+ // ConstFst<StdArc>, so do it manually.
+ bool binary = true, write_binary_header = false; // suppress the ^@B
+ Output ko(fst_out_str, binary, write_binary_header);
+ FstWriteOptions wopts(kaldi::PrintableWxfilename(fst_out_str));
+ cfst.Write(ko.Stream(), wopts);
+ }
+
+ KALDI_LOG << "Created grammar FST and wrote it to "
+ << fst_out_str;
+}
+
+
+int main(int argc, char *argv[]) {
+ try {
+ using namespace kaldi;
+ using namespace fst;
+ using kaldi::int32;
+
+ const char *usage =
+ "Construct GrammarFst and write it to disk (or convert it to ConstFst\n"
+ "and write that to disk instead). Mostly intended for demonstration\n"
+ "and testing purposes (since it may be more convenient to construct\n"
+ "GrammarFst from code). See kaldi-asr.org/doc/grammar.html\n"
+ "Can also be used to prepares FSTs for this use, by calling\n"
+ "PrepareForGrammarFst(), which does things like adding final-probs and\n"
+ "making small structural tweaks to the FST\n"
+ "\n"
+ "Usage (1): make-grammar-fst [options] <top-level-fst> <symbol1> <fst1> \\\n"
+ " [<symbol2> <fst2> ...]] <fst-out>\n"
+ "\n"
+ "<symbol1>, <symbol2> are the integer ids of the corresponding\n"
+ " user-defined nonterminal symbols (e.g. #nonterm:contact_list) in the\n"
+ " phones.txt file.\n"
+ "e.g.: make-grammar-fst --nonterm-phones-offset=317 HCLG.fst \\\n"
+ " 320 HCLG1.fst HCLG_grammar.fst\n"
+ "\n"
+ "Usage (2): make-grammar-fst <fst-in> <fst-out>\n"
+ " Prepare individual FST for compilation into GrammarFst.\n"
+ " E.g. make-grammar-fst HCLG.fst HCLGmod.fst. The outputs of this\n"
+ " will then become the arguments <top-level-fst>, <fst1>, ... for usage\n"
+ " pattern (1).\n"
+ "\n"
+ "The --nonterm-phones-offset option is required for both usage patterns.\n";
+
+
+ ParseOptions po(usage);
+
+
+ int32 nonterm_phones_offset = -1;
+ bool write_as_grammar = true;
+ bool make_mutable = false;
+
+ po.Register("nonterm-phones-offset", &nonterm_phones_offset,
+ "Integer id of #nonterm_bos in phones.txt");
+ po.Register("write-as-grammar", &write_as_grammar, "If true, "
+ "write as GrammarFst object; if false, convert to "
+ "ConstFst<StdArc> (readable by standard decoders) "
+ "and write that.");
+ po.Register("make-mutable", &make_mutable, "If true, "
+ "Make a GrammarFst using StdVectorFst as the "
+ "underlying FST instance type."
+ "Use const ConstFst<StdArc> otherwise.");
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() < 2 || po.NumArgs() % 2 != 0) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ if (nonterm_phones_offset < 0)
+ KALDI_ERR << "The --nonterm-phones-offset option must be supplied "
+ "and positive.";
+
+ if (po.NumArgs() == 2) {
+ // this usage pattern calls PrepareForGrammarFst().
+ VectorFst<StdArc> *fst = ReadFstKaldi(po.GetArg(1));
+ PrepareForGrammarFst(nonterm_phones_offset, fst);
+ // This will write it as VectorFst; to avoid it having to be converted to
+ // ConstFst when read again by make-grammar-fst, you may want to pipe
+ // through fstconvert --fst_type=const.
+ WriteFstKaldi(*fst, po.GetArg(2));
+ exit(0);
+ }
+
+ if (make_mutable) {
+ MakeGrammarFst<StdVectorFst>(po, nonterm_phones_offset, write_as_grammar);
+ } else {
+ MakeGrammarFst<const ConstFst<StdArc> >(po, nonterm_phones_offset, write_as_grammar);
+ }
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/Makefile b/runtime/onnxruntime/third_party/kaldi/fstext/Makefile
new file mode 100644
index 000000000..b76bd413c
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/Makefile
@@ -0,0 +1,30 @@
+
+# make "all" the target.
+all:
+
+# Disable linking math libs because not needed here. Just for compilation speed.
+# no, it's now needed for context-fst-test.
+# MATHLIB = NONE
+
+EXTRA_CXXFLAGS = -Wno-sign-compare
+
+include ../kaldi.mk
+
+TESTFILES = determinize-star-test \
+ pre-determinize-test trivial-factor-weight-test \
+ context-fst-test factor-test table-matcher-test fstext-utils-test \
+ remove-eps-local-test lattice-weight-test \
+ determinize-lattice-test lattice-utils-test deterministic-fst-test \
+ push-special-test epsilon-property-test prune-special-test
+
+OBJFILES = push-special.o kaldi-fst-io.o context-fst.o grammar-context-fst.o
+
+
+LIBNAME = kaldi-fstext
+
+# tree and matrix archives needed for test-context-fst
+# matrix archive needed for push-special.
+ADDLIBS = ../tree/kaldi-tree.a ../util/kaldi-util.a ../matrix/kaldi-matrix.a \
+ ../base/kaldi-base.a
+
+include ../makefiles/default_rules.mk
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/context-fst-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/context-fst-test.cc
new file mode 100644
index 000000000..65da1bb07
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/context-fst-test.cc
@@ -0,0 +1,256 @@
+// fstext/context-fst-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "fstext/context-fst.h"
+#include "fstext/fst-test-utils.h"
+#include "tree/context-dep.h"
+#include "util/kaldi-io.h"
+#include "base/kaldi-math.h"
+
+namespace fst
+{
+using std::vector;
+using std::cout;
+
+// GenAcceptorFromSequence generates a linear acceptor (identical input+output symbols) that has this
+// sequence of symbols, and
+template<class Arc>
+static VectorFst<Arc> *GenAcceptorFromSequence(const vector<typename Arc::Label> &symbols, float cost) {
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId StateId;
+
+ vector<float> split_cost(symbols.size()+1, 0.0); // for #-arcs + end-state.
+ { // compute split_cost. it must sum to "cost".
+ std::set<int32> indices;
+ size_t num_indices = 1 + (kaldi::Rand() % split_cost.size());
+ while (indices.size() < num_indices) indices.insert(kaldi::Rand() % split_cost.size());
+ for (std::set<int32>::iterator iter = indices.begin(); iter != indices.end(); ++iter) {
+ split_cost[*iter] = cost / num_indices;
+ }
+ }
+
+ VectorFst<Arc> *fst = new VectorFst<Arc>();
+ StateId cur_state = fst->AddState();
+ fst->SetStart(cur_state);
+ for (size_t i = 0; i < symbols.size(); i++) {
+ StateId next_state = fst->AddState();
+ Arc arc;
+ arc.ilabel = symbols[i];
+ arc.olabel = symbols[i];
+ arc.nextstate = next_state;
+ arc.weight = (Weight) split_cost[i];
+ fst->AddArc(cur_state, arc);
+ cur_state = next_state;
+
+ }
+ fst->SetFinal(cur_state, (Weight)split_cost[symbols.size()]);
+ return fst;
+}
+
+
+
+// CheckPhones is used to test the correctness of an FST that is the result of
+// composition with a ContextFst.
+template<class Arc>
+static float CheckPhones(const VectorFst<Arc> &linear_fst,
+ const vector<typename Arc::Label> &phone_ids,
+ const vector<typename Arc::Label> &disambig_ids,
+ const vector<typename Arc::Label> &phone_seq,
+ const vector<vector<typename Arc::Label> > &ilabel_info,
+ int N, int P) {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ assert(kaldi::IsSorted(phone_ids)); // so we can do binary_search.
+
+
+ vector<int32> input_syms;
+ vector<int32> output_syms;
+ Weight tot_cost;
+ bool ans = GetLinearSymbolSequence(linear_fst, &input_syms,
+ &output_syms, &tot_cost);
+ assert(ans); // should be linear.
+
+ vector<int32> phone_seq_check;
+ for (size_t i = 0; i < output_syms.size(); i++)
+ if (std::binary_search(phone_ids.begin(), phone_ids.end(), output_syms[i]))
+ phone_seq_check.push_back(output_syms[i]);
+
+ assert(phone_seq_check == phone_seq);
+
+ vector<vector<int32> > input_syms_long;
+ for (size_t i = 0; i < input_syms.size(); i++) {
+ Label isym = input_syms[i];
+ if (ilabel_info[isym].size() == 0) continue; // epsilon.
+ if ( (ilabel_info[isym].size() == 1 &&
+ ilabel_info[isym][0] <= 0) ) continue; // disambig.
+ input_syms_long.push_back(ilabel_info[isym]);
+ }
+
+ for (size_t i = 0; i < input_syms_long.size(); i++) {
+ vector<int32> phone_context_window(N); // phone at pos i will be at pos P in this window.
+ int pos = ((int)i) - P; // pos of first phone in window [ may be out of range] .
+ for (int j = 0; j < N; j++, pos++) {
+ if (static_cast<size_t>(pos) < phone_seq.size()) phone_context_window[j] = phone_seq[pos];
+ else phone_context_window[j] = 0; // 0 is a special symbol that context-dep-itf expects to see
+ // when no phone is present due to out-of-window. context-fst knows about this too.
+ }
+ assert(input_syms_long[i] == phone_context_window);
+ }
+ return tot_cost.Value();
+}
+
+
+
+
+template<class Arc>
+static VectorFst<Arc> *GenRandPhoneSeq(vector<typename Arc::Label> &phone_syms,
+ vector<typename Arc::Label> &disambig_syms,
+ typename Arc::Label subsequential_symbol,
+ int num_subseq_syms,
+ float seq_prob,
+ vector<typename Arc::Label> *phoneseq_out) {
+ KALDI_ASSERT(phoneseq_out != NULL);
+ typedef typename Arc::Label Label;
+ // Generate an FST that is a random phone sequence, ending
+ // with "num_subseq_syms" subsequential symbols. It will
+ // have disambiguation symbols randomly interspersed throughout.
+ // The number of phones is random (possibly zero).
+ size_t len = (kaldi::Rand() % 4) * (kaldi::Rand() % 3); // up to 3*2=6 phones.
+ float disambig_prob = 0.33;
+ phoneseq_out->clear();
+ vector<Label> syms; // the phones
+ for (size_t i = 0; i < len; i++) {
+ while (kaldi::RandUniform() < disambig_prob) syms.push_back(disambig_syms[kaldi::Rand() % disambig_syms.size()]);
+ Label phone_id = phone_syms[kaldi::Rand() % phone_syms.size()];
+ phoneseq_out->push_back(phone_id); // record in output the underlying phone sequence.
+ syms.push_back(phone_id);
+ }
+ for (size_t i = 0; static_cast<int32>(i) < num_subseq_syms; i++) {
+ while (kaldi::RandUniform() < disambig_prob) syms.push_back(disambig_syms[kaldi::Rand() % disambig_syms.size()]);
+ syms.push_back(subsequential_symbol);
+ }
+ while (kaldi::RandUniform() < disambig_prob) syms.push_back(disambig_syms[kaldi::Rand() % disambig_syms.size()]);
+
+ // OK, now have the symbols of the FST as a vector.
+ return GenAcceptorFromSequence<Arc>(syms, seq_prob);
+}
+
+// Don't instantiate with log semiring, as RandEquivalent may fail.
+// TestContestFst also test ReadILabelInfo and WriteILabelInfo.
+static void TestContextFst(bool verbose, bool use_matcher) {
+ typedef StdArc Arc;
+ typedef Arc::Label Label;
+ typedef Arc::StateId StateId;
+ typedef Arc::Weight Weight;
+
+ // Generate a random set of phones.
+ size_t num_phones = 1 + kaldi::Rand() % 10;
+ std::set<int32> phones_set;
+ while (phones_set.size() < num_phones) phones_set.insert(1 + kaldi::Rand() % (num_phones + 5)); // don't use 0 [== epsilon]
+ vector<int32> phones;
+ kaldi::CopySetToVector(phones_set, &phones);
+
+ int N = 1 + kaldi::Rand() % 4; // Context size, in range 1..4.
+ int P = kaldi::Rand() % N; // 1.. N-1.
+ if (verbose) std::cout << "N = "<< N << ", P = "<<P<<'\n';
+
+ Label subsequential_symbol = 1000;
+ vector<int32> disambig_syms;
+ for (size_t i =0; i < 5; i++) disambig_syms.push_back(500 + i);
+ vector<int32> phone_syms;
+ for (size_t i = 0; i < phones.size();i++) phone_syms.push_back(phones[i]);
+
+
+ InverseContextFst inv_cfst(subsequential_symbol,
+ phones, disambig_syms,
+ N, P);
+
+
+ /* Now create random phone-sequences and compose them with the context FST.
+ */
+
+ for (size_t p = 0; p < 10; p++) {
+ vector<int32> phone_seq;
+ int num_subseq = N - P - 1; // zero if P == N-1, i.e. P is last element, i.e. left-context only.
+ float tot_cost = 20.0 * kaldi::RandUniform();
+ VectorFst<Arc> *f = GenRandPhoneSeq<Arc>(phone_syms, disambig_syms, subsequential_symbol, num_subseq, tot_cost, &phone_seq);
+ if (verbose) {
+ std::cout << "Sequence FST is:\n";
+ { // Try to print the fst.
+ FstPrinter<Arc> fstprinter(*f, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ }
+
+ VectorFst<Arc> fst_composed;
+
+ ComposeDeterministicOnDemandInverse(*f, &inv_cfst, &fst_composed);
+
+
+ // Testing WriteILabelInfo and ReadILabelInfo.
+ {
+ bool binary = (kaldi::Rand() % 2 == 0);
+ WriteILabelInfo(kaldi::Output("tmpf", binary).Stream(),
+ binary, inv_cfst.IlabelInfo());
+
+ bool binary_in;
+ vector<vector<int32> > ilabel_info;
+ kaldi::Input ki("tmpf", &binary_in);
+ ReadILabelInfo(ki.Stream(),
+ binary_in, &ilabel_info);
+ assert(ilabel_info == inv_cfst.IlabelInfo());
+ }
+
+
+ if (verbose) {
+ std::cout << "Composed FST is:\n";
+ { // Try to print the fst.
+ FstPrinter<Arc> fstprinter(fst_composed, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ }
+
+ // now check the composed FST.
+ float tot_cost_check = CheckPhones<Arc>(fst_composed,
+ phone_syms,
+ disambig_syms,
+ phone_seq,
+ inv_cfst.IlabelInfo(),
+ N, P);
+ kaldi::AssertEqual(tot_cost, tot_cost_check);
+
+ delete f;
+ }
+
+ unlink("tmpf");
+}
+
+
+} // namespace fst
+
+int main() {
+
+ for (int i = 0;i < 16;i++) {
+ bool verbose = (i < 4);
+ bool use_matcher = ( (i/4) % 2 == 0);
+ fst::TestContextFst(verbose, use_matcher);
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/context-fst.cc b/runtime/onnxruntime/third_party/kaldi/fstext/context-fst.cc
new file mode 100644
index 000000000..d38214470
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/context-fst.cc
@@ -0,0 +1,401 @@
+// fstext/context-fst.cc
+
+// Copyright 2018 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "fstext/context-fst.h"
+#include "base/kaldi-error.h"
+
+namespace fst {
+using std::vector;
+
+
+InverseContextFst::InverseContextFst(
+ Label subsequential_symbol,
+ const vector<int32>& phones,
+ const vector<int32>& disambig_syms,
+ int32 context_width,
+ int32 central_position):
+ context_width_(context_width),
+ central_position_(central_position),
+ phone_syms_(phones),
+ disambig_syms_(disambig_syms),
+ subsequential_symbol_(subsequential_symbol) {
+
+ { // This block checks the inputs.
+ KALDI_ASSERT(subsequential_symbol != 0
+ && disambig_syms_.count(subsequential_symbol) == 0
+ && phone_syms_.count(subsequential_symbol) == 0);
+ if (phone_syms_.empty())
+ KALDI_WARN << "Context FST created but there are no phone symbols: probably "
+ "input FST was empty.";
+ KALDI_ASSERT(phone_syms_.count(0) == 0 && disambig_syms_.count(0) == 0 &&
+ central_position_ >= 0 && central_position_ < context_width_);
+ for (size_t i = 0; i < phones.size(); i++) {
+ KALDI_ASSERT(disambig_syms_.count(phones[i]) == 0);
+ }
+ }
+
+ // empty vector, will be the ilabel_info vector that corresponds to epsilon,
+ // in case our FST needs to output epsilons.
+ vector<int32> empty_vec;
+ Label epsilon_label = FindLabel(empty_vec);
+
+ // epsilon_vec is the phonetic context window we have at the very start of a
+ // sequence, meaning "no real phones have been seen yet".
+ vector<int32> epsilon_vec(context_width_ - 1, 0);
+ StateId start_state = FindState(epsilon_vec);
+
+ KALDI_ASSERT(epsilon_label == 0 && start_state == 0);
+
+ if (context_width_ > central_position_ + 1 && !disambig_syms_.empty()) {
+ // We add a symbol whose sequence representation is [ 0 ], and whose
+ // symbol-id is 1. This is treated as a disambiguation symbol, we call it
+ // #-1 in printed form. It is necessary to ensure that all determinizable
+ // LG's will have determinizable CLG's. The problem it fixes is quite
+ // subtle-- it relates to reordering of disambiguation symbols (they appear
+ // earlier in CLG than in LG, relative to phones), and the fact that if a
+ // disambig symbol appears at the very start of a sequence in CLG, it's not
+ // clear exatly where it appeared on the corresponding sequence at the input
+ // of LG.
+ vector<int32> pseudo_eps_vec;
+ pseudo_eps_vec.push_back(0);
+ pseudo_eps_symbol_= FindLabel(pseudo_eps_vec);
+ KALDI_ASSERT(pseudo_eps_symbol_ == 1);
+ } else {
+ pseudo_eps_symbol_ = 0; // use actual epsilon.
+ }
+}
+
+
+void InverseContextFst::ShiftSequenceLeft(Label label,
+ std::vector<int32> *phone_seq) {
+ if (!phone_seq->empty()) {
+ phone_seq->erase(phone_seq->begin());
+ phone_seq->push_back(label);
+ }
+}
+
+void InverseContextFst::GetFullPhoneSequence(
+ const std::vector<int32> &seq, Label label,
+ std::vector<int32> *full_phone_sequence) {
+ int32 context_width = context_width_;
+ full_phone_sequence->reserve(context_width);
+ full_phone_sequence->insert(full_phone_sequence->end(),
+ seq.begin(), seq.end());
+ full_phone_sequence->push_back(label);
+ for (int32 i = central_position_ + 1; i < context_width; i++) {
+ if ((*full_phone_sequence)[i] == subsequential_symbol_) {
+ (*full_phone_sequence)[i] = 0;
+ }
+ }
+}
+
+
+InverseContextFst::Weight InverseContextFst::Final(StateId s) {
+ KALDI_ASSERT(static_cast<size_t>(s) < state_seqs_.size());
+
+ const vector<int32> &phone_context = state_seqs_[s];
+
+ KALDI_ASSERT(phone_context.size() == context_width_ - 1);
+
+ bool has_final_prob;
+
+ if (central_position_ < context_width_ - 1) {
+ has_final_prob = (phone_context[central_position_] == subsequential_symbol_);
+ // if phone_context[central_position_] != subsequential_symbol_ then we have
+ // pending phones-in-context that we still need to output, so we need to
+ // consume more subsequential symbols before we can terminate.
+ } else {
+ has_final_prob = true;
+ }
+ return has_final_prob ? Weight::One() : Weight::Zero();
+}
+
+bool InverseContextFst::GetArc(StateId s, Label ilabel, Arc *arc) {
+ KALDI_ASSERT(ilabel != 0 && static_cast<size_t>(s) < state_seqs_.size() &&
+ state_seqs_[s].size() == context_width_ - 1);
+
+ if (IsDisambigSymbol(ilabel)) {
+ // A disambiguation-symbol self-loop arc.
+ CreateDisambigArc(s, ilabel, arc);
+ return true;
+ } else if (IsPhoneSymbol(ilabel)) {
+ const vector<int32> &seq = state_seqs_[s];
+ if (!seq.empty() && seq.back() == subsequential_symbol_) {
+ return false; // A real phone is not allowed to follow the subsequential
+ // symbol.
+ }
+
+ // next_seq will be 'seq' shifted left by 1, with 'ilabel' appended.
+ vector<int32> next_seq(seq);
+ ShiftSequenceLeft(ilabel, &next_seq);
+
+ // full-seq will be the full context window of size context_width_.
+ vector<int32> full_seq;
+ GetFullPhoneSequence(seq, ilabel, &full_seq);
+
+ StateId next_s = FindState(next_seq);
+
+ CreatePhoneOrEpsArc(s, next_s, ilabel, full_seq, arc);
+ return true;
+ } else if (ilabel == subsequential_symbol_) {
+ const vector<int32> &seq = state_seqs_[s];
+
+ if (central_position_ + 1 == context_width_ ||
+ seq[central_position_] == subsequential_symbol_) {
+ // We already had "enough" subsequential symbols in a row and don't want to
+ // accept any more, or we'd be making the subsequential symbol the central phone.
+ return false;
+ }
+
+ // full-seq will be the full context window of size context_width_.
+ vector<int32> full_seq;
+ GetFullPhoneSequence(seq, ilabel, &full_seq);
+
+ vector<int32> next_seq(seq);
+ ShiftSequenceLeft(ilabel, &next_seq);
+ StateId next_s = FindState(next_seq);
+
+ CreatePhoneOrEpsArc(s, next_s, ilabel, full_seq, arc);
+ return true;
+ } else {
+ KALDI_ERR << "ContextFst: CreateArc, invalid ilabel supplied [confusion "
+ << "about phone list or disambig symbols?]: " << ilabel;
+ }
+ return false; // won't get here. suppress compiler error.
+}
+
+
+void InverseContextFst::CreateDisambigArc(StateId s, Label ilabel, Arc *arc) {
+ // Creates a self-loop arc corresponding to the disambiguation symbol.
+ vector<int32> label_info; // This will be a vector containing just [ -olabel ].
+ label_info.push_back(-ilabel); // olabel is a disambiguation symbol. Use its negative
+ // so we can more easily distinguish them from phones.
+ Label olabel = FindLabel(label_info);
+ arc->ilabel = ilabel;
+ arc->olabel = olabel;
+ arc->weight = Weight::One();
+ arc->nextstate = s; // self-loop.
+}
+
+void InverseContextFst::CreatePhoneOrEpsArc(StateId src, StateId dest,
+ Label ilabel,
+ const vector<int32> &phone_seq,
+ Arc *arc) {
+ KALDI_PARANOID_ASSERT(phone_seq[central_position_] != subsequential_symbol_);
+
+ arc->ilabel = ilabel;
+ arc->weight = Weight::One();
+ arc->nextstate = dest;
+ if (phone_seq[central_position_] == 0) {
+ // This can happen at the beginning of the graph. In this case we don't
+ // output a real phone, we createdt an epsilon arc (but sometimes we need to
+ // use a special disambiguation symbol instead of epsilon).
+ arc->olabel = pseudo_eps_symbol_;
+ } else {
+ // We have a phone in the central position.
+ arc->olabel = FindLabel(phone_seq);
+ }
+}
+
+StdArc::StateId InverseContextFst::FindState(const vector<int32> &seq) {
+ // Finds state-id corresponding to this vector of phones. Inserts it if
+ // necessary.
+ KALDI_ASSERT(static_cast<int32>(seq.size()) == context_width_ - 1);
+ VectorToStateMap::const_iterator iter = state_map_.find(seq);
+ if (iter == state_map_.end()) { // Not already in map.
+ StateId this_state_id = (StateId)state_seqs_.size();
+ state_seqs_.push_back(seq);
+ state_map_[seq] = this_state_id;
+ return this_state_id;
+ } else {
+ return iter->second;
+ }
+}
+
+StdArc::Label InverseContextFst::FindLabel(const vector<int32> &label_vec) {
+ // Finds the ilabel corresponding to this vector (creates a new ilabel if
+ // necessary).
+ VectorToLabelMap::const_iterator iter = ilabel_map_.find(label_vec);
+ if (iter == ilabel_map_.end()) { // Not already in map.
+ Label this_label = ilabel_info_.size();
+ ilabel_info_.push_back(label_vec);
+ ilabel_map_[label_vec] = this_label;
+ return this_label;
+ } else {
+ return iter->second;
+ }
+}
+
+
+void ComposeContext(const vector<int32> &disambig_syms_in,
+ int32 context_width, int32 central_position,
+ VectorFst<StdArc> *ifst,
+ VectorFst<StdArc> *ofst,
+ vector<vector<int32> > *ilabels_out,
+ bool project_ifst) {
+ KALDI_ASSERT(ifst != NULL && ofst != NULL);
+ KALDI_ASSERT(context_width > 0);
+ KALDI_ASSERT(central_position >= 0);
+ KALDI_ASSERT(central_position < context_width);
+
+ vector<int32> disambig_syms(disambig_syms_in);
+ std::sort(disambig_syms.begin(), disambig_syms.end());
+
+ vector<int32> all_syms;
+ GetInputSymbols(*ifst, false/*no eps*/, &all_syms);
+ std::sort(all_syms.begin(), all_syms.end());
+ vector<int32> phones;
+ for (size_t i = 0; i < all_syms.size(); i++)
+ if (!std::binary_search(disambig_syms.begin(),
+ disambig_syms.end(), all_syms[i]))
+ phones.push_back(all_syms[i]);
+
+ // Get subsequential symbol that does not clash with
+ // any disambiguation symbol or symbol in the FST.
+ int32 subseq_sym = 1;
+ if (!all_syms.empty())
+ subseq_sym = std::max(subseq_sym, all_syms.back() + 1);
+ if (!disambig_syms.empty())
+ subseq_sym = std::max(subseq_sym, disambig_syms.back() + 1);
+
+ // if central_position == context_width-1, it's left-context, and no
+ // subsequential symbol is needed.
+ if (central_position != context_width-1) {
+ AddSubsequentialLoop(subseq_sym, ifst);
+ if (project_ifst) {
+ fst::Project(ifst, fst::PROJECT_INPUT);
+ }
+ }
+
+ InverseContextFst inv_c(subseq_sym, phones, disambig_syms,
+ context_width, central_position);
+
+ // The following statement is equivalent to the following
+ // (if FSTs had the '*' operator for composition):
+ // (*ofst) = inv(inv_c) * (*ifst)
+ ComposeDeterministicOnDemandInverse(*ifst, &inv_c, ofst);
+
+ inv_c.SwapIlabelInfo(ilabels_out);
+}
+
+void AddSubsequentialLoop(StdArc::Label subseq_symbol,
+ MutableFst<StdArc> *fst) {
+ typedef StdArc Arc;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ vector<StateId> final_states;
+ for (StateIterator<MutableFst<Arc> > siter(*fst); !siter.Done(); siter.Next()) {
+ StateId s = siter.Value();
+ if (fst->Final(s) != Weight::Zero()) final_states.push_back(s);
+ }
+
+ StateId superfinal = fst->AddState();
+ Arc arc(subseq_symbol, 0, Weight::One(), superfinal);
+ fst->AddArc(superfinal, arc); // loop at superfinal.
+ fst->SetFinal(superfinal, Weight::One());
+
+ for (size_t i = 0; i < final_states.size(); i++) {
+ StateId s = final_states[i];
+ fst->AddArc(s, Arc(subseq_symbol, 0, fst->Final(s), superfinal));
+ // No, don't remove the final-weights of the original states..
+ // this is so we can add the subsequential loop in cases where
+ // there is no context, and it won't hurt.
+ // fst->SetFinal(s, Weight::Zero());
+ arc.nextstate = final_states[i];
+ }
+}
+
+void WriteILabelInfo(std::ostream &os, bool binary,
+ const vector<vector<int32> > &info) {
+ int32 size = info.size();
+ kaldi::WriteBasicType(os, binary, size);
+ for (int32 i = 0; i < size; i++) {
+ kaldi::WriteIntegerVector(os, binary, info[i]);
+ }
+}
+
+
+void ReadILabelInfo(std::istream &is, bool binary,
+ vector<vector<int32> > *info) {
+ int32 size = info->size();
+ kaldi::ReadBasicType(is, binary, &size);
+ info->resize(size);
+ for (int32 i = 0; i < size; i++) {
+ kaldi::ReadIntegerVector(is, binary, &((*info)[i]));
+ }
+}
+
+SymbolTable *CreateILabelInfoSymbolTable(const vector<vector<int32> > &info,
+ const SymbolTable &phones_symtab,
+ std::string separator,
+ std::string initial_disambig) { // e.g. separator = "/", initial-disambig="#-1"
+ KALDI_ASSERT(!info.empty() && info[0].empty());
+ SymbolTable *ans = new SymbolTable("ilabel-info-symtab");
+ int64 s = ans->AddSymbol(phones_symtab.Find(static_cast<int64>(0)));
+ assert(s == 0);
+ for (size_t i = 1; i < info.size(); i++) {
+ if (info[i].size() == 0) {
+ KALDI_ERR << "Invalid ilabel-info";
+ }
+ if (info[i].size() == 1 &&
+ info[i][0] <= 0) {
+ if (info[i][0] == 0) { // special symbol at start that we want to call #-1.
+ s = ans->AddSymbol(initial_disambig);
+ if (s != i) {
+ KALDI_ERR << "Disambig symbol " << initial_disambig
+ << " already in vocab";
+ }
+ } else {
+ std::string disambig_sym = phones_symtab.Find(-info[i][0]);
+ if (disambig_sym == "") {
+ KALDI_ERR << "Disambig symbol " << -info[i][0]
+ << " not in phone symbol-table";
+ }
+ s = ans->AddSymbol(disambig_sym);
+ if (s != i) {
+ KALDI_ERR << "Disambig symbol " << disambig_sym
+ << " already in vocab";
+ }
+ }
+ } else {
+ // is a phone-context-window.
+ std::string newsym;
+ for (size_t j = 0; j < info[i].size(); j++) {
+ std::string phonesym = phones_symtab.Find(info[i][j]);
+ if (phonesym == "") {
+ KALDI_ERR << "Symbol " << info[i][j]
+ << " not in phone symbol-table";
+ }
+ if (j != 0) newsym += separator;
+ newsym += phonesym;
+ }
+ int64 s = ans->AddSymbol(newsym);
+ if (s != static_cast<int64>(i)) {
+ KALDI_ERR << "Some problem with duplicate symbols";
+ }
+ }
+ }
+ return ans;
+}
+
+
+
+
+} // end namespace fst
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/context-fst.h b/runtime/onnxruntime/third_party/kaldi/fstext/context-fst.h
new file mode 100644
index 000000000..b5271d146
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/context-fst.h
@@ -0,0 +1,340 @@
+// fstext/context-fst.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2018 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+//
+// This file includes material from the OpenFST Library v1.2.7 available at
+// http://www.openfst.org and released under the Apache License Version 2.0.
+//
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// Copyright 2005-2010 Google, Inc.
+// Author: [email protected] (Michael Riley)
+
+
+
+#ifndef KALDI_FSTEXT_CONTEXT_FST_H_
+#define KALDI_FSTEXT_CONTEXT_FST_H_
+
+/* This header defines a context FST "C" (the "C" in "HCLG") which transduces
+ from symbols representing phone context windows (e.g. "a, b, c") to
+ individual phones, e.g. "a". Search for "hbka.pdf" ("Speech Recognition
+ with Weighted Finite State Transducers") by M. Mohri, for more context.
+*/
+
+#include <unordered_map>
+using std::unordered_map;
+
+#include <algorithm>
+#include <string>
+#include <vector>
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+
+#include "util/const-integer-set.h"
+#include "fstext/deterministic-fst.h"
+
+namespace fst {
+
+
+
+
+/// Utility function for writing ilabel-info vectors to disk.
+void WriteILabelInfo(std::ostream &os, bool binary,
+ const std::vector<std::vector<int32> > &ilabel_info);
+
+/// Utility function for reading ilabel-info vectors from disk.
+void ReadILabelInfo(std::istream &is, bool binary,
+ std::vector<std::vector<int32> > *ilabel_info);
+
+
+/// The following function is mainly of use for printing and debugging.
+SymbolTable *CreateILabelInfoSymbolTable(const std::vector<std::vector<int32> > &ilabel_info,
+ const SymbolTable &phones_symtab,
+ std::string separator,
+ std::string disambig_prefix); // e.g. separator = "/", disambig_prefix = "#"
+
+
+
+/**
+ Used in the command-line tool fstcomposecontext. It creates a context FST and
+ composes it on the left with "ifst" to make "ofst". It outputs the label
+ information to ilabels_out. "ifst" is mutable because we need to add the
+ subsequential loop.
+
+ @param [in] disambig_syms List of disambiguation symbols, e.g. the integer
+ ids of #0, #1, #2 ... in the phones.txt.
+ @param [in] context_width Size of context window, e.g. 3 for triphone.
+ @param [in] central_position Central position in phonetic context window
+ (zero-based index), e.g. 1 for triphone.
+ @param [in,out] ifst The FST we are composing with C (e.g. LG.fst), mustable because
+ we need to add the subsequential loop to it.
+ @param [out] ofst Composed output FST (would be CLG.fst).
+ @param [out] ilabels_out Vector, indexed by ilabel of CLG.fst, providing information
+ about the meaning of that ilabel; see
+ "http://kaldi-asr.org/doc/tree_externals.html#tree_ilabel".
+ @param [in] project_ifst This is intended only to be set to true
+ in the program 'fstmakecontextfst'... if true, it will
+ project on the input after adding the subsequential loop
+ to 'ifst', which allows us to reconstruct the context
+ fst C.fst.
+ */
+void ComposeContext(const std::vector<int32> &disambig_syms,
+ int32 context_width, int32 central_position,
+ VectorFst<StdArc> *ifst,
+ VectorFst<StdArc> *ofst,
+ std::vector<std::vector<int32> > *ilabels_out,
+ bool project_ifst = false);
+
+
+/**
+ Modifies an FST so that it transuces the same paths, but the input side of the
+ paths can all have the subsequential symbol '$' appended to them any number of
+ times (we could easily specify the number of times, but accepting any number of
+ repetitions is just more convenient). The actual way we do this is for each
+ final state, we add a transition with weight equal to the final-weight of that
+ state, with input-symbol '$' and output-symbols \<eps\>, and ending in a new
+ super-final state that has unit final-probability and a unit-weight self-loop
+ with '$' on its input and \<eps\> on its output. The reason we don't just
+ add a loop to each final-state has to do with preserving stochasticity
+ (see \ref fst_algo_stochastic). We keep the final-probability in all the
+ original final-states rather than setting them to zero, so the resulting FST
+ can accept zero '$' symbols at the end (in case we had no right context).
+*/
+void AddSubsequentialLoop(StdArc::Label subseq_symbol,
+ MutableFst<StdArc> *fst);
+
+
+/*
+ InverseContextFst represents the inverse of the context FST "C" (the "C" in
+ "HCLG") which transduces from symbols representing phone context windows
+ (e.g. "a, b, c") to individual phones, e.g. "a". So InverseContextFst
+ transduces from phones to symbols representing phone context windows. The
+ point is that the inverse is deterministic, so the DeterministicOnDemandFst
+ interface is applicable, which turns out to be a convenient way to implement
+ this.
+
+ This doesn't implement the full Fst interface, it implements the
+ DeterministicOnDemandFst interface which is much simpler and which is
+ sufficient for what we need to do with this.
+
+ Search for "hbka.pdf" ("Speech Recognition with Weighted Finite State
+ Transducers") by M. Mohri, for more context.
+*/
+
+class InverseContextFst: public DeterministicOnDemandFst<StdArc> {
+public:
+ typedef StdArc Arc;
+ typedef typename StdArc::StateId StateId;
+ typedef typename StdArc::Weight Weight;
+ typedef typename StdArc::Label Label;
+
+ /**
+ Constructor.
+ @param [in] subsequential_symbol The integer id of the 'subsequential symbol'
+ (usually represented as '$') that terminates sequences on the
+ output of C.fst (input of InverseContextFst). Search for
+ "quential" in https://cs.nyu.edu/~mohri/pub/hbka.pdf.
+ This may just be the first unused integer id. Must be nonzer.
+ @param [in] phones List of integer ids of phones, as you would see in phones.txt
+ @param [in] disambig_syms List of integer ids of disambiguation symbols,
+ e.g. the ids of #0, #1, #2 in phones.txt
+ @param [in] context_width Size of context window, e.g. 3 for triphone.
+ @param [in] central_position Central position in context window (zero-based),
+ e.g. 1 for triphone.
+ See \ref graph_context for more details.
+ */
+ InverseContextFst(Label subsequential_symbol,
+ const std::vector<int32>& phones,
+ const std::vector<int32>& disambig_syms,
+ int32 context_width,
+ int32 central_position);
+
+
+ virtual StateId Start() { return 0; }
+
+ virtual Weight Final(StateId s);
+
+ /// Note: ilabel must not be epsilon.
+ virtual bool GetArc(StateId s, Label ilabel, Arc *arc);
+
+ ~InverseContextFst() { }
+
+ // Returns a reference to a vector<vector<int32> > with information about all
+ // the input symbols of C (i.e. all the output symbols of this
+ // InverseContextFst). See
+ // "http://kaldi-asr.org/doc/tree_externals.html#tree_ilabel".
+ const std::vector<std::vector<int32> > &IlabelInfo() const {
+ return ilabel_info_;
+ }
+
+ // A way to destructively obtain the ilabel-info. Only do this if you
+ // are just about to destroy this object.
+ void SwapIlabelInfo(std::vector<std::vector<int32> > *vec) { ilabel_info_.swap(*vec); }
+
+private:
+
+ /// Returns the state-id corresponding to this vector of phones; creates the
+ /// state it if necessary. Requires seq.size() == context_width_ - 1.
+ StateId FindState(const std::vector<int32> &seq);
+
+ /// Finds the label index corresponding to this context-window of phones
+ /// (likely of width context_width_). Inserts it into the
+ /// ilabel_info_/ilabel_map_ tables if necessary.
+ Label FindLabel(const std::vector<int32> &label_info);
+
+ inline bool IsDisambigSymbol(Label lab) { return (disambig_syms_.count(lab) != 0); }
+
+ inline bool IsPhoneSymbol(Label lab) { return (phone_syms_.count(lab) != 0); }
+
+ /// Create disambiguation-symbol self-loop arc; where 'ilabel' must correspond to
+ /// a disambiguation symbol. Called from CreateArc().
+ inline void CreateDisambigArc(StateId s, Label ilabel, Arc *arc);
+
+ /// Creates an arc, this function is to be called only when 'ilabel'
+ /// corresponds to a phone. Called from CreateArc(). The olabel may end be
+ /// epsilon, instead of a phone-in-context, if the system has right context
+ /// and we are very near the beginning of the phone sequence.
+ inline void CreatePhoneOrEpsArc(StateId src, StateId dst, Label ilabel,
+ const std::vector<int32> &phone_seq, Arc *arc);
+
+
+ /// If phone_seq is nonempty then this function it left by one and appends
+ /// 'label' to it, otherwise it does nothing. We expect (but do not check)
+ /// that phone_seq->size() == context_width_ - 1.
+ inline void ShiftSequenceLeft(Label label, std::vector<int32> *phone_seq);
+
+ /// This utility function does something equivalent to the following 3 steps:
+ /// *full_phone_sequence = seq;
+ /// full_phone_sequence->append(label)
+ /// Replace any values equal to 'subsequential_symbol_' in
+ /// full_phone_sequence with zero (this is to avoid having to keep track of
+ /// the value of 'subsequential_symbol_' outside of this program).
+ /// This function assumes that seq.size() == context_width_ - 1, and also that
+ /// 'subsequential_symbol_' does not appear in positions 0 through
+ /// central_position_ of 'seq'.
+ inline void GetFullPhoneSequence(const std::vector<int32> &seq, Label label,
+ std::vector<int32> *full_phone_sequence);
+
+ // Map type to map from vectors of int32 (representing phonetic contexts,
+ // which will be of dimension context_width - 1) to StateId (corresponding to
+ // the state index in this FST).
+ typedef unordered_map<std::vector<int32>, StateId,
+ kaldi::VectorHasher<int32> > VectorToStateMap;
+
+ // Map type to map from vectors of int32 (representing ilabel-info,
+ // see http://kaldi-asr.org/doc/tree_externals.html#tree_ilabel) to
+ // Label (the output label in this FST).
+ typedef unordered_map<std::vector<int32>, Label,
+ kaldi::VectorHasher<int32> > VectorToLabelMap;
+
+
+ // Sometimes called N, context_width_ this is the width of the
+ // phonetic context, e.g. 3 for triphone, 2 for biphone, one for monophone.
+ // It is a user-specified value.
+ int32 context_width_;
+
+ // Sometimes called P, central_position_ is is the (zero-based) "central
+ // position" in the context window, meaning the phone that is "in" a certain
+ // context. The most widely used values of (context-width, central-position)
+ // are: (3,1) for triphone, (1,0) for monophone, and (2, 1) for left biphone.
+ // This is also specified by the user. As an example, in the left-biphone
+ // [ 5, 6 ], we view it as "the phone numbered 6 with the phone numbered 5 as
+ // its left-context".
+ int32 central_position_;
+
+ // The following three variables were also passed in by the caller:
+
+ // 'phone_syms_' are a set of phone-ids, typically 1, 2, .. num_phones.
+ kaldi::ConstIntegerSet<Label> phone_syms_;
+
+ // disambig_syms_ is the set of integer ids of the disambiguation symbols,
+ // usually represented in text form as #0, #1, #2, etc. These are inserted
+ // into the grammar (for #0) and the lexicon (for #1, #2, ...) in order to
+ // make the composed FSTs determinizable. They are treated "specially" by the
+ // context FST in that they are not part of the context, they are just "passed
+ // through" via self-loops. See the Mohri chapter mrentioned above for more
+ // information.
+ kaldi::ConstIntegerSet<Label> disambig_syms_;
+
+ // subsequential_symbol_, represented as "$" in the Mohri chapter mentioned
+ // above, is something which terminates phonetic sequences to force out the
+ // last phones-in-context. In our implementation it's added to det(LG) as a
+ // self-loop on final states before composing with C.
+ // (c.f. AddSubsequentialLoop()).
+ Label subsequential_symbol_;
+
+
+ // pseudo_eps_symbol_, which in printed form we refer to as "#-1", is a symbol that
+ // appears on the ilabels of the context transducer C, i.e. the olabels of this
+ // FST which is C's inverse. It is a symbol we introduce to solve a special problem
+ // in systems with right-context (context_width_ > central_position_ + 1) that
+ // use disambiguation symbols. It exists to prevent CLG from being nondeterminizable.
+ //
+ // The issue is that, in this case, the disambiguation symbols are shifted
+ // left w.r.t. the phones, and there becomes an ambiguity, if a disambiguation
+ // symbol appears at the start of a sequence on the input of CLG, about
+ // whether it was at the very start of the input of LG, or just after, say,
+ // the first real phone. This can lead to determinization failure under
+ // certain circumstances. What we do if we need pseudo_eps_symbol_ to be not
+ // epsilon, we create a special symbol with symbol-id 1 and sequence
+ // representation (ilabels entry) [ 0 ] .
+ int32 pseudo_eps_symbol_;
+
+ // maps from vector<int32>, representing phonetic contexts of length
+ // context_width_ - 1, to StateId. (The states of the "C" fst correspond to
+ // phonetic contexts, but we only create them as and when they are needed).
+ VectorToStateMap state_map_;
+
+ // The inverse of 'state_map_': gives us the phonetic context corresponding to
+ // each state-id.
+ std::vector<std::vector<int32> > state_seqs_;
+
+ // maps from vector<int32>, representing phonetic contexts of length
+ // context_width_ - 1, to Label. These are actually the output labels of this
+ // InverseContextFst (because of the "Inverse" part), but for historical
+ // reasons and because we've used the term ilabels" in the documentation, we
+ // still call these "ilabels").
+ VectorToLabelMap ilabel_map_;
+
+ // ilabel_info_ is the reverse map of ilabel_map_.
+ // Indexed by olabel (although we call this ilabel_info_ for historical
+ // reasons and because is for the ilabels of C), ilabel_info_[i] gives
+ // information about the meaning of each symbol on the input of C
+ // aka the output of inv(C).
+ // See "http://kaldi-asr.org/doc/tree_externals.html#tree_ilabel".
+ std::vector<std::vector<int32> > ilabel_info_;
+
+};
+
+} // namespace fst
+
+
+#endif // KALDI_FSTEXT_CONTEXT_FST_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/deterministic-fst-inl.h b/runtime/onnxruntime/third_party/kaldi/fstext/deterministic-fst-inl.h
new file mode 100644
index 000000000..84eafe41e
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/deterministic-fst-inl.h
@@ -0,0 +1,512 @@
+// fstext/deterministic-fst-inl.h
+
+// Copyright 2011-2012 Gilles Boulianne
+// 2014 Telepoint Global Hosting Service, LLC. (Author: David Snyder)
+// 2012-2015 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_DETERMINISTIC_FST_INL_H_
+#define KALDI_FSTEXT_DETERMINISTIC_FST_INL_H_
+#include "base/kaldi-common.h"
+#include "fstext/fstext-utils.h"
+
+
+namespace fst {
+// Do not include this file directly. It is included by deterministic-fst.h.
+
+template<class Arc>
+typename Arc::StateId
+BackoffDeterministicOnDemandFst<Arc>::GetBackoffState(StateId s,
+ Weight *w) {
+ ArcIterator<Fst<Arc> > aiter(fst_, s);
+ if (aiter.Done()) // no arcs.
+ return kNoStateId;
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel == 0) {
+ *w = arc.weight;
+ return arc.nextstate;
+ } else {
+ return kNoStateId;
+ }
+}
+
+template<class Arc>
+typename Arc::Weight BackoffDeterministicOnDemandFst<Arc>::Final(StateId state) {
+ Weight w = fst_.Final(state);
+ if (w != Weight::Zero()) return w;
+ Weight backoff_w;
+ StateId backoff_state = GetBackoffState(state, &backoff_w);
+ if (backoff_state == kNoStateId) return Weight::Zero();
+ else return Times(backoff_w, this->Final(backoff_state));
+}
+
+template<class Arc>
+BackoffDeterministicOnDemandFst<Arc>::BackoffDeterministicOnDemandFst(
+ const Fst<Arc> &fst): fst_(fst) {
+#ifdef KALDI_PARANOID
+ KALDI_ASSERT(fst_.Properties(kILabelSorted|kIDeterministic, true) ==
+ (kILabelSorted|kIDeterministic) &&
+ "Input FST is not i-label sorted and deterministic.");
+#endif
+}
+
+template<class Arc>
+bool BackoffDeterministicOnDemandFst<Arc>::GetArc(
+ StateId s, Label ilabel, Arc *oarc) {
+ KALDI_ASSERT(ilabel != 0); // We don't allow GetArc for epsilon.
+
+ SortedMatcher<Fst<Arc> > sm(fst_, MATCH_INPUT, 1);
+ sm.SetState(s);
+ if (sm.Find(ilabel)) {
+ const Arc &arc = sm.Value();
+ *oarc = arc;
+ return true;
+ } else {
+ Weight backoff_w;
+ StateId backoff_state = GetBackoffState(s, &backoff_w);
+ if (backoff_state == kNoStateId) return false;
+ if (!this->GetArc(backoff_state, ilabel, oarc)) return false;
+ oarc->weight = Times(oarc->weight, backoff_w);
+ return true;
+ }
+}
+
+template<class Arc>
+UnweightedNgramFst<Arc>::UnweightedNgramFst(int n): n_(n) {
+ // Starting state is an empty vector
+ std::vector<Label> start_state;
+ state_vec_.push_back(start_state);
+ start_state_ = 0;
+ state_map_[start_state] = 0;
+}
+
+template<class Arc>
+bool UnweightedNgramFst<Arc>::GetArc(
+ StateId s, Label ilabel, Arc *oarc) {
+
+ // The state ids increment with each state we encounter.
+ // if the assert fails, then we are trying to access
+ // unseen states that are not immediately traversable.
+ KALDI_ASSERT(static_cast<size_t>(s) < state_vec_.size());
+ std::vector<Label> seq = state_vec_[s];
+ // Update state info.
+ seq.push_back(ilabel);
+ if (seq.size() > n_-1) {
+ // Remove oldest word in the history.
+ seq.erase(seq.begin());
+ }
+ std::pair<const std::vector<Label>, StateId> new_state(
+ seq,
+ static_cast<Label>(state_vec_.size()));
+ // Now get state id for destination state.
+ typedef typename MapType::iterator IterType;
+ std::pair<IterType, bool> result = state_map_.insert(new_state);
+ if (result.second == true) {
+ state_vec_.push_back(seq);
+ }
+ oarc->weight = Weight::One(); // Because the FST is unweightd.
+ oarc->ilabel = ilabel;
+ oarc->olabel = ilabel;
+ oarc->nextstate = result.first->second; // The next state id.
+ // All arcs can be matched.
+ return true;
+}
+
+template<class Arc>
+typename Arc::Weight UnweightedNgramFst<Arc>::Final(StateId state) {
+ KALDI_ASSERT(state < static_cast<StateId>(state_vec_.size()));
+ return Weight::One();
+}
+
+template<class Arc>
+ComposeDeterministicOnDemandFst<Arc>::ComposeDeterministicOnDemandFst(
+ DeterministicOnDemandFst<Arc> *fst1,
+ DeterministicOnDemandFst<Arc> *fst2): fst1_(fst1), fst2_(fst2) {
+ KALDI_ASSERT(fst1 != NULL && fst2 != NULL);
+ if (fst1_->Start() == -1 || fst2_->Start() == -1) {
+ start_state_ = -1;
+ next_state_ = 0; // actually we don't care about this value.
+ } else {
+ start_state_ = 0;
+ std::pair<StateId,StateId> start_pair(fst1_->Start(), fst2_->Start());
+ state_map_[start_pair] = start_state_;
+ state_vec_.push_back(start_pair);
+ next_state_ = 1;
+ }
+}
+
+template<class Arc>
+typename Arc::Weight ComposeDeterministicOnDemandFst<Arc>::Final(StateId s) {
+ KALDI_ASSERT(s < static_cast<StateId>(state_vec_.size()));
+ const std::pair<StateId, StateId> &pr (state_vec_[s]);
+ return Times(fst1_->Final(pr.first), fst2_->Final(pr.second));
+}
+
+template<class Arc>
+bool ComposeDeterministicOnDemandFst<Arc>::GetArc(StateId s, Label ilabel,
+ Arc *oarc) {
+ typedef typename MapType::iterator IterType;
+ KALDI_ASSERT(ilabel != 0 &&
+ "This program expects epsilon-free compact lattices as input");
+ KALDI_ASSERT(s < static_cast<StateId>(state_vec_.size()));
+ const std::pair<StateId, StateId> pr (state_vec_[s]);
+
+ Arc arc1;
+ if (!fst1_->GetArc(pr.first, ilabel, &arc1)) return false;
+ if (arc1.olabel == 0) { // There is no output label on the
+ // arc, so only the first state changes.
+ std::pair<const std::pair<StateId, StateId>, StateId> new_value(
+ std::pair<StateId, StateId>(arc1.nextstate, pr.second),
+ next_state_);
+
+ std::pair<IterType, bool> result = state_map_.insert(new_value);
+ oarc->ilabel = ilabel;
+ oarc->olabel = 0;
+ oarc->nextstate = result.first->second;
+ oarc->weight = arc1.weight;
+ if (result.second == true) { // was inserted
+ next_state_++;
+ const std::pair<StateId, StateId> &new_pair (new_value.first);
+ state_vec_.push_back(new_pair);
+ }
+ return true;
+ }
+ // There is an output label, so we need to traverse an arc on the
+ // second fst also.
+ Arc arc2;
+ if (!fst2_->GetArc(pr.second, arc1.olabel, &arc2)) return false;
+ std::pair<const std::pair<StateId, StateId>, StateId> new_value(
+ std::pair<StateId, StateId>(arc1.nextstate, arc2.nextstate),
+ next_state_);
+ std::pair<IterType, bool> result =
+ state_map_.insert(new_value);
+ oarc->ilabel = ilabel;
+ oarc->olabel = arc2.olabel;
+ oarc->nextstate = result.first->second;
+ oarc->weight = Times(arc1.weight, arc2.weight);
+ if (result.second == true) { // was inserted
+ next_state_++;
+ const std::pair<StateId, StateId> &new_pair (new_value.first);
+ state_vec_.push_back(new_pair);
+ }
+ return true;
+}
+
+template<class Arc>
+inline size_t CacheDeterministicOnDemandFst<Arc>::GetIndex(
+ StateId src_state, Label ilabel) {
+ const StateId p1 = 26597, p2 = 50329; // these are two
+ // values that I drew at random from a table of primes.
+ // note: num_cached_arcs_ > 0.
+
+ // We cast to size_t before the modulus, to ensure the
+ // result is positive.
+ return static_cast<size_t>(src_state * p1 + ilabel * p2) %
+ static_cast<size_t>(num_cached_arcs_);
+}
+
+template<class Arc>
+CacheDeterministicOnDemandFst<Arc>::CacheDeterministicOnDemandFst(
+ DeterministicOnDemandFst<Arc> *fst,
+ StateId num_cached_arcs): fst_(fst),
+ num_cached_arcs_(num_cached_arcs),
+ cached_arcs_(num_cached_arcs) {
+ KALDI_ASSERT(num_cached_arcs > 0);
+ for (StateId i = 0; i < num_cached_arcs; i++)
+ cached_arcs_[i].first = kNoStateId; // Invalidate all elements of the cache.
+}
+
+template<class Arc>
+bool CacheDeterministicOnDemandFst<Arc>::GetArc(StateId s, Label ilabel,
+ Arc *oarc) {
+ // Note: we don't cache anything in case a requested arc does not exist.
+ // In the uses that we imagine this will be put to, essentially all the
+ // requested arcs will exist. This only affects efficiency.
+ KALDI_ASSERT(s >= 0 && ilabel != 0);
+ size_t index = this->GetIndex(s, ilabel);
+ if (cached_arcs_[index].first == s &&
+ cached_arcs_[index].second.ilabel == ilabel) {
+ *oarc = cached_arcs_[index].second;
+ return true;
+ } else {
+ Arc arc;
+ if (fst_->GetArc(s, ilabel, &arc)) {
+ cached_arcs_[index].first = s;
+ cached_arcs_[index].second = arc;
+ *oarc = arc;
+ return true;
+ } else {
+ return false;
+ }
+ }
+}
+
+template<class Arc>
+LmExampleDeterministicOnDemandFst<Arc>::LmExampleDeterministicOnDemandFst(
+ void *lm, Label bos_symbol, Label eos_symbol):
+ lm_(lm), bos_symbol_(bos_symbol), eos_symbol_(eos_symbol) {
+ std::vector<Label> begin_state; // history state corresponding to beginning of sentence
+ begin_state.push_back(bos_symbol); // Depending how your LM is set up, you might
+ // want to have a history vector with more than one bos_symbol on it.
+
+ state_vec_.push_back(begin_state);
+ start_state_ = 0;
+ state_map_[begin_state] = 0;
+}
+
+template<class Arc>
+typename Arc::Weight LmExampleDeterministicOnDemandFst<Arc>::Final(StateId s) {
+ KALDI_ASSERT(static_cast<size_t>(s) < state_vec_.size());
+ // In a real version you would probably use the following variable somehow
+ // (commenting it because it's generating warnings).
+ // const std::vector<Label> &wseq = state_vec_[s];
+ float log_prob = -0.5; // e.g. log_prob = lm->GetLogProb(wseq, eos_symbol_);
+ return Weight(-log_prob); // assuming weight is FloatWeight.
+}
+
+template<class Arc>
+bool LmExampleDeterministicOnDemandFst<Arc>::GetArc(
+ StateId s, Label ilabel, Arc *oarc) {
+ KALDI_ASSERT(static_cast<size_t>(s) < state_vec_.size());
+ std::vector<Label> wseq = state_vec_[s];
+ float log_prob = -0.25; // e.g. log_prob = lm->GetLogProb(wseq, ilabel);
+ wseq.push_back(ilabel); // the code might be different if your histories are the
+ // other way around.
+
+ while (0) { // e.g. while !lm->HistoryStateExists(wseq)
+ wseq.erase(wseq.begin(), wseq.begin() + 1); // remove most distant element of history.
+ // note: if your histories are the other way round, you might just do
+ // wseq.pop() here.
+ }
+ if (log_prob == -std::numeric_limits<float>::infinity()) { // assume this
+ // is what happens if prob of the word is zero. Some LMs will never
+ // return zero.
+ return false; // no arc.
+ }
+ std::pair<const std::vector<Label>, StateId> new_value(
+ wseq,
+ static_cast<Label>(state_vec_.size()));
+
+ // Now get state id for destination state.
+ typedef typename MapType::iterator IterType;
+ std::pair<IterType, bool> result = state_map_.insert(new_value);
+ if (result.second == true) // was inserted
+ state_vec_.push_back(wseq);
+ oarc->ilabel = ilabel;
+ oarc->olabel = ilabel;
+ oarc->nextstate = result.first->second; // the next-state id.
+ oarc->weight = Weight(-log_prob);
+ return true;
+}
+
+
+template<class Arc>
+void ComposeDeterministicOnDemand(const Fst<Arc> &fst1,
+ DeterministicOnDemandFst<Arc> *fst2,
+ MutableFst<Arc> *fst_composed) {
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId StateId;
+ typedef std::pair<StateId, StateId> StatePair;
+ typedef unordered_map<StatePair, StateId,
+ kaldi::PairHasher<StateId> > MapType;
+ typedef typename MapType::iterator IterType;
+
+ fst_composed->DeleteStates();
+
+ MapType state_map;
+ std::queue<StatePair> state_queue;
+
+ // Set start state in fst_composed.
+ StateId s1 = fst1.Start(),
+ s2 = fst2->Start(),
+ start_state = fst_composed->AddState();
+ StatePair start_pair(s1, s2);
+ state_queue.push(start_pair);
+ fst_composed->SetStart(start_state);
+ // A mapping between pairs of states in fst1 and fst2 and the corresponding
+ // state in fst_composed.
+ std::pair<const StatePair, StateId> start_map(start_pair, start_state);
+ std::pair<IterType, bool> result = state_map.insert(start_map);
+ KALDI_ASSERT(result.second == true);
+
+ while (!state_queue.empty()) {
+ StatePair q = state_queue.front();
+ StateId q1 = q.first,
+ q2 = q.second;
+ state_queue.pop();
+ // If the product of the final weights of the two fsts is non-zero then
+ // we can set a final-prob in fst_composed
+ Weight final_weight = Times(fst1.Final(q1), fst2->Final(q2));
+ if (final_weight != Weight::Zero()) {
+ KALDI_ASSERT(state_map.find(q) != state_map.end());
+ fst_composed->SetFinal(state_map[q], final_weight);
+ }
+
+ // for each pair of edges from fst1 and fst2 at q1 and q2.
+ for (ArcIterator<Fst<Arc> > aiter(fst1, q1); !aiter.Done(); aiter.Next()) {
+ const Arc &arc1 = aiter.Value();
+ Arc arc2;
+ StatePair next_pair;
+ StateId next_state1 = arc1.nextstate,
+ next_state2,
+ next_state;
+ // If there is an epsilon on the arc of fst1 we transition to the next
+ // state but keep fst2 at the current state.
+ if (arc1.olabel == 0) {
+ next_state2 = q2;
+ } else {
+ bool match = fst2->GetArc(q2, arc1.olabel, &arc2);
+ if (!match) // There is no matching arc -> nothing to do.
+ continue;
+ next_state2 = arc2.nextstate;
+ }
+ next_pair = StatePair(next_state1, next_state2);
+ IterType sitr = state_map.find(next_pair);
+ // If sitr == state_map.end() then the state isn't in fst_composed yet.
+ if (sitr == state_map.end()) {
+ next_state = fst_composed->AddState();
+ std::pair<const StatePair, StateId> new_state(
+ next_pair, next_state);
+ std::pair<IterType, bool> result = state_map.insert(new_state);
+ // Since we already checked if state_map contained new_state,
+ // it should always be added if we reach here.
+ KALDI_ASSERT(result.second == true);
+ state_queue.push(next_pair);
+ // If sitr != state_map.end() then the next state is already in
+ // the state_map.
+ } else {
+ next_state = sitr->second;
+ }
+ if (arc1.olabel == 0) {
+ fst_composed->AddArc(state_map[q], Arc(arc1.ilabel, 0, arc1.weight,
+ next_state));
+ } else {
+ fst_composed->AddArc(state_map[q], Arc(arc1.ilabel, arc2.olabel,
+ Times(arc1.weight, arc2.weight), next_state));
+ }
+ }
+ }
+}
+
+
+// we are doing *fst_composed = Compose(Inverse(*left), right).
+template<class Arc>
+void ComposeDeterministicOnDemandInverse(const Fst<Arc> &right,
+ DeterministicOnDemandFst<Arc> *left,
+ MutableFst<Arc> *fst_composed) {
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId StateId;
+ typedef std::pair<StateId, StateId> StatePair;
+ typedef unordered_map<StatePair, StateId,
+ kaldi::PairHasher<StateId> > MapType;
+ typedef typename MapType::iterator IterType;
+
+ fst_composed->DeleteStates();
+
+ // the queue and map contain pairs (state-in-left, state-in-right)
+ MapType state_map;
+ std::queue<StatePair> state_queue;
+
+ // Set start state in fst_composed.
+ StateId s_left = left->Start(),
+ s_right = right.Start();
+ if (s_left == kNoStateId || s_right == kNoStateId)
+ return; // Empty result.
+ StatePair start_pair(s_left, s_right);
+ StateId start_state = fst_composed->AddState();
+ state_queue.push(start_pair);
+ fst_composed->SetStart(start_state);
+ // A mapping between pairs of states in *left and right, and the corresponding
+ // state in fst_composed.
+ std::pair<const StatePair, StateId> start_map(start_pair, start_state);
+ std::pair<IterType, bool> result = state_map.insert(start_map);
+ KALDI_ASSERT(result.second == true);
+
+ while (!state_queue.empty()) {
+ StatePair q = state_queue.front();
+ StateId q_left = q.first,
+ q_right = q.second;
+ state_queue.pop();
+ // If the product of the final weights of the two fsts is non-zero then
+ // we can set a final-prob in fst_composed
+ Weight final_weight = Times(left->Final(q_left), right.Final(q_right));
+ if (final_weight != Weight::Zero()) {
+ KALDI_ASSERT(state_map.find(q) != state_map.end());
+ fst_composed->SetFinal(state_map[q], final_weight);
+ }
+
+ for (ArcIterator<Fst<Arc> > aiter(right, q_right); !aiter.Done(); aiter.Next()) {
+ const Arc &arc_right = aiter.Value();
+ Arc arc_left;
+ StatePair next_pair;
+ StateId next_state_right = arc_right.nextstate,
+ next_state_left,
+ next_state;
+ // If there is an epsilon on the input side of the rigth arc, we
+ // transition to the next state of the output but keep 'left' at the
+ // current state.
+ if (arc_right.ilabel == 0) {
+ next_state_left = q_left;
+ } else {
+ bool match = left->GetArc(q_left, arc_right.ilabel, &arc_left);
+ if (!match) // There is no matching arc -> nothing to do.
+ continue;
+ // the next 'swap' is because we are composing with the inverse of
+ // *left. Just removing the swap statement wouldn't let us compose
+ // with non-inverted *left though, because the GetArc function call
+ // above interprets the second argument as an ilabel not an olabel.
+ std::swap(arc_left.ilabel, arc_left.olabel);
+ next_state_left = arc_left.nextstate;
+ }
+ next_pair = StatePair(next_state_left, next_state_right);
+ IterType sitr = state_map.find(next_pair);
+ // If sitr == state_map.end() then the state isn't in fst_composed yet.
+ if (sitr == state_map.end()) {
+ next_state = fst_composed->AddState();
+ std::pair<const StatePair, StateId> new_state(
+ next_pair, next_state);
+ std::pair<IterType, bool> result = state_map.insert(new_state);
+ // Since we already checked if state_map contained new_state,
+ // it should always be added if we reach here.
+ KALDI_ASSERT(result.second == true);
+ state_queue.push(next_pair);
+ // If sitr != state_map.end() then the next state is already in
+ // the state_map.
+ } else {
+ next_state = sitr->second;
+ }
+ if (arc_right.ilabel == 0) {
+ // we didn't get an actual arc from the left FST.
+ fst_composed->AddArc(state_map[q], Arc(0, arc_right.olabel,
+ arc_right.weight,
+ next_state));
+ } else {
+ fst_composed->AddArc(state_map[q],
+ Arc(arc_left.ilabel, arc_right.olabel,
+ Times(arc_left.weight, arc_right.weight),
+ next_state));
+ }
+ }
+ }
+}
+
+
+
+} // end namespace fst
+
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/deterministic-fst-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/deterministic-fst-test.cc
new file mode 100644
index 000000000..25c4eab9c
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/deterministic-fst-test.cc
@@ -0,0 +1,232 @@
+// fstext/deterministic-fst-test.cc
+
+// Copyright 2009-2011 Gilles Boulianne
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "fstext/deterministic-fst.h"
+#include "fstext/fst-test-utils.h"
+#include "util/kaldi-io.h"
+
+#include <sys/stat.h>
+
+namespace fst {
+using std::cout;
+using std::cerr;
+using std::endl;
+
+bool FileExists(std::string strFilename) {
+ struct stat stFileInfo;
+ bool blnReturn;
+ int intStat;
+
+ // Attempt to get the file attributes
+ intStat = stat(strFilename.c_str(), &stFileInfo);
+ if (intStat == 0) {
+ // We were able to get the file attributes
+ // so the file obviously exists.
+ blnReturn = true;
+ } else {
+ // We were not able to get the file attributes.
+ // This may mean that we don't have permission to
+ // access the folder which contains this file. If you
+ // need to do that level of checking, lookup the
+ // return values of stat which will give you
+ // more details on why stat failed.
+ blnReturn = false;
+ }
+
+ return blnReturn;
+}
+
+// Simplify writing
+typedef fst::StdArc StdArc;
+typedef fst::StdArc::Label Label;
+typedef fst::StdArc::StateId StateId;
+typedef fst::StdVectorFst StdVectorFst;
+typedef fst::StdArc::Weight Weight;
+
+
+// something that looks like a language model FST with epsilon backoffs
+StdVectorFst* CreateBackoffFst() {
+ StdVectorFst *fst = new StdVectorFst();
+ fst->AddState(); // state 0
+ fst->SetStart(0);
+ fst->AddArc(0, StdArc(10, 10, 0.0, 1));
+
+ fst->AddState(); // state 1
+ fst->AddArc(1, StdArc(12, 12, 0.0, 4));
+ fst->AddArc(1, StdArc(0,0, 0.1,2)); // backoff from 1 to 2
+
+ fst->AddState(); // state 2
+ fst->AddArc(2, StdArc(13, 13, 0.2, 4));
+ fst->AddArc(2, StdArc(0,0, 0.3,3)); // backoff from 2 to 3
+
+ fst->AddState(); // state 3
+ fst->AddArc(3, StdArc(14, 14, 0.4, 4));
+
+ fst->AddState(); // state 4
+ fst->AddArc(4, StdArc(15, 15, 0.5, 5));
+
+ fst->AddState(); // state 5
+ fst->SetFinal(5, 0.6);
+
+ return fst;
+}
+
+// what the resulting DeterministicOnDemand FST should be like
+StdVectorFst* CreateResultFst() {
+ StdVectorFst *fst = new StdVectorFst();
+ fst->AddState(); // state 0
+ fst->SetStart(0);
+ fst->AddArc(0, StdArc(10, 10, 0.0, 1));
+
+ fst->AddState(); // state 1
+ fst->AddArc(1, StdArc(12, 12, 0.0, 4));
+ fst->AddArc(1, StdArc(13,13,0.3,4)); // went through 1 backoff
+ fst->AddArc(1, StdArc(14,14,0.8,4)); // went through 2 backoffs
+
+ fst->AddState(); // state 2
+ fst->AddState(); // state 3
+
+ fst->AddState(); // state 4
+ fst->AddArc(4, StdArc(15, 15, 0.5, 5));
+
+ fst->AddState(); // state 5
+ fst->SetFinal(5, 0.6);
+
+ return fst;
+}
+
+void DeleteTestFst(StdVectorFst *fst) {
+ delete fst;
+}
+
+// Follow paths from an input fst representing a string
+// (poor man's composition)
+Weight WalkSinglePath(StdVectorFst *ifst, DeterministicOnDemandFst<StdArc> *dfst) {
+ StdArc oarc; // = new StdArc();
+ StateId isrc=ifst->Start();
+ StateId dsrc=dfst->Start();
+ Weight totalCost = Weight::One();
+
+ while (ifst->Final(isrc) == Weight::Zero()) { // while not final
+ fst::ArcIterator<StdVectorFst> aiter(*ifst, isrc);
+ const StdArc &iarc = aiter.Value();
+ if (dfst->GetArc(dsrc, iarc.olabel, &oarc)) {
+ Weight cost = Times(iarc.weight, oarc.weight);
+ // cout << " Matched label "<<iarc.olabel<<" at summed cost "<<cost<<endl;
+ totalCost = Times(totalCost, cost);
+ } else {
+ cout << " Can't match arc ["<<iarc.ilabel<<","<<iarc.olabel<<","<<iarc.weight<<"] from "<<isrc<<endl;
+ exit(1);
+ }
+ isrc = iarc.nextstate;
+ KALDI_LOG << "Setting dsrc = " << oarc.nextstate;
+ dsrc = oarc.nextstate;
+ }
+ totalCost = Times(totalCost, dfst->Final(dsrc));
+
+ cout << " Total cost: " << totalCost << endl;
+ return totalCost;
+}
+
+
+void TestBackoffAndCache() {
+ // Build from existing fst
+ cout << "Test with single generated backoff FST" << endl;
+ StdVectorFst *nfst = CreateBackoffFst();
+ StdVectorFst *rfst = CreateResultFst();
+
+ // before using, make sure that it is input sorted
+ ArcSort(nfst, StdILabelCompare());
+ BackoffDeterministicOnDemandFst<StdArc> dfst1a(*nfst);
+ CacheDeterministicOnDemandFst<StdArc> dfst1(&dfst1a);
+
+ // Compare all arcs in dfst1 with expected result
+ for (StateIterator<StdVectorFst> riter(*rfst); !riter.Done(); riter.Next()) {
+ StateId rsrc = riter.Value();
+ // verify that states have same weight (or final status)
+ assert(ApproxEqual(rfst->Final(rsrc), dfst1.Final(rsrc)));
+ for (ArcIterator<StdVectorFst> aiter(*rfst, rsrc); !aiter.Done(); aiter.Next()) {
+ StdArc rarc = aiter.Value();
+ StdArc darc;
+ if (dfst1.GetArc(rsrc, rarc.ilabel, &darc)) {
+ assert(ApproxEqual(rarc.weight, darc.weight, 0.001));
+ assert(rarc.ilabel==darc.ilabel);
+ assert(rarc.olabel==darc.olabel);
+ assert(rarc.nextstate == darc.nextstate);
+ cerr << " Got same arc at state "<<rsrc<<": "<<rarc.ilabel<<" "<<darc.ilabel<<endl;
+ } else {
+ cerr << "Couldn't find arc "<<rarc.ilabel<<" for state "<<rsrc<<endl;
+ exit(1);
+ }
+ }
+ }
+ delete nfst;
+ delete rfst;
+}
+
+void TestCompose() {
+ cout << "Test with single generated backoff FST" << endl;
+ StdVectorFst *nfst = CreateBackoffFst();
+ StdVectorFst *rfst = CreateResultFst();
+
+ StdVectorFst composed_fst;
+ Compose(*rfst, *rfst, &composed_fst);
+
+ // before using, make sure that it is input sorted
+ ArcSort(nfst, StdILabelCompare());
+ BackoffDeterministicOnDemandFst<StdArc> dfst1a(*nfst);
+ ComposeDeterministicOnDemandFst<StdArc> dfst1b(&dfst1a, &dfst1a);
+ CacheDeterministicOnDemandFst<StdArc> dfst1(&dfst1b);
+
+ typedef StdArc::StateId StateId;
+ std::map<StateId, StateId> state_map;
+ state_map[composed_fst.Start()] = dfst1.Start();
+
+ VectorFst<StdArc> path_fst;
+ ShortestPath(composed_fst, &path_fst);
+
+ BackoffDeterministicOnDemandFst<StdArc> dfst2(composed_fst);
+
+ Weight w1 = WalkSinglePath(&path_fst, &dfst1),
+ w2 = WalkSinglePath(&path_fst, &dfst2);
+ KALDI_ASSERT(ApproxEqual(w1, w2));
+
+ delete rfst;
+ delete nfst;
+
+ { // Mostly checking for compilation errors here.
+ LmExampleDeterministicOnDemandFst<StdArc> lm_eg(NULL, 2, 3);
+ KALDI_ASSERT(lm_eg.Start() == 0);
+ KALDI_ASSERT(lm_eg.Final(0).Value() == 0.5); // I made it this value.
+ StdArc arc;
+ bool b = lm_eg.GetArc(0, 100, &arc);
+ KALDI_ASSERT(b && arc.nextstate == 1 && arc.ilabel == 100 && arc.olabel == 100
+ && arc.weight.Value() == 0.25);
+ }
+}
+
+}
+
+
+int main() {
+ using namespace fst;
+ TestBackoffAndCache();
+ TestCompose();
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/deterministic-fst.h b/runtime/onnxruntime/third_party/kaldi/fstext/deterministic-fst.h
new file mode 100644
index 000000000..5dc616794
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/deterministic-fst.h
@@ -0,0 +1,335 @@
+// fstext/deterministic-fst.h
+
+// Copyright 2011-2012 Gilles Boulianne
+// 2014 Telepoint Global Hosting Service, LLC. (Author: David Snyder)
+// 2012-2015 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+//
+// This file includes material from the OpenFST Library v1.2.7 available at
+// http://www.openfst.org and released under the Apache License Version 2.0.
+//
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// Copyright 2005-2010 Google, Inc.
+// Author: [email protected] (Michael Riley)
+
+#ifndef KALDI_FSTEXT_DETERMINISTIC_FST_H_
+#define KALDI_FSTEXT_DETERMINISTIC_FST_H_
+
+/* This header defines the DeterministicOnDemand interface,
+ which is an FST with a special interface that allows
+ only a single arc with a non-epsilon input symbol
+ out of each state.
+*/
+
+#include <algorithm>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+
+#include "util/stl-utils.h"
+
+namespace fst {
+
+/// \addtogroup deterministic_fst_group "Classes and functions related to on-demand deterministic FST's"
+/// @{
+
+
+/// class DeterministicOnDemandFst is an "FST-like" base-class. It does not
+/// actually inherit from any Fst class because its interface is not exactly the
+/// same; it's much smaller. It assumes that the FST can have only one arc for
+/// any given input symbol, which makes the GetArc function below possible.
+/// (The FST is also assumed to be free of input epsilons). Note: we don't use
+/// "const" in this interface, because it creates problems when we do things
+/// like caching.
+template<class Arc>
+class DeterministicOnDemandFst {
+ public:
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::Label Label;
+
+ virtual StateId Start() = 0;
+
+ virtual Weight Final(StateId s) = 0;
+
+ /// Note: ilabel must not be epsilon.
+ virtual bool GetArc(StateId s, Label ilabel, Arc *oarc) = 0;
+
+ virtual ~DeterministicOnDemandFst() { }
+};
+
+/**
+ This class wraps an Fst, representing a language model, using the interface
+ for "BackoffDeterministicOnDemandFst". We expect that backoff arcs in the
+ language model will have the epsilon label (label 0) on the arcs, and that
+ there will be no other epsilons in the language model. We follow the epsilon
+ arcs as long as a particular arc (or a final-prob) is not found at the
+ current state.
+ */
+template<class Arc>
+class BackoffDeterministicOnDemandFst: public DeterministicOnDemandFst<Arc> {
+ public:
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Label Label;
+
+ explicit BackoffDeterministicOnDemandFst(const Fst<Arc> &fst);
+
+ StateId Start() { return fst_.Start(); }
+
+ Weight Final(StateId s);
+
+ bool GetArc(StateId s, Label ilabel, Arc *oarc);
+
+ private:
+ inline StateId GetBackoffState(StateId s, Weight *w);
+
+ const Fst<Arc> &fst_;
+};
+
+/**
+ Class ScaleDeterministicOnDemandFst takes another DeterministicOnDemandFst
+ and scales the weights (like applying a language-model scale). For instance,
+ to subtract existing LM scores from a lattice you could use this with
+ a negative weight; and to interpolate LMs you can also use this with
+ weights less than one.
+
+ It's specialized for StdArc because there is no generic way to scale weights.
+*/
+class ScaleDeterministicOnDemandFst: public DeterministicOnDemandFst<StdArc> {
+ public:
+ typedef StdArc::Weight Weight;
+ typedef StdArc::StateId StateId;
+ typedef StdArc::Label Label;
+
+ // Constructor does not take ownership of 'det_fst'.
+ ScaleDeterministicOnDemandFst(float scale,
+ DeterministicOnDemandFst<StdArc> *det_fst):
+ scale_(scale), det_fst_(*det_fst) { }
+
+ StateId Start() { return det_fst_.Start(); }
+
+ Weight Final(StateId s) {
+ // Note: Weight is indirectly a typedef to TropicalWeight.
+ Weight final = det_fst_.Final(s);
+ if (final == Weight::Zero()) return Weight::Zero();
+ else return TropicalWeight(final.Value() * scale_);
+ }
+
+ inline bool GetArc(StateId s, Label ilabel, StdArc *oarc) {
+ if (det_fst_.GetArc(s, ilabel, oarc)) {
+ oarc->weight = TropicalWeight(oarc->weight.Value() * scale_);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ private:
+ float scale_;
+ DeterministicOnDemandFst<StdArc> &det_fst_;
+};
+
+/**
+ The class UnweightedNgramFst is a DeterministicOnDemandFst whose states encode
+ an n-gram history. Conceptually, for n-gram order n and k labels, the FST is an
+ unweighted acceptor with about k^(n-1) states (ignoring end effects). However,
+ the FST is created on demand and doesn't need the label vocabulary; GetArc
+ matches on any input label. This class is primarily used together with
+ ComposeDeterministicOnDemandFst to expand the n-gram history of lattices, ensuring
+ that each arc has a sufficiently long unique word history.
+ */
+template<class Arc>
+class UnweightedNgramFst: public DeterministicOnDemandFst<Arc> {
+ public:
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Label Label;
+
+ UnweightedNgramFst(int n);
+
+ StateId Start() { return start_state_; };
+
+ Weight Final(StateId s);
+
+ bool GetArc(StateId s, Label ilabel, Arc *oarc);
+
+ private:
+ typedef unordered_map<std::vector<Label>,
+ StateId, kaldi::VectorHasher<Label> > MapType;
+ // The order of the n-gram.
+ int n_;
+ MapType state_map_;
+ StateId start_state_;
+ // Map from history-state to pair.
+ std::vector<std::vector<Label> > state_vec_;
+};
+
+template<class Arc>
+class ComposeDeterministicOnDemandFst: public DeterministicOnDemandFst<Arc> {
+ public:
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::Label Label;
+
+ /// Note: constructor does not "take ownership" of the input fst's. The input
+ /// fst's should be treated as const, in that their contents do not change,
+ /// but they are not const as the DeterministicOnDemandFst's data-access
+ /// functions are not const, for reasons relating to caching.
+ ComposeDeterministicOnDemandFst(DeterministicOnDemandFst<Arc> *fst1,
+ DeterministicOnDemandFst<Arc> *fst2);
+
+ virtual StateId Start() { return start_state_; }
+
+ virtual Weight Final(StateId s);
+
+ virtual bool GetArc(StateId s, Label ilabel, Arc *oarc);
+
+ private:
+ DeterministicOnDemandFst<Arc> *fst1_;
+ DeterministicOnDemandFst<Arc> *fst2_;
+ typedef unordered_map<std::pair<StateId, StateId>, StateId, kaldi::PairHasher<StateId> > MapType;
+ MapType state_map_;
+ std::vector<std::pair<StateId, StateId> > state_vec_; // maps from
+ // StateId to pair.
+ StateId next_state_;
+ StateId start_state_;
+};
+
+template<class Arc>
+class CacheDeterministicOnDemandFst: public DeterministicOnDemandFst<Arc> {
+ public:
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::Label Label;
+
+ /// We don't take ownership of this pointer. The argument is "really" const.
+ CacheDeterministicOnDemandFst(DeterministicOnDemandFst<Arc> *fst,
+ StateId num_cached_arcs = 100000);
+
+ virtual StateId Start() { return fst_->Start(); }
+
+ /// We don't bother caching the final-probs, just the arcs.
+ virtual Weight Final(StateId s) { return fst_->Final(s); }
+
+ virtual bool GetArc(StateId s, Label ilabel, Arc *oarc);
+
+ private:
+ // Get index for cached arc.
+ inline size_t GetIndex(StateId src_state, Label ilabel);
+
+ DeterministicOnDemandFst<Arc> *fst_;
+ StateId num_cached_arcs_;
+ std::vector<std::pair<StateId, Arc> > cached_arcs_;
+};
+
+
+/// This class is for didactic purposes, it does not really do anything.
+/// It shows how you would wrap a language model. Note: you should probably
+/// have <s> and </s> not be real words in your LM, but <s> correspond somehow
+/// to the initial-state of the LM, and </s> be encoded in the final-probs.
+template<class Arc>
+class LmExampleDeterministicOnDemandFst: public DeterministicOnDemandFst<Arc> {
+ public:
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::Label Label;
+
+ LmExampleDeterministicOnDemandFst(void *lm,
+ Label bos_symbol,
+ Label eos_symbol);
+
+
+ virtual StateId Start() { return start_state_; }
+
+ /// We don't bother caching the final-probs, just the arcs.
+ virtual Weight Final(StateId s);
+
+ virtual bool GetArc(StateId s, Label ilabel, Arc *oarc);
+
+ private:
+ // Get index for cached arc.
+ inline size_t GetIndex(StateId src_state, Label ilabel);
+
+ typedef unordered_map<std::vector<Label>, StateId, kaldi::VectorHasher<Label> > MapType;
+ void *lm_;
+ Label bos_symbol_; // beginning of sentence symbol
+ Label eos_symbol_; // end of sentence symbol.
+ // This example code does not handle <UNK>; we assume the LM has the same vocab as
+ // the recognizer.
+ MapType state_map_;
+ StateId start_state_;
+ std::vector<std::vector<Label> > state_vec_; // maps from history-state to pair.
+
+ void *lm; // wouldn't really be void.
+};
+
+
+// Compose an FST (which may be a lattice) with a DeterministicOnDemandFst and
+// store the result in fst_composed. This is mainly used for expanding lattice
+// n-gram histories, where fst1 is a lattice and fst2 is an UnweightedNgramFst.
+// This does not call Connect.
+template<class Arc>
+void ComposeDeterministicOnDemand(const Fst<Arc> &fst1,
+ DeterministicOnDemandFst<Arc> *fst2,
+ MutableFst<Arc> *fst_composed);
+
+/**
+ This function does
+ '*fst_composed = Compose(Inverse(*fst2), fst1)'
+ Note that the arguments are reversed; this is unfortunate but it's
+ because the fst2 argument needs to be non-const and non-const arguments
+ must follow const ones.
+ This is the counterpart to ComposeDeterministicOnDemand, used for
+ the case where the DeterministicOnDemandFst is on the left. The
+ reason why we need to make the left-hand argument to compose the
+ inverse of 'fst2' (i.e. with the input and output symbols swapped),
+ is that the DeterministicOnDemandFst interface only supports lookup
+ by ilabel (see its function GetArc).
+ This does not call Connect().
+*/
+template<class Arc>
+void ComposeDeterministicOnDemandInverse(const Fst<Arc> &fst1,
+ DeterministicOnDemandFst<Arc> *fst2,
+ MutableFst<Arc> *fst_composed);
+
+
+
+
+/// @}
+
+} // namespace fst
+
+#include "deterministic-fst-inl.h"
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/determinize-lattice-inl.h b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-lattice-inl.h
new file mode 100644
index 000000000..059c9e99b
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-lattice-inl.h
@@ -0,0 +1,1296 @@
+// fstext/determinize-lattice-inl.h
+
+// Copyright 2009-2012 Microsoft Corporation
+// 2012-2013 Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_DETERMINIZE_LATTICE_INL_H_
+#define KALDI_FSTEXT_DETERMINIZE_LATTICE_INL_H_
+// Do not include this file directly. It is included by determinize-lattice.h
+
+#include <vector>
+#include <climits>
+
+namespace fst {
+
+// This class maps back and forth from/to integer id's to sequences of strings.
+// used in determinization algorithm. It is constructed in such a way that
+// finding the string-id of the successor of (string, next-label) has constant time.
+
+// Note: class IntType, typically int32, is the type of the element in the
+// string (typically a template argument of the CompactLatticeWeightTpl).
+
+template<class IntType> class LatticeStringRepository {
+ public:
+ struct Entry {
+ const Entry *parent; // NULL for empty string.
+ IntType i;
+ inline bool operator == (const Entry &other) const {
+ return (parent == other.parent && i == other.i);
+ }
+ Entry() { }
+ Entry(const Entry &e): parent(e.parent), i(e.i) {}
+ };
+ // Note: all Entry* pointers returned in function calls are
+ // owned by the repository itself, not by the caller!
+
+ // Interface guarantees empty string is NULL.
+ inline const Entry *EmptyString() { return NULL; }
+
+ // Returns string of "parent" with i appended. Pointer
+ // owned by repository
+ const Entry *Successor(const Entry *parent, IntType i) {
+ new_entry_->parent = parent;
+ new_entry_->i = i;
+
+ std::pair<typename SetType::iterator, bool> pr = set_.insert(new_entry_);
+ if (pr.second) { // Was successfully inserted (was not there). We need to
+ // replace the element we inserted, which resides on the
+ // stack, with one from the heap.
+ const Entry *ans = new_entry_;
+ new_entry_ = new Entry();
+ return ans;
+ } else { // Was not inserted because an equivalent Entry already
+ // existed.
+ return *pr.first;
+ }
+ }
+
+ const Entry *Concatenate (const Entry *a, const Entry *b) {
+ if (a == NULL) return b;
+ else if (b == NULL) return a;
+ std::vector<IntType> v;
+ ConvertToVector(b, &v);
+ const Entry *ans = a;
+ for(size_t i = 0; i < v.size(); i++)
+ ans = Successor(ans, v[i]);
+ return ans;
+ }
+ const Entry *CommonPrefix (const Entry *a, const Entry *b) {
+ std::vector<IntType> a_vec, b_vec;
+ ConvertToVector(a, &a_vec);
+ ConvertToVector(b, &b_vec);
+ const Entry *ans = NULL;
+ for(size_t i = 0; i < a_vec.size() && i < b_vec.size() &&
+ a_vec[i] == b_vec[i]; i++)
+ ans = Successor(ans, a_vec[i]);
+ return ans;
+ }
+
+ // removes any elements from b that are not part of
+ // a common prefix with a.
+ void ReduceToCommonPrefix(const Entry *a,
+ std::vector<IntType> *b) {
+ size_t a_size = Size(a), b_size = b->size();
+ while (a_size> b_size) {
+ a = a->parent;
+ a_size--;
+ }
+ if (b_size > a_size)
+ b_size = a_size;
+ typename std::vector<IntType>::iterator b_begin = b->begin();
+ while (a_size != 0) {
+ if (a->i != *(b_begin + a_size - 1))
+ b_size = a_size - 1;
+ a = a->parent;
+ a_size--;
+ }
+ if (b_size != b->size())
+ b->resize(b_size);
+ }
+
+ // removes the first n elements of a.
+ const Entry *RemovePrefix(const Entry *a, size_t n) {
+ if (n==0) return a;
+ std::vector<IntType> a_vec;
+ ConvertToVector(a, &a_vec);
+ assert(a_vec.size() >= n);
+ const Entry *ans = NULL;
+ for(size_t i = n; i < a_vec.size(); i++)
+ ans = Successor(ans, a_vec[i]);
+ return ans;
+ }
+
+
+
+ // Returns true if a is a prefix of b. If a is prefix of b,
+ // time taken is |b| - |a|. Else, time taken is |b|.
+ bool IsPrefixOf(const Entry *a, const Entry *b) const {
+ if(a == NULL) return true; // empty string prefix of all.
+ if (a == b) return true;
+ if (b == NULL) return false;
+ return IsPrefixOf(a, b->parent);
+ }
+
+
+ inline size_t Size(const Entry *entry) const {
+ size_t ans = 0;
+ while (entry != NULL) {
+ ans++;
+ entry = entry->parent;
+ }
+ return ans;
+ }
+
+ void ConvertToVector(const Entry *entry, std::vector<IntType> *out) const {
+ size_t length = Size(entry);
+ out->resize(length);
+ if (entry != NULL) {
+ typename std::vector<IntType>::reverse_iterator iter = out->rbegin();
+ while (entry != NULL) {
+ *iter = entry->i;
+ entry = entry->parent;
+ ++iter;
+ }
+ }
+ }
+
+ const Entry *ConvertFromVector(const std::vector<IntType> &vec) {
+ const Entry *e = NULL;
+ for(size_t i = 0; i < vec.size(); i++)
+ e = Successor(e, vec[i]);
+ return e;
+ }
+
+ LatticeStringRepository() { new_entry_ = new Entry; }
+
+ void Destroy() {
+ for (typename SetType::iterator iter = set_.begin();
+ iter != set_.end();
+ ++iter)
+ delete *iter;
+ SetType tmp;
+ tmp.swap(set_);
+ if (new_entry_) {
+ delete new_entry_;
+ new_entry_ = NULL;
+ }
+ }
+
+ // Rebuild will rebuild this object, guaranteeing only
+ // to preserve the Entry values that are in the vector pointed
+ // to (this list does not have to be unique). The point of
+ // this is to save memory.
+ void Rebuild(const std::vector<const Entry*> &to_keep) {
+ SetType tmp_set;
+ for (typename std::vector<const Entry*>::const_iterator
+ iter = to_keep.begin();
+ iter != to_keep.end(); ++iter)
+ RebuildHelper(*iter, &tmp_set);
+ // Now delete all elems not in tmp_set.
+ for (typename SetType::iterator iter = set_.begin();
+ iter != set_.end(); ++iter) {
+ if (tmp_set.count(*iter) == 0)
+ delete (*iter); // delete the Entry; not needed.
+ }
+ set_.swap(tmp_set);
+ }
+
+ ~LatticeStringRepository() { Destroy(); }
+ int32 MemSize() const {
+ return set_.size() * sizeof(Entry) * 2; // this is a lower bound
+ // on the size this structure might take.
+ }
+ private:
+ class EntryKey { // Hash function object.
+ public:
+ inline size_t operator()(const Entry *entry) const {
+ size_t prime = 49109;
+ return static_cast<size_t>(entry->i)
+ + prime * reinterpret_cast<size_t>(entry->parent);
+ }
+ };
+ class EntryEqual {
+ public:
+ inline bool operator()(const Entry *e1, const Entry *e2) const {
+ return (*e1 == *e2);
+ }
+ };
+ typedef std::unordered_set<const Entry*, EntryKey, EntryEqual> SetType;
+
+ void RebuildHelper(const Entry *to_add, SetType *tmp_set) {
+ while(true) {
+ if (to_add == NULL) return;
+ typename SetType::iterator iter = tmp_set->find(to_add);
+ if (iter == tmp_set->end()) { // not in tmp_set.
+ tmp_set->insert(to_add);
+ to_add = to_add->parent; // and loop.
+ } else {
+ return;
+ }
+ }
+ }
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(LatticeStringRepository);
+ Entry *new_entry_; // We always have a pre-allocated Entry ready to use,
+ // to avoid unnecessary news and deletes.
+ SetType set_;
+
+};
+
+
+
+
+// class LatticeDeterminizer is templated on the same types that
+// CompactLatticeWeight is templated on: the base weight (Weight), typically
+// LatticeWeightTpl<float> etc. but could also be e.g. TropicalWeight, and the
+// IntType, typically int32, used for the output symbols in the compact
+// representation of strings [note: the output symbols would usually be
+// p.d.f. id's in the anticipated use of this code] It has a special requirement
+// on the Weight type: that there should be a Compare function on the weights
+// such that Compare(w1, w2) returns -1 if w1 < w2, 0 if w1 == w2, and +1 if w1 >
+// w2. This requires that there be a total order on the weights.
+
+template<class Weight, class IntType> class LatticeDeterminizer {
+ public:
+ // Output to Gallic acceptor (so the strings go on weights, and there is a 1-1 correspondence
+ // between our states and the states in ofst. If destroy == true, release memory as we go
+ // (but we cannot output again).
+
+ typedef CompactLatticeWeightTpl<Weight, IntType> CompactWeight;
+ typedef ArcTpl<CompactWeight> CompactArc; // arc in compact, acceptor form of lattice
+ typedef ArcTpl<Weight> Arc; // arc in non-compact version of lattice
+
+
+ // Output to standard FST with CompactWeightTpl<Weight> as its weight type (the
+ // weight stores the original output-symbol strings). If destroy == true,
+ // release memory as we go (but we cannot output again).
+ void Output(MutableFst<CompactArc> *ofst, bool destroy = true) {
+ assert(determinized_);
+ typedef typename Arc::StateId StateId;
+ StateId nStates = static_cast<StateId>(output_arcs_.size());
+ if (destroy)
+ FreeMostMemory();
+ ofst->DeleteStates();
+ ofst->SetStart(kNoStateId);
+ if (nStates == 0) {
+ return;
+ }
+ for (StateId s = 0;s < nStates;s++) {
+ OutputStateId news = ofst->AddState();
+ assert(news == s);
+ }
+ ofst->SetStart(0);
+ // now process transitions.
+ for (StateId this_state = 0; this_state < nStates; this_state++) {
+ std::vector<TempArc> &this_vec(output_arcs_[this_state]);
+ typename std::vector<TempArc>::const_iterator iter = this_vec.begin(), end = this_vec.end();
+
+ for (;iter != end; ++iter) {
+ const TempArc &temp_arc(*iter);
+ CompactArc new_arc;
+ std::vector<Label> seq;
+ repository_.ConvertToVector(temp_arc.string, &seq);
+ CompactWeight weight(temp_arc.weight, seq);
+ if (temp_arc.nextstate == kNoStateId) { // is really final weight.
+ ofst->SetFinal(this_state, weight);
+ } else { // is really an arc.
+ new_arc.nextstate = temp_arc.nextstate;
+ new_arc.ilabel = temp_arc.ilabel;
+ new_arc.olabel = temp_arc.ilabel; // acceptor. input == output.
+ new_arc.weight = weight; // includes string and weight.
+ ofst->AddArc(this_state, new_arc);
+ }
+ }
+ // Free up memory. Do this inside the loop as ofst is also allocating memory
+ if (destroy) { std::vector<TempArc> temp; std::swap(temp, this_vec); }
+ }
+ if (destroy) { std::vector<std::vector<TempArc> > temp; std::swap(temp, output_arcs_); }
+ }
+
+ // Output to standard FST with Weight as its weight type. We will create extra
+ // states to handle sequences of symbols on the output. If destroy == true,
+ // release memory as we go (but we cannot output again).
+ void Output(MutableFst<Arc> *ofst, bool destroy = true) {
+ // Outputs to standard fst.
+ OutputStateId nStates = static_cast<OutputStateId>(output_arcs_.size());
+ ofst->DeleteStates();
+ if (nStates == 0) {
+ ofst->SetStart(kNoStateId);
+ return;
+ }
+ if (destroy)
+ FreeMostMemory();
+ // Add basic states-- but we will add extra ones to account for strings on output.
+ for (OutputStateId s = 0;s < nStates;s++) {
+ OutputStateId news = ofst->AddState();
+ assert(news == s);
+ }
+ ofst->SetStart(0);
+ for (OutputStateId this_state = 0; this_state < nStates; this_state++) {
+ std::vector<TempArc> &this_vec(output_arcs_[this_state]);
+
+ typename std::vector<TempArc>::const_iterator iter = this_vec.begin(), end = this_vec.end();
+ for (; iter != end; ++iter) {
+ const TempArc &temp_arc(*iter);
+ std::vector<Label> seq;
+ repository_.ConvertToVector(temp_arc.string, &seq);
+
+ if (temp_arc.nextstate == kNoStateId) { // Really a final weight.
+ // Make a sequence of states going to a final state, with the strings
+ // as labels. Put the weight on the first arc.
+ OutputStateId cur_state = this_state;
+ for (size_t i = 0; i < seq.size(); i++) {
+ OutputStateId next_state = ofst->AddState();
+ Arc arc;
+ arc.nextstate = next_state;
+ arc.weight = (i == 0 ? temp_arc.weight : Weight::One());
+ arc.ilabel = 0; // epsilon.
+ arc.olabel = seq[i];
+ ofst->AddArc(cur_state, arc);
+ cur_state = next_state;
+ }
+ ofst->SetFinal(cur_state, (seq.size() == 0 ? temp_arc.weight : Weight::One()));
+ } else { // Really an arc.
+ OutputStateId cur_state = this_state;
+ // Have to be careful with this integer comparison (i+1 < seq.size()) because unsigned.
+ // i < seq.size()-1 could fail for zero-length sequences.
+ for (size_t i = 0; i+1 < seq.size();i++) {
+ // for all but the last element of seq, create new state.
+ OutputStateId next_state = ofst->AddState();
+ Arc arc;
+ arc.nextstate = next_state;
+ arc.weight = (i == 0 ? temp_arc.weight : Weight::One());
+ arc.ilabel = (i == 0 ? temp_arc.ilabel : 0); // put ilabel on first element of seq.
+ arc.olabel = seq[i];
+ ofst->AddArc(cur_state, arc);
+ cur_state = next_state;
+ }
+ // Add the final arc in the sequence.
+ Arc arc;
+ arc.nextstate = temp_arc.nextstate;
+ arc.weight = (seq.size() <= 1 ? temp_arc.weight : Weight::One());
+ arc.ilabel = (seq.size() <= 1 ? temp_arc.ilabel : 0);
+ arc.olabel = (seq.size() > 0 ? seq.back() : 0);
+ ofst->AddArc(cur_state, arc);
+ }
+ }
+ // Free up memory. Do this inside the loop as ofst is also allocating memory
+ if (destroy) {
+ std::vector<TempArc> temp; temp.swap(this_vec);
+ }
+ }
+ if (destroy) {
+ std::vector<std::vector<TempArc> > temp;
+ temp.swap(output_arcs_);
+ repository_.Destroy();
+ }
+ }
+
+
+ // Initializer. After initializing the object you will typically
+ // call Determinize() and then call one of the Output functions.
+ // Note: ifst.Copy() will generally do a
+ // shallow copy. We do it like this for memory safety, rather than
+ // keeping a reference or pointer to ifst_.
+ LatticeDeterminizer(const Fst<Arc> &ifst,
+ DeterminizeLatticeOptions opts):
+ num_arcs_(0), num_elems_(0), ifst_(ifst.Copy()), opts_(opts),
+ equal_(opts_.delta), determinized_(false),
+ minimal_hash_(3, hasher_, equal_), initial_hash_(3, hasher_, equal_) {
+ KALDI_ASSERT(Weight::Properties() & kIdempotent); // this algorithm won't
+ // work correctly otherwise.
+ }
+
+ // frees all except output_arcs_, which contains the important info
+ // we need to output the FST.
+ void FreeMostMemory() {
+ if (ifst_) {
+ delete ifst_;
+ ifst_ = NULL;
+ }
+ for (typename MinimalSubsetHash::iterator iter = minimal_hash_.begin();
+ iter != minimal_hash_.end(); ++iter)
+ delete iter->first;
+ { MinimalSubsetHash tmp; tmp.swap(minimal_hash_); }
+ for (typename InitialSubsetHash::iterator iter = initial_hash_.begin();
+ iter != initial_hash_.end(); ++iter)
+ delete iter->first;
+ { InitialSubsetHash tmp; tmp.swap(initial_hash_); }
+ { std::vector<std::vector<Element>* > output_states_tmp;
+ output_states_tmp.swap(output_states_); }
+ { std::vector<char> tmp; tmp.swap(isymbol_or_final_); }
+ { std::vector<OutputStateId> tmp; tmp.swap(queue_); }
+ { std::vector<std::pair<Label, Element> > tmp; tmp.swap(all_elems_tmp_); }
+ }
+
+ ~LatticeDeterminizer() {
+ FreeMostMemory(); // rest is deleted by destructors.
+ }
+ void RebuildRepository() { // rebuild the string repository,
+ // freeing stuff we don't need.. we call this when memory usage
+ // passes a supplied threshold. We need to accumulate all the
+ // strings we need the repository to "remember", then tell it
+ // to clean the repository.
+ std::vector<StringId> needed_strings;
+ for (size_t i = 0; i < output_arcs_.size(); i++)
+ for (size_t j = 0; j < output_arcs_[i].size(); j++)
+ needed_strings.push_back(output_arcs_[i][j].string);
+
+ // the following loop covers strings present in minimal_hash_
+ // which are also accessible via output_states_.
+ for (size_t i = 0; i < output_states_.size(); i++)
+ for (size_t j = 0; j < output_states_[i]->size(); j++)
+ needed_strings.push_back((*(output_states_[i]))[j].string);
+
+ // the following loop covers strings present in initial_hash_.
+ for (typename InitialSubsetHash::const_iterator
+ iter = initial_hash_.begin();
+ iter != initial_hash_.end(); ++iter) {
+ const std::vector<Element> &vec = *(iter->first);
+ Element elem = iter->second;
+ for (size_t i = 0; i < vec.size(); i++)
+ needed_strings.push_back(vec[i].string);
+ needed_strings.push_back(elem.string);
+ }
+
+ std::sort(needed_strings.begin(), needed_strings.end());
+ needed_strings.erase(std::unique(needed_strings.begin(),
+ needed_strings.end()),
+ needed_strings.end()); // uniq the strings.
+ repository_.Rebuild(needed_strings);
+ }
+
+ bool CheckMemoryUsage() {
+ int32 repo_size = repository_.MemSize(),
+ arcs_size = num_arcs_ * sizeof(TempArc),
+ elems_size = num_elems_ * sizeof(Element),
+ total_size = repo_size + arcs_size + elems_size;
+ if (opts_.max_mem > 0 && total_size > opts_.max_mem) { // We passed the memory threshold.
+ // This is usually due to the repository getting large, so we
+ // clean this out.
+ RebuildRepository();
+ int32 new_repo_size = repository_.MemSize(),
+ new_total_size = new_repo_size + arcs_size + elems_size;
+
+ KALDI_VLOG(2) << "Rebuilt repository in determinize-lattice: repository shrank from "
+ << repo_size << " to " << new_repo_size << " bytes (approximately)";
+
+ if (new_total_size > static_cast<int32>(opts_.max_mem * 0.8)) {
+ // Rebuilding didn't help enough-- we need a margin to stop
+ // having to rebuild too often.
+ KALDI_WARN << "Failure in determinize-lattice: size exceeds maximum "
+ << opts_.max_mem << " bytes; (repo,arcs,elems) = ("
+ << repo_size << "," << arcs_size << "," << elems_size
+ << "), after rebuilding, repo size was " << new_repo_size;
+ return false;
+ }
+ }
+ return true;
+ }
+
+ // Returns true on success. Can fail for out-of-memory
+ // or max-states related reasons.
+ bool Determinize(bool *debug_ptr) {
+ assert(!determinized_);
+ // This determinizes the input fst but leaves it in the "special format"
+ // in "output_arcs_". Must be called after Initialize(). To get the
+ // output, call one of the Output routines.
+ try {
+ InitializeDeterminization(); // some start-up tasks.
+ while (!queue_.empty()) {
+ OutputStateId out_state = queue_.back();
+ queue_.pop_back();
+ ProcessState(out_state);
+ if (debug_ptr && *debug_ptr) Debug(); // will exit.
+ if (!CheckMemoryUsage()) return false;
+ }
+ return (determinized_ = true);
+ } catch (const std::bad_alloc &) {
+ int32 repo_size = repository_.MemSize(),
+ arcs_size = num_arcs_ * sizeof(TempArc),
+ elems_size = num_elems_ * sizeof(Element),
+ total_size = repo_size + arcs_size + elems_size;
+ KALDI_WARN << "Memory allocation error doing lattice determinization; using "
+ << total_size << " bytes (max = " << opts_.max_mem
+ << " (repo,arcs,elems) = ("
+ << repo_size << "," << arcs_size << "," << elems_size << ")";
+ return (determinized_ = false);
+ } catch (const std::runtime_error &) {
+ KALDI_WARN << "Caught exception doing lattice determinization";
+ return (determinized_ = false);
+ }
+ }
+ private:
+
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId; // use this when we don't know if it's input or output.
+ typedef typename Arc::StateId InputStateId; // state in the input FST.
+ typedef typename Arc::StateId OutputStateId; // same as above but distinguish
+ // states in output Fst.
+
+
+ typedef LatticeStringRepository<IntType> StringRepositoryType;
+ typedef const typename StringRepositoryType::Entry* StringId;
+
+ // Element of a subset [of original states]
+ struct Element {
+ StateId state; // use StateId as this is usually InputStateId but in one case
+ // OutputStateId.
+ StringId string;
+ Weight weight;
+ bool operator != (const Element &other) const {
+ return (state != other.state || string != other.string ||
+ weight != other.weight);
+ }
+ // This operator is only intended to support sorting in EpsilonClosure()
+ bool operator < (const Element &other) const {
+ return state < other.state;
+ }
+ };
+
+ // Arcs in the format we temporarily create in this class (a representation, essentially of
+ // a Gallic Fst).
+ struct TempArc {
+ Label ilabel;
+ StringId string; // Look it up in the StringRepository, it's a sequence of Labels.
+ OutputStateId nextstate; // or kNoState for final weights.
+ Weight weight;
+ };
+
+ // Hashing function used in hash of subsets.
+ // A subset is a pointer to vector<Element>.
+ // The Elements are in sorted order on state id, and without repeated states.
+ // Because the order of Elements is fixed, we can use a hashing function that is
+ // order-dependent. However the weights are not included in the hashing function--
+ // we hash subsets that differ only in weight to the same key. This is not optimal
+ // in terms of the O(N) performance but typically if we have a lot of determinized
+ // states that differ only in weight then the input probably was pathological in some way,
+ // or even non-determinizable.
+ // We don't quantize the weights, in order to avoid inexactness in simple cases.
+ // Instead we apply the delta when comparing subsets for equality, and allow a small
+ // difference.
+
+ class SubsetKey {
+ public:
+ size_t operator ()(const std::vector<Element> * subset) const { // hashes only the state and string.
+ size_t hash = 0, factor = 1;
+ for (typename std::vector<Element>::const_iterator iter= subset->begin(); iter != subset->end(); ++iter) {
+ hash *= factor;
+ hash += iter->state + reinterpret_cast<size_t>(iter->string);
+ factor *= 23531; // these numbers are primes.
+ }
+ return hash;
+ }
+ };
+
+ // This is the equality operator on subsets. It checks for exact match on state-id
+ // and string, and approximate match on weights.
+ class SubsetEqual {
+ public:
+ bool operator ()(const std::vector<Element> * s1, const std::vector<Element> * s2) const {
+ size_t sz = s1->size();
+ assert(sz>=0);
+ if (sz != s2->size()) return false;
+ typename std::vector<Element>::const_iterator iter1 = s1->begin(),
+ iter1_end = s1->end(), iter2=s2->begin();
+ for (; iter1 < iter1_end; ++iter1, ++iter2) {
+ if (iter1->state != iter2->state ||
+ iter1->string != iter2->string ||
+ ! ApproxEqual(iter1->weight, iter2->weight, delta_)) return false;
+ }
+ return true;
+ }
+ float delta_;
+ SubsetEqual(float delta): delta_(delta) {}
+ SubsetEqual(): delta_(kDelta) {}
+ };
+
+ // Operator that says whether two Elements have the same states.
+ // Used only for debug.
+ class SubsetEqualStates {
+ public:
+ bool operator ()(const std::vector<Element> * s1, const std::vector<Element> * s2) const {
+ size_t sz = s1->size();
+ assert(sz>=0);
+ if (sz != s2->size()) return false;
+ typename std::vector<Element>::const_iterator iter1 = s1->begin(),
+ iter1_end = s1->end(), iter2=s2->begin();
+ for (; iter1 < iter1_end; ++iter1, ++iter2) {
+ if (iter1->state != iter2->state) return false;
+ }
+ return true;
+ }
+ };
+
+ // Define the hash type we use to map subsets (in minimal
+ // representation) to OutputStateId.
+ typedef std::unordered_map<const std::vector<Element>*, OutputStateId,
+ SubsetKey, SubsetEqual> MinimalSubsetHash;
+
+ // Define the hash type we use to map subsets (in initial
+ // representation) to OutputStateId, together with an
+ // extra weight. [note: we interpret the Element.state in here
+ // as an OutputStateId even though it's declared as InputStateId;
+ // these types are the same anyway].
+ typedef std::unordered_map<const std::vector<Element>*, Element,
+ SubsetKey, SubsetEqual> InitialSubsetHash;
+
+
+ // converts the representation of the subset from canonical (all states) to
+ // minimal (only states with output symbols on arcs leaving them, and final
+ // states). Output is not necessarily normalized, even if input_subset was.
+ void ConvertToMinimal(std::vector<Element> *subset) {
+ assert(!subset->empty());
+ typename std::vector<Element>::iterator cur_in = subset->begin(),
+ cur_out = subset->begin(), end = subset->end();
+ while (cur_in != end) {
+ if(IsIsymbolOrFinal(cur_in->state)) { // keep it...
+ *cur_out = *cur_in;
+ cur_out++;
+ }
+ cur_in++;
+ }
+ subset->resize(cur_out - subset->begin());
+ }
+
+ // Takes a minimal, normalized subset, and converts it to an OutputStateId.
+ // Involves a hash lookup, and possibly adding a new OutputStateId.
+ // If it creates a new OutputStateId, it adds it to the queue.
+ OutputStateId MinimalToStateId(const std::vector<Element> &subset) {
+ typename MinimalSubsetHash::const_iterator iter
+ = minimal_hash_.find(&subset);
+ if (iter != minimal_hash_.end()) // Found a matching subset.
+ return iter->second;
+ OutputStateId ans = static_cast<OutputStateId>(output_arcs_.size());
+ std::vector<Element> *subset_ptr = new std::vector<Element>(subset);
+ output_states_.push_back(subset_ptr);
+ num_elems_ += subset_ptr->size();
+ output_arcs_.push_back(std::vector<TempArc>());
+ minimal_hash_[subset_ptr] = ans;
+ queue_.push_back(ans);
+ return ans;
+ }
+
+
+ // Given a normalized initial subset of elements (i.e. before epsilon closure),
+ // compute the corresponding output-state.
+ OutputStateId InitialToStateId(const std::vector<Element> &subset_in,
+ Weight *remaining_weight,
+ StringId *common_prefix) {
+ typename InitialSubsetHash::const_iterator iter
+ = initial_hash_.find(&subset_in);
+ if (iter != initial_hash_.end()) { // Found a matching subset.
+ const Element &elem = iter->second;
+ *remaining_weight = elem.weight;
+ *common_prefix = elem.string;
+ if (elem.weight == Weight::Zero())
+ KALDI_WARN << "Zero weight!"; // TEMP
+ return elem.state;
+ }
+ // else no matching subset-- have to work it out.
+ std::vector<Element> subset(subset_in);
+ // Follow through epsilons. Will add no duplicate states. note: after
+ // EpsilonClosure, it is the same as "canonical" subset, except not
+ // normalized (actually we never compute the normalized canonical subset,
+ // only the normalized minimal one).
+ EpsilonClosure(&subset); // follow epsilons.
+ ConvertToMinimal(&subset); // remove all but emitting and final states.
+
+ Element elem; // will be used to store remaining weight and string, and
+ // OutputStateId, in initial_hash_;
+ NormalizeSubset(&subset, &elem.weight, &elem.string); // normalize subset; put
+ // common string and weight in "elem". The subset is now a minimal,
+ // normalized subset.
+
+ OutputStateId ans = MinimalToStateId(subset);
+ *remaining_weight = elem.weight;
+ *common_prefix = elem.string;
+ if (elem.weight == Weight::Zero())
+ KALDI_WARN << "Zero weight!"; // TEMP
+
+ // Before returning "ans", add the initial subset to the hash,
+ // so that we can bypass the epsilon-closure etc., next time
+ // we process the same initial subset.
+ std::vector<Element> *initial_subset_ptr = new std::vector<Element>(subset_in);
+ elem.state = ans;
+ initial_hash_[initial_subset_ptr] = elem;
+ num_elems_ += initial_subset_ptr->size(); // keep track of memory usage.
+ return ans;
+ }
+
+ // returns the Compare value (-1 if a < b, 0 if a == b, 1 if a > b) according
+ // to the ordering we defined on strings for the CompactLatticeWeightTpl.
+ // see function
+ // inline int Compare (const CompactLatticeWeightTpl<WeightType,IntType> &w1,
+ // const CompactLatticeWeightTpl<WeightType,IntType> &w2)
+ // in lattice-weight.h.
+ // this is the same as that, but optimized for our data structures.
+ inline int Compare(const Weight &a_w, StringId a_str,
+ const Weight &b_w, StringId b_str) const {
+ int weight_comp = fst::Compare(a_w, b_w);
+ if (weight_comp != 0) return weight_comp;
+ // now comparing strings.
+ if (a_str == b_str) return 0;
+ std::vector<IntType> a_vec, b_vec;
+ repository_.ConvertToVector(a_str, &a_vec);
+ repository_.ConvertToVector(b_str, &b_vec);
+ // First compare their lengths.
+ int a_len = a_vec.size(), b_len = b_vec.size();
+ // use opposite order on the string lengths (c.f. Compare in
+ // lattice-weight.h)
+ if (a_len > b_len) return -1;
+ else if (a_len < b_len) return 1;
+ for(int i = 0; i < a_len; i++) {
+ if (a_vec[i] < b_vec[i]) return -1;
+ else if (a_vec[i] > b_vec[i]) return 1;
+ }
+ assert(0); // because we checked if a_str == b_str above, shouldn't reach here
+ return 0;
+ }
+
+
+ // This function computes epsilon closure of subset of states by following epsilon links.
+ // Called by InitialToStateId and Initialize.
+ // Has no side effects except on the string repository. The "output_subset" is not
+ // necessarily normalized (in the sense of there being no common substring), unless
+ // input_subset was.
+ void EpsilonClosure(std::vector<Element> *subset) {
+ // at input, subset must have only one example of each StateId. [will still
+ // be so at output]. This function follows input-epsilons, and augments the
+ // subset accordingly.
+
+ std::deque<Element> queue;
+ std::unordered_map<InputStateId, Element> cur_subset;
+ typedef typename std::unordered_map<InputStateId, Element>::iterator MapIter;
+ typedef typename std::vector<Element>::const_iterator VecIter;
+
+ for (VecIter iter = subset->begin(); iter != subset->end(); ++iter) {
+ queue.push_back(*iter);
+ cur_subset[iter->state] = *iter;
+ }
+
+ // find whether input fst is known to be sorted on input label.
+ bool sorted = ((ifst_->Properties(kILabelSorted, false) & kILabelSorted) != 0);
+ bool replaced_elems = false; // relates to an optimization, see below.
+ int counter = 0; // stops infinite loops here for non-lattice-determinizable input;
+ // useful in testing.
+ while (queue.size() != 0) {
+ Element elem = queue.front();
+ queue.pop_front();
+
+ // The next if-statement is a kind of optimization. It's to prevent us
+ // unnecessarily repeating the processing of a state. "cur_subset" always
+ // contains only one Element with a particular state. The issue is that
+ // whenever we modify the Element corresponding to that state in "cur_subset",
+ // both the new (optimal) and old (less-optimal) Element will still be in
+ // "queue". The next if-statement stops us from wasting compute by
+ // processing the old Element.
+ if (replaced_elems && cur_subset[elem.state] != elem)
+ continue;
+ if (opts_.max_loop > 0 && counter++ > opts_.max_loop) {
+ KALDI_ERR << "Lattice determinization aborted since looped more than "
+ << opts_.max_loop << " times during epsilon closure";
+ }
+ for (ArcIterator<Fst<Arc> > aiter(*ifst_, elem.state); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (sorted && arc.ilabel != 0) break; // Break from the loop: due to sorting there will be no
+ // more transitions with epsilons as input labels.
+ if (arc.ilabel == 0
+ && arc.weight != Weight::Zero()) { // Epsilon transition.
+ Element next_elem;
+ next_elem.state = arc.nextstate;
+ next_elem.weight = Times(elem.weight, arc.weight);
+ // now must append strings
+ if (arc.olabel == 0)
+ next_elem.string = elem.string;
+ else
+ next_elem.string = repository_.Successor(elem.string, arc.olabel);
+
+ MapIter iter = cur_subset.find(next_elem.state);
+ if (iter == cur_subset.end()) {
+ // was no such StateId: insert and add to queue.
+ cur_subset[next_elem.state] = next_elem;
+ queue.push_back(next_elem);
+ } else {
+ // was not inserted because one already there. In normal determinization we'd
+ // add the weights. Here, we find which one has the better weight, and
+ // keep its corresponding string.
+ int comp = Compare(next_elem.weight, next_elem.string,
+ iter->second.weight, iter->second.string);
+ if(comp == 1) { // next_elem is better, so use its (weight, string)
+ iter->second.string = next_elem.string;
+ iter->second.weight = next_elem.weight;
+ queue.push_back(next_elem);
+ replaced_elems = true;
+ }
+ // else it is the same or worse, so use original one.
+ }
+ }
+ }
+ }
+
+ { // copy cur_subset to subset.
+ subset->clear();
+ subset->reserve(cur_subset.size());
+ MapIter iter = cur_subset.begin(), end = cur_subset.end();
+ for (; iter != end; ++iter) subset->push_back(iter->second);
+ // sort by state ID, because the subset hash function is order-dependent(see SubsetKey)
+ std::sort(subset->begin(), subset->end());
+ }
+ }
+
+
+ // This function works out the final-weight of the determinized state.
+ // called by ProcessSubset.
+ // Has no side effects except on the variable repository_, and output_arcs_.
+
+ void ProcessFinal(OutputStateId output_state) {
+ const std::vector<Element> &minimal_subset = *(output_states_[output_state]);
+ // processes final-weights for this subset.
+
+ // minimal_subset may be empty if the graphs is not connected/trimmed, I think,
+ // do don't check that it's nonempty.
+ bool is_final = false;
+ StringId final_string = NULL; // = NULL to keep compiler happy.
+ Weight final_weight = Weight::Zero();
+ typename std::vector<Element>::const_iterator iter = minimal_subset.begin(), end = minimal_subset.end();
+ for (; iter != end; ++iter) {
+ const Element &elem = *iter;
+ Weight this_final_weight = Times(elem.weight, ifst_->Final(elem.state));
+ StringId this_final_string = elem.string;
+ if (this_final_weight != Weight::Zero() &&
+ (!is_final || Compare(this_final_weight, this_final_string,
+ final_weight, final_string) == 1)) { // the new
+ // (weight, string) pair is more in semiring than our current
+ // one.
+ is_final = true;
+ final_weight = this_final_weight;
+ final_string = this_final_string;
+ }
+ }
+ if (is_final) {
+ // store final weights in TempArc structure, just like a transition.
+ TempArc temp_arc;
+ temp_arc.ilabel = 0;
+ temp_arc.nextstate = kNoStateId; // special marker meaning "final weight".
+ temp_arc.string = final_string;
+ temp_arc.weight = final_weight;
+ output_arcs_[output_state].push_back(temp_arc);
+ num_arcs_++;
+ }
+ }
+
+ // NormalizeSubset normalizes the subset "elems" by
+ // removing any common string prefix (putting it in common_str),
+ // and dividing by the total weight (putting it in tot_weight).
+ void NormalizeSubset(std::vector<Element> *elems,
+ Weight *tot_weight,
+ StringId *common_str) {
+ if(elems->empty()) { // just set common_str, tot_weight
+ KALDI_WARN << "[empty subset]"; // TEMP
+ // to defaults and return...
+ *common_str = repository_.EmptyString();
+ *tot_weight = Weight::Zero();
+ return;
+ }
+ size_t size = elems->size();
+ std::vector<IntType> common_prefix;
+ repository_.ConvertToVector((*elems)[0].string, &common_prefix);
+ Weight weight = (*elems)[0].weight;
+ for (size_t i = 1; i < size; i++) {
+ weight = Plus(weight, (*elems)[i].weight);
+ repository_.ReduceToCommonPrefix((*elems)[i].string, &common_prefix);
+ }
+ assert(weight != Weight::Zero()); // we made sure to ignore arcs with zero
+ // weights on them, so we shouldn't have zero here.
+ size_t prefix_len = common_prefix.size();
+ for (size_t i = 0; i < size; i++) {
+ (*elems)[i].weight = Divide((*elems)[i].weight, weight, DIVIDE_LEFT);
+ (*elems)[i].string =
+ repository_.RemovePrefix((*elems)[i].string, prefix_len);
+ }
+ *common_str = repository_.ConvertFromVector(common_prefix);
+ *tot_weight = weight;
+ }
+
+ // Take a subset of Elements that is sorted on state, and
+ // merge any Elements that have the same state (taking the best
+ // (weight, string) pair in the semiring).
+ void MakeSubsetUnique(std::vector<Element> *subset) {
+ typedef typename std::vector<Element>::iterator IterType;
+
+ // This assert is designed to fail (usually) if the subset is not sorted on
+ // state.
+ assert(subset->size() < 2 || (*subset)[0].state <= (*subset)[1].state);
+
+ IterType cur_in = subset->begin(), cur_out = cur_in, end = subset->end();
+ size_t num_out = 0;
+ // Merge elements with same state-id
+ while (cur_in != end) { // while we have more elements to process.
+ // At this point, cur_out points to location of next place we want to put an element,
+ // cur_in points to location of next element we want to process.
+ if (cur_in != cur_out) *cur_out = *cur_in;
+ cur_in++;
+ while (cur_in != end && cur_in->state == cur_out->state) {
+ if (Compare(cur_in->weight, cur_in->string,
+ cur_out->weight, cur_out->string) == 1) {
+ // if *cur_in > *cur_out in semiring, then take *cur_in.
+ cur_out->string = cur_in->string;
+ cur_out->weight = cur_in->weight;
+ }
+ cur_in++;
+ }
+ cur_out++;
+ num_out++;
+ }
+ subset->resize(num_out);
+ }
+
+ // ProcessTransition is called from "ProcessTransitions". Broken out for
+ // clarity. Processes a transition from state "state". The set of Elements
+ // represents a set of next-states with associated weights and strings, each
+ // one arising from an arc from some state in a determinized-state; the
+ // next-states are not necessarily unique (i.e. there may be >1 entry
+ // associated with each), and any such sets of Elements have to be merged
+ // within this routine (we take the [weight, string] pair that's better in the
+ // semiring).
+ void ProcessTransition(OutputStateId state, Label ilabel, std::vector<Element> *subset) {
+ MakeSubsetUnique(subset); // remove duplicates with the same state.
+
+ StringId common_str;
+ Weight tot_weight;
+ NormalizeSubset(subset, &tot_weight, &common_str);
+
+ OutputStateId nextstate;
+ {
+ Weight next_tot_weight;
+ StringId next_common_str;
+ nextstate = InitialToStateId(*subset,
+ &next_tot_weight,
+ &next_common_str);
+ common_str = repository_.Concatenate(common_str, next_common_str);
+ tot_weight = Times(tot_weight, next_tot_weight);
+ }
+
+ // Now add an arc to the next state (would have been created if necessary by
+ // InitialToStateId).
+ TempArc temp_arc;
+ temp_arc.ilabel = ilabel;
+ temp_arc.nextstate = nextstate;
+ temp_arc.string = common_str;
+ temp_arc.weight = tot_weight;
+ output_arcs_[state].push_back(temp_arc); // record the arc.
+ num_arcs_++;
+ }
+
+
+ // "less than" operator for pair<Label, Element>. Used in ProcessTransitions.
+ // Lexicographical order, which only compares the state when ordering the
+ // "Element" member of the pair.
+
+ class PairComparator {
+ public:
+ inline bool operator () (const std::pair<Label, Element> &p1, const std::pair<Label, Element> &p2) {
+ if (p1.first < p2.first) return true;
+ else if (p1.first > p2.first) return false;
+ else {
+ return p1.second.state < p2.second.state;
+ }
+ }
+ };
+
+
+ // ProcessTransitions processes emitting transitions (transitions
+ // with ilabels) out of this subset of states.
+ // Does not consider final states. Breaks the emitting transitions up by ilabel,
+ // and creates a new transition in the determinized FST for each unique ilabel.
+ // Does this by creating a big vector of pairs <Label, Element> and then sorting them
+ // using a lexicographical ordering, and calling ProcessTransition for each range
+ // with the same ilabel.
+ // Side effects on repository, and (via ProcessTransition) on Q_, hash_,
+ // and output_arcs_.
+
+ void ProcessTransitions(OutputStateId output_state) {
+ const std::vector<Element> &minimal_subset = *(output_states_[output_state]);
+ // it's possible that minimal_subset could be empty if there are
+ // unreachable parts of the graph, so don't check that it's nonempty.
+ std::vector<std::pair<Label, Element> > &all_elems(all_elems_tmp_); // use class member
+ // to avoid memory allocation/deallocation.
+ {
+ // Push back into "all_elems", elements corresponding to all
+ // non-epsilon-input transitions out of all states in "minimal_subset".
+ typename std::vector<Element>::const_iterator iter = minimal_subset.begin(), end = minimal_subset.end();
+ for (;iter != end; ++iter) {
+ const Element &elem = *iter;
+ for (ArcIterator<Fst<Arc> > aiter(*ifst_, elem.state); ! aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0
+ && arc.weight != Weight::Zero()) { // Non-epsilon transition -- ignore epsilons here.
+ std::pair<Label, Element> this_pr;
+ this_pr.first = arc.ilabel;
+ Element &next_elem(this_pr.second);
+ next_elem.state = arc.nextstate;
+ next_elem.weight = Times(elem.weight, arc.weight);
+ if (arc.olabel == 0) // output epsilon
+ next_elem.string = elem.string;
+ else
+ next_elem.string = repository_.Successor(elem.string, arc.olabel);
+ all_elems.push_back(this_pr);
+ }
+ }
+ }
+ }
+ PairComparator pc;
+ std::sort(all_elems.begin(), all_elems.end(), pc);
+ // now sorted first on input label, then on state.
+ typedef typename std::vector<std::pair<Label, Element> >::const_iterator PairIter;
+ PairIter cur = all_elems.begin(), end = all_elems.end();
+ std::vector<Element> this_subset;
+ while (cur != end) {
+ // Process ranges that share the same input symbol.
+ Label ilabel = cur->first;
+ this_subset.clear();
+ while (cur != end && cur->first == ilabel) {
+ this_subset.push_back(cur->second);
+ cur++;
+ }
+ // We now have a subset for this ilabel.
+ assert(!this_subset.empty()); // temp.
+ ProcessTransition(output_state, ilabel, &this_subset);
+ }
+ all_elems.clear(); // as it's a class variable-- want it to stay
+ // emtpy.
+ }
+
+
+
+ // ProcessState does the processing of a determinized state, i.e. it creates
+ // transitions out of it and the final-probability if any.
+ void ProcessState(OutputStateId output_state) {
+ ProcessFinal(output_state);
+ ProcessTransitions(output_state);
+ }
+
+
+ void Debug() { // this function called if you send a signal
+ // SIGUSR1 to the process (and it's caught by the handler in
+ // fstdeterminizestar). It prints out some traceback
+ // info and exits.
+
+ KALDI_WARN << "Debug function called (probably SIGUSR1 caught)";
+ // free up memory from the hash as we need a little memory
+ { MinimalSubsetHash hash_tmp; hash_tmp.swap(minimal_hash_); }
+
+ if (output_arcs_.size() <= 2) {
+ KALDI_ERR << "Nothing to trace back";
+ }
+ size_t max_state = output_arcs_.size() - 2; // Don't take the last
+ // one as we might be halfway into constructing it.
+
+ std::vector<OutputStateId> predecessor(max_state+1, kNoStateId);
+ for (size_t i = 0; i < max_state; i++) {
+ for (size_t j = 0; j < output_arcs_[i].size(); j++) {
+ OutputStateId nextstate = output_arcs_[i][j].nextstate;
+ // Always find an earlier-numbered predecessor; this
+ // is always possible because of the way the algorithm
+ // works.
+ if (nextstate <= max_state && nextstate > i)
+ predecessor[nextstate] = i;
+ }
+ }
+ std::vector<std::pair<Label, StringId> > traceback;
+ // 'traceback' is a pair of (ilabel, olabel-seq).
+ OutputStateId cur_state = max_state; // A recently constructed state.
+
+ while (cur_state != 0 && cur_state != kNoStateId) {
+ OutputStateId last_state = predecessor[cur_state];
+ std::pair<Label, StringId> p;
+ size_t i;
+ for (i = 0; i < output_arcs_[last_state].size(); i++) {
+ if (output_arcs_[last_state][i].nextstate == cur_state) {
+ p.first = output_arcs_[last_state][i].ilabel;
+ p.second = output_arcs_[last_state][i].string;
+ traceback.push_back(p);
+ break;
+ }
+ }
+ KALDI_ASSERT(i != output_arcs_[last_state].size()); // Or fell off loop.
+ cur_state = last_state;
+ }
+ if (cur_state == kNoStateId)
+ KALDI_WARN << "Traceback did not reach start state "
+ << "(possibly debug-code error)";
+
+ std::stringstream ss;
+ ss << "Traceback follows in format "
+ << "ilabel (olabel olabel) ilabel (olabel) ... :";
+ for (ssize_t i = traceback.size() - 1; i >= 0; i--) {
+ ss << ' ' << traceback[i].first << " ( ";
+ std::vector<Label> seq;
+ repository_.ConvertToVector(traceback[i].second, &seq);
+ for (size_t j = 0; j < seq.size(); j++)
+ ss << seq[j] << ' ';
+ ss << ')';
+ }
+ KALDI_ERR << ss.str();
+ }
+
+ bool IsIsymbolOrFinal(InputStateId state) { // returns true if this state
+ // of the input FST either is final or has an osymbol on an arc out of it.
+ // Uses the vector isymbol_or_final_ as a cache for this info.
+ assert(state >= 0);
+ if (isymbol_or_final_.size() <= state)
+ isymbol_or_final_.resize(state+1, static_cast<char>(OSF_UNKNOWN));
+ if (isymbol_or_final_[state] == static_cast<char>(OSF_NO))
+ return false;
+ else if (isymbol_or_final_[state] == static_cast<char>(OSF_YES))
+ return true;
+ // else work it out...
+ isymbol_or_final_[state] = static_cast<char>(OSF_NO);
+ if (ifst_->Final(state) != Weight::Zero())
+ isymbol_or_final_[state] = static_cast<char>(OSF_YES);
+ for (ArcIterator<Fst<Arc> > aiter(*ifst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0 && arc.weight != Weight::Zero()) {
+ isymbol_or_final_[state] = static_cast<char>(OSF_YES);
+ return true;
+ }
+ }
+ return IsIsymbolOrFinal(state); // will only recurse once.
+ }
+
+ void InitializeDeterminization() {
+ if(ifst_->Properties(kExpanded, false) != 0) { // if we know the number of
+ // states in ifst_, it might be a bit more efficient
+ // to pre-size the hashes so we're not constantly rebuilding them.
+#if !(__GNUC__ == 4 && __GNUC_MINOR__ == 0)
+ StateId num_states =
+ down_cast<const ExpandedFst<Arc>*, const Fst<Arc> >(ifst_)->NumStates();
+ minimal_hash_.rehash(num_states/2 + 3);
+ initial_hash_.rehash(num_states/2 + 3);
+#endif
+ }
+ InputStateId start_id = ifst_->Start();
+ if (start_id != kNoStateId) {
+ /* Insert determinized-state corresponding to the start state into hash and
+ queue. Unlike all the other states, we don't "normalize" the representation
+ of this determinized-state before we put it into minimal_hash_. This is actually
+ what we want, as otherwise we'd have problems dealing with any extra weight
+ and string and might have to create a "super-initial" state which would make
+ the output nondeterministic. Normalization is only needed to make the
+ determinized output more minimal anyway, it's not needed for correctness.
+ Note, we don't put anything in the initial_hash_. The initial_hash_ is only
+ a lookaside buffer anyway, so this isn't a problem-- it will get populated
+ later if it needs to be.
+ */
+ Element elem;
+ elem.state = start_id;
+ elem.weight = Weight::One();
+ elem.string = repository_.EmptyString(); // Id of empty sequence.
+ std::vector<Element> subset;
+ subset.push_back(elem);
+ EpsilonClosure(&subset); // follow through epsilon-inputs links
+ ConvertToMinimal(&subset); // remove all but final states and
+ // states with input-labels on arcs out of them.
+ std::vector<Element> *subset_ptr = new std::vector<Element>(subset);
+ assert(output_arcs_.empty() && output_states_.empty());
+ // add the new state...
+ output_states_.push_back(subset_ptr);
+ output_arcs_.push_back(std::vector<TempArc>());
+ OutputStateId initial_state = 0;
+ minimal_hash_[subset_ptr] = initial_state;
+ queue_.push_back(initial_state);
+ }
+ }
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(LatticeDeterminizer);
+
+
+ std::vector<std::vector<Element>* > output_states_; // maps from output state to
+ // minimal representation [normalized].
+ // View pointers as owned in
+ // minimal_hash_.
+ std::vector<std::vector<TempArc> > output_arcs_; // essentially an FST in our format.
+
+ int num_arcs_; // keep track of memory usage: number of arcs in output_arcs_
+ int num_elems_; // keep track of memory usage: number of elems in output_states_
+
+ const Fst<Arc> *ifst_;
+ DeterminizeLatticeOptions opts_;
+ SubsetKey hasher_; // object that computes keys-- has no data members.
+ SubsetEqual equal_; // object that compares subsets-- only data member is delta_.
+ bool determinized_; // set to true when user called Determinize(); used to make
+ // sure this object is used correctly.
+ MinimalSubsetHash minimal_hash_; // hash from Subset to OutputStateId. Subset is "minimal
+ // representation" (only include final and states and states with
+ // nonzero ilabel on arc out of them. Owns the pointers
+ // in its keys.
+ InitialSubsetHash initial_hash_; // hash from Subset to Element, which
+ // represents the OutputStateId together
+ // with an extra weight and string. Subset
+ // is "initial representation". The extra
+ // weight and string is needed because after
+ // we convert to minimal representation and
+ // normalize, there may be an extra weight
+ // and string. Owns the pointers
+ // in its keys.
+ std::vector<OutputStateId> queue_; // Queue of output-states to process. Starts with
+ // state 0, and increases and then (hopefully) decreases in length during
+ // determinization. LIFO queue (queue discipline doesn't really matter).
+
+ std::vector<std::pair<Label, Element> > all_elems_tmp_; // temporary vector used in ProcessTransitions.
+
+ enum IsymbolOrFinal { OSF_UNKNOWN = 0, OSF_NO = 1, OSF_YES = 2 };
+
+ std::vector<char> isymbol_or_final_; // A kind of cache; it says whether
+ // each state is (emitting or final) where emitting means it has at least one
+ // non-epsilon output arc. Only accessed by IsIsymbolOrFinal()
+
+ LatticeStringRepository<IntType> repository_; // defines a compact and fast way of
+ // storing sequences of labels.
+};
+
+
+// normally Weight would be LatticeWeight<float> (which has two floats),
+// or possibly TropicalWeightTpl<float>, and IntType would be int32.
+template<class Weight, class IntType>
+bool DeterminizeLattice(const Fst<ArcTpl<Weight> > &ifst,
+ MutableFst<ArcTpl<Weight> > *ofst,
+ DeterminizeLatticeOptions opts,
+ bool *debug_ptr) {
+ ofst->SetInputSymbols(ifst.InputSymbols());
+ ofst->SetOutputSymbols(ifst.OutputSymbols());
+ LatticeDeterminizer<Weight, IntType> det(ifst, opts);
+ if (!det.Determinize(debug_ptr))
+ return false;
+ det.Output(ofst);
+ return true;
+}
+
+
+// normally Weight would be LatticeWeight<float> (which has two floats),
+// or possibly TropicalWeightTpl<float>, and IntType would be int32.
+template<class Weight, class IntType>
+bool DeterminizeLattice(const Fst<ArcTpl<Weight> >&ifst,
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > >*ofst,
+ DeterminizeLatticeOptions opts,
+ bool *debug_ptr) {
+ ofst->SetInputSymbols(ifst.InputSymbols());
+ ofst->SetOutputSymbols(ifst.OutputSymbols());
+ LatticeDeterminizer<Weight, IntType> det(ifst, opts);
+ if (!det.Determinize(debug_ptr))
+ return false;
+ det.Output(ofst);
+ return true;
+}
+
+} // namespace fst
+
+#endif // KALDI_FSTEXT_DETERMINIZE_LATTICE_INL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/determinize-lattice-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-lattice-test.cc
new file mode 100644
index 000000000..886aa4cc1
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-lattice-test.cc
@@ -0,0 +1,174 @@
+// fstext/determinize-lattice-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "fstext/determinize-lattice.h"
+#include "fstext/lattice-utils.h"
+#include "fstext/fst-test-utils.h"
+#include "base/kaldi-math.h"
+
+namespace fst {
+using std::vector;
+using std::cout;
+
+void TestLatticeStringRepository() {
+ typedef int32 IntType;
+
+ LatticeStringRepository<IntType> sr;
+ typedef LatticeStringRepository<IntType>::Entry Entry;
+
+ for(int i = 0; i < 100; i++) {
+ int len = kaldi::Rand() % 5;
+ vector<IntType> str(len), str2(kaldi::Rand() % 4);
+ const Entry *e = NULL;
+ for(int i = 0; i < len; i++) {
+ str[i] = kaldi::Rand() % 5;
+ e = sr.Successor(e, str[i]);
+ }
+ sr.ConvertToVector(e, &str2);
+ assert(str == str2);
+
+ int len2 = kaldi::Rand() % 5;
+ str2.resize(len2);
+ const Entry *f = sr.EmptyString(); // NULL
+ for(int i = 0; i < len2; i++) {
+ str2[i] = kaldi::Rand() % 5;
+ f = sr.Successor(f, str2[i]);
+ }
+ vector<IntType> prefix, prefix2(kaldi::Rand() % 10),
+ prefix3;
+ for(int i = 0; i < len && i < len2; i++) {
+ if (str[i] == str2[i]) prefix.push_back(str[i]);
+ else break;
+ }
+ const Entry *g = sr.CommonPrefix(e, f);
+ sr.ConvertToVector(g, &prefix2);
+ sr.ConvertToVector(e, &prefix3);
+ sr.ReduceToCommonPrefix(f, &prefix3);
+ assert(prefix == prefix2);
+ assert(prefix == prefix3);
+ assert(sr.IsPrefixOf(g, e));
+ assert(sr.IsPrefixOf(g, f));
+ if (str.size() > prefix.size())
+ assert(!sr.IsPrefixOf(e, g));
+ }
+}
+
+
+// test that determinization proceeds correctly on general
+// FSTs (not guaranteed determinzable, but we use the
+// max-states option to stop it getting out of control).
+template<class Arc> void TestDeterminizeLattice() {
+ typedef typename Arc::Weight Weight;
+ typedef int32 Int;
+ typedef ArcTpl<CompactLatticeWeightTpl<Weight, Int> > CompactArc;
+
+ for(int i = 0; i < 100; i++) {
+ RandFstOptions opts;
+ opts.n_states = 4;
+ opts.n_arcs = 10;
+ opts.n_final = 2;
+ opts.allow_empty = false;
+ opts.weight_multiplier = 0.5; // impt for the randomly generated weights
+ // to be exactly representable in float,
+ // or this test fails because numerical differences can cause symmetry in
+ // weights to be broken, which causes the wrong path to be chosen as far
+ // as the string part is concerned.
+
+ VectorFst<Arc> *fst = RandFst<Arc>();
+ std::cout << "FST before lattice-determinizing is:\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ VectorFst<Arc> det_fst;
+ try {
+ DeterminizeLatticeOptions lat_opts;
+ lat_opts.max_mem = 100;
+
+ if (!DeterminizeLattice<TropicalWeight, int32>(*fst, &det_fst, lat_opts, NULL))
+ throw std::runtime_error("could not determinize");
+ std::cout << "FST after lattice-determinizing is:\n";
+ {
+ FstPrinter<Arc> fstprinter(det_fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ assert(det_fst.Properties(kIDeterministic, true) & kIDeterministic);
+ // OK, now determinize it a different way and check equivalence.
+ // [note: it's not normal determinization, it's taking the best path
+ // for any input-symbol sequence....
+ VectorFst<CompactArc> compact_fst, compact_det_fst;
+ ConvertLattice<Weight, Int>(*fst, &compact_fst, false);
+ std::cout << "Compact FST is:\n";
+ {
+ FstPrinter<CompactArc> fstprinter(compact_fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ if (kaldi::Rand() % 2 == 1)
+ ConvertLattice<Weight, Int>(det_fst, &compact_det_fst, false);
+ else
+ if (!DeterminizeLattice<TropicalWeight, int32>(*fst, &compact_det_fst, lat_opts, NULL))
+ throw std::runtime_error("could not determinize");
+
+ std::cout << "Compact version of determinized FST is:\n";
+ {
+ FstPrinter<CompactArc> fstprinter(compact_det_fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ assert(RandEquivalent(compact_det_fst, compact_fst, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length, max*/));
+ } catch (...) {
+ std::cout << "Failed to lattice-determinize this FST (probably not determinizable)\n";
+ }
+ delete fst;
+ }
+}
+
+// test that determinization proceeds correctly on acyclic FSTs
+// (guaranteed determinizable in this sense).
+template<class Arc> void TestDeterminizeLattice2() {
+ RandFstOptions opts;
+ opts.acyclic = true;
+ for(int i = 0; i < 100; i++) {
+ VectorFst<Arc> *fst = RandFst<Arc>(opts);
+ std::cout << "FST before lattice-determinizing is:\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ VectorFst<Arc> ofst;
+ DeterminizeLattice<TropicalWeight, int32>(*fst, &ofst);
+ std::cout << "FST after lattice-determinizing is:\n";
+ {
+ FstPrinter<Arc> fstprinter(ofst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ delete fst;
+ }
+}
+
+
+} // end namespace fst
+
+int main() {
+ using namespace fst;
+ TestLatticeStringRepository();
+ TestDeterminizeLattice<StdArc>();
+ TestDeterminizeLattice2<StdArc>();
+ std::cout << "Tests succeeded\n";
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/determinize-lattice.h b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-lattice.h
new file mode 100644
index 000000000..3a23bec3f
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-lattice.h
@@ -0,0 +1,150 @@
+// fstext/determinize-lattice.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_DETERMINIZE_LATTICE_H_
+#define KALDI_FSTEXT_DETERMINIZE_LATTICE_H_
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+#include <algorithm>
+#include <map>
+#include <set>
+#include <vector>
+#include "fstext/lattice-weight.h"
+
+namespace fst {
+
+/// \addtogroup fst_extensions
+/// @{
+
+
+// For example of usage, see test-determinize-lattice.cc
+
+/*
+ DeterminizeLattice implements a special form of determinization
+ with epsilon removal, optimized for a phase of lattice generation.
+ Its input is an FST with weight-type BaseWeightType (usually a pair of floats,
+ with a lexicographical type of order, such as LatticeWeightTpl<float>).
+ Typically this would be a state-level lattice, with input symbols equal to
+ words, and output-symbols equal to p.d.f's (so like the inverse of HCLG). Imagine representing this as an
+ acceptor of type CompactLatticeWeightTpl<float>, in which the input/output
+ symbols are words, and the weights contain the original weights together with
+ strings (with zero or one symbol in them) containing the original output labels
+ (the p.d.f.'s). We determinize this using acceptor determinization with
+ epsilon removal. Remember (from lattice-weight.h) that
+ CompactLatticeWeightTpl has a special kind of semiring where we always take
+ the string corresponding to the best cost (of type BaseWeightType), and
+ discard the other. This corresponds to taking the best output-label sequence
+ (of p.d.f.'s) for each input-label sequence (of words). We couldn't use the
+ Gallic weight for this, or it would die as soon as it detected that the input
+ FST was non-functional. In our case, any acyclic FST (and many cyclic ones)
+ can be determinized.
+ We assume that there is a function
+ Compare(const BaseWeightType &a, const BaseWeightType &b)
+ that returns (-1, 0, 1) according to whether (a < b, a == b, a > b) in the
+ total order on the BaseWeightType... this information should be the
+ same as NaturalLess would give, but it's more efficient to do it this way.
+ You can define this for things like TropicalWeight if you need to instantiate
+ this class for that weight type.
+
+ We implement this determinization in a special way to make it efficient for
+ the types of FSTs that we will apply it to. One issue is that if we
+ explicitly represent the strings (in CompactLatticeWeightTpl) as vectors of
+ type vector<IntType>, the algorithm takes time quadratic in the length of
+ words (in states), because propagating each arc involves copying a whole
+ vector (of integers representing p.d.f.'s). Instead we use a hash structure
+ where each string is a pointer (Entry*), and uses a hash from (Entry*,
+ IntType), to the successor string (and a way to get the latest IntType and the
+ ancestor Entry*). [this is the class LatticeStringRepository].
+
+ Another issue is that rather than representing a determinized-state as a
+ collection of (state, weight), we represent it in a couple of reduced forms.
+ Suppose a determinized-state is a collection of (state, weight) pairs; call
+ this the "canonical representation". Note: these collections are always
+ normalized to remove any common weight and string part. Define end-states as
+ the subset of states that have an arc out of them with a label on, or are
+ final. If we represent a determinized-state a the set of just its (end-state,
+ weight) pairs, this will be a valid and more compact representation, and will
+ lead to a smaller set of determinized states (like early minimization). Call
+ this collection of (end-state, weight) pairs the "minimal representation". As
+ a mechanism to reduce compute, we can also consider another representation.
+ In the determinization algorithm, we start off with a set of (begin-state,
+ weight) pairs (where the "begin-states" are initial or have a label on the
+ transition into them), and the "canonical representation" consists of the
+ epsilon-closure of this set (i.e. follow epsilons). Call this set of
+ (begin-state, weight) pairs, appropriately normalized, the "initial
+ representation". If two initial representations are the same, the "canonical
+ representation" and hence the "minimal representation" will be the same. We
+ can use this to reduce compute. Note that if two initial representations are
+ different, this does not preclude the other representations from being the same.
+
+*/
+
+struct DeterminizeLatticeOptions {
+ float delta; // A small offset used to measure equality of weights.
+ int max_mem; // If >0, determinization will fail and return false
+ // when the algorithm's (approximate) memory consumption crosses this threshold.
+ int max_loop; // If >0, can be used to detect non-determinizable input
+ // (a case that wouldn't be caught by max_mem).
+ DeterminizeLatticeOptions(): delta(kDelta),
+ max_mem(-1),
+ max_loop(-1) { }
+};
+
+/**
+ This function implements the normal version of DeterminizeLattice, in which
+ the output strings are represented using sequences of arcs, where all but
+ the first one has an epsilon on the input side. The debug_ptr argument is
+ an optional pointer to a bool that, if it becomes true while the algorithm
+ is executing, the algorithm will print a traceback and terminate (used in
+ fstdeterminizestar.cc debug non-terminating determinization). More
+ efficient if ifst is arc-sorted on input label. If the number of arcs gets
+ more than max_states, it will throw std::runtime_error (otherwise this code
+ does not use exceptions). This is mainly useful for debug. */
+template<class Weight, class IntType>
+bool DeterminizeLattice(
+ const Fst<ArcTpl<Weight> > &ifst,
+ MutableFst<ArcTpl<Weight> > *ofst,
+ DeterminizeLatticeOptions opts = DeterminizeLatticeOptions(),
+ bool *debug_ptr = NULL);
+
+
+/* This is a version of DeterminizeLattice with a slightly more "natural" output format,
+ where the output sequences are encoded using the CompactLatticeArcTpl template
+ (i.e. the sequences of output symbols are represented directly as strings)
+ More efficient if ifst is arc-sorted on input label.
+ If the #arcs gets more than max_arcs, it will throw std::runtime_error (otherwise
+ this code does not use exceptions). This is mainly useful for debug.
+*/
+template<class Weight, class IntType>
+bool DeterminizeLattice(
+ const Fst<ArcTpl<Weight> >&ifst,
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > > *ofst,
+ DeterminizeLatticeOptions opts = DeterminizeLatticeOptions(),
+ bool *debug_ptr = NULL);
+
+
+
+
+/// @} end "addtogroup fst_extensions"
+
+} // end namespace fst
+
+#include "fstext/determinize-lattice-inl.h"
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/determinize-star-inl.h b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-star-inl.h
new file mode 100644
index 000000000..36c9ba397
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-star-inl.h
@@ -0,0 +1,1134 @@
+// fstext/determinize-star-inl.h
+
+// Copyright 2009-2011 Microsoft Corporation; Jan Silovsky
+// 2015 Hainan Xu
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_DETERMINIZE_STAR_INL_H_
+#define KALDI_FSTEXT_DETERMINIZE_STAR_INL_H_
+// Do not include this file directly. It is included by determinize-star.h
+
+#include "base/kaldi-error.h"
+
+#include <unordered_map>
+using std::unordered_map;
+
+#include <vector>
+#include <climits>
+
+namespace fst {
+
+// This class maps back and forth from/to integer id's to sequences of strings.
+// used in determinization algorithm.
+
+template<class Label, class StringId> class StringRepository {
+ // Label and StringId are both integer types, possibly the same.
+ // This is a utility that maps back and forth between a vector<Label> and StringId
+ // representation of sequences of Labels. It is to save memory, and to save compute.
+ // We treat sequences of length zero and one separately, for efficiency.
+
+ public:
+ class VectorKey { // Hash function object.
+ public:
+ size_t operator()(const std::vector<Label> *vec) const {
+ assert(vec != NULL);
+ size_t hash = 0, factor = 1;
+ for (typename std::vector<Label>::const_iterator it = vec->begin();
+ it != vec->end(); it++) {
+ hash += factor*(*it);
+ factor *= 103333; // just an arbitrary prime number.
+ }
+ return hash;
+ }
+ };
+ class VectorEqual { // Equality-operator function object.
+ public:
+ size_t operator()(const std::vector<Label> *vec1, const std::vector<Label> *vec2) const {
+ return (*vec1 == *vec2);
+ }
+ };
+
+ typedef unordered_map<const std::vector<Label>*, StringId, VectorKey, VectorEqual> MapType;
+
+ StringId IdOfEmpty() { return no_symbol; }
+
+ StringId IdOfLabel(Label l) {
+ if (l>= 0 && l <= (Label) single_symbol_range) {
+ return l + single_symbol_start;
+ } else {
+ // l is out of the allowed range so we have to treat it as a sequence of length one. Should be v. rare.
+ std::vector<Label> v; v.push_back(l);
+ return IdOfSeqInternal(v);
+ }
+ }
+
+ StringId IdOfSeq(const std::vector<Label> &v) { // also works for sizes 0 and 1.
+ size_t sz = v.size();
+ if (sz == 0) return no_symbol;
+ else if (v.size() == 1) return IdOfLabel(v[0]);
+ else return IdOfSeqInternal(v);
+ }
+
+ inline bool IsEmptyString(StringId id) {
+ return id == no_symbol;
+ }
+ void SeqOfId(StringId id, std::vector<Label> *v) {
+ if (id == no_symbol) v->clear();
+ else if (id>=single_symbol_start) {
+ v->resize(1); (*v)[0] = id - single_symbol_start;
+ } else {
+ assert(static_cast<size_t>(id) < vec_.size());
+ *v = *(vec_[id]);
+ }
+ }
+ StringId RemovePrefix(StringId id, size_t prefix_len) {
+ if (prefix_len == 0) return id;
+ else {
+ std::vector<Label> v;
+ SeqOfId(id, &v);
+ size_t sz = v.size();
+ assert(sz >= prefix_len);
+ std::vector<Label> v_noprefix(sz - prefix_len);
+ for (size_t i = 0;i < sz-prefix_len;i++) v_noprefix[i] = v[i+prefix_len];
+ return IdOfSeq(v_noprefix);
+ }
+ }
+
+ StringRepository() {
+ // The following are really just constants but don't want to complicate compilation so make them
+ // class variables. Due to the brokenness of <limits>, they can't be accessed as constants.
+ string_end = (std::numeric_limits<StringId>::max() / 2) - 1; // all hash values must be <= this.
+ no_symbol = (std::numeric_limits<StringId>::max() / 2); // reserved for empty sequence.
+ single_symbol_start = (std::numeric_limits<StringId>::max() / 2) + 1;
+ single_symbol_range = std::numeric_limits<StringId>::max() - single_symbol_start;
+ }
+ void Destroy() {
+ for (typename std::vector<std::vector<Label>* >::iterator iter = vec_.begin(); iter != vec_.end(); ++iter)
+ delete *iter;
+ std::vector<std::vector<Label>* > tmp_vec;
+ tmp_vec.swap(vec_);
+ MapType tmp_map;
+ tmp_map.swap(map_);
+ }
+ ~StringRepository() {
+ Destroy();
+ }
+
+ private:
+ KALDI_DISALLOW_COPY_AND_ASSIGN(StringRepository);
+
+ StringId IdOfSeqInternal(const std::vector<Label> &v) {
+ typename MapType::iterator iter = map_.find(&v);
+ if (iter != map_.end()) {
+ return iter->second;
+ } else { // must add it to map.
+ StringId this_id = (StringId) vec_.size();
+ std::vector<Label> *v_new = new std::vector<Label> (v);
+ vec_.push_back(v_new);
+ map_[v_new] = this_id;
+ assert(this_id < string_end); // or we used up the labels.
+ return this_id;
+ }
+ }
+
+ std::vector<std::vector<Label>* > vec_;
+ MapType map_;
+
+ static const StringId string_start = (StringId) 0; // This must not change. It's assumed.
+ StringId string_end; // = (numeric_limits<StringId>::max() / 2) - 1; // all hash values must be <= this.
+ StringId no_symbol; // = (numeric_limits<StringId>::max() / 2); // reserved for empty sequence.
+ StringId single_symbol_start; // = (numeric_limits<StringId>::max() / 2) + 1;
+ StringId single_symbol_range; // = numeric_limits<StringId>::max() - single_symbol_start;
+};
+
+
+template<class F> class DeterminizerStar {
+ typedef typename F::Arc Arc;
+ public:
+ // Output to Gallic acceptor (so the strings go on weights, and there is a 1-1 correspondence
+ // between our states and the states in ofst. If destroy == true, release memory as we go
+ // (but we cannot output again).
+ void Output(MutableFst<GallicArc<Arc> > *ofst, bool destroy = true);
+
+ // Output to standard FST. We will create extra states to handle sequences of symbols
+ // on the output. If destroy == true, release memory as we go
+ // (but we cannot output again).
+
+ void Output(MutableFst<Arc> *ofst, bool destroy = true);
+
+
+ // Initializer. After initializing the object you will typically call
+ // Determinize() and then one of the Output functions.
+ DeterminizerStar(const Fst<Arc> &ifst, float delta = kDelta,
+ int max_states = -1, bool allow_partial = false):
+ ifst_(ifst.Copy()), delta_(delta), max_states_(max_states),
+ determinized_(false), allow_partial_(allow_partial),
+ is_partial_(false), equal_(delta),
+ hash_(ifst.Properties(kExpanded, false) ?
+ down_cast<const ExpandedFst<Arc>*,
+ const Fst<Arc> >(&ifst)->NumStates()/2 + 3 : 20,
+ hasher_, equal_),
+ epsilon_closure_(ifst_, max_states, &repository_, delta) { }
+
+ void Determinize(bool *debug_ptr) {
+ assert(!determinized_);
+ // This determinizes the input fst but leaves it in the "special format"
+ // in "output_arcs_".
+ InputStateId start_id = ifst_->Start();
+ if (start_id == kNoStateId) { determinized_ = true; return; } // Nothing to do.
+ else { // Insert start state into hash and queue.
+ Element elem;
+ elem.state = start_id;
+ elem.weight = Weight::One();
+ elem.string = repository_.IdOfEmpty(); // Id of empty sequence.
+ std::vector<Element> vec;
+ vec.push_back(elem);
+ OutputStateId cur_id = SubsetToStateId(vec);
+ assert(cur_id == 0 && "Do not call Determinize twice.");
+ }
+ while (!Q_.empty()) {
+ std::pair<std::vector<Element>*, OutputStateId> cur_pair = Q_.front();
+ Q_.pop_front();
+ ProcessSubset(cur_pair);
+ if (debug_ptr && *debug_ptr) Debug(); // will exit.
+ if (max_states_ > 0 && output_arcs_.size() > max_states_) {
+ if (allow_partial_ == false) {
+ KALDI_ERR << "Determinization aborted since passed " << max_states_
+ << " states";
+ } else {
+ KALDI_WARN << "Determinization terminated since passed " << max_states_
+ << " states, partial results will be generated";
+ is_partial_ = true;
+ break;
+ }
+ }
+ }
+ determinized_ = true;
+ }
+
+ bool IsPartial() {
+ return is_partial_;
+ }
+
+ // frees all except output_arcs_, which contains the important info
+ // we need to output.
+ void FreeMostMemory() {
+ if (ifst_) {
+ delete ifst_;
+ ifst_ = NULL;
+ }
+ for (typename SubsetHash::iterator iter = hash_.begin();
+ iter != hash_.end(); ++iter)
+ delete iter->first;
+ SubsetHash tmp;
+ tmp.swap(hash_);
+ }
+
+ ~DeterminizerStar() {
+ FreeMostMemory();
+ }
+ private:
+ typedef typename Arc::Label Label;
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId InputStateId;
+ typedef typename Arc::StateId OutputStateId; // same as above but distinguish states in output Fst.
+ typedef typename Arc::Label StringId; // Id type used in the StringRepository
+ typedef StringRepository<Label, StringId> StringRepositoryType;
+
+
+ // Element of a subset [of original states]
+
+ struct Element {
+ InputStateId state;
+ StringId string;
+ Weight weight;
+ bool operator != (const Element &other) const {
+ return (state != other.state || string != other.string ||
+ weight != other.weight);
+ }
+ };
+
+ // Arcs in the format we temporarily create in this class (a representation, essentially of
+ // a Gallic Fst).
+ struct TempArc {
+ Label ilabel;
+ StringId ostring; // Look it up in the StringRepository, it's a sequence of Labels.
+ OutputStateId nextstate; // or kNoState for final weights.
+ Weight weight;
+ };
+
+
+ // Hashing function used in hash of subsets.
+ // A subset is a pointer to vector<Element>.
+ // The Elements are in sorted order on state id, and without repeated states.
+ // Because the order of Elements is fixed, we can use a hashing function that is
+ // order-dependent. However the weights are not included in the hashing function--
+ // we hash subsets that differ only in weight to the same key. This is not optimal
+ // in terms of the O(N) performance but typically if we have a lot of determinized
+ // states that differ only in weight then the input probably was pathological in some way,
+ // or even non-determinizable.
+ // We don't quantize the weights, in order to avoid inexactness in simple cases.
+ // Instead we apply the delta when comparing subsets for equality, and allow a small
+ // difference.
+
+ class SubsetKey {
+ public:
+ size_t operator ()(const std::vector<Element> * subset) const { // hashes only the state and string.
+ size_t hash = 0, factor = 1;
+ for (typename std::vector<Element>::const_iterator iter = subset->begin();
+ iter != subset->end(); ++iter) {
+ hash *= factor;
+ hash += iter->state + size_t(103333) * iter->string;
+ factor *= 23531; // these numbers are primes.
+ }
+ return hash;
+ }
+ };
+
+ // This is the equality operator on subsets. It checks for exact match on state-id
+ // and string, and approximate match on weights.
+ class SubsetEqual {
+ public:
+ bool operator ()(const std::vector<Element> *s1,
+ const std::vector<Element> *s2) const {
+ size_t sz = s1->size();
+ assert(sz >= 0);
+ if (sz != s2->size()) return false;
+ typename std::vector<Element>::const_iterator iter1 = s1->begin(),
+ iter1_end = s1->end(), iter2 = s2->begin();
+ for (; iter1 < iter1_end; ++iter1, ++iter2) {
+ if (iter1->state != iter2->state ||
+ iter1->string != iter2->string ||
+ ! ApproxEqual(iter1->weight, iter2->weight, delta_))
+ return false;
+ }
+ return true;
+ }
+ float delta_;
+ SubsetEqual(float delta): delta_(delta) {}
+ SubsetEqual(): delta_(kDelta) {}
+ };
+
+ // Operator that says whether two Elements have the same states.
+ // Used only for debug.
+ class SubsetEqualStates {
+ public:
+ bool operator ()(const std::vector<Element> *s1, const std::vector<Element> *s2) const {
+ size_t sz = s1->size();
+ assert(sz>=0);
+ if (sz != s2->size()) return false;
+ typename std::vector<Element>::const_iterator iter1 = s1->begin(),
+ iter1_end = s1->end(), iter2=s2->begin();
+ for (; iter1 < iter1_end; ++iter1, ++iter2) {
+ if (iter1->state != iter2->state) return false;
+ }
+ return true;
+ }
+ };
+
+ // Define the hash type we use to store subsets.
+ typedef unordered_map<const std::vector<Element>*, OutputStateId, SubsetKey, SubsetEqual> SubsetHash;
+
+ class EpsilonClosure {
+ public:
+ EpsilonClosure(const Fst<Arc> *ifst, int max_states,
+ StringRepository<Label, StringId> *repository, float delta):
+ ifst_(ifst), max_states_(max_states), repository_(repository),
+ delta_(delta) {
+
+ }
+
+ // This function computes epsilon closure of subset of states by following epsilon links.
+ // Called by ProcessSubset.
+ // Has no side effects except on the repository.
+ void GetEpsilonClosure(const std::vector<Element> &input_subset,
+ std::vector<Element> *output_subset);
+
+ private:
+ struct EpsilonClosureInfo {
+ EpsilonClosureInfo() {}
+ EpsilonClosureInfo(const Element &e, const Weight &w, bool i) :
+ element(e), weight_to_process(w), in_queue(i) {}
+ // the weight in the Element struct is the total current weight
+ // that has been processed already
+ Element element;
+ // this stores the weight that we haven't processed (propagated)
+ Weight weight_to_process;
+ // whether "this" struct is in the queue
+ // we store the info here so that we don't have to look it up every time
+ bool in_queue;
+ bool operator<(const EpsilonClosureInfo &other) const {
+ return this->element.state < other.element.state;
+ }
+ };
+
+ // to further speed up EpsilonClosure() computation, we have 2 queues
+ // the 2nd queue is used when we first iterate over the input set -
+ // if queue_2_.empty() then we directly set output_set equal to input_set
+ // and return immediately
+ // Since Epsilon arcs are relatively rare, this way we could efficiently
+ // detect the epsilon-free case, without having to waste our computation e.g.
+ // allocating the EpsilonClosureInfo structure; this also lets us do a
+ // level-by-level traversal, which could avoid some (unfortunately not all)
+ // duplicate computation if epsilons form a DAG that is not a tree
+ //
+ // We put the queues here for better efficiency for memory allocation
+ std::deque<typename Arc::StateId> queue_;
+ std::vector<Element> queue_2_;
+
+ // the following 2 structures together form our *virtual "map"*
+ // basically we need a map from state_id to EpsilonClosureInfo that operates
+ // in O(1) time, while still takes relatively small mem, and this does it well
+ // for efficiency we don't clear id_to_index_ of its outdated information
+ // As a result each time we do a look-up, we need to check
+ // if (ecinfo_[id_to_index_[id]].element.state == id)
+ // Yet this is still faster than using a std::map<StateId, EpsilonClosureInfo>
+ std::vector<int> id_to_index_;
+ // unlike id_to_index_, we clear the content of ecinfo_ each time we call
+ // EpsilonClosure(). This needed because we need an efficient way to
+ // traverse the virtual map - it is just too costly to traverse the
+ // id_to_index_ vector.
+ std::vector<EpsilonClosureInfo> ecinfo_;
+
+ // Add one element (elem) into cur_subset
+ // it also adds the necessary stuff to queue_, set the correct weight
+ void AddOneElement(const Element &elem, const Weight &unprocessed_weight);
+
+ // Sub-routine that we call in EpsilonClosure()
+ // It takes the current "unprocessed_weight" and propagate it to the
+ // states accessible from elem.state by an epsilon arc
+ // and add the results to cur_subset.
+ // save_to_queue_2 is set true when we iterate over the initial subset
+ // - then we save it to queue_2 s.t. if it's empty, we directly return
+ // the input set
+ void ExpandOneElement(const Element &elem,
+ bool sorted,
+ const Weight &unprocessed_weight,
+ bool save_to_queue_2 = false);
+
+ // no pointers below would take the ownership
+ const Fst<Arc> *ifst_;
+ int max_states_;
+ StringRepository<Label, StringId> *repository_;
+ float delta_;
+ };
+
+
+ // This function works out the final-weight of the determinized state.
+ // called by ProcessSubset.
+ // Has no side effects except on the variable repository_, and output_arcs_.
+
+ void ProcessFinal(const std::vector<Element> &closed_subset, OutputStateId state) {
+ // processes final-weights for this subset.
+ bool is_final = false;
+ StringId final_string = 0; // = 0 to keep compiler happy.
+ Weight final_weight = Weight::One(); // This value will never be accessed, and
+ // we just set it to avoid spurious compiler warnings. We avoid setting it
+ // to Zero() because floating-point infinities can sometimes generate
+ // interrupts and slow things down.
+ typename std::vector<Element>::const_iterator iter = closed_subset.begin(),
+ end = closed_subset.end();
+ for (; iter != end; ++iter) {
+ const Element &elem = *iter;
+ Weight this_final_weight = ifst_->Final(elem.state);
+ if (this_final_weight != Weight::Zero()) {
+ if (!is_final) { // first final-weight
+ final_string = elem.string;
+ final_weight = Times(elem.weight, this_final_weight);
+ is_final = true;
+ } else { // already have one.
+ if (final_string != elem.string) {
+ KALDI_ERR << "FST was not functional -> not determinizable";
+ }
+ final_weight = Plus(final_weight, Times(elem.weight, this_final_weight));
+ }
+ }
+ }
+ if (is_final) {
+ // store final weights in TempArc structure, just like a transition.
+ TempArc temp_arc;
+ temp_arc.ilabel = 0;
+ temp_arc.nextstate = kNoStateId; // special marker meaning "final weight".
+ temp_arc.ostring = final_string;
+ temp_arc.weight = final_weight;
+ output_arcs_[state].push_back(temp_arc);
+ }
+ }
+
+ // ProcessTransition is called from "ProcessTransitions". Broken out for
+ // clarity. Has side effects on output_arcs_, and (via SubsetToStateId), Q_
+ // and hash_.
+ void ProcessTransition(OutputStateId state, Label ilabel, std::vector<Element> *subset);
+
+ // "less than" operator for pair<Label, Element>. Used in ProcessTransitions.
+ // Lexicographical order, with comparing the state only for "Element".
+
+ class PairComparator {
+ public:
+ inline bool operator () (const std::pair<Label, Element> &p1, const std::pair<Label, Element> &p2) {
+ if (p1.first < p2.first) return true;
+ else if (p1.first > p2.first) return false;
+ else {
+ return p1.second.state < p2.second.state;
+ }
+ }
+ };
+
+
+ // ProcessTransitions handles transitions out of this subset of states.
+ // Ignores epsilon transitions (epsilon closure already handled that).
+ // Does not consider final states. Breaks the transitions up by ilabel,
+ // and creates a new transition in determinized FST, for each ilabel.
+ // Does this by creating a big vector of pairs <Label, Element> and then sorting them
+ // using a lexicographical ordering, and calling ProcessTransition for each range
+ // with the same ilabel.
+ // Side effects on repository, and (via ProcessTransition) on Q_, hash_,
+ // and output_arcs_.
+ void ProcessTransitions(const std::vector<Element> &closed_subset, OutputStateId state) {
+ std::vector<std::pair<Label, Element> > all_elems;
+ { // Push back into "all_elems", elements corresponding to all non-epsilon-input transitions
+ // out of all states in "closed_subset".
+ typename std::vector<Element>::const_iterator iter = closed_subset.begin(),
+ end = closed_subset.end();
+ for (; iter != end; ++iter) {
+ const Element &elem = *iter;
+ for (ArcIterator<Fst<Arc> > aiter(*ifst_, elem.state);
+ !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0) { // Non-epsilon transition -- ignore epsilons here.
+ std::pair<Label, Element> this_pr;
+ this_pr.first = arc.ilabel;
+ Element &next_elem(this_pr.second);
+ next_elem.state = arc.nextstate;
+ next_elem.weight = Times(elem.weight, arc.weight);
+ if (arc.olabel == 0) // output epsilon-- this is simple case so
+ // handle separately for efficiency
+ next_elem.string = elem.string;
+ else {
+ std::vector<Label> seq;
+ repository_.SeqOfId(elem.string, &seq);
+ seq.push_back(arc.olabel);
+ next_elem.string = repository_.IdOfSeq(seq);
+ }
+ all_elems.push_back(this_pr);
+ }
+ }
+ }
+ }
+ PairComparator pc;
+ std::sort(all_elems.begin(), all_elems.end(), pc);
+ // now sorted first on input label, then on state.
+ typedef typename std::vector<std::pair<Label, Element> >::const_iterator PairIter;
+ PairIter cur = all_elems.begin(), end = all_elems.end();
+ std::vector<Element> this_subset;
+ while (cur != end) {
+ // Process ranges that share the same input symbol.
+ Label ilabel = cur->first;
+ this_subset.clear();
+ while (cur != end && cur->first == ilabel) {
+ this_subset.push_back(cur->second);
+ cur++;
+ }
+ // We now have a subset for this ilabel.
+ ProcessTransition(state, ilabel, &this_subset);
+ }
+ }
+
+ // SubsetToStateId converts a subset (vector of Elements) to a StateId in the output
+ // fst. This is a hash lookup; if no such state exists, it adds a new state to the hash
+ // and adds a new pair to the queue.
+ // Side effects on hash_ and Q_, and on output_arcs_ [just affects the size].
+ OutputStateId SubsetToStateId(const std::vector<Element> &subset) { // may add the subset to the queue.
+ typedef typename SubsetHash::iterator IterType;
+ IterType iter = hash_.find(&subset);
+ if (iter == hash_.end()) { // was not there.
+ std::vector<Element> *new_subset = new std::vector<Element>(subset);
+ OutputStateId new_state_id = (OutputStateId) output_arcs_.size();
+ bool ans = hash_.insert(std::pair<const std::vector<Element>*,
+ OutputStateId>(new_subset,
+ new_state_id)).second;
+ assert(ans);
+ output_arcs_.push_back(std::vector<TempArc>());
+ if (allow_partial_ == false) {
+ // If --allow-partial is not requested, we do the old way.
+ Q_.push_front(std::pair<std::vector<Element>*, OutputStateId>(new_subset, new_state_id));
+ } else {
+ // If --allow-partial is requested, we do breadth first search. This
+ // ensures that when we return partial results, we return the states
+ // that are reachable by the fewest steps from the start state.
+ Q_.push_back(std::pair<std::vector<Element>*, OutputStateId>(new_subset, new_state_id));
+ }
+ return new_state_id;
+ } else {
+ return iter->second; // the OutputStateId.
+ }
+ }
+
+
+ // ProcessSubset does the processing of a determinized state, i.e. it creates
+ // transitions out of it and adds new determinized states to the queue if necessary.
+ // The first stage is "EpsilonClosure" (follow epsilons to get a possibly larger set
+ // of (states, weights)). After that we ignore epsilons. We process the final-weight
+ // of the state, and then handle transitions out (this may add more determinized states
+ // to the queue).
+ void ProcessSubset(const std::pair<std::vector<Element>*, OutputStateId> & pair) {
+ const std::vector<Element> *subset = pair.first;
+ OutputStateId state = pair.second;
+
+ std::vector<Element> closed_subset; // subset after epsilon closure.
+ epsilon_closure_.GetEpsilonClosure(*subset, &closed_subset);
+
+ // Now follow non-epsilon arcs [and also process final states]
+ ProcessFinal(closed_subset, state);
+
+ // Now handle transitions out of these states.
+ ProcessTransitions(closed_subset, state);
+ }
+
+ void Debug();
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(DeterminizerStar);
+ std::deque<std::pair<std::vector<Element>*, OutputStateId> > Q_; // queue of subsets to be processed.
+
+ std::vector<std::vector<TempArc> > output_arcs_; // essentially an FST in our format.
+
+ const Fst<Arc> *ifst_;
+ float delta_;
+ int max_states_;
+ bool determinized_; // used to check usage.
+ bool allow_partial_; // output paritial results or not
+ bool is_partial_; // if we get partial results or not
+ SubsetKey hasher_; // object that computes keys-- has no data members.
+ SubsetEqual equal_; // object that compares subsets-- only data member is delta_.
+ SubsetHash hash_; // hash from Subset to StateId in final Fst.
+
+ StringRepository<Label, StringId> repository_; // associate integer id's with sequences of labels.
+ EpsilonClosure epsilon_closure_;
+};
+
+
+template<class F>
+bool DeterminizeStar(F &ifst, MutableFst<typename F::Arc> *ofst,
+ float delta, bool *debug_ptr, int max_states,
+ bool allow_partial) {
+ ofst->SetOutputSymbols(ifst.OutputSymbols());
+ ofst->SetInputSymbols(ifst.InputSymbols());
+ DeterminizerStar<F> det(ifst, delta, max_states, allow_partial);
+ det.Determinize(debug_ptr);
+ det.Output(ofst);
+ return det.IsPartial();
+}
+
+
+template<class F>
+bool DeterminizeStar(F &ifst,
+ MutableFst<GallicArc<typename F::Arc> > *ofst, float delta,
+ bool *debug_ptr, int max_states,
+ bool allow_partial) {
+ ofst->SetOutputSymbols(ifst.InputSymbols());
+ ofst->SetInputSymbols(ifst.InputSymbols());
+ DeterminizerStar<F> det(ifst, delta, max_states, allow_partial);
+ det.Determinize(debug_ptr);
+ det.Output(ofst);
+ return det.IsPartial();
+}
+
+template<class F>
+void DeterminizerStar<F>::EpsilonClosure::
+ GetEpsilonClosure(const std::vector<Element> &input_subset,
+ std::vector<Element> *output_subset) {
+ ecinfo_.resize(0);
+ size_t size = input_subset.size();
+ // find whether input fst is known to be sorted in input label.
+ bool sorted =
+ ((ifst_->Properties(kILabelSorted, false) & kILabelSorted) != 0);
+
+ // size is still the input_subset.size()
+ for (size_t i = 0; i < size; i++) {
+ ExpandOneElement(input_subset[i], sorted, input_subset[i].weight, true);
+ }
+
+ size_t s = queue_2_.size();
+ if (s == 0) {
+ *output_subset = input_subset;
+ return;
+ } else {
+ // queue_2 not empty. Need to create the vector<info>
+ for (size_t i = 0; i < size; i++) {
+ // the weight has not been processed yet,
+ // so put all of them in the "weight_to_process"
+ ecinfo_.push_back(EpsilonClosureInfo(input_subset[i],
+ input_subset[i].weight,
+ false));
+ ecinfo_.back().element.weight = Weight::Zero(); // clear the weight
+
+ if (id_to_index_.size() < input_subset[i].state + 1) {
+ id_to_index_.resize(2 * input_subset[i].state + 1, -1);
+ }
+ id_to_index_[input_subset[i].state] = ecinfo_.size() - 1;
+ }
+ }
+
+ {
+ Element elem;
+ elem.weight = Weight::Zero();
+ for (size_t i = 0; i < s; i++) {
+ elem.state = queue_2_[i].state;
+ elem.string = queue_2_[i].string;
+ AddOneElement(elem, queue_2_[i].weight);
+ }
+ queue_2_.resize(0);
+ }
+
+ int counter = 0; // relates to max-states option, used for test.
+ while (!queue_.empty()) {
+ InputStateId id = queue_.front();
+
+ // no need to check validity of the index
+ // since anything in the queue we are sure they're in the "virtual set"
+ int index = id_to_index_[id];
+ EpsilonClosureInfo &info = ecinfo_[index];
+ Element &elem = info.element;
+ Weight unprocessed_weight = info.weight_to_process;
+
+ elem.weight = Plus(elem.weight, unprocessed_weight);
+ info.weight_to_process = Weight::Zero();
+
+ info.in_queue = false;
+ queue_.pop_front();
+
+ if (max_states_ > 0 && counter++ > max_states_) {
+ KALDI_ERR << "Determinization aborted since looped more than "
+ << max_states_ << " times during epsilon closure";
+ }
+
+ // generally we need to be careful about iterator-invalidation problem
+ // here we pass a reference (elem), which could be an issue.
+ // In the beginning of ExpandOneElement, we make a copy of elem.string
+ // to avoid that issue
+ ExpandOneElement(elem, sorted, unprocessed_weight);
+ }
+
+ {
+ // this sorting is based on StateId
+ std::sort(ecinfo_.begin(), ecinfo_.end());
+
+ output_subset->clear();
+
+ size = ecinfo_.size();
+ output_subset->reserve(size);
+ for (size_t i = 0; i < size; i++) {
+ EpsilonClosureInfo& info = ecinfo_[i];
+ if (info.weight_to_process != Weight::Zero()) {
+ info.element.weight = Plus(info.element.weight, info.weight_to_process);
+ }
+ output_subset->push_back(info.element);
+ }
+ }
+}
+
+template<class F>
+void DeterminizerStar<F>::EpsilonClosure::
+ AddOneElement(const Element &elem, const Weight &unprocessed_weight) {
+ // first we try to find the element info in the ecinfo_ vector
+ int index = -1;
+ if (elem.state < id_to_index_.size()) {
+ index = id_to_index_[elem.state];
+ }
+ if (index != -1) {
+ if (index >= ecinfo_.size()) {
+ index = -1;
+ }
+ // since ecinfo_ might store outdated information, we need to check
+ else if (ecinfo_[index].element.state != elem.state) {
+ index = -1;
+ }
+ }
+
+ if (index == -1) {
+ // was no such StateId: insert and add to queue.
+ ecinfo_.push_back(EpsilonClosureInfo(elem, unprocessed_weight, true));
+ size_t size = id_to_index_.size();
+ if (size < elem.state + 1) {
+ // double the size to reduce memory operations
+ id_to_index_.resize(2 * elem.state + 1, -1);
+ }
+ id_to_index_[elem.state] = ecinfo_.size() - 1;
+ queue_.push_back(elem.state);
+
+ } else { // one is already there. Add weights.
+ EpsilonClosureInfo &info = ecinfo_[index];
+ if (info.element.string != elem.string) {
+ // Non-functional FST.
+ std::ostringstream ss;
+ ss << "FST was not functional -> not determinizable.";
+ { // Print some debugging information. Can be helpful to debug
+ // the inputs when FSTs are mysteriously non-functional.
+ std::vector<Label> tmp_seq;
+ repository_->SeqOfId(info.element.string, &tmp_seq);
+ ss << "\nFirst string:";
+ for (size_t i = 0; i < tmp_seq.size(); i++)
+ ss << ' ' << tmp_seq[i];
+ ss << "\nSecond string:";
+ repository_->SeqOfId(elem.string, &tmp_seq);
+ for (size_t i = 0; i < tmp_seq.size(); i++)
+ ss << ' ' << tmp_seq[i];
+ }
+ KALDI_ERR << ss.str();
+ }
+
+ info.weight_to_process =
+ Plus(info.weight_to_process, unprocessed_weight);
+
+ if (!info.in_queue) {
+ // this is because the code in "else" below: the
+ // iter->second.weight_to_process might not be Zero()
+ Weight weight = Plus(info.element.weight, info.weight_to_process);
+
+ // What is done below is, we propagate the weight (by adding them
+ // to the queue only when the change is big enough;
+ // otherwise we just store the weight, until before returning
+ // we add the element.weight and weight_to_process together
+ if (! ApproxEqual(weight, info.element.weight, delta_)) {
+ // add extra part of weight to queue.
+ info.in_queue = true;
+ queue_.push_back(elem.state);
+ }
+ }
+ }
+}
+
+template<class F>
+void DeterminizerStar<F>::EpsilonClosure::ExpandOneElement(
+ const Element &elem,
+ bool sorted,
+ const Weight &unprocessed_weight,
+ bool save_to_queue_2) {
+ StringId str = elem.string; // copy it here because there is an iterator-
+ // - invalidation problem (it really happens for some FSTs)
+
+ // now we are going to propagate the "unprocessed_weight"
+ for (ArcIterator<Fst<Arc> > aiter(*ifst_, elem.state);
+ !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (sorted && arc.ilabel > 0) {
+ break;
+ // Break from the loop: due to sorting there will be no
+ // more transitions with epsilons as input labels.
+ }
+ if (arc.ilabel != 0) {
+ continue; // we only process epsilons here
+ }
+ Element next_elem;
+ next_elem.state = arc.nextstate;
+ next_elem.weight = Weight::Zero();
+ Weight next_unprocessed_weight
+ = Times(unprocessed_weight, arc.weight);
+
+ // now must append strings
+ if (arc.olabel == 0) {
+ next_elem.string = str;
+ } else {
+ std::vector<Label> seq;
+ repository_->SeqOfId(str, &seq);
+ if (arc.olabel != 0)
+ seq.push_back(arc.olabel);
+ next_elem.string = repository_->IdOfSeq(seq);
+ }
+ if (save_to_queue_2) {
+ next_elem.weight = next_unprocessed_weight;
+ queue_2_.push_back(next_elem);
+ } else {
+ AddOneElement(next_elem, next_unprocessed_weight);
+ }
+ }
+}
+
+template<class F>
+void DeterminizerStar<F>::Output(MutableFst<GallicArc<Arc> > *ofst,
+ bool destroy) {
+ assert(determinized_);
+ if (destroy) determinized_ = false;
+ typedef GallicWeight<Label, Weight> ThisGallicWeight;
+ typedef typename Arc::StateId StateId;
+ if (destroy)
+ FreeMostMemory();
+ StateId nStates = static_cast<StateId>(output_arcs_.size());
+ ofst->DeleteStates();
+ ofst->SetStart(kNoStateId);
+ if (nStates == 0) {
+ return;
+ }
+ for (StateId s = 0;s < nStates;s++) {
+ OutputStateId news = ofst->AddState();
+ assert(news == s);
+ }
+ ofst->SetStart(0);
+ // now process transitions.
+ for (StateId this_state = 0; this_state < nStates; this_state++) {
+ std::vector<TempArc> &this_vec(output_arcs_[this_state]);
+ typename std::vector<TempArc>::const_iterator iter = this_vec.begin(),
+ end = this_vec.end();
+ for (; iter != end; ++iter) {
+ const TempArc &temp_arc(*iter);
+ GallicArc<Arc> new_arc;
+ std::vector<Label> seq;
+ repository_.SeqOfId(temp_arc.ostring, &seq);
+ StringWeight<Label, STRING_LEFT> string_weight;
+ for (size_t i = 0;i < seq.size();i++) string_weight.PushBack(seq[i]);
+ ThisGallicWeight gallic_weight(string_weight, temp_arc.weight);
+
+ if (temp_arc.nextstate == kNoStateId) { // is really final weight.
+ ofst->SetFinal(this_state, gallic_weight);
+ } else { // is really an arc.
+ new_arc.nextstate = temp_arc.nextstate;
+ new_arc.ilabel = temp_arc.ilabel;
+ new_arc.olabel = temp_arc.ilabel; // acceptor. input == output.
+ new_arc.weight = gallic_weight; // includes string and weight.
+ ofst->AddArc(this_state, new_arc);
+ }
+ }
+ // Free up memory. Do this inside the loop as ofst is also allocating memory
+ if (destroy) { std::vector<TempArc> temp; temp.swap(this_vec); }
+ }
+ if (destroy) { std::vector<std::vector<TempArc> > temp; temp.swap(output_arcs_); }
+}
+
+template<class F>
+void DeterminizerStar<F>::Output(MutableFst<Arc> *ofst, bool destroy) {
+ assert(determinized_);
+ if (destroy) determinized_ = false;
+ // Outputs to standard fst.
+ OutputStateId num_states = static_cast<OutputStateId>(output_arcs_.size());
+ if (destroy)
+ FreeMostMemory();
+ ofst->DeleteStates();
+ if (num_states == 0) {
+ ofst->SetStart(kNoStateId);
+ return;
+ }
+ // Add basic states-- but will add extra ones to account for strings on output.
+ for (OutputStateId s = 0; s < num_states; s++) {
+ OutputStateId news = ofst->AddState();
+ assert(news == s);
+ }
+ ofst->SetStart(0);
+ for (OutputStateId this_state = 0; this_state < num_states; this_state++) {
+ std::vector<TempArc> &this_vec(output_arcs_[this_state]);
+
+ typename std::vector<TempArc>::const_iterator iter = this_vec.begin(),
+ end = this_vec.end();
+ for (; iter != end; ++iter) {
+ const TempArc &temp_arc(*iter);
+ std::vector<Label> seq;
+ repository_.SeqOfId(temp_arc.ostring, &seq);
+ if (temp_arc.nextstate == kNoStateId) { // Really a final weight.
+ // Make a sequence of states going to a final state, with the strings as labels.
+ // Put the weight on the first arc.
+ OutputStateId cur_state = this_state;
+ for (size_t i = 0; i < seq.size();i++) {
+ OutputStateId next_state = ofst->AddState();
+ Arc arc;
+ arc.nextstate = next_state;
+ arc.weight = (i == 0 ? temp_arc.weight : Weight::One());
+ arc.ilabel = 0; // epsilon.
+ arc.olabel = seq[i];
+ ofst->AddArc(cur_state, arc);
+ cur_state = next_state;
+ }
+ ofst->SetFinal(cur_state, (seq.size() == 0 ? temp_arc.weight : Weight::One()));
+ } else { // Really an arc.
+ OutputStateId cur_state = this_state;
+ // Have to be careful with this integer comparison (i+1 < seq.size()) because unsigned.
+ // i < seq.size()-1 could fail for zero-length sequences.
+ for (size_t i = 0; i+1 < seq.size();i++) {
+ // for all but the last element of seq, create new state.
+ OutputStateId next_state = ofst->AddState();
+ Arc arc;
+ arc.nextstate = next_state;
+ arc.weight = (i == 0 ? temp_arc.weight : Weight::One());
+ arc.ilabel = (i == 0 ? temp_arc.ilabel : 0); // put ilabel on first element of seq.
+ arc.olabel = seq[i];
+ ofst->AddArc(cur_state, arc);
+ cur_state = next_state;
+ }
+ // Add the final arc in the sequence.
+ Arc arc;
+ arc.nextstate = temp_arc.nextstate;
+ arc.weight = (seq.size() <= 1 ? temp_arc.weight : Weight::One());
+ arc.ilabel = (seq.size() <= 1 ? temp_arc.ilabel : 0);
+ arc.olabel = (seq.size() > 0 ? seq.back() : 0);
+ ofst->AddArc(cur_state, arc);
+ }
+ }
+ // Free up memory. Do this inside the loop as ofst is also allocating memory
+ if (destroy) { std::vector<TempArc> temp; temp.swap(this_vec); }
+ }
+ if (destroy) {
+ std::vector<std::vector<TempArc> > temp;
+ temp.swap(output_arcs_);
+ repository_.Destroy();
+ }
+}
+
+template<class F> void DeterminizerStar<F>::
+ProcessTransition(OutputStateId state, Label ilabel, std::vector<Element> *subset) {
+ // At input, "subset" may contain duplicates for a given dest state (but in sorted
+ // order). This function removes duplicates from "subset", normalizes it, and adds
+ // a transition to the dest. state (possibly affecting Q_ and hash_, if state did not
+ // exist).
+
+ typedef typename std::vector<Element>::iterator IterType;
+ { // This block makes the subset have one unique Element per state, adding the weights.
+ IterType cur_in = subset->begin(), cur_out = cur_in, end = subset->end();
+ size_t num_out = 0;
+ // Merge elements with same state-id
+ while (cur_in != end) { // while we have more elements to process.
+ // At this point, cur_out points to location of next place we want to put an element,
+ // cur_in points to location of next element we want to process.
+ if (cur_in != cur_out) *cur_out = *cur_in;
+ cur_in++;
+ while (cur_in != end && cur_in->state == cur_out->state) { // merge elements.
+ if (cur_in->string != cur_out->string) {
+ KALDI_ERR << "FST was not functional -> not determinizable";
+ }
+ cur_out->weight = Plus(cur_out->weight, cur_in->weight);
+ cur_in++;
+ }
+ cur_out++;
+ num_out++;
+ }
+ subset->resize(num_out);
+ }
+
+ StringId common_str;
+ Weight tot_weight;
+ { // This block computes common_str and tot_weight (essentially: the common divisor)
+ // and removes them from the elements.
+ std::vector<Label> seq;
+
+ IterType begin = subset->begin(), iter, end = subset->end();
+ { // This block computes "seq", which is the common prefix, and "common_str",
+ // which is the StringId version of "seq".
+ std::vector<Label> tmp_seq;
+ for (iter = begin; iter != end; ++iter) {
+ if (iter == begin) {
+ repository_.SeqOfId(iter->string, &seq);
+ } else {
+ repository_.SeqOfId(iter->string, &tmp_seq);
+ if (tmp_seq.size() < seq.size()) seq.resize(tmp_seq.size()); // size of shortest one.
+ for (size_t i = 0; i < seq.size(); i++) // seq.size() is the shorter one at this point.
+ if (tmp_seq[i] != seq[i]) seq.resize(i);
+ }
+ if (seq.size() == 0) break; // will not get any prefix.
+ }
+ common_str = repository_.IdOfSeq(seq);
+ }
+
+ { // This block computes "tot_weight".
+ iter = begin;
+ tot_weight = iter->weight;
+ for (++iter; iter != end; ++iter)
+ tot_weight = Plus(tot_weight, iter->weight);
+ }
+
+ // Now divide out common stuff from elements.
+ size_t prefix_len = seq.size();
+ for (iter = begin; iter != end; ++iter) {
+ iter->weight = Divide(iter->weight, tot_weight);
+ iter->string = repository_.RemovePrefix(iter->string, prefix_len);
+ }
+ }
+
+ // Now add an arc to the state that the subset represents.
+ // We may create a new state id for this (in SubsetToStateId).
+ TempArc temp_arc;
+ temp_arc.ilabel = ilabel;
+ temp_arc.nextstate = SubsetToStateId(*subset); // may or may not really add the subset.
+ temp_arc.ostring = common_str;
+ temp_arc.weight = tot_weight;
+ output_arcs_[state].push_back(temp_arc); // record the arc.
+}
+
+template<class F>
+void DeterminizerStar<F>::Debug() {
+ // this function called if you send a signal
+ // SIGUSR1 to the process (and it's caught by the handler in
+ // fstdeterminizestar). It prints out some traceback
+ // info and exits.
+
+ KALDI_WARN << "Debug function called (probably SIGUSR1 caught)";
+ // free up memory from the hash as we need a little memory
+ { SubsetHash hash_tmp; std::swap(hash_tmp, hash_); }
+
+ if (output_arcs_.size() <= 2) {
+ KALDI_ERR << "Nothing to trace back";
+ }
+ size_t max_state = output_arcs_.size() - 2; // don't take the last
+ // one as we might be halfway into constructing it.
+
+ std::vector<OutputStateId> predecessor(max_state+1, kNoStateId);
+ for (size_t i = 0; i < max_state; i++) {
+ for (size_t j = 0; j < output_arcs_[i].size(); j++) {
+ OutputStateId nextstate = output_arcs_[i][j].nextstate;
+ // Always find an earlier-numbered predecessor; this
+ // is always possible because of the way the algorithm
+ // works.
+ if (nextstate <= max_state && nextstate > i)
+ predecessor[nextstate] = i;
+ }
+ }
+ std::vector<std::pair<Label, StringId> > traceback;
+ // 'traceback' is a pair of (ilabel, olabel-seq).
+ OutputStateId cur_state = max_state; // A recently constructed state.
+
+ while (cur_state != 0 && cur_state != kNoStateId) {
+ OutputStateId last_state = predecessor[cur_state];
+ std::pair<Label, StringId> p;
+ size_t i;
+ for (i = 0; i < output_arcs_[last_state].size(); i++) {
+ if (output_arcs_[last_state][i].nextstate == cur_state) {
+ p.first = output_arcs_[last_state][i].ilabel;
+ p.second = output_arcs_[last_state][i].ostring;
+ traceback.push_back(p);
+ break;
+ }
+ }
+ KALDI_ASSERT(i != output_arcs_[last_state].size()); // Or fell off loop.
+ cur_state = last_state;
+ }
+ if (cur_state == kNoStateId)
+ KALDI_WARN << "Traceback did not reach start state "
+ << "(possibly debug-code error)";
+
+ std::stringstream ss;
+ ss << "Traceback follows in format "
+ << "ilabel (olabel olabel) ilabel (olabel) ... :";
+ for (ssize_t i = traceback.size() - 1; i >= 0; i--) {
+ ss << ' ' << traceback[i].first << " ( ";
+ std::vector<Label> seq;
+ repository_.SeqOfId(traceback[i].second, &seq);
+ for (size_t j = 0; j < seq.size(); j++)
+ ss << seq[j] << ' ';
+ ss << ')';
+ }
+ KALDI_ERR << ss.str();
+}
+
+} // namespace fst
+
+#endif // KALDI_FSTEXT_DETERMINIZE_STAR_INL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/determinize-star-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-star-test.cc
new file mode 100644
index 000000000..814e6a38d
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-star-test.cc
@@ -0,0 +1,508 @@
+// fstext/determinize-star-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2015 Hainan Xu
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "base/kaldi-math.h"
+#include "fstext/pre-determinize.h"
+#include "fstext/determinize-star.h"
+#include "fstext/trivial-factor-weight.h"
+#include "fstext/fst-test-utils.h"
+
+
+namespace fst
+{
+
+// test that determinization proceeds correctly on general
+// FSTs (not guaranteed determinzable, but we use the
+// max-states option to stop it getting out of control).
+template<class Arc> void TestDeterminizeGeneral() {
+ int max_states = 100; // don't allow more det-states than this.
+ for(int i = 0; i < 100; i++) {
+ VectorFst<Arc> *fst = RandFst<Arc>();
+ std::cout << "FST before determinizing is:\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ VectorFst<Arc> ofst;
+ try {
+ DeterminizeStar<Fst<Arc> >(*fst, &ofst, kDelta, NULL, max_states);
+ std::cout << "FST after determinizing is:\n";
+ {
+ FstPrinter<Arc> fstprinter(ofst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ assert(RandEquivalent(*fst, ofst, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length, max*/));
+ } catch (...) {
+ std::cout << "Failed to determinize *this FST (probably not determinizable)\n";
+ }
+ delete fst;
+ }
+}
+
+
+// Don't instantiate with log semiring, as RandEquivalent may fail.
+template<class Arc> void TestDeterminize() {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = new VectorFst<Arc>();
+ int n_syms = 2 + kaldi::Rand() % 5, n_states = 3 + kaldi::Rand() % 10, n_arcs = 5 + kaldi::Rand() % 30, n_final = 1 + kaldi::Rand()%3; // Up to 2 unique symbols.
+ std::cout << "Testing pre-determinize with "<<n_syms<<" symbols, "<<n_states<<" states and "<<n_arcs<<" arcs and "<<n_final<<" final states.\n";
+ SymbolTable *sptr = NULL;
+
+ std::vector<Label> all_syms; // including epsilon.
+ // Put symbols in the symbol table from 1..n_syms-1.
+ for (size_t i = 0;i < (size_t)n_syms;i++)
+ all_syms.push_back(i);
+
+ // Create states.
+ std::vector<StateId> all_states;
+ for (size_t i = 0;i < (size_t)n_states;i++) {
+ StateId this_state = fst->AddState();
+ if (i == 0) fst->SetStart(i);
+ all_states.push_back(this_state);
+ }
+ // Set final states.
+ for (size_t j = 0;j < (size_t)n_final;j++) {
+ StateId id = all_states[kaldi::Rand() % n_states];
+ Weight weight = (Weight)(0.33*(kaldi::Rand() % 5) );
+ printf("calling SetFinal with %d and %f\n", id, weight.Value());
+ fst->SetFinal(id, weight);
+ }
+ // Create arcs.
+ for (size_t i = 0;i < (size_t)n_arcs;i++) {
+ Arc a;
+ a.nextstate = all_states[kaldi::Rand() % n_states];
+ a.ilabel = all_syms[kaldi::Rand() % n_syms];
+ a.olabel = all_syms[kaldi::Rand() % n_syms]; // same input+output vocab.
+ a.weight = (Weight) (0.33*(kaldi::Rand() % 2));
+ StateId start_state = all_states[kaldi::Rand() % n_states];
+ fst->AddArc(start_state, a);
+ }
+
+ std::cout <<" printing before trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ // Trim resulting FST.
+ Connect(fst);
+
+ std::cout <<" printing after trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ VectorFst<Arc> *fst_copy_orig = new VectorFst<Arc>(*fst);
+
+ std::vector<Label> extra_syms;
+ if (fst->Start() != kNoStateId) { // "Connect" did not make it empty....
+ PreDeterminize(fst, 1000, &extra_syms);
+ }
+
+ std::cout <<" printing after predeterminization\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ { // Remove epsilon. All default args.
+ bool connect = true;
+ Weight weight_threshold = Weight::Zero();
+ int64 nstate = -1; // Relates to pruning.
+ double delta = kDelta; // I think a small weight value. Relates to some kind of pruning,
+ // I guess. But with no epsilon cycles, probably doensn't matter.
+ RmEpsilon(fst, connect, weight_threshold, nstate, delta);
+ }
+
+ std::cout <<" printing after epsilon removal\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ VectorFst<Arc> ofst_orig;
+ VectorFst<Arc> ofst_star;
+
+ {
+ printf("Determinizing with baseline\n");
+ DeterminizeOptions<Arc> opts; // Default options.
+ Determinize(*fst, &ofst_orig, opts);
+ }
+
+ {
+ printf("Determinizing with DeterminizeStar\n");
+ DeterminizeStar(*fst, &ofst_star);
+ }
+
+ {
+ std::cout <<" printing after determinization [baseline]\n";
+ FstPrinter<Arc> fstprinter(ofst_orig, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ assert(ofst_orig.Properties(kIDeterministic, true) == kIDeterministic);
+ }
+
+ {
+ std::cout <<" printing after determinization [star]\n";
+ FstPrinter<Arc> fstprinter(ofst_star, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ assert(ofst_star.Properties(kIDeterministic, true) == kIDeterministic);
+ }
+
+ assert(RandEquivalent(ofst_orig, ofst_star, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ int64 num_removed = DeleteISymbols(&ofst_star, extra_syms);
+ std::cout <<" printing after removing "<<num_removed<<" instances of extra symbols\n";
+ {
+ FstPrinter<Arc> fstprinter(ofst_star, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ std::cout <<" Checking equivalent to original FST.\n";
+ // giving Rand() as a seed stops the random number generator from always being reset to
+ // the same point each time, while maintaining determinism of the test.
+ assert(RandEquivalent(ofst_star, *fst_copy_orig, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ delete fst;
+ delete fst_copy_orig;
+}
+
+// Don't call this-- the test will fail due to the FST being non-functional.
+template<class Arc> void TestDeterminize2() {
+ for(int i = 0; i < 10; i++) {
+ RandFstOptions opts;
+ opts.acyclic = true;
+ VectorFst<Arc> *ifst = RandFst<Arc>(opts);
+ VectorFst<Arc> ofst;
+ Determinize(*ifst, &ofst);
+ assert(RandEquivalent(*ifst, ofst, 5, 0.01, kaldi::Rand(), 100));
+ delete ifst;
+ }
+}
+
+template<class Arc> void TestPush() {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = new VectorFst<Arc>();
+ int n_syms = 2 + kaldi::Rand() % 5, n_states = 3 + kaldi::Rand() % 10, n_arcs = 5 + kaldi::Rand() % 30, n_final = 1 + kaldi::Rand()%3; // Up to 2 unique symbols.
+ std::cout << "Testing pre-determinize with "<<n_syms<<" symbols, "<<n_states<<" states and "<<n_arcs<<" arcs and "<<n_final<<" final states.\n";
+ SymbolTable *sptr = NULL;
+
+ std::vector<Label> all_syms; // including epsilon.
+ // Put symbols in the symbol table from 1..n_syms-1.
+ for (size_t i = 0;i < (size_t)n_syms;i++)
+ all_syms.push_back(i);
+
+ // Create states.
+ std::vector<StateId> all_states;
+ for (size_t i = 0;i < (size_t)n_states;i++) {
+ StateId this_state = fst->AddState();
+ if (i == 0) fst->SetStart(i);
+ all_states.push_back(this_state);
+ }
+ // Set final states.
+ for (size_t j = 0;j < (size_t)n_final;j++) {
+ StateId id = all_states[kaldi::Rand() % n_states];
+ Weight weight = (Weight)(0.33*(kaldi::Rand() % 5) );
+ printf("calling SetFinal with %d and %f\n", id, weight.Value());
+ fst->SetFinal(id, weight);
+ }
+ // Create arcs.
+ for (size_t i = 0;i < (size_t)n_arcs;i++) {
+ Arc a;
+ a.nextstate = all_states[kaldi::Rand() % n_states];
+ a.ilabel = all_syms[kaldi::Rand() % n_syms];
+ a.olabel = all_syms[kaldi::Rand() % n_syms]; // same input+output vocab.
+ a.weight = (Weight) (0.33*(kaldi::Rand() % 2));
+ StateId start_state = all_states[kaldi::Rand() % n_states];
+ fst->AddArc(start_state, a);
+ }
+
+ std::cout <<" printing before trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ // Trim resulting FST.
+ Connect(fst);
+
+ std::cout <<" printing after trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ VectorFst<Arc> *fst_copy_orig = new VectorFst<Arc>(*fst);
+
+ std::vector<Label> extra_syms;
+ if (fst->Start() != kNoStateId) { // "Connect" did not make it empty....
+ PreDeterminize(fst, 1000, &extra_syms);
+ }
+
+ VectorFst<Arc> fst_pushed;
+ std::cout << "Pushing FST\n";
+ Push<Arc, REWEIGHT_TO_INITIAL>(*fst, &fst_pushed, kPushWeights|kPushLabels, kDelta);
+
+ std::cout <<" printing after pushing\n";
+ {
+ FstPrinter<Arc> fstprinter(fst_pushed, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ assert(RandEquivalent(*fst, fst_pushed, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ delete fst;
+ delete fst_copy_orig;
+}
+
+// Don't instantiate with log semiring, as RandEquivalent may fail.
+template<class Arc> void TestMinimize() {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = new VectorFst<Arc>();
+ int n_syms = 2 + kaldi::Rand() % 5, n_states = 3 + kaldi::Rand() % 10, n_arcs = 5 + kaldi::Rand() % 30, n_final = 1 + kaldi::Rand()%3; // Up to 2 unique symbols.
+ std::cout << "Testing pre-determinize with "<<n_syms<<" symbols, "<<n_states<<" states and "<<n_arcs<<" arcs and "<<n_final<<" final states.\n";
+ SymbolTable *sptr =NULL;
+
+ std::vector<Label> all_syms; // including epsilon.
+ // Put symbols in the symbol table from 1..n_syms-1.
+ for (size_t i = 0;i < (size_t)n_syms;i++)
+ all_syms.push_back(i);
+
+ // Create states.
+ std::vector<StateId> all_states;
+ for (size_t i = 0;i < (size_t)n_states;i++) {
+ StateId this_state = fst->AddState();
+ if (i == 0) fst->SetStart(i);
+ all_states.push_back(this_state);
+ }
+ // Set final states.
+ for (size_t j = 0;j < (size_t)n_final;j++) {
+ StateId id = all_states[kaldi::Rand() % n_states];
+ Weight weight = (Weight)(0.33*(kaldi::Rand() % 5) );
+ printf("calling SetFinal with %d and %f\n", id, weight.Value());
+ fst->SetFinal(id, weight);
+ }
+ // Create arcs.
+ for (size_t i = 0;i < (size_t)n_arcs;i++) {
+ Arc a;
+ a.nextstate = all_states[kaldi::Rand() % n_states];
+ a.ilabel = all_syms[kaldi::Rand() % n_syms];
+ a.olabel = all_syms[kaldi::Rand() % n_syms]; // same input+output vocab.
+ a.weight = (Weight) (0.33*(kaldi::Rand() % 2));
+ StateId start_state = all_states[kaldi::Rand() % n_states];
+ fst->AddArc(start_state, a);
+ }
+
+ std::cout <<" printing before trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ // Trim resulting FST.
+ Connect(fst);
+
+ std::cout <<" printing after trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ VectorFst<Arc> *fst_copy_orig = new VectorFst<Arc>(*fst);
+
+ std::vector<Label> extra_syms;
+ if (fst->Start() != kNoStateId) { // "Connect" did not make it empty....
+ PreDeterminize(fst, 1000, &extra_syms);
+ }
+
+ std::cout <<" printing after predeterminization\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ { // Remove epsilon. All default args.
+ bool connect = true;
+ Weight weight_threshold = Weight::Zero();
+ int64 nstate = -1; // Relates to pruning.
+ double delta = kDelta; // I think a small weight value. Relates to some kind of pruning,
+ // I guess. But with no epsilon cycles, probably doensn't matter.
+ RmEpsilon(fst, connect, weight_threshold, nstate, delta);
+ }
+
+ std::cout <<" printing after epsilon removal\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ VectorFst<Arc> ofst_orig;
+ VectorFst<Arc> ofst_star;
+
+ {
+ printf("Determinizing with baseline\n");
+ DeterminizeOptions<Arc> opts; // Default options.
+ Determinize(*fst, &ofst_orig, opts);
+ }
+ {
+ std::cout <<" printing after determinization [baseline]\n";
+ FstPrinter<Arc> fstprinter(ofst_orig, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ {
+ printf("Determinizing with DeterminizeStar to Gallic semiring\n");
+ VectorFst<GallicArc<Arc> > gallic_fst;
+
+ DeterminizeStar(*fst, &gallic_fst);
+ {
+ std::cout <<" printing after determinization by DeterminizeStar [in gallic]\n";
+ FstPrinter<GallicArc< Arc> > fstprinter(gallic_fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ printf("Pushing weights\n");
+ Push(&gallic_fst, REWEIGHT_TO_INITIAL, kDelta);
+
+ {
+ std::cout <<" printing after pushing weights [in gallic]\n";
+ FstPrinter<GallicArc< Arc> > fstprinter(gallic_fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ printf("Minimizing [in Gallic]\n");
+ Minimize(&gallic_fst);
+ {
+ std::cout <<" printing after minimization [in gallic]\n";
+ FstPrinter<GallicArc< Arc> > fstprinter(gallic_fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ printf("Converting gallic back to regular [my approach]\n");
+ TrivialFactorWeightFst< GallicArc<Arc, GALLIC_LEFT>, GallicFactor<typename Arc::Label,
+ typename Arc::Weight, GALLIC_LEFT> > fwfst(gallic_fst);
+ {
+ std::cout <<" printing factor-weight FST\n";
+ FstPrinter<GallicArc< Arc> > fstprinter(fwfst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ Map(fwfst, &ofst_star, FromGallicMapper<Arc, GALLIC_LEFT>());
+
+ {
+ std::cout <<" printing after converting back to regular FST\n";
+ FstPrinter<Arc> fstprinter(ofst_star, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ }
+
+
+ assert(RandEquivalent(ofst_orig, ofst_star, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+
+ int64 num_removed = DeleteISymbols(&ofst_star, extra_syms);
+ std::cout <<" printing after removing "<<num_removed<<" instances of extra symbols\n";
+ {
+ FstPrinter<Arc> fstprinter(ofst_star, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ std::cout <<" Checking equivalent to original FST.\n";
+ // giving Rand() as a seed stops the random number generator from always being reset to
+ // the same point each time, while maintaining determinism of the test.
+ assert(RandEquivalent(ofst_star, *fst_copy_orig, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ delete fst;
+ delete fst_copy_orig;
+}
+
+
+template<class Arc, class inttype> void TestStringRepository() {
+ typedef typename Arc::Label Label;
+
+ StringRepository<Label, inttype> sr;
+
+ int N = 100;
+ if (sizeof(inttype) == 1) N = 64;
+ std::vector<std::vector<Label> > strings(N);
+ std::vector<inttype> ids(N);
+
+ for (int i = 0;i < N;i++) {
+ size_t len = kaldi::Rand() % 4;
+ std::vector<Label> vec;
+ for (size_t j = 0;j < len;j++) vec.push_back( (kaldi::Rand()%10) + 150*(kaldi::Rand()%2)); // make it have reasonable range.
+ if (i < 500 && vec.size() == 0) ids[i] = sr.IdOfEmpty();
+ else if (i < 500 && vec.size() == 1) ids[i] = sr.IdOfLabel(vec[0]);
+ else ids[i] = sr.IdOfSeq(vec);
+
+ strings[i] = vec;
+ }
+
+ for (int i = 0;i < N;i++) {
+ std::vector<Label> tmpv;
+ tmpv.push_back(10); // just put in garbage.
+ sr.SeqOfId(ids[i], &tmpv);
+ assert(tmpv == strings[i]);
+ assert(sr.IdOfSeq(strings[i]) == ids[i]);
+ if (strings[i].size() == 0) assert(ids[i] == sr.IdOfEmpty());
+ if (strings[i].size() == 1) assert(ids[i] == sr.IdOfLabel(strings[i][0]));
+
+ if (sizeof(inttype) != 1) {
+ size_t prefix_len = kaldi::Rand() % (strings[i].size() + 1);
+ inttype s2 = sr.RemovePrefix(ids[i], prefix_len);
+ std::vector<Label> vec2;
+ sr.SeqOfId(s2, &vec2);
+ for (size_t j = 0;j < strings[i].size()-prefix_len;j++) {
+ assert(vec2[j] == strings[i][j+prefix_len]);
+ }
+ }
+
+ }
+}
+
+
+} // end namespace fst
+
+
+int main() {
+ for (int i = 0;i < 3;i++) { // We would need more iterations to check
+ // this properly.
+ fst::TestStringRepository<fst::StdArc, int>();
+ fst::TestStringRepository<fst::StdArc, unsigned int>();
+ // Not for use with char, but this helps reveal some kinds of bugs.
+ fst::TestStringRepository<fst::StdArc, unsigned char>();
+ fst::TestStringRepository<fst::StdArc, char>();
+ fst::TestDeterminizeGeneral<fst::StdArc>();
+ fst::TestDeterminize<fst::StdArc>();
+ // fst::TestDeterminize2<fst::StdArc>();
+ fst::TestPush<fst::StdArc>();
+ fst::TestMinimize<fst::StdArc>();
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/determinize-star.h b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-star.h
new file mode 100644
index 000000000..253068ec5
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/determinize-star.h
@@ -0,0 +1,123 @@
+// fstext/determinize-star.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2014 Guoguo Chen
+// 2015 Hainan Xu
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_DETERMINIZE_STAR_H_
+#define KALDI_FSTEXT_DETERMINIZE_STAR_H_
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+#include <algorithm>
+#include <map>
+#include <set>
+#include <vector>
+#include <stdexcept> // this algorithm uses exceptions
+
+namespace fst {
+
+/// \addtogroup fst_extensions
+/// @{
+
+
+// For example of usage, see test-determinize-star.cc
+
+/*
+ DeterminizeStar implements determinization with epsilon removal, which we
+ distinguish with a star.
+
+ We define a determinized* FST as one in which no state has more than one
+ transition with the same input-label. Epsilon input labels are not allowed
+ except starting from states that have exactly one arc exiting them (and are
+ not final). [In the normal definition of determinized, epsilon-input labels
+ are not allowed at all, whereas in Mohri's definition, epsilons are treated
+ as ordinary symbols]. The determinized* definition is intended to simulate
+ the effect of allowing strings of output symbols at each state.
+
+ The algorithm implemented here takes an Fst<Arc>, and a pointer to a
+ MutableFst<Arc> where it puts its output. The weight type is assumed to be a
+ float-weight. It does epsilon removal and determinization.
+ This algorithm may fail if the input has epsilon cycles under
+ certain circumstances (i.e. the semiring is non-idempotent, e.g. the log
+ semiring, or there are negative cost epsilon cycles).
+
+ This implementation is much less fancy than the one in fst/determinize.h, and
+ does not have an "on-demand" version.
+
+ The algorithm is a fairly normal determinization algorithm. We keep in
+ memory the subsets of states, together with their leftover strings and their
+ weights. The only difference is we detect input epsilon transitions and
+ treat them "specially".
+*/
+
+
+// This algorithm will be slightly faster if you sort the input fst on input label.
+
+/**
+ This function implements the normal version of DeterminizeStar, in which the
+ output strings are represented using sequences of arcs, where all but the
+ first one has an epsilon on the input side. The debug_ptr argument is an
+ optional pointer to a bool that, if it becomes true while the algorithm is
+ executing, the algorithm will print a traceback and terminate (used in
+ fstdeterminizestar.cc debug non-terminating determinization).
+ If max_states is positive, it will stop determinization and throw an
+ exception as soon as the max-states is reached. This can be useful in test.
+ If allow_partial is true, the algorithm will output partial results when the
+ specified max_states is reached (when larger than zero), instead of throwing
+ out an error.
+
+ Caution, the return status is un-intuitive: this function will return false if
+ determinization completed normally, and true if it was stopped early by
+ reaching the 'max-states' limit, and a partial FST was generated.
+*/
+template<class F>
+bool DeterminizeStar(F &ifst, MutableFst<typename F::Arc> *ofst,
+ float delta = kDelta,
+ bool *debug_ptr = NULL,
+ int max_states = -1,
+ bool allow_partial = false);
+
+
+
+/* This is a version of DeterminizeStar with a slightly more "natural" output format,
+ where the output sequences are encoded using the GallicArc (i.e. the output symbols
+ are strings.
+ If max_states is positive, it will stop determinization and throw an
+ exception as soon as the max-states is reached. This can be useful in test.
+ If allow_partial is true, the algorithm will output partial results when the
+ specified max_states is reached (when larger than zero), instead of throwing
+ out an error.
+
+ Caution, the return status is un-intuitive: this function will return false if
+ determinization completed normally, and true if it was stopped early by
+ reaching the 'max-states' limit, and a partial FST was generated.
+*/
+template<class F>
+bool DeterminizeStar(F &ifst, MutableFst<GallicArc<typename F::Arc> > *ofst,
+ float delta = kDelta, bool *debug_ptr = NULL,
+ int max_states = -1,
+ bool allow_partial = false);
+
+
+/// @} end "addtogroup fst_extensions"
+
+} // end namespace fst
+
+#include "fstext/determinize-star-inl.h"
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/epsilon-property-inl.h b/runtime/onnxruntime/third_party/kaldi/fstext/epsilon-property-inl.h
new file mode 100644
index 000000000..a0308bf91
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/epsilon-property-inl.h
@@ -0,0 +1,126 @@
+// fstext/epsilon-property-inl.h
+
+// Copyright 2014 Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_EPSILON_PROPERTY_INL_H_
+#define KALDI_FSTEXT_EPSILON_PROPERTY_INL_H_
+
+namespace fst {
+
+
+
+template<class Arc>
+void ComputeStateInfo(const VectorFst<Arc> &fst,
+ std::vector<char> *epsilon_info) {
+ typedef typename Arc::StateId StateId;
+ typedef VectorFst<Arc> Fst;
+ epsilon_info->clear();
+ epsilon_info->resize(fst.NumStates(), static_cast<char>(0));
+ for (StateId s = 0; s < fst.NumStates(); s++) {
+ for (ArcIterator<Fst> aiter(fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel == 0 && arc.olabel == 0) {
+ (*epsilon_info)[arc.nextstate] |= static_cast<char>(kStateHasEpsilonArcsEntering);
+ (*epsilon_info)[s] |= static_cast<char>(kStateHasEpsilonArcsLeaving);
+ } else {
+ (*epsilon_info)[arc.nextstate] |= static_cast<char>(kStateHasNonEpsilonArcsEntering);
+ (*epsilon_info)[s] |= static_cast<char>(kStateHasNonEpsilonArcsLeaving);
+ }
+ }
+ }
+}
+
+template<class Arc>
+void EnsureEpsilonProperty(VectorFst<Arc> *fst) {
+
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ typedef VectorFst<Arc> Fst;
+ std::vector<char> epsilon_info;
+ ComputeStateInfo(*fst, &epsilon_info);
+
+
+ StateId num_states_old = fst->NumStates();
+ StateId non_coaccessible_state = fst->AddState();
+
+ /// new_state_vec is for those states that have both epsilon and
+ /// non-epsilon arcs entering. For these states, we'll create a new
+ /// state for the non-epsilon arcs to enter and put it in this array,
+ /// and we'll put an epsilon transition from the new state to the old state.
+ std::vector<StateId> new_state_vec(num_states_old, kNoStateId);
+ for (StateId s = 0; s < num_states_old; s++) {
+ if ((epsilon_info[s] & kStateHasEpsilonArcsEntering) != 0 &&
+ (epsilon_info[s] & kStateHasNonEpsilonArcsEntering) != 0) {
+ assert(s != fst->Start()); // a type of cyclic FST we can't handle
+ // easily.
+ StateId new_state = fst->AddState();
+ new_state_vec[s] = new_state;
+ fst->AddArc(new_state, Arc(0, 0, Weight::One(), s));
+ }
+ }
+
+ /// First modify arcs to point to states in new_state_vec when
+ /// necessary.
+ for (StateId s = 0; s < num_states_old; s++) {
+ for (MutableArcIterator<Fst> aiter(fst, s);
+ !aiter.Done(); aiter.Next()) {
+ Arc arc = aiter.Value();
+ if (arc.ilabel != 0 || arc.olabel != 0) { // non-epsilon arc
+ StateId replacement_state;
+ if (arc.nextstate >= 0 && arc.nextstate < num_states_old &&
+ (replacement_state = new_state_vec[arc.nextstate]) !=
+ kNoStateId) {
+ arc.nextstate = replacement_state;
+ aiter.SetValue(arc);
+ }
+ }
+ }
+ }
+
+ /// Now handle the situation where states have both epsilon and non-epsilon
+ /// arcs leaving.
+ for (StateId s = 0; s < num_states_old; s++) {
+ if ((epsilon_info[s] & kStateHasEpsilonArcsLeaving) != 0 &&
+ (epsilon_info[s] & kStateHasNonEpsilonArcsLeaving) != 0) {
+ // state has non-epsilon and epsilon arcs leaving.
+ // create a new state and move the non-epsilon arcs to leave
+ // from there instead.
+ StateId new_state = fst->AddState();
+ for (MutableArcIterator<Fst> aiter(fst, s); !aiter.Done();
+ aiter.Next()) {
+ Arc arc = aiter.Value();
+ if (arc.ilabel != 0 || arc.olabel != 0) { // non-epsilon arc.
+ assert(arc.nextstate != s); // we don't handle cyclic FSTs.
+ // move this arc to leave from the new state:
+ fst->AddArc(new_state, arc);
+ arc.nextstate = non_coaccessible_state;
+ aiter.SetValue(arc); // invalidate the arc, Connect() will remove it.
+ }
+ }
+ // Create an epsilon arc to the new state.
+ fst->AddArc(s, Arc(0, 0, Weight::One(), new_state));
+ }
+ }
+ Connect(fst); // Removes arcs to the non-coaccessible state.
+}
+
+
+
+} // namespace fst.
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/epsilon-property-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/epsilon-property-test.cc
new file mode 100644
index 000000000..904de82fc
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/epsilon-property-test.cc
@@ -0,0 +1,58 @@
+// fstext/epsilon-property-test.cc
+
+// Copyright 2014 Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "fstext/rand-fst.h"
+#include "fstext/epsilon-property.h"
+
+
+namespace fst {
+
+void TestEnsureEpsilonProperty() {
+
+ for (int32 i = 0; i < 10; i++) {
+ RandFstOptions opts;
+ opts.acyclic = true;
+ VectorFst<LogArc> *fst = RandFst<LogArc>(opts);
+ VectorFst<LogArc> fst2(*fst); // copy it...
+ EnsureEpsilonProperty(&fst2);
+
+ std::vector<char> info;
+ ComputeStateInfo(fst2, &info);
+ for (size_t i = 0; i < info.size(); i++) {
+ char c = info[i];
+ assert(!((c & kStateHasEpsilonArcsEntering) != 0 &&
+ (c & kStateHasNonEpsilonArcsEntering) != 0));
+ assert(!((c & kStateHasEpsilonArcsLeaving) != 0 &&
+ (c & kStateHasNonEpsilonArcsLeaving) != 0));
+ }
+ assert(RandEquivalent(fst2, *fst, 5, 0.01, kaldi::Rand(), 10));
+ delete fst;
+ }
+}
+
+} // end namespace fst
+
+int main() {
+ using namespace fst;
+ for (int i = 0; i < 2; i++) {
+ TestEnsureEpsilonProperty();
+ }
+ std::cout << "Test OK\n";
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/epsilon-property.h b/runtime/onnxruntime/third_party/kaldi/fstext/epsilon-property.h
new file mode 100644
index 000000000..31516e485
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/epsilon-property.h
@@ -0,0 +1,60 @@
+// fstext/epsilon-property.h
+
+// Copyright 2014 Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_EPSILON_PROPERTY_H_
+#define KALDI_FSTEXT_EPSILON_PROPERTY_H_
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+
+namespace fst {
+
+enum {
+ kStateHasEpsilonArcsEntering = 0x1,
+ kStateHasNonEpsilonArcsEntering = 0x2,
+ kStateHasEpsilonArcsLeaving = 0x4,
+ kStateHasNonEpsilonArcsLeaving = 0x8
+}; // use 'char' for this enum.
+
+/// This function will set epsilon_info to have size equal to the
+/// NumStates() of the FST, containing a logical-or of the enum
+/// values kStateHasEpsilonArcsEntering, kStateHasNonEpsilonArcsEntering,
+/// kStateHasEpsilonArcsLeaving, and kStateHasNonEpsilonArcsLeaving.
+/// The meaning should be obvious. Note: an epsilon arc is defined
+/// as an arc where ilabel == olabel == 0.
+template<class Arc>
+void ComputeStateInfo(const VectorFst<Arc> &fst,
+ std::vector<char> *epsilon_info);
+
+/// This function modifies the fst (while maintaining equivalence) in such a way
+/// that, after the modification, all states of the FST which have epsilon-arcs
+/// entering them, have no non-epsilon arcs entering them, and all states which
+/// have epsilon-arcs leaving them, have no non-epsilon arcs leaving them. It does
+/// this by creating extra states and adding extra epsilon transitions. An epsilon
+/// arc is defined as an arc where both the ilabel and the olabel are epsilons.
+/// This function may fail with KALDI_ASSERT for certain cyclic FSTs, but is safe
+/// in the acyclic case.
+template<class Arc>
+void EnsureEpsilonProperty(VectorFst<Arc> *fst);
+
+} // end namespace fst
+
+
+#include "fstext/epsilon-property-inl.h"
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/factor-inl.h b/runtime/onnxruntime/third_party/kaldi/fstext/factor-inl.h
new file mode 100644
index 000000000..44fc6f214
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/factor-inl.h
@@ -0,0 +1,284 @@
+// fstext/factor-inl.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_FACTOR_INL_H_
+#define KALDI_FSTEXT_FACTOR_INL_H_
+
+#include "util/stl-utils.h"
+// Do not include this file directly. It is included by factor.h.
+
+namespace fst {
+
+// GetStateProperties takes in an FST and a number "max_state" which is the
+// highest numbered state in the FST (this could be fst.NumStates()-1 for an
+// ExpandedFst, or derived from some kind of traversal). It outputs a vector
+// numbered from 0..max_state, of type FstStateProperties which is a bitmask
+// with information about the states.
+
+// GetStateProperties has not been tested directly (only implicitly via
+// testing Factor).
+template<class Arc>
+void GetStateProperties(const Fst<Arc> &fst,
+ typename Arc::StateId max_state,
+ std::vector<StatePropertiesType> *props) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ assert(props != NULL);
+ props->clear();
+ if (fst.Start() < 0) return; // Empty fst.
+ props->resize(max_state+1, 0);
+ assert(fst.Start() <= max_state);
+ (*props)[fst.Start()] |= kStateInitial;
+ for (StateId s = 0; s <= max_state; s++) {
+ StatePropertiesType &s_info = (*props)[s];
+ for (ArcIterator<Fst<Arc> > aiter(fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0) s_info |= kStateIlabelsOut;
+ if (arc.olabel != 0) s_info |= kStateOlabelsOut;
+ StateId nexts = arc.nextstate;
+ assert(nexts <= max_state); // or input was invalid.
+ StatePropertiesType &nexts_info = (*props)[nexts];
+ if (s_info&kStateArcsOut) s_info |= kStateMultipleArcsOut;
+ s_info |= kStateArcsOut;
+ if (nexts_info&kStateArcsIn) nexts_info |= kStateMultipleArcsIn;
+ nexts_info |= kStateArcsIn;
+ }
+ if (fst.Final(s) != Weight::Zero()) s_info |= kStateFinal;
+ }
+}
+
+
+
+template<class Arc, class I>
+void Factor(const Fst<Arc> &fst, MutableFst<Arc> *ofst,
+ std::vector<std::vector<I> > *symbols_out) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Label Label;
+ typedef typename Arc::Weight Weight;
+ assert(symbols_out != NULL);
+ ofst->DeleteStates();
+ if (fst.Start() < 0) return; // empty FST.
+ std::vector<StateId> order;
+ DfsOrderVisitor<Arc> dfs_order_visitor(&order);
+ DfsVisit(fst, &dfs_order_visitor);
+ assert(order.size() > 0);
+ StateId max_state = *(std::max_element(order.begin(), order.end()));
+ std::vector<StatePropertiesType> state_properties;
+ GetStateProperties(fst, max_state, &state_properties);
+
+ std::vector<bool> remove(max_state+1); // if true, will remove this state.
+
+ // Now identify states that will be removed (made the middle of a chain).
+ // The basic rule is that if the FstStateProperties equals
+ // (kStateArcsIn|kStateArcsOut) or (kStateArcsIn|kStateArcsOut|kStateIlabelsOut),
+ // then it is in the middle of a chain. This eliminates state with
+ // multiple input or output arcs, final states, and states with arcs out
+ // that have olabels [we assume these are pushed to the left, so occur on the
+ // 1st arc of a chain.
+
+ for (StateId i = 0; i <= max_state; i++)
+ remove[i] = (state_properties[i] == (kStateArcsIn|kStateArcsOut)
+ || state_properties[i] == (kStateArcsIn|kStateArcsOut|kStateIlabelsOut));
+ std::vector<StateId> state_mapping(max_state+1, kNoStateId);
+
+ typedef unordered_map<std::vector<I>, Label, kaldi::VectorHasher<I> > SymbolMapType;
+ SymbolMapType symbol_mapping;
+ Label symbol_counter = 0;
+ {
+ std::vector<I> eps;
+ symbol_mapping[eps] = symbol_counter++;
+ }
+ std::vector<I> this_sym; // a temporary used inside the loop.
+ for (size_t i = 0; i < order.size(); i++) {
+ StateId state = order[i];
+ if (!remove[state]) { // Process this state...
+ StateId &new_state = state_mapping[state];
+ if (new_state == kNoStateId) new_state = ofst->AddState();
+ for (ArcIterator<Fst<Arc> > aiter(fst, state); !aiter.Done(); aiter.Next()) {
+ Arc arc = aiter.Value();
+ if (arc.ilabel == 0) this_sym.clear();
+ else {
+ this_sym.resize(1);
+ this_sym[0] = arc.ilabel;
+ }
+ while (remove[arc.nextstate]) {
+ ArcIterator<Fst<Arc> > aiter2(fst, arc.nextstate);
+ assert(!aiter2.Done());
+ const Arc &nextarc = aiter2.Value();
+ arc.weight = Times(arc.weight, nextarc.weight);
+ assert(nextarc.olabel == 0);
+ if (nextarc.ilabel != 0) this_sym.push_back(nextarc.ilabel);
+ assert(static_cast<Label>(static_cast<I>(nextarc.ilabel))
+ == nextarc.ilabel); // check within integer range.
+ arc.nextstate = nextarc.nextstate;
+ }
+ StateId &new_nextstate = state_mapping[arc.nextstate];
+ if (new_nextstate == kNoStateId) new_nextstate = ofst->AddState();
+ arc.nextstate = new_nextstate;
+ if (symbol_mapping.count(this_sym) != 0) arc.ilabel = symbol_mapping[this_sym];
+ else arc.ilabel = symbol_mapping[this_sym] = symbol_counter++;
+ ofst->AddArc(new_state, arc);
+ }
+ if (fst.Final(state) != Weight::Zero())
+ ofst->SetFinal(new_state, fst.Final(state));
+ }
+ }
+ ofst->SetStart(state_mapping[fst.Start()]);
+
+ // Now output the symbol sequences.
+ symbols_out->resize(symbol_counter);
+ for (typename SymbolMapType::const_iterator iter = symbol_mapping.begin();
+ iter != symbol_mapping.end(); ++iter) {
+ (*symbols_out)[iter->second] = iter->first;
+ }
+}
+
+template<class Arc>
+void Factor(const Fst<Arc> &fst, MutableFst<Arc> *ofst1,
+ MutableFst<Arc> *ofst2) {
+ typedef typename Arc::Label Label;
+ std::vector<std::vector<Label> > symbols;
+ Factor(fst, ofst2, &symbols);
+ CreateFactorFst(symbols, ofst1);
+}
+
+template<class Arc, class I>
+void ExpandInputSequences(const std::vector<std::vector<I> > &sequences,
+ MutableFst<Arc> *fst) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Label Label;
+ typedef typename Arc::Weight Weight;
+ fst->SetInputSymbols(NULL);
+ size_t size = sequences.size();
+ if (sequences.size() > 0) assert(sequences[0].size() == 0); // should be eps.
+ StateId num_states_at_start = fst->NumStates();
+ for (StateId s = 0; s < num_states_at_start; s++) {
+ StateId num_arcs = fst->NumArcs(s);
+ for (StateId aidx = 0; aidx < num_arcs; aidx++) {
+ ArcIterator<MutableFst<Arc> > aiter(*fst, s);
+ aiter.Seek(aidx);
+ Arc arc = aiter.Value();
+
+ Label ilabel = arc.ilabel;
+ Label dest_state = arc.nextstate;
+ if (ilabel != 0) { // non-eps [nothing to do if eps]...
+ assert(ilabel < static_cast<Label>(size));
+ size_t len = sequences[ilabel].size();
+ if (len <= 1) {
+ if (len == 0) arc.ilabel = 0;
+ else arc.ilabel = sequences[ilabel][0];
+ MutableArcIterator<MutableFst<Arc> > mut_aiter(fst, s);
+ mut_aiter.Seek(aidx);
+ mut_aiter.SetValue(arc);
+ } else { // len>=2. Must create new states...
+ StateId curstate = -1; // keep compiler happy: this value never used.
+ for (size_t n = 0; n < len; n++) { // adding/modifying "len" arcs.
+ StateId nextstate;
+ if (n < len-1) {
+ nextstate = fst->AddState();
+ assert(nextstate >= num_states_at_start);
+ } else nextstate = dest_state; // going back to original arc's
+ // destination.
+ if (n == 0) {
+ arc.ilabel = sequences[ilabel][0];
+ arc.nextstate = nextstate;
+ MutableArcIterator<MutableFst<Arc> > mut_aiter(fst, s);
+ mut_aiter.Seek(aidx);
+ mut_aiter.SetValue(arc);
+ } else {
+ arc.ilabel = sequences[ilabel][n];
+ arc.olabel = 0;
+ arc.weight = Weight::One();
+ arc.nextstate = nextstate;
+ fst->AddArc(curstate, arc);
+ }
+ curstate = nextstate;
+ }
+ }
+ }
+ }
+ }
+}
+
+
+
+template<class Arc, class I>
+void CreateFactorFst(const std::vector<std::vector<I> > &sequences,
+ MutableFst<Arc> *fst) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Label Label;
+ typedef typename Arc::Weight Weight;
+
+ assert(fst != NULL);
+ fst->DeleteStates();
+ StateId loopstate = fst->AddState();
+ assert(loopstate == 0);
+ fst->SetStart(0);
+ fst->SetFinal(0, Weight::One());
+ if (sequences.size() != 0) assert(sequences[0].size() == 0); // can't replace epsilon...
+
+ for (Label olabel = 1; olabel < static_cast<Label>(sequences.size()); olabel++) {
+ size_t len = sequences[olabel].size();
+ if (len == 0) {
+ Arc arc(0, olabel, Weight::One(), loopstate);
+ fst->AddArc(loopstate, arc);
+ } else {
+ StateId curstate = loopstate;
+ for (size_t i = 0; i < len; i++) {
+ StateId nextstate = (i == len-1 ? loopstate : fst->AddState());
+ Arc arc(sequences[olabel][i], (i == 0 ? olabel : 0), Weight::One(), nextstate);
+ fst->AddArc(curstate, arc);
+ curstate = nextstate;
+ }
+ }
+ }
+ fst->SetProperties(kOLabelSorted, kOLabelSorted);
+}
+
+
+template<class Arc, class I>
+void CreateMapFst(const std::vector<I> &symbol_map,
+ MutableFst<Arc> *fst) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Label Label;
+ typedef typename Arc::Weight Weight;
+
+ assert(fst != NULL);
+ fst->DeleteStates();
+ StateId loopstate = fst->AddState();
+ assert(loopstate == 0);
+ fst->SetStart(0);
+ fst->SetFinal(0, Weight::One());
+ assert(symbol_map.empty() || symbol_map[0] == 0); // FST cannot map epsilon to something else.
+ for (Label olabel = 1; olabel < static_cast<Label>(symbol_map.size()); olabel++) {
+ Arc arc(symbol_map[olabel], olabel, Weight::One(), loopstate);
+ fst->AddArc(loopstate, arc);
+ }
+}
+
+
+
+
+} // end namespace fst.
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/factor-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/factor-test.cc
new file mode 100644
index 000000000..687d0ad59
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/factor-test.cc
@@ -0,0 +1,191 @@
+// fstext/factor-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "fstext/factor.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/fst-test-utils.h"
+#include "base/kaldi-math.h"
+
+
+namespace fst
+{
+using std::vector;
+
+// Don't instantiate with log semiring, as RandEquivalent may fail.
+template<class Arc> static void TestFactor() {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> fst;
+ int n_syms = 2 + kaldi::Rand() % 5, n_arcs = 5 + kaldi::Rand() % 30, n_final = 1 + kaldi::Rand()%10;
+
+ SymbolTable symtab("my-symbol-table"), *sptr = &symtab;
+
+ vector<Label> all_syms; // including epsilon.
+ // Put symbols in the symbol table from 1..n_syms-1.
+ for (size_t i = 0;i < (size_t)n_syms;i++) {
+ std::stringstream ss;
+ if (i == 0) ss << "<eps>";
+ else ss<<i;
+ Label cur_lab = sptr->AddSymbol(ss.str());
+ assert(cur_lab == (Label)i);
+ all_syms.push_back(cur_lab);
+ }
+ assert(all_syms[0] == 0);
+
+ fst.AddState();
+ int cur_num_states = 1;
+ for (int i = 0; i < n_arcs; i++) {
+ StateId src_state = kaldi::Rand() % cur_num_states;
+ StateId dst_state;
+ if (kaldi::RandUniform() < 0.1) dst_state = kaldi::Rand() % cur_num_states;
+ else {
+ dst_state = cur_num_states++; fst.AddState();
+ }
+ Arc arc;
+ if (kaldi::RandUniform() < 0.5) arc.ilabel = all_syms[kaldi::Rand()%all_syms.size()];
+ else arc.ilabel = 0;
+ if (kaldi::RandUniform() < 0.5) arc.olabel = all_syms[kaldi::Rand()%all_syms.size()];
+ else arc.olabel = 0;
+ arc.weight = (Weight) (0 + 0.1*(kaldi::Rand() % 5));
+ arc.nextstate = dst_state;
+ fst.AddArc(src_state, arc);
+ }
+ for (int i = 0; i < n_final; i++) {
+ fst.SetFinal(kaldi::Rand() % cur_num_states, (Weight) (0 + 0.1*(kaldi::Rand() % 5)));
+ }
+
+ if (kaldi::RandUniform() < 0.8) fst.SetStart(0); // usually leads to nicer examples.
+ else fst.SetStart(kaldi::Rand() % cur_num_states);
+
+ std::cout <<" printing before trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ // Trim resulting FST.
+ Connect(&fst);
+
+ std::cout <<" printing after trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ if (fst.Start() == kNoStateId) return; // "Connect" made it empty.
+
+ VectorFst<Arc> fst_pushed;
+ Push<Arc, REWEIGHT_TO_INITIAL>(fst, &fst_pushed, kPushLabels);
+
+ VectorFst<Arc> fst_factored;
+ vector<vector<typename Arc::Label> > symbols;
+
+ Factor(fst, &fst_factored, &symbols);
+
+ // Check no epsilons in "symbols".
+ for (size_t i = 0; i < symbols.size(); i++)
+ assert(symbols[i].size() == 0 || *(std::min(symbols[i].begin(), symbols[i].end())) > 0);
+
+ VectorFst<Arc> fst_factored_pushed;
+ vector<vector<typename Arc::Label> > symbols_pushed;
+ Factor(fst_pushed, &fst_factored_pushed, &symbols_pushed);
+
+ std::cout << "Unfactored has "<<fst.NumStates()<<" states, factored has "<<fst_factored.NumStates()<<", and pushed+factored has "<<fst_factored_pushed.NumStates()<<'\n';
+
+ assert(fst_factored.NumStates() <= fst.NumStates());
+ // assert(fst_factored_pushed.NumStates() <= fst_factored.NumStates()); // pushing should only help. [ no, it doesn't]
+ assert(fst_factored_pushed.NumStates() <= fst_pushed.NumStates());
+
+ VectorFst<Arc> fst_factored_copy(fst_factored);
+
+ VectorFst<Arc> fst_factored_unfactored(fst_factored);
+ ExpandInputSequences(symbols, &fst_factored_unfactored);
+
+ VectorFst<Arc> factor_fst;
+ CreateFactorFst(symbols, &factor_fst);
+ VectorFst<Arc> fst_factored_unfactored2;
+ Compose(factor_fst, fst_factored, &fst_factored_unfactored2);
+
+ ExpandInputSequences(symbols_pushed, &fst_factored_pushed);
+
+ assert(RandEquivalent(fst, fst_factored_unfactored, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ assert(RandEquivalent(fst, fst_factored_unfactored2, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ assert(RandEquivalent(fst, fst_factored_pushed, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ { // Have tested for equivalence; now do another test: that FactorFst actually finds all
+ // the factors. Do this by inserting factors using ExpandInputSequences and making sure it gets
+ // rid of them all.
+ Label max_label = *(std::max_element(all_syms.begin(), all_syms.end()));
+ vector<vector<Label> > new_labels(max_label+1);
+ for (Label l = 1; l < static_cast<Label>(new_labels.size()); l++) {
+ int n = kaldi::Rand() % 5;
+ for (int i = 0; i < n; i++) new_labels[l].push_back(kaldi::Rand() % 100);
+ }
+ VectorFst<Arc> fst_expanded(fst);
+ ExpandInputSequences(new_labels, &fst_expanded);
+
+ vector<vector<Label> > factors;
+ VectorFst<Arc> fst_reduced;
+ Factor(fst_expanded, &fst_reduced, &factors);
+ assert(fst_reduced.NumStates() <= fst.NumStates()); // Checking that it found all the factors.
+ }
+
+ { // This block test MapInputSymbols [but relies on the correctness of Factor
+ // and ExpandInputSequences to do so].
+
+ std::map<Label, Label> symbols_reverse_map; // from new->old.
+ symbols_reverse_map[0] = 0; // map eps to eps.
+ for (Label i = 1; i < static_cast<Label>(symbols.size()); i++) {
+ Label new_i;
+ do {
+ new_i = kaldi::Rand() % (symbols.size() + 20);
+ } while (symbols_reverse_map.count(new_i) == 1);
+ symbols_reverse_map[new_i] = i;
+ }
+ vector<vector<Label> > symbols_new;
+ vector<Label> symbol_map(symbols.size()); // from old->new.
+ typename std::map<Label, Label>::iterator iter = symbols_reverse_map.begin();
+ for (; iter != symbols_reverse_map.end(); iter++) {
+ Label new_label = iter->first, old_label = iter->second;
+ if (new_label >= static_cast<Label>(symbols_new.size())) symbols_new.resize(new_label+1);
+ symbols_new[new_label] = symbols[old_label];
+ symbol_map[old_label] = new_label;
+ }
+ MapInputSymbols(symbol_map, &fst_factored_copy);
+ ExpandInputSequences(symbols_new, &fst_factored_copy);
+ assert(RandEquivalent(fst, fst_factored_copy,
+ 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/,
+ 100/*path length-- max?*/));
+ }
+
+}
+
+
+} // namespace fst
+
+int main() {
+ using namespace fst;
+ for (int i = 0;i < 25;i++) {
+ TestFactor<fst::StdArc>();
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/factor.h b/runtime/onnxruntime/third_party/kaldi/fstext/factor.h
new file mode 100644
index 000000000..5b34f4051
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/factor.h
@@ -0,0 +1,158 @@
+// fstext/factor.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_FACTOR_H_
+#define KALDI_FSTEXT_FACTOR_H_
+
+/*
+ This header declares the Factor function, which takes an FST and
+ compresses it by detecting linear chains of states, and creating
+ special input symbols that represent these chains. It outputs enough
+ information to be able to reconstruct the original sequences [i.e.
+ the mapping between the new symbols, and sequences of the original
+ symbols]. It ensures that the original symbols all have the same
+ number as a corresponding "new" symbol representing a sequence of length
+ one; this enables certain optimizations later on.
+*/
+
+
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+#include "util/const-integer-set.h"
+
+namespace fst {
+
+
+/**
+ Factor identifies linear chains of states with an olabel (if any)
+ only on the first arc of the chain, and possibly a sequence of
+ ilabels; it outputs an FST with different symbols on the input
+ that represent sequences of the original input symbols; it outputs
+ the mapping from the new symbol to sequences of original symbols,
+ as "symbols" [zero is reserved for epsilon].
+
+ As a side effect it also sorts the FST in depth-first order. Factor will
+ usually do the best job when the olabels have been pushed to the left,
+ i.e. if you make a call like
+
+ Push<Arc, REWEIGHT_TO_INITIAL>(fsta, &fstb, kPushLabels);
+
+ This is because it only creates a chain with olabels on the first arc of the
+ chain (or a chain with no olabels). [it's possible to construct cases where
+ pushing makes things worse, though]. After Factor, the composition of *ofst
+ with the result of calling CreateFactorFst(*symbols) should be equivalent to
+ fst. Alternatively, calling ExpandInputSequences with ofst and *symbols
+ would produce something equivalent to fst.
+*/
+
+template<class Arc, class I>
+void Factor(const Fst<Arc> &fst, MutableFst<Arc> *ofst,
+ std::vector<std::vector<I> > *symbols);
+
+
+/// This is a more conventional interface of Factor that outputs
+/// the result as two FSTs.
+template<class Arc>
+void Factor(const Fst<Arc> &fst, MutableFst<Arc> *ofst1,
+ MutableFst<Arc> *ofst2);
+
+
+
+/// ExpandInputSequences expands out the input symbols into sequences of input
+/// symbols. It creates linear chains of states for each arc that had >1
+/// augmented symbol on it. It also sets the input symbol table to NULL, since
+/// in case you did have a symbol table there it would no longer be valid. It
+/// leaves any weight and output symbols on the first arc of the chain.
+template<class Arc, class I>
+void ExpandInputSequences(const std::vector<std::vector<I> > &sequences,
+ MutableFst<Arc> *fst);
+
+
+/// The function CreateFactorFst will create an FST that expands out the
+/// "factors" that are the indices of the "sequences" array, into linear sequences
+/// of symbols. There is a single start and end state (state 0), and for each
+/// nonzero index i into the array "sequences", there is an arc from state 0 that
+/// has output-label i, and enters a chain of states with output epsilons and input
+/// labels corresponding to the remaining elements of the sequences, terminating
+/// again in state 0. This FST is output-deterministic and sorted on olabel.
+/// Composing an FST on the left with the output of this function, should be the
+/// same as calling "ExpandInputSequences". Use TableCompose (see table-matcher.h)
+/// for efficiency.
+template<class Arc, class I>
+void CreateFactorFst(const std::vector<std::vector<I> > &sequences,
+ MutableFst<Arc> *fst);
+
+
+/// CreateMapFst will create an FST representing this symbol_map. The
+/// FST has a single loop state with single-arc loops with
+/// isymbol = symbol_map[i], osymbol = i. The resulting FST applies this
+/// map to the input symbols of something we compose with it on the right.
+/// Must have symbol_map[0] == 0.
+template<class Arc, class I>
+void CreateMapFst(const std::vector<I> &symbol_map,
+ MutableFst<Arc> *fst);
+
+
+enum StatePropertiesEnum
+{ kStateFinal = 0x1,
+ kStateInitial = 0x2,
+ kStateArcsIn = 0x4,
+ kStateMultipleArcsIn = 0x8,
+ kStateArcsOut = 0x10,
+ kStateMultipleArcsOut = 0x20,
+ kStateOlabelsOut = 0x40,
+ kStateIlabelsOut = 0x80 };
+
+typedef unsigned char StatePropertiesType;
+
+/**
+ This function works out various properties of the states in the
+ FST, using the bit properties defined in StatePropertiesEnum. */
+template<class Arc>
+void GetStateProperties(const Fst<Arc> &fst,
+ typename Arc::StateId max_state,
+ std::vector<StatePropertiesType> *props);
+
+
+
+template<class Arc>
+class DfsOrderVisitor {
+ // visitor class that gives the user the dfs order,
+ // c.f. dfs-visit.h. Used in factor-fst-impl.h
+ typedef typename Arc::StateId StateId;
+ public:
+ DfsOrderVisitor(std::vector<StateId> *order): order_(order) { order->clear(); }
+ void InitVisit(const Fst<Arc> &fst) {}
+ bool InitState(StateId s, StateId) { order_->push_back(s); return true; }
+ bool TreeArc(StateId, const Arc&) { return true; }
+ bool BackArc(StateId, const Arc&) { return true; }
+ bool ForwardOrCrossArc(StateId, const Arc&) { return true; }
+ void FinishState(StateId, StateId, const Arc *) { }
+ void FinishVisit() { }
+ private:
+ std::vector<StateId> *order_;
+};
+
+
+
+} // namespace fst
+
+#include "factor-inl.h"
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/fst-test-utils.h b/runtime/onnxruntime/third_party/kaldi/fstext/fst-test-utils.h
new file mode 100644
index 000000000..df12e042c
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/fst-test-utils.h
@@ -0,0 +1,33 @@
+// fstext/fst-test-utils.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_FST_TEST_UTILS_H_
+#define KALDI_FSTEXT_FST_TEST_UTILS_H_
+
+
+#include <sstream>
+#include <string>
+
+// Just some #includes.
+#include "fst/script/print-impl.h"
+#include "fstext/rand-fst.h"
+
+
+#endif
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/fstext-lib.h b/runtime/onnxruntime/third_party/kaldi/fstext/fstext-lib.h
new file mode 100644
index 000000000..bdb8ff730
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/fstext-lib.h
@@ -0,0 +1,36 @@
+// fstext/fstext-lib.h
+
+// Copyright 2009-2012 Microsoft Corporation Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_FSTEXT_LIB_H_
+#define KALDI_FSTEXT_FSTEXT_LIB_H_
+#include "fst/fstlib.h"
+#include "fstext/context-fst.h"
+#include "fstext/determinize-star.h"
+#include "fstext/factor.h"
+#include "fstext/fst-test-utils.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/pre-determinize.h"
+#include "fstext/table-matcher.h"
+#include "fstext/trivial-factor-weight.h"
+#include "fstext/lattice-weight.h"
+#include "fstext/lattice-utils.h"
+#include "fstext/determinize-lattice.h"
+#include "fstext/deterministic-fst.h"
+#include "fstext/kaldi-fst-io.h"
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/fstext-utils-inl.h b/runtime/onnxruntime/third_party/kaldi/fstext/fstext-utils-inl.h
new file mode 100644
index 000000000..853697387
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/fstext-utils-inl.h
@@ -0,0 +1,1284 @@
+// fstext/fstext-utils-inl.h
+
+// Copyright 2009-2012 Microsoft Corporation Johns Hopkins University (Author: Daniel Povey)
+// 2014 Telepoint Global Hosting Service, LLC. (Author: David Snyder)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_FSTEXT_UTILS_INL_H_
+#define KALDI_FSTEXT_FSTEXT_UTILS_INL_H_
+#include <cstring>
+#include "base/kaldi-common.h"
+#include "util/stl-utils.h"
+#include "util/text-utils.h"
+#include "util/kaldi-io.h"
+#include "fstext/factor.h"
+#include "fstext/pre-determinize.h"
+#include "fstext/determinize-star.h"
+
+#include <sstream>
+#include <algorithm>
+#include <string>
+
+namespace fst {
+
+
+
+template<class Arc>
+typename Arc::Label HighestNumberedOutputSymbol(const Fst<Arc> &fst) {
+ typename Arc::Label ans = 0;
+ for (StateIterator<Fst<Arc> > siter(fst); !siter.Done(); siter.Next()) {
+ typename Arc::StateId s = siter.Value();
+ for (ArcIterator<Fst<Arc> > aiter(fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ ans = std::max(ans, arc.olabel);
+ }
+ }
+ return ans;
+}
+
+template<class Arc>
+typename Arc::Label HighestNumberedInputSymbol(const Fst<Arc> &fst) {
+ typename Arc::Label ans = 0;
+ for (StateIterator<Fst<Arc> > siter(fst); !siter.Done(); siter.Next()) {
+ typename Arc::StateId s = siter.Value();
+ for (ArcIterator<Fst<Arc> > aiter(fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ ans = std::max(ans, arc.ilabel);
+ }
+ }
+ return ans;
+}
+
+template<class Arc>
+typename Arc::StateId NumArcs(const ExpandedFst<Arc> &fst) {
+ typedef typename Arc::StateId StateId;
+ StateId num_arcs = 0;
+ for (StateId s = 0; s < fst.NumStates(); s++)
+ num_arcs += fst.NumArcs(s);
+ return num_arcs;
+}
+
+template<class Arc, class I>
+void GetOutputSymbols(const Fst<Arc> &fst,
+ bool include_eps,
+ std::vector<I> *symbols) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ std::set<I> all_syms;
+ for (StateIterator<Fst<Arc> > siter(fst); !siter.Done(); siter.Next()) {
+ typename Arc::StateId s = siter.Value();
+ for (ArcIterator<Fst<Arc> > aiter(fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ all_syms.insert(arc.olabel);
+ }
+ }
+
+ // Remove epsilon, if instructed.
+ if (!include_eps && !all_syms.empty() && *all_syms.begin() == 0)
+ all_syms.erase(0);
+ KALDI_ASSERT(symbols != NULL);
+ kaldi::CopySetToVector(all_syms, symbols);
+}
+
+template<class Arc, class I>
+void GetInputSymbols(const Fst<Arc> &fst,
+ bool include_eps,
+ std::vector<I> *symbols) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ unordered_set<I> all_syms;
+ for (StateIterator<Fst<Arc> > siter(fst); !siter.Done(); siter.Next()) {
+ typename Arc::StateId s = siter.Value();
+ for (ArcIterator<Fst<Arc> > aiter(fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ all_syms.insert(arc.ilabel);
+ }
+ }
+ // Remove epsilon, if instructed.
+ if (!include_eps && all_syms.count(0) != 0)
+ all_syms.erase(0);
+ KALDI_ASSERT(symbols != NULL);
+ kaldi::CopySetToVector(all_syms, symbols);
+ std::sort(symbols->begin(), symbols->end());
+}
+
+template<class Arc, class I>
+class RemoveSomeInputSymbolsMapper {
+public:
+ Arc operator ()(const Arc &arc_in) {
+ Arc ans = arc_in;
+ if (to_remove_set_.count(ans.ilabel) != 0) ans.ilabel = 0; // remove this symbol
+ return ans;
+ }
+ MapFinalAction FinalAction() { return MAP_NO_SUPERFINAL; }
+ MapSymbolsAction InputSymbolsAction() { return MAP_CLEAR_SYMBOLS; }
+ MapSymbolsAction OutputSymbolsAction() { return MAP_COPY_SYMBOLS; }
+ uint64 Properties(uint64 props) const {
+ // remove the following as we don't know now if any of them are true.
+ uint64 to_remove = kAcceptor|kNotAcceptor|kIDeterministic|kNonIDeterministic|
+ kNoEpsilons|kNoIEpsilons|kILabelSorted|kNotILabelSorted;
+ return props & ~to_remove;
+ }
+ RemoveSomeInputSymbolsMapper(const std::vector<I> &to_remove):
+ to_remove_set_(to_remove) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ assert(to_remove_set_.count(0) == 0); // makes no sense to remove epsilon.
+ }
+private:
+ kaldi::ConstIntegerSet<I> to_remove_set_;
+};
+
+template<class Arc, class I>
+using LookaheadFst = ArcMapFst<Arc, Arc, RemoveSomeInputSymbolsMapper<Arc, I> >;
+
+// Lookahead composition is used for optimized online
+// composition of FSTs during decoding. See
+// nnet3/nnet3-latgen-faster-lookahead.cc. For details of compose filters
+// see DefaultLookAhead in fst/compose.h
+template<class Arc, class I>
+LookaheadFst<Arc, I> *LookaheadComposeFst(const Fst<Arc> &ifst1,
+ const Fst<Arc> &ifst2,
+ const std::vector<I> &to_remove) {
+ fst::CacheOptions cache_opts(true, 1 << 25LL);
+ fst::CacheOptions cache_opts_map(true, 0);
+ fst::ArcMapFstOptions arcmap_opts(cache_opts);
+ RemoveSomeInputSymbolsMapper<Arc, I> mapper(to_remove);
+ return new LookaheadFst<Arc, I>(ComposeFst<Arc>(ifst1, ifst2, cache_opts), mapper, arcmap_opts);
+}
+
+template<class Arc, class I>
+void RemoveSomeInputSymbols(const std::vector<I> &to_remove,
+ MutableFst<Arc> *fst) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ RemoveSomeInputSymbolsMapper<Arc, I> mapper(to_remove);
+ Map(fst, mapper);
+}
+
+template<class Arc, class I>
+class MapInputSymbolsMapper {
+ public:
+ Arc operator ()(const Arc &arc_in) {
+ Arc ans = arc_in;
+ if (ans.ilabel > 0 &&
+ ans.ilabel < static_cast<typename Arc::Label>((*symbol_mapping_).size()))
+ ans.ilabel = (*symbol_mapping_)[ans.ilabel];
+ return ans;
+ }
+ MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; }
+ MapSymbolsAction InputSymbolsAction() const { return MAP_CLEAR_SYMBOLS; }
+ MapSymbolsAction OutputSymbolsAction() const { return MAP_COPY_SYMBOLS; }
+ uint64 Properties(uint64 props) const { // Not tested.
+ bool remove_epsilons = (symbol_mapping_->size() > 0 && (*symbol_mapping_)[0] != 0);
+ bool add_epsilons = (symbol_mapping_->size() > 1 &&
+ *std::min_element(symbol_mapping_->begin()+1, symbol_mapping_->end()) == 0);
+
+ // remove the following as we don't know now if any of them are true.
+ uint64 props_to_remove = kAcceptor|kNotAcceptor|kIDeterministic|kNonIDeterministic|
+ kILabelSorted|kNotILabelSorted;
+ if (remove_epsilons) props_to_remove |= kEpsilons|kIEpsilons;
+ if (add_epsilons) props_to_remove |= kNoEpsilons|kNoIEpsilons;
+ uint64 props_to_add = 0;
+ if (remove_epsilons && !add_epsilons) props_to_add |= kNoEpsilons|kNoIEpsilons;
+ return (props & ~props_to_remove) | props_to_add;
+ }
+ // initialize with copy = false only if the "to_remove" argument will not be deleted
+ // in the lifetime of this object.
+ MapInputSymbolsMapper(const std::vector<I> &to_remove, bool copy) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ if (copy) symbol_mapping_ = new std::vector<I> (to_remove);
+ else symbol_mapping_ = &to_remove;
+ owned = copy;
+ }
+ ~MapInputSymbolsMapper() { if (owned && symbol_mapping_ != NULL) delete symbol_mapping_; }
+ private:
+ bool owned;
+ const std::vector<I> *symbol_mapping_;
+};
+
+template<class Arc, class I>
+void MapInputSymbols(const std::vector<I> &symbol_mapping,
+ MutableFst<Arc> *fst) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ // false == don't copy the "symbol_mapping", retain pointer--
+ // safe since short-lived object.
+ MapInputSymbolsMapper<Arc, I> mapper(symbol_mapping, false);
+ Map(fst, mapper);
+}
+
+template<class Arc, class I>
+bool GetLinearSymbolSequence(const Fst<Arc> &fst,
+ std::vector<I> *isymbols_out,
+ std::vector<I> *osymbols_out,
+ typename Arc::Weight *tot_weight_out) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ Weight tot_weight = Weight::One();
+ std::vector<I> ilabel_seq;
+ std::vector<I> olabel_seq;
+
+ StateId cur_state = fst.Start();
+ if (cur_state == kNoStateId) { // empty sequence.
+ if (isymbols_out != NULL) isymbols_out->clear();
+ if (osymbols_out != NULL) osymbols_out->clear();
+ if (tot_weight_out != NULL) *tot_weight_out = Weight::Zero();
+ return true;
+ }
+ while (1) {
+ Weight w = fst.Final(cur_state);
+ if (w != Weight::Zero()) { // is final..
+ tot_weight = Times(tot_weight, w);
+ if (fst.NumArcs(cur_state) != 0) return false;
+ if (isymbols_out != NULL) *isymbols_out = ilabel_seq;
+ if (osymbols_out != NULL) *osymbols_out = olabel_seq;
+ if (tot_weight_out != NULL) *tot_weight_out = tot_weight;
+ return true;
+ } else {
+ if (fst.NumArcs(cur_state) != 1) return false;
+
+ ArcIterator<Fst<Arc> > iter(fst, cur_state); // get the only arc.
+ const Arc &arc = iter.Value();
+ tot_weight = Times(tot_weight, arc.weight);
+ if (arc.ilabel != 0) ilabel_seq.push_back(arc.ilabel);
+ if (arc.olabel != 0) olabel_seq.push_back(arc.olabel);
+ cur_state = arc.nextstate;
+ }
+ }
+}
+
+
+// see fstext-utils.h for comment.
+template<class Arc>
+void ConvertNbestToVector(const Fst<Arc> &fst,
+ std::vector<VectorFst<Arc> > *fsts_out) {
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId StateId;
+ fsts_out->clear();
+ StateId start_state = fst.Start();
+ if (start_state == kNoStateId) return; // No output.
+ size_t n_arcs = fst.NumArcs(start_state);
+ bool start_is_final = (fst.Final(start_state) != Weight::Zero());
+ fsts_out->reserve(n_arcs + (start_is_final ? 1 : 0));
+
+ if (start_is_final) {
+ fsts_out->resize(fsts_out->size() + 1);
+ StateId start_state_out = fsts_out->back().AddState();
+ fsts_out->back().SetFinal(start_state_out, fst.Final(start_state));
+ }
+
+ for (ArcIterator<Fst<Arc> > start_aiter(fst, start_state);
+ !start_aiter.Done();
+ start_aiter.Next()) {
+ fsts_out->resize(fsts_out->size() + 1);
+ VectorFst<Arc> &ofst = fsts_out->back();
+ const Arc &first_arc = start_aiter.Value();
+ StateId cur_state = start_state,
+ cur_ostate = ofst.AddState();
+ ofst.SetStart(cur_ostate);
+ StateId next_ostate = ofst.AddState();
+ ofst.AddArc(cur_ostate, Arc(first_arc.ilabel, first_arc.olabel,
+ first_arc.weight, next_ostate));
+ cur_state = first_arc.nextstate;
+ cur_ostate = next_ostate;
+ while (1) {
+ size_t this_n_arcs = fst.NumArcs(cur_state);
+ KALDI_ASSERT(this_n_arcs <= 1); // or it violates our assumptions
+ // about the input.
+ if (this_n_arcs == 1) {
+ KALDI_ASSERT(fst.Final(cur_state) == Weight::Zero());
+ // or problem with ShortestPath.
+ ArcIterator<Fst<Arc> > aiter(fst, cur_state);
+ const Arc &arc = aiter.Value();
+ next_ostate = ofst.AddState();
+ ofst.AddArc(cur_ostate, Arc(arc.ilabel, arc.olabel,
+ arc.weight, next_ostate));
+ cur_state = arc.nextstate;
+ cur_ostate = next_ostate;
+ } else {
+ KALDI_ASSERT(fst.Final(cur_state) != Weight::Zero());
+ // or problem with ShortestPath.
+ ofst.SetFinal(cur_ostate, fst.Final(cur_state));
+ break;
+ }
+ }
+ }
+}
+
+
+// see fstext-utils.sh for comment.
+template<class Arc>
+void NbestAsFsts(const Fst<Arc> &fst,
+ size_t n,
+ std::vector<VectorFst<Arc> > *fsts_out) {
+ KALDI_ASSERT(n > 0);
+ KALDI_ASSERT(fsts_out != NULL);
+ VectorFst<Arc> nbest_fst;
+ ShortestPath(fst, &nbest_fst, n);
+ ConvertNbestToVector(nbest_fst, fsts_out);
+}
+
+template<class Arc, class I>
+void MakeLinearAcceptorWithAlternatives(const std::vector<std::vector<I> > &labels,
+ MutableFst<Arc> *ofst) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ ofst->DeleteStates();
+ StateId cur_state = ofst->AddState();
+ ofst->SetStart(cur_state);
+ for (size_t i = 0; i < labels.size(); i++) {
+ KALDI_ASSERT(labels[i].size() != 0);
+ StateId next_state = ofst->AddState();
+ for (size_t j = 0; j < labels[i].size(); j++) {
+ Arc arc(labels[i][j], labels[i][j], Weight::One(), next_state);
+ ofst->AddArc(cur_state, arc);
+ }
+ cur_state = next_state;
+ }
+ ofst->SetFinal(cur_state, Weight::One());
+}
+
+template<class Arc, class I>
+void MakeLinearAcceptor(const std::vector<I> &labels, MutableFst<Arc> *ofst) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ ofst->DeleteStates();
+ StateId cur_state = ofst->AddState();
+ ofst->SetStart(cur_state);
+ for (size_t i = 0; i < labels.size(); i++) {
+ StateId next_state = ofst->AddState();
+ Arc arc(labels[i], labels[i], Weight::One(), next_state);
+ ofst->AddArc(cur_state, arc);
+ cur_state = next_state;
+ }
+ ofst->SetFinal(cur_state, Weight::One());
+}
+
+
+template<class I>
+void GetSymbols(const SymbolTable &symtab,
+ bool include_eps,
+ std::vector<I> *syms_out) {
+ KALDI_ASSERT(syms_out != NULL);
+ syms_out->clear();
+ for (SymbolTableIterator iter(symtab);
+ !iter.Done();
+ iter.Next()) {
+ if (include_eps || iter.Value() != 0) {
+ syms_out->push_back(iter.Value());
+ KALDI_ASSERT(syms_out->back() == iter.Value()); // an integer-range thing.
+ }
+ }
+}
+
+template<class Arc>
+void SafeDeterminizeWrapper(MutableFst<Arc> *ifst, MutableFst<Arc> *ofst, float delta) {
+ typename Arc::Label highest_sym = HighestNumberedInputSymbol(*ifst);
+ std::vector<typename Arc::Label> extra_syms;
+ PreDeterminize(ifst,
+ (typename Arc::Label)(highest_sym+1),
+ &extra_syms);
+ DeterminizeStar(*ifst, ofst, delta);
+ RemoveSomeInputSymbols(extra_syms, ofst); // remove the extra symbols.
+}
+
+
+template<class Arc>
+void SafeDeterminizeMinimizeWrapper(MutableFst<Arc> *ifst, VectorFst<Arc> *ofst, float delta) {
+ typename Arc::Label highest_sym = HighestNumberedInputSymbol(*ifst);
+ std::vector<typename Arc::Label> extra_syms;
+ PreDeterminize(ifst,
+ (typename Arc::Label)(highest_sym+1),
+ &extra_syms);
+ DeterminizeStar(*ifst, ofst, delta);
+ RemoveSomeInputSymbols(extra_syms, ofst); // remove the extra symbols.
+ RemoveEpsLocal(ofst); // this is "safe" and will never hurt.
+ MinimizeEncoded(ofst, delta);
+}
+
+
+inline
+void DeterminizeStarInLog(VectorFst<StdArc> *fst, float delta, bool *debug_ptr, int max_states) {
+ // DeterminizeStarInLog determinizes 'fst' in the log semiring, using
+ // the DeterminizeStar algorithm (which also removes epsilons).
+
+ ArcSort(fst, ILabelCompare<StdArc>()); // helps DeterminizeStar to be faster.
+ VectorFst<LogArc> *fst_log = new VectorFst<LogArc>; // Want to determinize in log semiring.
+ Cast(*fst, fst_log);
+ VectorFst<StdArc> tmp;
+ *fst = tmp; // make fst empty to free up memory. [actually may make no difference..]
+ VectorFst<LogArc> *fst_det_log = new VectorFst<LogArc>;
+ DeterminizeStar(*fst_log, fst_det_log, delta, debug_ptr, max_states);
+ Cast(*fst_det_log, fst);
+ delete fst_log;
+ delete fst_det_log;
+}
+
+inline
+void DeterminizeInLog(VectorFst<StdArc> *fst) {
+ // DeterminizeInLog determinizes 'fst' in the log semiring.
+
+ ArcSort(fst, ILabelCompare<StdArc>()); // helps DeterminizeStar to be faster.
+ VectorFst<LogArc> *fst_log = new VectorFst<LogArc>; // Want to determinize in log semiring.
+ Cast(*fst, fst_log);
+ VectorFst<StdArc> tmp;
+ *fst = tmp; // make fst empty to free up memory. [actually may make no difference..]
+ VectorFst<LogArc> *fst_det_log = new VectorFst<LogArc>;
+ Determinize(*fst_log, fst_det_log);
+ Cast(*fst_det_log, fst);
+ delete fst_log;
+ delete fst_det_log;
+}
+
+
+
+// make it inline to avoid having to put it in a .cc file.
+// destructive algorithm (changes ifst as well as ofst).
+inline
+void SafeDeterminizeMinimizeWrapperInLog(VectorFst<StdArc> *ifst, VectorFst<StdArc> *ofst, float delta) {
+ VectorFst<LogArc> *ifst_log = new VectorFst<LogArc>; // Want to determinize in log semiring.
+ Cast(*ifst, ifst_log);
+ VectorFst<LogArc> *ofst_log = new VectorFst<LogArc>;
+ SafeDeterminizeWrapper(ifst_log, ofst_log, delta);
+ Cast(*ofst_log, ofst);
+ delete ifst_log;
+ delete ofst_log;
+ RemoveEpsLocal(ofst); // this is "safe" and will never hurt. Do this in tropical, which is important.
+ MinimizeEncoded(ofst, delta); // Non-deterministic minimization will fail in log semiring so do it with StdARc.
+}
+
+inline
+void SafeDeterminizeWrapperInLog(VectorFst<StdArc> *ifst, VectorFst<StdArc> *ofst, float delta) {
+ VectorFst<LogArc> *ifst_log = new VectorFst<LogArc>; // Want to determinize in log semiring.
+ Cast(*ifst, ifst_log);
+ VectorFst<LogArc> *ofst_log = new VectorFst<LogArc>;
+ SafeDeterminizeWrapper(ifst_log, ofst_log, delta);
+ Cast(*ofst_log, ofst);
+ delete ifst_log;
+ delete ofst_log;
+}
+
+
+
+template<class Arc>
+void RemoveWeights(MutableFst<Arc> *ifst) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ for (StateIterator<MutableFst<Arc> > siter(*ifst); !siter.Done(); siter.Next()) {
+ StateId s = siter.Value();
+ for (MutableArcIterator<MutableFst<Arc> > aiter(ifst, s); !aiter.Done(); aiter.Next()) {
+ Arc arc(aiter.Value());
+ arc.weight = Weight::One();
+ aiter.SetValue(arc);
+ }
+ if (ifst->Final(s) != Weight::Zero())
+ ifst->SetFinal(s, Weight::One());
+ }
+ ifst->SetProperties(kUnweighted, kUnweighted);
+}
+
+// Used in PrecedingInputSymbolsAreSame (non-functor version), and
+// similar routines.
+template<class T> struct IdentityFunction {
+ typedef T Arg;
+ typedef T Result;
+ T operator () (const T &t) const { return t; }
+};
+
+template<class Arc>
+bool PrecedingInputSymbolsAreSame(bool start_is_epsilon, const Fst<Arc> &fst) {
+ IdentityFunction<typename Arc::Label> f;
+ return PrecedingInputSymbolsAreSameClass(start_is_epsilon, fst, f);
+}
+
+template<class Arc, class F> // F is functor type from labels to classes.
+bool PrecedingInputSymbolsAreSameClass(bool start_is_epsilon, const Fst<Arc> &fst, const F &f) {
+ typedef typename F::Result ClassType;
+ typedef typename Arc::StateId StateId;
+ std::vector<ClassType> classes;
+ ClassType noClass = f(kNoLabel);
+
+ if (start_is_epsilon) {
+ StateId start_state = fst.Start();
+ if (start_state < 0 || start_state == kNoStateId)
+ return true; // empty fst-- doesn't matter.
+ classes.resize(start_state+1, noClass);
+ classes[start_state] = 0;
+ }
+
+ for (StateIterator<Fst<Arc> > siter(fst); !siter.Done(); siter.Next()) {
+ StateId s = siter.Value();
+ for (ArcIterator<Fst<Arc> > aiter(fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (classes.size() <= arc.nextstate)
+ classes.resize(arc.nextstate+1, noClass);
+ if (classes[arc.nextstate] == noClass)
+ classes[arc.nextstate] = f(arc.ilabel);
+ else
+ if (classes[arc.nextstate] != f(arc.ilabel))
+ return false;
+ }
+ }
+ return true;
+}
+
+template<class Arc>
+bool FollowingInputSymbolsAreSame(bool end_is_epsilon, const Fst<Arc> &fst) {
+ IdentityFunction<typename Arc::Label> f;
+ return FollowingInputSymbolsAreSameClass(end_is_epsilon, fst, f);
+}
+
+
+template<class Arc, class F>
+bool FollowingInputSymbolsAreSameClass(bool end_is_epsilon, const Fst<Arc> &fst, const F &f) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ typedef typename F::Result ClassType;
+ const ClassType noClass = f(kNoLabel), epsClass = f(0);
+ for (StateIterator<Fst<Arc> > siter(fst); !siter.Done(); siter.Next()) {
+ StateId s = siter.Value();
+ ClassType c = noClass;
+ for (ArcIterator<Fst<Arc> > aiter(fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (c == noClass)
+ c = f(arc.ilabel);
+ else
+ if (c != f(arc.ilabel))
+ return false;
+ }
+ if (end_is_epsilon && c != noClass &&
+ c != epsClass && fst.Final(s) != Weight::Zero())
+ return false;
+ }
+ return true;
+}
+
+template<class Arc>
+void MakePrecedingInputSymbolsSame(bool start_is_epsilon, MutableFst<Arc> *fst) {
+ IdentityFunction<typename Arc::Label> f;
+ MakePrecedingInputSymbolsSameClass(start_is_epsilon, fst, f);
+}
+
+template<class Arc, class F>
+void MakePrecedingInputSymbolsSameClass(bool start_is_epsilon, MutableFst<Arc> *fst, const F &f) {
+ typedef typename F::Result ClassType;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ std::vector<ClassType> classes;
+ ClassType noClass = f(kNoLabel);
+ ClassType epsClass = f(0);
+ if (start_is_epsilon) { // treat having-start-state as epsilon in-transition.
+ StateId start_state = fst->Start();
+ if (start_state < 0 || start_state == kNoStateId) // empty FST.
+ return;
+ classes.resize(start_state+1, noClass);
+ classes[start_state] = epsClass;
+ }
+
+ // Find bad states (states with multiple input-symbols into them).
+ std::set<StateId> bad_states; // states that we need to change.
+ for (StateIterator<Fst<Arc> > siter(*fst); !siter.Done(); siter.Next()) {
+ StateId s = siter.Value();
+ for (ArcIterator<Fst<Arc> > aiter(*fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (classes.size() <= static_cast<size_t>(arc.nextstate))
+ classes.resize(arc.nextstate+1, noClass);
+ if (classes[arc.nextstate] == noClass)
+ classes[arc.nextstate] = f(arc.ilabel);
+ else
+ if (classes[arc.nextstate] != f(arc.ilabel))
+ bad_states.insert(arc.nextstate);
+ }
+ }
+ if (bad_states.empty()) return; // Nothing to do.
+ kaldi::ConstIntegerSet<StateId> bad_states_ciset(bad_states); // faster lookup.
+
+ // Work out list of arcs we have to change as (state, arc-offset).
+ // Can't do the actual changes in this pass, since we have to add new
+ // states which invalidates the iterators.
+ std::vector<std::pair<StateId, size_t> > arcs_to_change;
+ for (StateIterator<Fst<Arc> > siter(*fst); !siter.Done(); siter.Next()) {
+ StateId s = siter.Value();
+ for (ArcIterator<Fst<Arc> > aiter(*fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0 &&
+ bad_states_ciset.count(arc.nextstate) != 0)
+ arcs_to_change.push_back(std::make_pair(s, aiter.Position()));
+ }
+ }
+ KALDI_ASSERT(!arcs_to_change.empty()); // since !bad_states.empty().
+
+ std::map<std::pair<StateId, ClassType>, StateId> state_map;
+ // state_map is a map from (bad-state, input-symbol-class) to dummy-state.
+
+ for (size_t i = 0; i < arcs_to_change.size(); i++) {
+ StateId s = arcs_to_change[i].first;
+ ArcIterator<MutableFst<Arc> > aiter(*fst, s);
+ aiter.Seek(arcs_to_change[i].second);
+ Arc arc = aiter.Value();
+
+ // Transition is non-eps transition to "bad" state. Introduce new state (or find
+ // existing one).
+ std::pair<StateId, ClassType> p(arc.nextstate, f(arc.ilabel));
+ if (state_map.count(p) == 0) {
+ StateId newstate = state_map[p] = fst->AddState();
+ fst->AddArc(newstate, Arc(0, 0, Weight::One(), arc.nextstate));
+ }
+ StateId dst_state = state_map[p];
+ arc.nextstate = dst_state;
+
+ // Initialize the MutableArcIterator only now, as the call to NewState()
+ // may have invalidated the first arc iterator.
+ MutableArcIterator<MutableFst<Arc> > maiter(fst, s);
+ maiter.Seek(arcs_to_change[i].second);
+ maiter.SetValue(arc);
+ }
+}
+
+template<class Arc>
+void MakeFollowingInputSymbolsSame(bool end_is_epsilon, MutableFst<Arc> *fst) {
+ IdentityFunction<typename Arc::Label> f;
+ MakeFollowingInputSymbolsSameClass(end_is_epsilon, fst, f);
+}
+
+template<class Arc, class F>
+void MakeFollowingInputSymbolsSameClass(bool end_is_epsilon, MutableFst<Arc> *fst, const F &f) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ typedef typename F::Result ClassType;
+ std::vector<StateId> bad_states;
+ ClassType noClass = f(kNoLabel);
+ ClassType epsClass = f(0);
+ for (StateIterator<Fst<Arc> > siter(*fst); !siter.Done(); siter.Next()) {
+ StateId s = siter.Value();
+ ClassType c = noClass;
+ bool bad = false;
+ for (ArcIterator<Fst<Arc> > aiter(*fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (c == noClass)
+ c = f(arc.ilabel);
+ else
+ if (c != f(arc.ilabel)) {
+ bad = true;
+ break;
+ }
+ }
+ if (end_is_epsilon && c != noClass &&
+ c != epsClass && fst->Final(s) != Weight::Zero())
+ bad = true;
+ if (bad)
+ bad_states.push_back(s);
+ }
+ std::vector<Arc> my_arcs;
+ for (size_t i = 0; i < bad_states.size(); i++) {
+ StateId s = bad_states[i];
+ my_arcs.clear();
+ for (ArcIterator<MutableFst<Arc> > aiter(*fst, s); !aiter.Done(); aiter.Next())
+ my_arcs.push_back(aiter.Value());
+
+ for (size_t j = 0; j < my_arcs.size(); j++) {
+ Arc &arc = my_arcs[j];
+ if (arc.ilabel != 0) {
+ StateId newstate = fst->AddState();
+ // Create a new state for each non-eps arc in original FST, out of each bad state.
+ // Not as optimal as it could be, but does avoid some complicated weight-pushing
+ // issues in which, to maintain stochasticity, we would have to know which semiring
+ // we want to maintain stochasticity in.
+ fst->AddArc(newstate, Arc(arc.ilabel, 0, Weight::One(), arc.nextstate));
+ MutableArcIterator<MutableFst<Arc> > maiter(fst, s);
+ maiter.Seek(j);
+ maiter.SetValue(Arc(0, arc.olabel, arc.weight, newstate));
+ }
+ }
+ }
+}
+
+
+template<class Arc>
+VectorFst<Arc>* MakeLoopFst(const std::vector<const ExpandedFst<Arc> *> &fsts) {
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Label Label;
+
+ VectorFst<Arc> *ans = new VectorFst<Arc>;
+ StateId loop_state = ans->AddState(); // = 0.
+ ans->SetStart(loop_state);
+ ans->SetFinal(loop_state, Weight::One());
+
+ // "cache" is used as an optimization when some of the pointers in "fsts"
+ // may have the same value.
+ unordered_map<const ExpandedFst<Arc> *, Arc> cache;
+
+ for (Label i = 0; i < static_cast<Label>(fsts.size()); i++) {
+ const ExpandedFst<Arc> *fst = fsts[i];
+ if (fst == NULL) continue;
+ { // optimization with cache: helpful if some members of "fsts" may
+ // contain the same pointer value (e.g. in GetHTransducer).
+ typename unordered_map<const ExpandedFst<Arc> *, Arc>::iterator
+ iter = cache.find(fst);
+ if (iter != cache.end()) {
+ Arc arc = iter->second;
+ arc.olabel = i;
+ ans->AddArc(0, arc);
+ continue;
+ }
+ }
+
+ KALDI_ASSERT(fst->Properties(kAcceptor, true) == kAcceptor); // expect acceptor.
+
+ StateId fst_num_states = fst->NumStates();
+ StateId fst_start_state = fst->Start();
+
+ if (fst_start_state == kNoStateId)
+ continue; // empty fst.
+
+ bool share_start_state =
+ fst->Properties(kInitialAcyclic, true) == kInitialAcyclic
+ && fst->NumArcs(fst_start_state) == 1
+ && fst->Final(fst_start_state) == Weight::Zero();
+
+ std::vector<StateId> state_map(fst_num_states); // fst state -> ans state
+ for (StateId s = 0; s < fst_num_states; s++) {
+ if (s == fst_start_state && share_start_state) state_map[s] = loop_state;
+ else state_map[s] = ans->AddState();
+ }
+ if (!share_start_state) {
+ Arc arc(0, i, Weight::One(), state_map[fst_start_state]);
+ cache[fst] = arc;
+ ans->AddArc(0, arc);
+ }
+ for (StateId s = 0; s < fst_num_states; s++) {
+ // Add arcs out of state s.
+ for (ArcIterator<ExpandedFst<Arc> > aiter(*fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ Label olabel = (s == fst_start_state && share_start_state ? i : 0);
+ Arc newarc(arc.ilabel, olabel, arc.weight, state_map[arc.nextstate]);
+ ans->AddArc(state_map[s], newarc);
+ if (s == fst_start_state && share_start_state)
+ cache[fst] = newarc;
+ }
+ if (fst->Final(s) != Weight::Zero()) {
+ KALDI_ASSERT(!(s == fst_start_state && share_start_state));
+ ans->AddArc(state_map[s], Arc(0, 0, fst->Final(s), loop_state));
+ }
+ }
+ }
+ return ans;
+}
+
+
+template<class Arc>
+void ClearSymbols(bool clear_input,
+ bool clear_output,
+ MutableFst<Arc> *fst) {
+ for (StateIterator<MutableFst<Arc> > siter(*fst);
+ !siter.Done();
+ siter.Next()) {
+ typename Arc::StateId s = siter.Value();
+ for (MutableArcIterator<MutableFst<Arc> > aiter(fst, s);
+ !aiter.Done();
+ aiter.Next()) {
+ Arc arc = aiter.Value();
+ bool change = false;
+ if (clear_input && arc.ilabel != 0) {
+ arc.ilabel = 0;
+ change = true;
+ }
+ if (clear_output && arc.olabel != 0) {
+ arc.olabel = 0;
+ change = true;
+ }
+ if (change) {
+ aiter.SetValue(arc);
+ }
+ }
+ }
+}
+
+
+template<class Arc>
+void ApplyProbabilityScale(float scale, MutableFst<Arc> *fst) {
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId StateId;
+ for (StateIterator<MutableFst<Arc> > siter(*fst);
+ !siter.Done();
+ siter.Next()) {
+ StateId s = siter.Value();
+ for (MutableArcIterator<MutableFst<Arc> > aiter(fst, s);
+ !aiter.Done();
+ aiter.Next()) {
+ Arc arc = aiter.Value();
+ arc.weight = Weight(arc.weight.Value() * scale);
+ aiter.SetValue(arc);
+ }
+ if (fst->Final(s) != Weight::Zero())
+ fst->SetFinal(s, Weight(fst->Final(s).Value() * scale));
+ }
+}
+
+
+// return arc-offset of self-loop with ilabel (or -1 if none exists).
+// if more than one such self-loop, pick first one.
+template<class Arc>
+ssize_t FindSelfLoopWithILabel(const Fst<Arc> &fst, typename Arc::StateId s) {
+ for (ArcIterator<Fst<Arc> > aiter(fst, s); !aiter.Done(); aiter.Next())
+ if (aiter.Value().nextstate == s
+ && aiter.Value().ilabel != 0) return static_cast<ssize_t>(aiter.Position());
+ return static_cast<ssize_t>(-1);
+}
+
+
+template<class Arc>
+bool EqualAlign(const Fst<Arc> &ifst,
+ typename Arc::StateId length,
+ int rand_seed,
+ MutableFst<Arc> *ofst,
+ int num_retries) {
+ srand(rand_seed);
+ KALDI_ASSERT(ofst->NumStates() == 0); // make sure ofst empty.
+ // make sure all states can reach final-state (or this algorithm may enter
+ // infinite loop.
+ KALDI_ASSERT(ifst.Properties(kCoAccessible, true) == kCoAccessible);
+
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ if (ifst.Start() == kNoStateId) {
+ KALDI_WARN << "Empty input fst.";
+ return false;
+ }
+ // First select path through ifst.
+ std::vector<StateId> path;
+ std::vector<size_t> arc_offsets; // arc taken out of each state.
+ std::vector<int> nof_ilabels;
+
+ StateId num_ilabels = 0;
+ int retry_no = 0;
+
+ // Under normal circumstances, this will be one-pass-only process
+ // Multiple tries might be needed in special cases, typically when
+ // the number of frames is close to number of transitions from
+ // the start node to the final node. It usually happens for really
+ // short utterances
+ do {
+ num_ilabels = 0;
+ arc_offsets.clear();
+ path.clear();
+ path.push_back(ifst.Start());
+
+ while (1) {
+ // Select either an arc or final-prob.
+ StateId s = path.back();
+ size_t num_arcs = ifst.NumArcs(s);
+ size_t num_arcs_tot = num_arcs;
+ if (ifst.Final(s) != Weight::Zero()) num_arcs_tot++;
+ // kaldi::RandInt is a bit like Rand(), but gets around situations
+ // where RAND_MAX is very small.
+ // Change this to Rand() % num_arcs_tot if compile issues arise
+ size_t arc_offset = static_cast<size_t>(kaldi::RandInt(0, num_arcs_tot-1));
+
+ if (arc_offset < num_arcs) { // an actual arc.
+ ArcIterator<Fst<Arc> > aiter(ifst, s);
+ aiter.Seek(arc_offset);
+ const Arc &arc = aiter.Value();
+ if (arc.nextstate == s) {
+ continue; // don't take this self-loop arc
+ } else {
+ arc_offsets.push_back(arc_offset);
+ path.push_back(arc.nextstate);
+ if (arc.ilabel != 0) num_ilabels++;
+ }
+ } else {
+ break; // Chose final-prob.
+ }
+ }
+
+ nof_ilabels.push_back(num_ilabels);
+ } while (( ++retry_no < num_retries) && (num_ilabels > length));
+
+ if (num_ilabels > length) {
+ std::stringstream ilabel_vec;
+ std::copy(nof_ilabels.begin(), nof_ilabels.end(),
+ std::ostream_iterator<int>(ilabel_vec, ","));
+ std::string s = ilabel_vec.str();
+ s.erase(s.end() - 1);
+ KALDI_WARN << "EqualAlign: the randomly constructed paths lengths: " << s;
+ KALDI_WARN << "EqualAlign: utterance has too few frames " << length
+ << " to align.";
+ return false; // can't make it shorter by adding self-loops!.
+ }
+
+ StateId num_self_loops = 0;
+ std::vector<ssize_t> self_loop_offsets(path.size());
+ for (size_t i = 0; i < path.size(); i++)
+ if ( (self_loop_offsets[i] = FindSelfLoopWithILabel(ifst, path[i]))
+ != static_cast<ssize_t>(-1) )
+ num_self_loops++;
+
+ if (num_self_loops == 0
+ && num_ilabels < length) {
+ KALDI_WARN << "No self-loops on chosen path; cannot match length.";
+ return false; // no self-loops to make it longer.
+ }
+
+ StateId num_extra = length - num_ilabels; // Number of self-loops we need.
+
+ StateId min_num_loops = 0;
+ if (num_extra != 0) min_num_loops = num_extra / num_self_loops; // prevent div by zero.
+ StateId num_with_one_more_loop = num_extra - (min_num_loops*num_self_loops);
+ KALDI_ASSERT(num_with_one_more_loop < num_self_loops || num_self_loops == 0);
+
+ ofst->AddState();
+ ofst->SetStart(0);
+ StateId cur_state = 0;
+ StateId counter = 0; // tell us when we should stop adding one more loop.
+ for (size_t i = 0; i < path.size(); i++) {
+ // First, add any self-loops that are necessary.
+ StateId num_loops = 0;
+ if (self_loop_offsets[i] != static_cast<ssize_t>(-1)) {
+ num_loops = min_num_loops + (counter < num_with_one_more_loop ? 1 : 0);
+ counter++;
+ }
+ for (StateId j = 0; j < num_loops; j++) {
+ ArcIterator<Fst<Arc> > aiter(ifst, path[i]);
+ aiter.Seek(self_loop_offsets[i]);
+ Arc arc = aiter.Value();
+ KALDI_ASSERT(arc.nextstate == path[i]
+ && arc.ilabel != 0); // make sure self-loop with ilabel.
+ StateId next_state = ofst->AddState();
+ ofst->AddArc(cur_state, Arc(arc.ilabel, arc.olabel, arc.weight, next_state));
+ cur_state = next_state;
+ }
+ if (i+1 < path.size()) { // add forward transition.
+ ArcIterator<Fst<Arc> > aiter(ifst, path[i]);
+ aiter.Seek(arc_offsets[i]);
+ Arc arc = aiter.Value();
+ KALDI_ASSERT(arc.nextstate == path[i+1]);
+ StateId next_state = ofst->AddState();
+ ofst->AddArc(cur_state, Arc(arc.ilabel, arc.olabel, arc.weight, next_state));
+ cur_state = next_state;
+ } else { // add final-prob.
+ Weight weight = ifst.Final(path[i]);
+ KALDI_ASSERT(weight != Weight::Zero());
+ ofst->SetFinal(cur_state, weight);
+ }
+ }
+ return true;
+}
+
+
+// This function identifies two types of useless arcs:
+// those where arc A and arc B both go from state X to
+// state Y with the same input symbol (remove the one
+// with smaller probability, or an arbitrary one if they
+// are the same); and those where A is an arc from state X
+// to state X, with epsilon input symbol [remove A].
+// Only works for tropical (not log) semiring as it uses
+// NaturalLess.
+template<class Arc>
+void RemoveUselessArcs(MutableFst<Arc> *fst) {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ NaturalLess<Weight> nl;
+ StateId non_coacc_state = kNoStateId;
+ size_t num_arcs_removed = 0, tot_arcs = 0;
+ for (StateIterator<MutableFst<Arc> > siter(*fst);
+ !siter.Done();
+ siter.Next()) {
+ std::vector<size_t> arcs_to_delete;
+ std::vector<Arc> arcs;
+ // pair2arclist lets us look up the arcs
+ std::map<std::pair<Label, StateId>, std::vector<size_t> > pair2arclist;
+ StateId state = siter.Value();
+ for (ArcIterator<MutableFst<Arc> > aiter(*fst, state);
+ !aiter.Done();
+ aiter.Next()) {
+ size_t pos = arcs.size();
+ const Arc &arc = aiter.Value();
+ arcs.push_back(arc);
+ pair2arclist[std::make_pair(arc.ilabel, arc.nextstate)].push_back(pos);
+ }
+ typename std::map<std::pair<Label, StateId>, std::vector<size_t> >::iterator
+ iter = pair2arclist.begin(), end = pair2arclist.end();
+ for (; iter!= end; ++iter) {
+ const std::vector<size_t> &poslist = iter->second;
+ if (poslist.size() > 1) { // >1 arc with same ilabel, dest-state
+ size_t best_pos = poslist[0];
+ Weight best_weight = arcs[best_pos].weight;
+ for (size_t j = 1; j < poslist.size(); j++) {
+ size_t pos = poslist[j];
+ Weight this_weight = arcs[pos].weight;
+ if (nl(this_weight, best_weight)) { // NaturalLess seems to be somehow
+ // "backwards".
+ best_weight = this_weight; // found a better one.
+ best_pos = pos;
+ }
+ }
+ for (size_t j = 0; j < poslist.size(); j++)
+ if (poslist[j] != best_pos)
+ arcs_to_delete.push_back(poslist[j]);
+ } else {
+ KALDI_ASSERT(poslist.size() == 1);
+ size_t pos = poslist[0];
+ Arc &arc = arcs[pos];
+ if (arc.ilabel == 0 && arc.nextstate == state)
+ arcs_to_delete.push_back(pos);
+ }
+ }
+ tot_arcs += arcs.size();
+ if (arcs_to_delete.size() != 0) {
+ num_arcs_removed += arcs_to_delete.size();
+ if (non_coacc_state == kNoStateId)
+ non_coacc_state = fst->AddState();
+ MutableArcIterator<MutableFst<Arc> > maiter(fst, state);
+ for (size_t j = 0; j < arcs_to_delete.size(); j++) {
+ size_t pos = arcs_to_delete[j];
+ maiter.Seek(pos);
+ arcs[pos].nextstate = non_coacc_state;
+ maiter.SetValue(arcs[pos]);
+ }
+ }
+ }
+ if (non_coacc_state != kNoStateId)
+ Connect(fst);
+ KALDI_VLOG(1) << "removed " << num_arcs_removed << " of " << tot_arcs
+ << "arcs.";
+}
+
+template<class Arc>
+void PhiCompose(const Fst<Arc> &fst1,
+ const Fst<Arc> &fst2,
+ typename Arc::Label phi_label,
+ MutableFst<Arc> *ofst) {
+ KALDI_ASSERT(phi_label != kNoLabel); // just use regular compose in this case.
+ typedef Fst<Arc> F;
+ typedef PhiMatcher<SortedMatcher<F> > PM;
+ CacheOptions base_opts;
+ base_opts.gc_limit = 0; // Cache only the last state for fastest copy.
+ // ComposeFstImplOptions templated on matcher for fst1, matcher for fst2.
+ // The matcher for fst1 doesn't matter; we'll use fst2's matcher.
+ ComposeFstImplOptions<SortedMatcher<F>, PM> impl_opts(base_opts);
+
+ // the false below is something called phi_loop which is something I don't
+ // fully understand, but I don't think we want it.
+
+ // These pointers are taken ownership of, by ComposeFst.
+ PM *phi_matcher =
+ new PM(fst2, MATCH_INPUT, phi_label, false);
+ SortedMatcher<F> *sorted_matcher =
+ new SortedMatcher<F>(fst1, MATCH_NONE); // tell it
+ // not to use this matcher, as this would mean we would
+ // not follow phi transitions.
+ impl_opts.matcher1 = sorted_matcher;
+ impl_opts.matcher2 = phi_matcher;
+ *ofst = ComposeFst<Arc>(fst1, fst2, impl_opts);
+ Connect(ofst);
+}
+
+template<class Arc>
+void PropagateFinalInternal(
+ typename Arc::Label phi_label,
+ typename Arc::StateId s,
+ MutableFst<Arc> *fst) {
+ typedef typename Arc::Weight Weight;
+ if (fst->Final(s) == Weight::Zero()) {
+ // search for phi transition. We assume there
+ // is just one-- phi nondeterminism is not allowed
+ // anyway.
+ int num_phis = 0;
+ for (ArcIterator<Fst<Arc> > aiter(*fst, s);
+ !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel == phi_label) {
+ num_phis++;
+ if (arc.nextstate == s) continue; // don't expect
+ // phi loops but ignore them anyway.
+
+ // If this recurses infinitely, it means there
+ // are loops of phi transitions, which there should
+ // not be in a normal backoff LM. We could make this
+ // routine work for this case, but currently there is
+ // no need.
+ PropagateFinalInternal(phi_label, arc.nextstate, fst);
+ if (fst->Final(arc.nextstate) != Weight::Zero())
+ fst->SetFinal(s, Times(fst->Final(arc.nextstate), arc.weight));
+ }
+ KALDI_ASSERT(num_phis <= 1 && "Phi nondeterminism found");
+ }
+ }
+}
+
+template<class Arc>
+void PropagateFinal(typename Arc::Label phi_label,
+ MutableFst<Arc> *fst) {
+ typedef typename Arc::StateId StateId;
+ if (fst->Properties(kIEpsilons, true)) // just warn.
+ KALDI_WARN << "PropagateFinal: this may not work as desired "
+ "since your FST has input epsilons.";
+ StateId num_states = fst->NumStates();
+ for (StateId s = 0; s < num_states; s++)
+ PropagateFinalInternal(phi_label, s, fst);
+}
+
+template<class Arc>
+void RhoCompose(const Fst<Arc> &fst1,
+ const Fst<Arc> &fst2,
+ typename Arc::Label rho_label,
+ MutableFst<Arc> *ofst) {
+ KALDI_ASSERT(rho_label != kNoLabel); // just use regular compose in this case.
+ typedef Fst<Arc> F;
+ typedef RhoMatcher<SortedMatcher<F> > RM;
+ CacheOptions base_opts;
+ base_opts.gc_limit = 0; // Cache only the last state for fastest copy.
+ // ComposeFstImplOptions templated on matcher for fst1, matcher for fst2.
+ // The matcher for fst1 doesn't matter; we'll use fst2's matcher.
+ ComposeFstImplOptions<SortedMatcher<F>, RM> impl_opts(base_opts);
+
+ // the false below is something called rho_loop which is something I don't
+ // fully understand, but I don't think we want it.
+
+ // These pointers are taken ownership of, by ComposeFst.
+ RM *rho_matcher =
+ new RM(fst2, MATCH_INPUT, rho_label);
+ SortedMatcher<F> *sorted_matcher =
+ new SortedMatcher<F>(fst1, MATCH_NONE); // tell it
+ // not to use this matcher, as this would mean we would
+ // not follow rho transitions.
+ impl_opts.matcher1 = sorted_matcher;
+ impl_opts.matcher2 = rho_matcher;
+ *ofst = ComposeFst<Arc>(fst1, fst2, impl_opts);
+ Connect(ofst);
+}
+
+
+// Declare an override of the template below.
+template<>
+inline bool IsStochasticFst(const Fst<LogArc> &fst,
+ float delta,
+ LogArc::Weight *min_sum,
+ LogArc::Weight *max_sum);
+
+// Will override this for LogArc where NaturalLess will not work.
+template<class Arc>
+inline bool IsStochasticFst(const Fst<Arc> &fst,
+ float delta,
+ typename Arc::Weight *min_sum,
+ typename Arc::Weight *max_sum) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ NaturalLess<Weight> nl;
+ bool first_time = true;
+ bool ans = true;
+ if (min_sum) *min_sum = Arc::Weight::One();
+ if (max_sum) *max_sum = Arc::Weight::One();
+ for (StateIterator<Fst<Arc> > siter(fst); !siter.Done(); siter.Next()) {
+ StateId s = siter.Value();
+ Weight sum = fst.Final(s);
+ for (ArcIterator<Fst<Arc> > aiter(fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ sum = Plus(sum, arc.weight);
+ }
+ if (!ApproxEqual(Weight::One(), sum, delta)) ans = false;
+ if (first_time) {
+ first_time = false;
+ if (max_sum) *max_sum = sum;
+ if (min_sum) *min_sum = sum;
+ } else {
+ if (max_sum && nl(*max_sum, sum)) *max_sum = sum;
+ if (min_sum && nl(sum, *min_sum)) *min_sum = sum;
+ }
+ }
+ if (first_time) { // just avoid NaNs if FST was empty.
+ if (max_sum) *max_sum = Weight::One();
+ if (min_sum) *min_sum = Weight::One();
+ }
+ return ans;
+}
+
+
+// Overriding template for LogArc as NaturalLess does not work there.
+template<>
+inline bool IsStochasticFst(const Fst<LogArc> &fst,
+ float delta,
+ LogArc::Weight *min_sum,
+ LogArc::Weight *max_sum) {
+ typedef LogArc Arc;
+ typedef Arc::StateId StateId;
+ typedef Arc::Weight Weight;
+ bool first_time = true;
+ bool ans = true;
+ if (min_sum) *min_sum = LogArc::Weight::One();
+ if (max_sum) *max_sum = LogArc::Weight::One();
+ for (StateIterator<Fst<Arc> > siter(fst); !siter.Done(); siter.Next()) {
+ StateId s = siter.Value();
+ Weight sum = fst.Final(s);
+ for (ArcIterator<Fst<Arc> > aiter(fst, s); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ sum = Plus(sum, arc.weight);
+ }
+ if (!ApproxEqual(Weight::One(), sum, delta)) ans = false;
+ if (first_time) {
+ first_time = false;
+ if (max_sum) *max_sum = sum;
+ if (min_sum) *min_sum = sum;
+ } else {
+ // note that max and min are reversed from their normal
+ // meanings here (max and min w.r.t. the underlying probabilities).
+ if (max_sum && sum.Value() < max_sum->Value()) *max_sum = sum;
+ if (min_sum && sum.Value() > min_sum->Value()) *min_sum = sum;
+ }
+ }
+ if (first_time) { // just avoid NaNs if FST was empty.
+ if (max_sum) *max_sum = Weight::One();
+ if (min_sum) *min_sum = Weight::One();
+ }
+ return ans;
+}
+
+// Tests whether a tropical FST is stochastic in the log
+// semiring. (casts it and does the check.)
+// This function deals with the generic fst.
+// This version currently supports ConstFst<StdArc> or VectorFst<StdArc>.
+// Otherwise, it will be died with an error.
+inline bool IsStochasticFstInLog(const Fst<StdArc> &fst,
+ float delta,
+ StdArc::Weight *min_sum,
+ StdArc::Weight *max_sum) {
+ bool ans = false;
+ LogArc::Weight log_min = LogArc::Weight::One(),
+ log_max = LogArc::Weight::Zero();
+ if (fst.Type() == "const") {
+ ConstFst<LogArc> logfst;
+ Cast(dynamic_cast<const ConstFst<StdArc>&>(fst), &logfst);
+ ans = IsStochasticFst(logfst, delta, &log_min, &log_max);
+ } else if (fst.Type() == "vector") {
+ VectorFst<LogArc> logfst;
+ Cast(dynamic_cast<const VectorFst<StdArc>&>(fst), &logfst);
+ ans = IsStochasticFst(logfst, delta, &log_min, &log_max);
+ } else {
+ KALDI_ERR << "This version currently supports ConstFst<StdArc> "
+ << "or VectorFst<StdArc>";
+ }
+ if (min_sum) *min_sum = StdArc::Weight(log_min.Value());
+ if (max_sum) *max_sum = StdArc::Weight(log_max.Value());
+ return ans;
+}
+
+} // namespace fst.
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/fstext-utils-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/fstext-utils-test.cc
new file mode 100644
index 000000000..4ce296f09
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/fstext-utils-test.cc
@@ -0,0 +1,434 @@
+// fstext/fstext-utils-test.cc
+
+// Copyright 2009-2012 Microsoft Corporation Daniel Povey
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "base/kaldi-common.h" // for exceptions
+#include "fstext/fstext-utils.h"
+#include "fstext/fst-test-utils.h"
+#include "util/stl-utils.h"
+#include "base/kaldi-math.h"
+
+namespace fst
+{
+using std::vector;
+using std::cout;
+
+template<class Arc, class I>
+void TestMakeLinearAcceptor() {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ int len = kaldi::Rand() % 10;
+ vector<I> vec;
+ vector<I> vec_nozeros;
+ for (int i = 0; i < len; i++) {
+ int j = kaldi::Rand() % len;
+ vec.push_back(j);
+ if (j != 0) vec_nozeros.push_back(j);
+ }
+
+
+ VectorFst<Arc> vfst;
+ MakeLinearAcceptor(vec, &vfst);
+ vector<I> vec2;
+ vector<I> vec3;
+ Weight w;
+ GetLinearSymbolSequence(vfst, &vec2, &vec3, &w);
+ assert(w == Weight::One());
+ assert(vec_nozeros == vec2);
+ assert(vec_nozeros == vec3);
+
+ if (vec2.size() != 0 || vec3.size() != 0) { // This test might not work
+ // for empty sequences...
+ {
+ vector<VectorFst<Arc> > fstvec;
+ NbestAsFsts(vfst, 1, &fstvec);
+ KALDI_ASSERT(fstvec.size() == 1);
+ assert(RandEquivalent(vfst, fstvec[0], 2/*paths*/, 0.01/*delta*/,
+ kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ }
+ }
+ bool include_eps = (kaldi::Rand() % 2 == 0);
+ if (!include_eps) vec = vec_nozeros;
+ kaldi::SortAndUniq(&vec);
+
+ vector<I> vec4;
+ GetInputSymbols(vfst, include_eps, &vec4);
+ assert(vec4 == vec);
+ vector<I> vec5;
+ GetInputSymbols(vfst, include_eps, &vec5);
+}
+
+
+template<class Arc> void TestDeterminizeStarInLog() {
+ VectorFst<Arc> *fst = RandFst<Arc>();
+ VectorFst<Arc> fst_copy(fst);
+ typename Arc::Label next_sym = 1 + HighestNumberedInputSymbol(*fst);
+ vector<typename Arc::Label> syms;
+ PreDeterminize(fst, NULL, "#", next_sym, &syms);
+
+
+}
+
+ // Don't instantiate with log semiring, as RandEquivalent may fail.
+template<class Arc> void TestSafeDeterminizeWrapper() { // also tests SafeDeterminizeMinimizeWrapper().
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = new VectorFst<Arc>();
+ int n_syms = 2 + kaldi::Rand() % 5, n_states = 3 + kaldi::Rand() % 10, n_arcs = 5 + kaldi::Rand() % 30, n_final = 1 + kaldi::Rand()%3; // Up to 2 unique symbols.
+ cout << "Testing pre-determinize with "<<n_syms<<" symbols, "<<n_states<<" states and "<<n_arcs<<" arcs and "<<n_final<<" final states.\n";
+ SymbolTable *sptr = new SymbolTable("my-symbol-table");
+ sptr->AddSymbol("<eps>");
+ delete sptr;
+ sptr = new SymbolTable("my-symbol-table");
+
+ vector<Label> all_syms; // including epsilon.
+ // Put symbols in the symbol table from 1..n_syms-1.
+ for (size_t i = 0;i < (size_t)n_syms;i++) {
+ std::stringstream ss;
+ if (i == 0) ss << "<eps>";
+ else ss<<i;
+ Label cur_lab = sptr->AddSymbol(ss.str());
+ assert(cur_lab == (Label)i);
+ all_syms.push_back(cur_lab);
+ }
+ assert(all_syms[0] == 0);
+
+ // Create states.
+ vector<StateId> all_states;
+ for (size_t i = 0;i < (size_t)n_states;i++) {
+ StateId this_state = fst->AddState();
+ if (i == 0) fst->SetStart(i);
+ all_states.push_back(this_state);
+ }
+ // Set final states.
+ for (size_t j = 0;j < (size_t)n_final;j++) {
+ StateId id = all_states[kaldi::Rand() % n_states];
+ Weight weight = (Weight)(0.33*(kaldi::Rand() % 5) );
+ printf("calling SetFinal with %d and %f\n", id, weight.Value());
+ fst->SetFinal(id, weight);
+ }
+ // Create arcs.
+ for (size_t i = 0;i < (size_t)n_arcs;i++) {
+ Arc a;
+ a.nextstate = all_states[kaldi::Rand() % n_states];
+ a.ilabel = all_syms[kaldi::Rand() % n_syms];
+ a.olabel = all_syms[kaldi::Rand() % n_syms]; // same input+output vocab.
+ a.weight = (Weight) (0.33*(kaldi::Rand() % 2));
+ StateId start_state = all_states[kaldi::Rand() % n_states];
+ fst->AddArc(start_state, a);
+ }
+
+ std::cout <<" printing before trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ // Trim resulting FST.
+ Connect(fst);
+
+ std::cout <<" printing after trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ VectorFst<Arc> *fst_copy_orig = new VectorFst<Arc>(*fst);
+
+ VectorFst<Arc> *fst_det = new VectorFst<Arc>;
+
+ vector<Label> extra_syms;
+ if (fst->Start() != kNoStateId) { // "Connect" did not make it empty....
+ if (kaldi::Rand() % 2 == 0)
+ SafeDeterminizeWrapper(fst_copy_orig, fst_det);
+ else {
+ if (kaldi::Rand() % 2 == 0)
+ SafeDeterminizeMinimizeWrapper(fst_copy_orig, fst_det);
+ else
+ SafeDeterminizeMinimizeWrapperInLog(fst_copy_orig, fst_det);
+ }
+
+ // no because does shortest-dist on weights even if not pushing on them.
+ // PushInLog<REWEIGHT_TO_INITIAL>(fst_det, kPushLabels); // will always succeed.
+ KALDI_LOG << "Num states [orig]: " << fst->NumStates() << "[det]" << fst_det->NumStates();
+ assert(RandEquivalent(*fst, *fst_det, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ }
+ delete fst;
+ delete fst_copy_orig;
+ delete fst_det;
+ delete sptr;
+}
+
+
+ // Don't instantiate with log semiring, as RandEquivalent may fail.
+void TestPushInLog() { // also tests SafeDeterminizeMinimizeWrapper().
+ typedef StdArc Arc;
+ typedef Arc::Label Label;
+ typedef Arc::StateId StateId;
+ typedef Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = RandFst<Arc>();
+ VectorFst<Arc> fst2(*fst);
+ PushInLog<REWEIGHT_TO_INITIAL>(&fst2, kPushLabels|kPushWeights, 0.01); // speed it up using large delta.
+ assert(RandEquivalent(*fst, fst2, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ delete fst;
+}
+
+
+
+template<class Arc> void TestAcceptorMinimize() {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = RandFst<Arc>();
+
+ Project(fst, PROJECT_INPUT);
+ RemoveWeights(fst);
+
+ VectorFst<Arc> fst2(*fst);
+ internal::AcceptorMinimize(&fst2);
+
+ assert(RandEquivalent(*fst, fst2, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ delete fst;
+}
+
+
+template<class Arc> void TestMakeSymbolsSame() {
+
+ VectorFst<Arc> *fst = RandFst<Arc>();
+ bool foll = (kaldi::Rand() % 2 == 0);
+ bool is_symbol = (kaldi::Rand() % 2 == 0);
+
+
+ VectorFst<Arc> fst2(*fst);
+
+ if (foll) {
+ MakeFollowingInputSymbolsSame(is_symbol, &fst2);
+ assert(FollowingInputSymbolsAreSame(is_symbol, fst2));
+ } else {
+ MakePrecedingInputSymbolsSame(is_symbol, &fst2);
+ assert(PrecedingInputSymbolsAreSame(is_symbol, fst2));
+ }
+
+
+ assert(RandEquivalent(*fst, fst2, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ delete fst;
+}
+
+
+template<class Arc>
+struct TestFunctor {
+ typedef int32 Result;
+ typedef typename Arc::Label Arg;
+ Result operator () (Arg a) const {
+ if (a == kNoLabel) return -1;
+ else if (a == 0) return 0;
+ else {
+ return 1 + ((a-1) % 10);
+ }
+ }
+};
+
+template<class Arc> void TestMakeSymbolsSameClass() {
+
+ VectorFst<Arc> *fst = RandFst<Arc>();
+ bool foll = (kaldi::Rand() % 2 == 0);
+ bool is_symbol = (kaldi::Rand() % 2 == 0);
+
+
+ VectorFst<Arc> fst2(*fst);
+
+ TestFunctor<Arc> f;
+ if (foll) {
+ MakeFollowingInputSymbolsSameClass(is_symbol, &fst2, f);
+ assert(FollowingInputSymbolsAreSameClass(is_symbol, fst2, f));
+ } else {
+ MakePrecedingInputSymbolsSameClass(is_symbol, &fst2, f);
+ assert(PrecedingInputSymbolsAreSameClass(is_symbol, fst2, f));
+ }
+
+ assert(RandEquivalent(*fst, fst2, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ delete fst;
+}
+
+
+// MakeLoopFstCompare is as MakeLoopFst but implmented differently [ less efficiently
+// but more clearly], so we can check for equivalence.
+template<class Arc>
+VectorFst<Arc>* MakeLoopFstCompare(const vector<const ExpandedFst<Arc> *> &fsts) {
+ VectorFst<Arc> *ans = new VectorFst<Arc>;
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ for (Label i = 0; i < fsts.size(); i++) {
+ if (fsts[i] != NULL) {
+ VectorFst<Arc> i_fst; // accepts symbol i on output.
+ i_fst.AddState(); i_fst.AddState();
+ i_fst.SetStart(0); i_fst.SetFinal(1, Weight::One());
+ i_fst.AddArc(0, Arc(0, i, Weight::One(), 1));
+ VectorFst<Arc> other_fst(*(fsts[i])); // copy it.
+ ClearSymbols(false, true, &other_fst); // Clear output symbols so symbols
+ // are on input side.
+ Concat(&i_fst, other_fst); // now i_fst is "i_fst [concat] other_fst".
+ Union(ans, i_fst);
+ }
+ }
+ Closure(ans, CLOSURE_STAR);
+ return ans;
+}
+
+
+template<class Arc> void TestMakeLoopFst() {
+
+ int num_fsts = kaldi::Rand() % 10;
+ vector<const ExpandedFst<Arc>* > fsts(num_fsts, (const ExpandedFst<Arc>*)NULL);
+ for (int i = 0; i < num_fsts; i++) {
+ if (kaldi::Rand() % 2 == 0) { // put an fst there.
+ VectorFst<Arc> *fst = RandFst<Arc>();
+ Project(fst, PROJECT_INPUT); // make input & output labels the same.
+ fsts[i] = fst;
+ } else { // this is to test that it works with the caching.
+ fsts[i] = fsts[i/2];
+ }
+ }
+
+ VectorFst<Arc> *fst1 = MakeLoopFst(fsts),
+ *fst2 = MakeLoopFstCompare(fsts);
+
+ assert(fst1->Properties(kOLabelSorted, kOLabelSorted) != 0);
+
+ assert(RandEquivalent(*fst1, *fst2, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst1;
+ delete fst2;
+ std::sort(fsts.begin(), fsts.end());
+ fsts.erase(std::unique(fsts.begin(), fsts.end()), fsts.end());
+ for (int i = 0; i < (int)fsts.size(); i++)
+ delete fsts[i];
+}
+
+
+
+template<class Arc>
+void TestEqualAlign() {
+ for (size_t i = 0; i < 4; i++) {
+ RandFstOptions opts;
+ opts.allow_empty = false;
+ VectorFst<Arc> *fst = RandFst<Arc>();
+ int length = 10 + kaldi::Rand() % 20;
+
+ VectorFst<Arc> fst_path;
+ if (EqualAlign(*fst, length, kaldi::Rand(), &fst_path)) {
+ std::cout << "EqualAlign succeeded\n";
+ vector<int32> isymbol_seq, osymbol_seq;
+ typename Arc::Weight weight;
+ GetLinearSymbolSequence(fst_path, &isymbol_seq, &osymbol_seq, &weight);
+ assert(isymbol_seq.size() == length);
+ Invert(&fst_path);
+ VectorFst<Arc> fst_composed;
+ Compose(fst_path, *fst, &fst_composed);
+ assert(fst_composed.Start() != kNoStateId); // make sure nonempty.
+ } else {
+ std::cout << "EqualAlign did not generate alignment\n";
+ }
+ delete fst;
+ }
+}
+
+
+template<class Arc> void Print(const Fst<Arc> &fst, std::string message) {
+ std::cout << message << "\n";
+ FstPrinter<Arc> fstprinter(fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+}
+
+
+template<class Arc>
+void TestRemoveUselessArcs() {
+ for (size_t i = 0; i < 4; i++) {
+ RandFstOptions opts;
+ opts.allow_empty = false;
+ VectorFst<Arc> *fst = RandFst<Arc>();
+ // Print(*fst, "[testremoveuselessarcs]:fst:");
+ UniformArcSelector<Arc> selector;
+ RandGenOptions<UniformArcSelector<Arc> > randgen_opts(selector);
+ VectorFst<Arc> fst_path;
+ RandGen(*fst, &fst_path, randgen_opts);
+ Project(&fst_path, PROJECT_INPUT);
+ // Print(fst_path, "[testremoveuselessarcs]:fstpath:");
+
+ VectorFst<Arc> fst_nouseless(*fst);
+ RemoveUselessArcs(&fst_nouseless);
+ // Print(fst_nouseless, "[testremoveuselessarcs]:fst_nouseless:");
+
+ VectorFst<Arc> orig_composed,
+ nouseless_composed;
+ Compose(fst_path, *fst, &orig_composed);
+ Compose(fst_path, fst_nouseless, &nouseless_composed);
+
+ // Print(orig_composed, "[testremoveuselessarcs]:orig_composed");
+ // Print(nouseless_composed, "[testremoveuselessarcs]:nouseless_composed");
+
+ VectorFst<Arc> orig_bestpath,
+ nouseless_bestpath;
+ ShortestPath(orig_composed, &orig_bestpath);
+ ShortestPath(nouseless_composed, &nouseless_bestpath);
+ // Print(orig_bestpath, "[testremoveuselessarcs]:orig_bestpath");
+ // Print(nouseless_bestpath, "[testremoveuselessarcs]:nouseless_bestpath");
+
+ typename Arc::Weight worig, wnouseless;
+ GetLinearSymbolSequence<Arc, int>(orig_bestpath, NULL, NULL, &worig);
+ GetLinearSymbolSequence<Arc, int>(nouseless_bestpath, NULL, NULL, &wnouseless);
+ assert(ApproxEqual(worig, wnouseless, kDelta));
+
+ // assert(RandEquivalent(orig_bestpath, nouseless_bestpath, 5/*paths*/, 0.01/*delta*/, Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst;
+ }
+}
+
+
+
+} // end namespace fst
+
+
+int main() {
+ for (int i = 0; i < 5; i++) {
+ fst::TestMakeLinearAcceptor<fst::StdArc, int>(); // this also tests GetLinearSymbolSequence, GetInputSymbols and GetOutputSymbols.
+ fst::TestMakeLinearAcceptor<fst::StdArc, int32>();
+ fst::TestMakeLinearAcceptor<fst::StdArc, uint32>();
+ fst::TestSafeDeterminizeWrapper<fst::StdArc>();
+ fst::TestAcceptorMinimize<fst::StdArc>();
+ fst::TestMakeSymbolsSame<fst::StdArc>();
+ fst::TestMakeSymbolsSame<fst::LogArc>();
+ fst::TestMakeSymbolsSameClass<fst::StdArc>();
+ fst::TestMakeSymbolsSameClass<fst::LogArc>();
+ fst::TestMakeLoopFst<fst::StdArc>();
+ fst::TestMakeLoopFst<fst::LogArc>();
+ fst::TestEqualAlign<fst::StdArc>();
+ fst::TestEqualAlign<fst::LogArc>();
+ fst::TestRemoveUselessArcs<fst::StdArc>();
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/fstext-utils.h b/runtime/onnxruntime/third_party/kaldi/fstext/fstext-utils.h
new file mode 100644
index 000000000..5789dbe7c
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/fstext-utils.h
@@ -0,0 +1,427 @@
+// fstext/fstext-utils.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2012-2013 Johns Hopkins University (Author: Daniel Povey)
+// 2013 Guoguo Chen
+// 2014 Telepoint Global Hosting Service, LLC. (Author: David Snyder)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_FSTEXT_UTILS_H_
+#define KALDI_FSTEXT_FSTEXT_UTILS_H_
+#include <algorithm>
+#include <map>
+#include <set>
+#include <vector>
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+#include "fstext/determinize-star.h"
+#include "fstext/remove-eps-local.h"
+#include "base/kaldi-common.h" // for error reporting macros.
+#include "util/text-utils.h" // for SplitStringToVector
+#include "fst/script/print-impl.h"
+
+namespace fst {
+
+/// Returns the highest numbered output symbol id of the FST (or zero
+/// for an empty FST.
+template<class Arc>
+typename Arc::Label HighestNumberedOutputSymbol(const Fst<Arc> &fst);
+
+/// Returns the highest numbered input symbol id of the FST (or zero
+/// for an empty FST.
+template<class Arc>
+typename Arc::Label HighestNumberedInputSymbol(const Fst<Arc> &fst);
+
+/// Returns the total number of arcs in an FST.
+template<class Arc>
+typename Arc::StateId NumArcs(const ExpandedFst<Arc> &fst);
+
+/// GetInputSymbols gets the list of symbols on the input of fst
+/// (including epsilon, if include_eps == true), as a sorted, unique
+/// list.
+template<class Arc, class I>
+void GetInputSymbols(const Fst<Arc> &fst,
+ bool include_eps,
+ std::vector<I> *symbols);
+
+/// GetOutputSymbols gets the list of symbols on the output of fst
+/// (including epsilon, if include_eps == true)
+template<class Arc, class I>
+void GetOutputSymbols(const Fst<Arc> &fst,
+ bool include_eps,
+ std::vector<I> *symbols);
+
+/// ClearSymbols sets all the symbols on the input and/or
+/// output side of the FST to zero, as specified.
+/// It does not alter the symbol tables.
+template<class Arc>
+void ClearSymbols(bool clear_input,
+ bool clear_output,
+ MutableFst<Arc> *fst);
+
+template<class I>
+void GetSymbols(const SymbolTable &symtab,
+ bool include_eps,
+ std::vector<I> *syms_out);
+
+
+
+inline
+void DeterminizeStarInLog(VectorFst<StdArc> *fst, float delta = kDelta, bool *debug_ptr = NULL,
+ int max_states = -1);
+
+
+// e.g. of using this function: PushInLog<REWEIGHT_TO_INITIAL>(fst, kPushWeights|kPushLabels);
+
+template<ReweightType rtype> // == REWEIGHT_TO_{INITIAL, FINAL}
+void PushInLog(VectorFst<StdArc> *fst, uint32 ptype, float delta = kDelta) {
+
+ // PushInLog pushes the FST
+ // and returns a new pushed FST (labels and weights pushed to the left).
+ VectorFst<LogArc> *fst_log = new VectorFst<LogArc>; // Want to determinize in log semiring.
+ Cast(*fst, fst_log);
+ VectorFst<StdArc> tmp;
+ *fst = tmp; // free up memory.
+ VectorFst<LogArc> *fst_pushed_log = new VectorFst<LogArc>;
+ Push<LogArc, rtype>(*fst_log, fst_pushed_log, ptype, delta);
+ Cast(*fst_pushed_log, fst);
+ delete fst_log;
+ delete fst_pushed_log;
+}
+
+// Minimizes after encoding; applicable to all FSTs. It is like what you get
+// from the Minimize() function, except it will not push the weights, or the
+// symbols. This is better for our recipes, as we avoid ever pushing the
+// weights. However, it will only minimize optimally if your graphs are such
+// that the symbols are as far to the left as they can go, and the weights
+// in combinable paths are the same... hard to formalize this, but it's something
+// that is satisified by our normal FSTs.
+template<class Arc>
+void MinimizeEncoded(VectorFst<Arc> *fst, float delta = kDelta) {
+
+ Map(fst, QuantizeMapper<Arc>(delta));
+ EncodeMapper<Arc> encoder(kEncodeLabels | kEncodeWeights, ENCODE);
+ Encode(fst, &encoder);
+ internal::AcceptorMinimize(fst);
+ Decode(fst, encoder);
+}
+
+
+/// GetLinearSymbolSequence gets the symbol sequence from a linear FST.
+/// If the FST is not just a linear sequence, it returns false. If it is
+/// a linear sequence (including the empty FST), it returns true. In this
+/// case it outputs the symbol
+/// sequences as "isymbols_out" and "osymbols_out" (removing epsilons), and
+/// the total weight as "tot_weight". The total weight will be Weight::Zero()
+/// if the FST is empty. If any of the output pointers are NULL, it does not
+/// create that output.
+template<class Arc, class I>
+bool GetLinearSymbolSequence(const Fst<Arc> &fst,
+ std::vector<I> *isymbols_out,
+ std::vector<I> *osymbols_out,
+ typename Arc::Weight *tot_weight_out);
+
+
+/// This function converts an FST with a special structure, which is
+/// output by the OpenFst functions ShortestPath and RandGen, and converts
+/// them into a std::vector of separate FSTs. This special structure is that
+/// the only state that has more than one (arcs-out or final-prob) is the
+/// start state. fsts_out is resized to the appropriate size.
+template<class Arc>
+void ConvertNbestToVector(const Fst<Arc> &fst,
+ std::vector<VectorFst<Arc> > *fsts_out);
+
+
+/// Takes the n-shortest-paths (using ShortestPath), but outputs
+/// the result as a vector of up to n fsts. This function will
+/// size the "fsts_out" vector to however many paths it got
+/// (which will not exceed n). n must be >= 1.
+template<class Arc>
+void NbestAsFsts(const Fst<Arc> &fst,
+ size_t n,
+ std::vector<VectorFst<Arc> > *fsts_out);
+
+
+
+
+/// Creates unweighted linear acceptor from symbol sequence.
+template<class Arc, class I>
+void MakeLinearAcceptor(const std::vector<I> &labels, MutableFst<Arc> *ofst);
+
+
+
+/// Creates an unweighted acceptor with a linear structure, with alternatives
+/// at each position. Epsilon is treated like a normal symbol here.
+/// Each position in "labels" must have at least one alternative.
+template<class Arc, class I>
+void MakeLinearAcceptorWithAlternatives(const std::vector<std::vector<I> > &labels,
+ MutableFst<Arc> *ofst);
+
+
+/// Does PreDeterminize and DeterminizeStar and then removes the disambiguation symbols.
+/// This is a form of determinization that will never blow up.
+/// Note that ifst is non-const and can be considered to be destroyed by this
+/// operation.
+/// Does not do epsilon removal (RemoveEpsLocal)-- this is so it's safe to cast to
+/// log and do this, and maintain equivalence in tropical.
+
+template<class Arc>
+void SafeDeterminizeWrapper(MutableFst<Arc> *ifst, MutableFst<Arc> *ofst, float delta = kDelta);
+
+
+/// SafeDeterminizeMinimizeWapper is as SafeDeterminizeWrapper except that it also
+/// minimizes (encoded minimization, which is safe). This algorithm will destroy "ifst".
+template<class Arc>
+void SafeDeterminizeMinimizeWrapper(MutableFst<Arc> *ifst, VectorFst<Arc> *ofst, float delta = kDelta);
+
+
+/// SafeDeterminizeMinimizeWapperInLog is as SafeDeterminizeMinimizeWrapper except
+/// it first casts tothe log semiring.
+void SafeDeterminizeMinimizeWrapperInLog(VectorFst<StdArc> *ifst, VectorFst<StdArc> *ofst, float delta = kDelta);
+
+
+
+/// RemoveSomeInputSymbols removes any symbol that appears in "to_remove", from
+/// the input side of the FST, replacing them with epsilon.
+template<class Arc, class I>
+void RemoveSomeInputSymbols(const std::vector<I> &to_remove,
+ MutableFst<Arc> *fst);
+
+// MapInputSymbols will replace any input symbol i that is between 0 and
+// symbol_map.size()-1, with symbol_map[i]. It removes the input symbol
+// table of the FST.
+template<class Arc, class I>
+void MapInputSymbols(const std::vector<I> &symbol_map,
+ MutableFst<Arc> *fst);
+
+
+template<class Arc>
+void RemoveWeights(MutableFst<Arc> *fst);
+
+
+
+
+/// Returns true if and only if the FST is such that the input symbols
+/// on arcs entering any given state all have the same value.
+/// if "start_is_epsilon", treat start-state as an epsilon input arc
+/// [i.e. ensure only epsilon can enter start-state].
+template<class Arc>
+bool PrecedingInputSymbolsAreSame(bool start_is_epsilon, const Fst<Arc> &fst);
+
+
+/// This is as PrecedingInputSymbolsAreSame, but with a functor f that maps labels to classes.
+/// The function tests whether the symbols preceding any given state are in the same
+/// class.
+/// Formally, f is of a type F that has an operator of type
+/// F::Result F::operator() (F::Arg a) const;
+/// where F::Result is an integer type and F::Arc can be constructed from Arc::Label.
+/// this must apply to valid labels and also to kNoLabel (so we can have a marker for
+/// the invalid labels.
+template<class Arc, class F>
+bool PrecedingInputSymbolsAreSameClass(bool start_is_epsilon, const Fst<Arc> &fst, const F &f);
+
+
+/// Returns true if and only if the FST is such that the input symbols
+/// on arcs exiting any given state all have the same value.
+/// If end_is_epsilon, treat end-state as an epsilon output arc [i.e. ensure
+/// end-states cannot have non-epsilon output transitions.]
+template<class Arc>
+bool FollowingInputSymbolsAreSame(bool end_is_epsilon, const Fst<Arc> &fst);
+
+
+template<class Arc, class F>
+bool FollowingInputSymbolsAreSameClass(bool end_is_epsilon, const Fst<Arc> &fst, const F &f);
+
+
+/// MakePrecedingInputSymbolsSame ensures that all arcs entering any given fst
+/// state have the same input symbol. It does this by detecting states
+/// that have differing input symbols going in, and inserting, for each of
+/// the preceding arcs with non-epsilon input symbol, a new dummy state that
+/// has an epsilon link to the fst state.
+/// If "start_is_epsilon", ensure that start-state can have only epsilon-links
+/// into it.
+template<class Arc>
+void MakePrecedingInputSymbolsSame(bool start_is_epsilon, MutableFst<Arc> *fst);
+
+
+/// As MakePrecedingInputSymbolsSame, but takes a functor object that maps labels to classes.
+template<class Arc, class F>
+void MakePrecedingInputSymbolsSameClass(bool start_is_epsilon, MutableFst<Arc> *fst, const F &f);
+
+
+/// MakeFollowingInputSymbolsSame ensures that all arcs exiting any given fst
+/// state have the same input symbol. It does this by detecting states that have
+/// differing input symbols on arcs that exit it, and inserting, for each of the
+/// following arcs with non-epsilon input symbol, a new dummy state that has an
+/// input-epsilon link from the fst state. The output symbol and weight stay on the
+/// link to the dummy state (in order to keep the FST output-deterministic and
+/// stochastic, if it already was).
+/// If end_is_epsilon, treat "being a final-state" like having an epsilon output
+/// link.
+template<class Arc>
+void MakeFollowingInputSymbolsSame(bool end_is_epsilon, MutableFst<Arc> *fst);
+
+/// As MakeFollowingInputSymbolsSame, but takes a functor object that maps labels to classes.
+template<class Arc, class F>
+void MakeFollowingInputSymbolsSameClass(bool end_is_epsilon, MutableFst<Arc> *fst, const F &f);
+
+
+
+
+/// MakeLoopFst creates an FST that has a state that is both initial and
+/// final (weight == Weight::One()), and for each non-NULL pointer fsts[i],
+/// it has an arc out whose output-symbol is i and which goes to a
+/// sub-graph whose input language is equivalent to fsts[i], where the
+/// final-state becomes a transition to the loop-state. Each fst in "fsts"
+/// should be an acceptor. The fst MakeLoopFst returns is output-deterministic,
+/// but not output-epsilon free necessarily, and arcs are sorted on output label.
+/// Note: if some of the pointers in the input vector "fsts" have the same
+/// value, "MakeLoopFst" uses this to speed up the computation.
+
+/// Formally: suppose I is the set of indexes i such that fsts[i] != NULL.
+/// Let L[i] be the language that the acceptor fsts[i] accepts.
+/// Let the language K be the set of input-output pairs i:l such
+/// that i in I and l in L[i]. Then the FST returned by MakeLoopFst
+/// accepts the language K*, where * is the Kleene closure (CLOSURE_STAR)
+/// of K.
+
+/// We could have implemented this via a combination of "project",
+/// "concat", "union" and "closure". But that FST would have been
+/// less well optimized and would have a lot of final-states.
+
+template<class Arc>
+VectorFst<Arc>* MakeLoopFst(const std::vector<const ExpandedFst<Arc> *> &fsts);
+
+
+/// ApplyProbabilityScale is applicable to FSTs in the log or tropical semiring.
+/// It multiplies the arc and final weights by "scale" [this is not the Mul
+/// operation of the semiring, it's actual multiplication, which is equivalent
+/// to taking a power in the semiring].
+template<class Arc>
+void ApplyProbabilityScale(float scale, MutableFst<Arc> *fst);
+
+
+
+
+
+/// EqualAlign is similar to RandGen, but it generates a sequence with exactly "length"
+/// input symbols. It returns true on success, false on failure (failure is partly
+/// random but should never happen in practice for normal speech models.)
+/// It generates a random path through the input FST, finds out which subset of the
+/// states it visits along the way have self-loops with inupt symbols on them, and
+/// outputs a path with exactly enough self-loops to have the requested number
+/// of input symbols.
+/// Note that EqualAlign does not use the probabilities on the FST. It just uses
+/// equal probabilities in the first stage of selection (since the output will anyway
+/// not be a truly random sample from the FST).
+/// The input fst "ifst" must be connected or this may enter an infinite loop.
+template<class Arc>
+bool EqualAlign(const Fst<Arc> &ifst, typename Arc::StateId length,
+ int rand_seed, MutableFst<Arc> *ofst, int num_retries = 10);
+
+
+
+// RemoveUselessArcs removes arcs such that there is no input symbol
+// sequence for which the best path through the FST would contain
+// those arcs [for these purposes, epsilon is not treated as a real symbol].
+// This is mainly geared towards decoding-graph FSTs which may contain
+// transitions that have less likely words on them that would never be
+// taken. We do not claim that this algorithm removes all such arcs;
+// it just does the best job it can.
+// Only works for tropical (not log) semiring as it uses
+// NaturalLess.
+template<class Arc>
+void RemoveUselessArcs(MutableFst<Arc> *fst);
+
+
+// PhiCompose is a version of composition where
+// the right hand FST (fst2) is treated as a backoff
+// LM, with the phi symbol (e.g. #0) treated as a
+// "failure transition", only taken when we don't
+// have a match for the requested symbol.
+template<class Arc>
+void PhiCompose(const Fst<Arc> &fst1,
+ const Fst<Arc> &fst2,
+ typename Arc::Label phi_label,
+ MutableFst<Arc> *fst);
+
+// PropagateFinal propagates final-probs through
+// "phi" transitions (note that here, phi_label may
+// be epsilon if you want). If you have a backoff LM
+// with special symbols ("phi") on the backoff arcs
+// instead of epsilon, you may use PhiCompose to compose
+// with it, but this won't do the right thing w.r.t.
+// final probabilities. You should first call PropagateFinal
+// on the FST with phi's i it (fst2 in PhiCompose above),
+// to fix this. If a state does not have a final-prob,
+// but has a phi transition, it makes the state's final-prob
+// (phi-prob * final-prob-of-dest-state), and does this
+// recursively i.e. follows phi transitions on the dest state
+// first. It behaves as if there were a super-final state
+// with a special symbol leading to it, from each currently
+// final state. Note that this may not behave as desired
+// if there are epsilons in your FST; it might be better
+// to remove those before calling this function.
+
+template<class Arc>
+void PropagateFinal(typename Arc::Label phi_label,
+ MutableFst<Arc> *fst);
+
+// RhoCompose is a version of composition where
+// the right hand FST (fst2) has speciall "rho transitions"
+// which are taken whenever no normal transition matches; these
+// transitions will be rewritten with whatever symbol was on
+// the first FST.
+template<class Arc>
+void RhoCompose(const Fst<Arc> &fst1,
+ const Fst<Arc> &fst2,
+ typename Arc::Label rho_label,
+ MutableFst<Arc> *fst);
+
+/** This function returns true if, in the semiring of the FST, the sum (within
+ the semiring) of all the arcs out of each state in the FST is one, to within
+ delta. After MakeStochasticFst, this should be true (for a connected FST).
+
+ @param fst [in] the FST that we are testing.
+ @param delta [in] the tolerance to within which we test equality to 1.
+ @param min_sum [out] if non, NULL, contents will be set to the minimum sum of weights.
+ @param max_sum [out] if non, NULL, contents will be set to the maximum sum of weights.
+ @return Returns true if the FST is stochastic, and false otherwise.
+*/
+
+template<class Arc>
+bool IsStochasticFst(const Fst<Arc> &fst,
+ float delta = kDelta, // kDelta = 1.0/1024.0 by default.
+ typename Arc::Weight *min_sum = NULL,
+ typename Arc::Weight *max_sum = NULL);
+
+
+
+
+// IsStochasticFstInLog makes sure it's stochastic after casting to log.
+inline bool IsStochasticFstInLog(const Fst<StdArc> &fst,
+ float delta = kDelta, // kDelta = 1.0/1024.0 by default.
+ StdArc::Weight *min_sum = NULL,
+ StdArc::Weight *max_sum = NULL);
+
+
+} // end namespace fst
+
+
+#include "fstext/fstext-utils-inl.h"
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/grammar-context-fst.cc b/runtime/onnxruntime/third_party/kaldi/fstext/grammar-context-fst.cc
new file mode 100644
index 000000000..a9917d3b1
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/grammar-context-fst.cc
@@ -0,0 +1,228 @@
+// fstext/grammar-context-fst.cc
+
+// Copyright 2018 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "fstext/grammar-context-fst.h"
+#include "base/kaldi-error.h"
+#include "util/stl-utils.h"
+
+namespace fst {
+using std::vector;
+
+InverseLeftBiphoneContextFst::InverseLeftBiphoneContextFst(
+ Label nonterm_phones_offset,
+ const vector<int32>& phones,
+ const vector<int32>& disambig_syms):
+ nonterm_phones_offset_(nonterm_phones_offset),
+ phone_syms_(phones),
+ disambig_syms_(disambig_syms) {
+
+ { // This block does some checks.
+ std::vector<int32> all_inputs(phones);
+ all_inputs.insert(all_inputs.end(), disambig_syms.begin(),
+ disambig_syms.end());
+ all_inputs.push_back(nonterm_phones_offset);
+ size_t size = all_inputs.size();
+ kaldi::SortAndUniq(&all_inputs);
+ if (all_inputs.size() != size) {
+ KALDI_ERR << "There was overlap between disambig symbols, phones, "
+ "and/or --nonterm-phones-offset";
+ }
+ if (all_inputs.front() <= 0)
+ KALDI_ERR << "Symbols <= 0 were passed in as phones, disambig-syms, "
+ "or nonterm-phones-offset.";
+ if (all_inputs.back() != nonterm_phones_offset) {
+ // the value passed --nonterm-phones-offset is not higher numbered
+ // than all the phones and disambig syms... do some more checking.
+ for (int32 i = 1; i < 4; i++) {
+ int32 symbol = nonterm_phones_offset + i;
+ // None of the symbols --nonterm-phones-offset + {kNontermBos, kNontermBegin,
+ // kNontermEnd, kNontermReenter, kNontermUserDefined}
+ // (i.e. the special symbols plus the first user-defined symbol) may be
+ // listed as phones or disambig symbols... this doesn't make sense. We
+ // do allow disambig symbols to be higher-numbered than the nonterminal
+ // sybols, just in case that happens to be needed, but they can't overlap.
+ if (std::binary_search(all_inputs.begin(), all_inputs.end(), symbol)) {
+ KALDI_ERR << "The symbol " << symbol
+ << " = --nonterm-phones-offset + " << i
+ << " was listed as a phone or disambig symbol.";
+ }
+ }
+ }
+ if (phone_syms_.empty())
+ KALDI_WARN << "Context FST created but there are no phone symbols: probably "
+ "input FST was empty.";
+ }
+
+ // empty vector, will be the ilabel_info vector that corresponds to epsilon,
+ // in case our FST needs to output epsilons.
+ vector<int32> empty_vec;
+ Label epsilon_label = FindLabel(empty_vec);
+ // Make sure that a label is assigned for epsilon.
+ KALDI_ASSERT(epsilon_label == 0);
+}
+
+
+InverseLeftBiphoneContextFst::Weight InverseLeftBiphoneContextFst::Final(StateId s) {
+ if (s == 0 || phone_syms_.count(s) != 0 ||
+ s == GetPhoneSymbolFor(kNontermEnd))
+ return Weight::One();
+ else
+ return Weight::Zero();
+}
+
+bool InverseLeftBiphoneContextFst::GetArc(
+ StateId s, Label ilabel, Arc *arc) {
+ // it's a rule of the DeterministicOnDemandFst that the ilabel cannot be zero.q
+ KALDI_ASSERT(ilabel != 0);
+
+ arc->ilabel = ilabel;
+ arc->weight = Weight::One();
+
+ if (s == 0 || phone_syms_.count(s) != 0) {
+ // This is an epsilon or phone state.
+ if (phone_syms_.count(ilabel) != 0) {
+ // The ilabel is a phone.
+ std::vector<int32> context_window(2);
+ context_window[0] = s;
+ context_window[1] = ilabel;
+ arc->olabel = FindLabel(context_window);
+ arc->nextstate = ilabel;
+ return true;
+ } else if (disambig_syms_.count(ilabel) != 0) {
+ // the ilabel is a disambiguation symbol. Make a self-loop arc that
+ // replicates the disambiguation symbol on the input.
+ // The ilabel-info vector for disambig symbols is just a single element
+ // consisting of the negative of the disambig symbols (for easier
+ // identification from code).
+ std::vector<int32> this_ilabel_info(1);
+ this_ilabel_info[0] = -ilabel;
+ arc->olabel = FindLabel(this_ilabel_info);
+ arc->nextstate = s;
+ return true;
+ } else if (ilabel == GetPhoneSymbolFor(kNontermBegin) &&
+ s == 0) {
+ // We were at the start state and saw the symbol #nonterm_begin.
+ // Output nothing, but transition to the special #nonterm_begin state.
+ // when we're in that state, arcs for phones generate special
+ // osymbols corresponding to pairs like (#nonterm_begin, p1).
+ arc->olabel = 0;
+ arc->nextstate = GetPhoneSymbolFor(kNontermBegin);
+ return true;
+ } else if (ilabel == GetPhoneSymbolFor(kNontermEnd)) {
+ // we saw #nonterm_end.
+ std::vector<int32> this_ilabel_info(2);
+ this_ilabel_info[0] = -(GetPhoneSymbolFor(kNontermEnd));
+ this_ilabel_info[1] = (s != 0 ? s : GetPhoneSymbolFor(kNontermBos));
+ arc->olabel = FindLabel(this_ilabel_info);
+ arc->nextstate = GetPhoneSymbolFor(kNontermEnd);
+ return true;
+ } else if (ilabel >= GetPhoneSymbolFor(kNontermUserDefined)) {
+ // Assume this ilabel is a user-defined nonterminal.
+ // Transition to the state kNontermUserDefined, with an olabel
+ // (#nonterm:foo, p1) where 'p1' is the current left-context.
+ std::vector<int32> this_ilabel_info(2);
+ this_ilabel_info[0] = -ilabel;
+ this_ilabel_info[1] = (s != 0 ? s : GetPhoneSymbolFor(kNontermBos));
+ arc->olabel = FindLabel(this_ilabel_info);
+ // the destination state is not specific to this user-defined symbol, it's
+ // a generic destination state.
+ arc->nextstate = GetPhoneSymbolFor(kNontermUserDefined);
+ return true;
+ } else {
+ return false;
+ }
+ } else if (s == GetPhoneSymbolFor(kNontermBegin)) {
+ if (phone_syms_.count(ilabel) != 0 || ilabel == GetPhoneSymbolFor(kNontermBos)) {
+ std::vector<int32> this_ilabel_info(2);
+ this_ilabel_info[0] = -GetPhoneSymbolFor(kNontermBegin);
+ this_ilabel_info[1] = ilabel;
+ arc->nextstate = (ilabel == GetPhoneSymbolFor(kNontermBos) ? 0 : ilabel);
+ arc->olabel = FindLabel(this_ilabel_info);
+ return true;
+ } else {
+ return false;
+ }
+ } else if (s == GetPhoneSymbolFor(kNontermEnd)) {
+ return false;
+ } else if (s == GetPhoneSymbolFor(kNontermUserDefined)) {
+ if (phone_syms_.count(ilabel) != 0 || ilabel == GetPhoneSymbolFor(kNontermBos)) {
+ std::vector<int32> this_ilabel_info(2);
+ this_ilabel_info[0] = -GetPhoneSymbolFor(kNontermReenter);
+ this_ilabel_info[1] = ilabel;
+ arc->nextstate = (ilabel == GetPhoneSymbolFor(kNontermBos) ? 0 : ilabel);
+ arc->olabel = FindLabel(this_ilabel_info);
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ // likely code error.
+ KALDI_ERR << "Invalid state encountered";
+ return false; // won't get here. suppress compiler error.
+ }
+}
+
+StdArc::Label InverseLeftBiphoneContextFst::FindLabel(const vector<int32> &label_vec) {
+ // Finds the ilabel corresponding to this vector (creates a new ilabel if
+ // necessary).
+ VectorToLabelMap::const_iterator iter = ilabel_map_.find(label_vec);
+ if (iter == ilabel_map_.end()) { // Not already in map.
+ Label this_label = ilabel_info_.size();
+ ilabel_info_.push_back(label_vec);
+ ilabel_map_[label_vec] = this_label;
+ return this_label;
+ } else {
+ return iter->second;
+ }
+}
+
+
+void ComposeContextLeftBiphone(
+ int32 nonterm_phones_offset,
+ const vector<int32> &disambig_syms_in,
+ const VectorFst<StdArc> &ifst,
+ VectorFst<StdArc> *ofst,
+ std::vector<std::vector<int32> > *ilabels) {
+
+ vector<int32> disambig_syms(disambig_syms_in);
+ std::sort(disambig_syms.begin(), disambig_syms.end());
+
+ vector<int32> all_syms;
+ GetInputSymbols(ifst, false/*no eps*/, &all_syms);
+ std::sort(all_syms.begin(), all_syms.end());
+ vector<int32> phones;
+ for (size_t i = 0; i < all_syms.size(); i++)
+ if (!std::binary_search(disambig_syms.begin(),
+ disambig_syms.end(), all_syms[i]) &&
+ all_syms[i] < nonterm_phones_offset)
+ phones.push_back(all_syms[i]);
+
+
+ InverseLeftBiphoneContextFst inv_c(nonterm_phones_offset,
+ phones, disambig_syms);
+
+ // The following statement is equivalent to the following
+ // (if FSTs had the '*' operator for composition):
+ // (*ofst) = inv(inv_c) * (*ifst)
+ ComposeDeterministicOnDemandInverse(ifst, &inv_c, ofst);
+
+ inv_c.SwapIlabelInfo(ilabels);
+}
+
+} // end namespace fst
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/grammar-context-fst.h b/runtime/onnxruntime/third_party/kaldi/fstext/grammar-context-fst.h
new file mode 100644
index 000000000..20fd2456d
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/grammar-context-fst.h
@@ -0,0 +1,287 @@
+// fstext/grammar-context-fst.h
+
+// Copyright 2018 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+//
+
+
+#ifndef KALDI_FSTEXT_GRAMMAR_CONTEXT_FST_H_
+#define KALDI_FSTEXT_GRAMMAR_CONTEXT_FST_H_
+
+/* This header defines a special form of the context FST "C" (the "C" in "HCLG")
+ that integrates with our framework for building dynamic graphs for grammars
+ that are too big to statically create, or graphs with on-the-fly pieces that
+ you want to create at recognition time without building the whole graph.
+
+ This framework is limited to only work with models with left-biphone context.
+ (Fortunately this doesn't impact results, as our best models are all 'chain'
+ models with left biphone context).
+
+ The main code exported from here is the class InverseLeftBiphoneContextFst,
+ which is similar to the InverseContextFst defined in context-fst.h, but
+ is limited to left-biphone context and also supports certain special
+ extensions we need to compile grammars.
+
+ See \ref grammar (../doc/grammar.dox) for high-level
+ documentation on how this framework works.
+*/
+
+
+#include <algorithm>
+#include <string>
+#include <vector>
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+
+#include "util/const-integer-set.h"
+#include "fstext/deterministic-fst.h"
+#include "fstext/context-fst.h"
+
+namespace fst {
+
+
+/**
+ An anonymous enum to define some values for symbols used in our grammar-fst
+ framework. Please understand this with reference to the documentation in
+ \ref grammar (../doc/grammar.dox). This enum defines
+ the values of nonterminal-related symbols in phones.txt. They are not
+ the actual values-- they will be shifted by adding the value
+ nonterm_phones_offset which is passed in by the command-line flag
+ --nonterm-phones-offset.
+
+ */
+
+enum NonterminalValues {
+ kNontermBos = 0, // #nonterm_bos
+ kNontermBegin = 1, // #nonterm_begin
+ kNontermEnd = 2, // #nonterm_end
+ kNontermReenter = 3, // #nonterm_reenter
+ kNontermUserDefined = 4, // the lowest-numbered user-defined nonterminal, e.g. #nonterm:foo
+ // kNontermMediumNumber and kNontermBigNumber come into the encoding of
+ // nonterminal-related symbols in HCLG.fst. The only hard constraint on them
+ // is that kNontermBigNumber must be bigger than the biggest transition-id in
+ // your system, and kNontermMediumNumber must be >0. These values were chosen
+ // for ease of human inspection of numbers encoded with them.
+ kNontermMediumNumber = 1000,
+ kNontermBigNumber = 10000000
+};
+
+
+
+// Returns the smallest multiple of 1000 that is strictly greater than
+// nonterm_phones_offset. Used in the encoding of special symbol in HCLG;
+// they are encoded as
+// special_symbol =
+// kNontermBigNumber + (nonterminal * encoding_multiple) + phone_index
+inline int32 GetEncodingMultiple(int32 nonterm_phones_offset) {
+ int32 medium_number = static_cast<int32>(kNontermMediumNumber);
+ return medium_number *
+ ((nonterm_phones_offset + medium_number) / medium_number);
+}
+
+/**
+ This is a variant of the function ComposeContext() which is to be used
+ with our "grammar FST" framework (see \ref graph_context, i.e.
+ ../doc/grammar.dox, for more details). This does not take
+ the 'context_width' and 'central_position' arguments because they are
+ assumed to be 2 and 1 respectively (meaning, left-biphone phonetic context).
+
+ This function creates a context FST and composes it on the left with "ifst"
+ to make "ofst".
+
+ @param [in] nonterm_phones_offset The integer id of the symbol
+ #nonterm_bos in the phones.txt file. You can just set this
+ to a large value (like 1 million) if you are not actually using
+ nonterminals (e.g. for testing purposes).
+ @param [in] disambig_syms List of disambiguation symbols, e.g. the integer
+ ids of #0, #1, #2 ... in the phones.txt.
+ @param [in,out] ifst The FST we are composing with C (e.g. LG.fst).
+ @param [out] ofst Composed output FST (would be CLG.fst).
+ @param [out] ilabels Vector, indexed by ilabel of CLG.fst, providing information
+ about the meaning of that ilabel; see \ref tree_ilabel
+ (http://kaldi-asr.org/doc/tree_externals.html#tree_ilabel)
+ and also \ref grammar_special_clg
+ (http://kaldi-asr.org/doc/grammar#grammar_special_clg).
+ */
+void ComposeContextLeftBiphone(
+ int32 nonterm_phones_offset,
+ const std::vector<int32> &disambig_syms,
+ const VectorFst<StdArc> &ifst,
+ VectorFst<StdArc> *ofst,
+ std::vector<std::vector<int32> > *ilabels);
+
+
+
+/*
+ InverseLeftBiphoneContextFst represents the inverse of the context FST "C" (the "C" in
+ "HCLG") which transduces from symbols representing phone context windows
+ (e.g. "a, b, c") to individual phones, e.g. "a". So InverseContextFst
+ transduces from phones to symbols representing phone context windows. The
+ point is that the inverse is deterministic, so the DeterministicOnDemandFst
+ interface is applicable, which turns out to be a convenient way to implement
+ this.
+
+ This doesn't implement the full Fst interface, it implements the
+ DeterministicOnDemandFst interface which is much simpler and which is
+ sufficient for what we need to do with this.
+
+ Search for "hbka.pdf" ("Speech Recognition with Weighted Finite State
+ Transducers") by M. Mohri, for more context.
+*/
+
+class InverseLeftBiphoneContextFst: public DeterministicOnDemandFst<StdArc> {
+public:
+ typedef StdArc Arc;
+ typedef typename StdArc::StateId StateId;
+ typedef typename StdArc::Weight Weight;
+ typedef typename StdArc::Label Label;
+
+ /**
+ Constructor. This does not take the arguments 'context_width' or
+ 'central_position' because they are assumed to be (2, 1) meaning a
+ system with left-biphone context; and there is no subsequential
+ symbol because it is not needed in systems without right context.
+
+ @param [in] nonterm_phones_offset The integer id of the symbol
+ #nonterm_bos in the phones.txt file. You can just set this to
+ a large value (like 1 million) if you are not actually using
+ nonterminals (e.g. for testing purposes).
+ @param [in] phones List of integer ids of phones, as you would see in phones.txt
+ @param [in] disambig_syms List of integer ids of disambiguation symbols,
+ e.g. the ids of #0, #1, #2 in phones.txt
+
+ See \ref graph_context for more details.
+ */
+ InverseLeftBiphoneContextFst(Label nonterm_phones_offset,
+ const std::vector<int32>& phones,
+ const std::vector<int32>& disambig_syms);
+
+ /**
+ Here is a note on the state space of InverseLeftBiphoneContextFst;
+ see \ref grammar_special_c which has some documentation on this.
+
+ The state space uses the same numbering as phones.txt.
+
+ State 0 means the beginning-of-sequence state, where there is no left
+ context.
+
+ For each phone p in the list 'phones' passed to the constructor (i.e. in
+ the set passed to the constructor), the state 'p' corresponds to a
+ left-context of that phone.
+
+ If p is equal to nonterm_phones_offset_ + kNontermBegin (i.e. the
+ integer form of `\#nonterm_begin`), then this is the state we transition
+ to when we see that symbol starting from left-context==0 (no context). The
+ transition to this special state will have epsilon on the output. (talking
+ here about inv(C), not C, so input/output are reversed).
+ The state is nonfinal and when we see a regular phone p1 or #nonterm_bos, instead of
+ outputting that phone in context, we output the pair (#nonterm_begin,p1) or
+ (#nonterm_begin,#nonterm_bos). This state is not final.
+
+ If p is equal to nonterm_phones_offset_ + kNontermUserDefined, then this
+ is the state we transition to when we see any user-defined nonterminal.
+ Transitions to this special state have olabels of the form (#nonterm:foo,p1)
+ where p1 is the preceding context (with #nonterm_begin if that context was
+ 0); transitions out of it have olabels of the form (#nonterm_reenter,p2), where
+ p2 is the phone on the ilabel of that transition. Again: talking about inv(C).
+ This state is not final.
+
+ If p is equal to nonterm_phones_offset_ + kNontermEnd, then this is
+ the state we transition to when we see the ilabel #nonterm_end. The olabels
+ on the transitions to it (talking here about inv(C), so ilabels and olabels
+ are reversed) are of the form (#nonterm_end, p1) where p1 corresponds to the
+ context we were in. This state is final.
+ */
+
+
+ virtual StateId Start() { return 0; }
+
+ virtual Weight Final(StateId s);
+
+ /// Note: ilabel must not be epsilon.
+ virtual bool GetArc(StateId s, Label ilabel, Arc *arc);
+
+ ~InverseLeftBiphoneContextFst() { }
+
+ // Returns a reference to a vector<vector<int32> > with information about all
+ // the input symbols of C (i.e. all the output symbols of this
+ // InverseContextFst). See
+ // "http://kaldi-asr.org/doc/tree_externals.html#tree_ilabel".
+ const std::vector<std::vector<int32> > &IlabelInfo() const {
+ return ilabel_info_;
+ }
+
+ // A way to destructively obtain the ilabel-info. Only do this if you
+ // are just about to destroy this object.
+ void SwapIlabelInfo(std::vector<std::vector<int32> > *vec) { ilabel_info_.swap(*vec); }
+
+private:
+
+ inline int32 GetPhoneSymbolFor(enum NonterminalValues n) {
+ return nonterm_phones_offset_ + static_cast<int32>(n);
+ }
+
+ /// Finds the label index corresponding to this context-window of phones
+ /// (likely of width context_width_). Inserts it into the
+ /// ilabel_info_/ilabel_map_ tables if necessary.
+ Label FindLabel(const std::vector<int32> &label_info);
+
+
+ // Map type to map from vectors of int32 (representing ilabel-info,
+ // see http://kaldi-asr.org/doc/tree_externals.html#tree_ilabel) to
+ // Label (the output label in this FST).
+ typedef unordered_map<std::vector<int32>, Label,
+ kaldi::VectorHasher<int32> > VectorToLabelMap;
+
+
+ // The following three variables were also passed in by the caller:
+ int32 nonterm_phones_offset_;
+
+ // 'phone_syms_' are a set of phone-ids, typically 1, 2, .. num_phones.
+ kaldi::ConstIntegerSet<Label> phone_syms_;
+
+ // disambig_syms_ is the set of integer ids of the disambiguation symbols,
+ // usually represented in text form as #0, #1, #2, etc. These are inserted
+ // into the grammar (for #0) and the lexicon (for #1, #2, ...) in order to
+ // make the composed FSTs determinizable. They are treated "specially" by the
+ // context FST in that they are not part of the context, they are just "passed
+ // through" via self-loops. See the Mohri chapter mrentioned above for more
+ // information.
+ kaldi::ConstIntegerSet<Label> disambig_syms_;
+
+
+ // maps from vector<int32>, representing phonetic contexts of length
+ // context_width_ - 1, to Label. These are actually the output labels of this
+ // InverseContextFst (because of the "Inverse" part), but for historical
+ // reasons and because we've used the term ilabels" in the documentation, we
+ // still call these "ilabels").
+ VectorToLabelMap ilabel_map_;
+
+ // ilabel_info_ is the reverse map of ilabel_map_.
+ // Indexed by olabel (although we call this ilabel_info_ for historical
+ // reasons and because is for the ilabels of C), ilabel_info_[i] gives
+ // information about the meaning of each symbol on the input of C
+ // aka the output of inv(C).
+ // See "http://kaldi-asr.org/doc/tree_externals.html#tree_ilabel".
+ std::vector<std::vector<int32> > ilabel_info_;
+
+};
+
+} // namespace fst
+
+
+#endif // KALDI_FSTEXT_GRAMMAR_CONTEXT_FST_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/kaldi-fst-io-inl.h b/runtime/onnxruntime/third_party/kaldi/fstext/kaldi-fst-io-inl.h
new file mode 100644
index 000000000..b6bae4b9d
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/kaldi-fst-io-inl.h
@@ -0,0 +1,211 @@
+// fstext/kaldi-fst-io-inl.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2012-2015 Johns Hopkins University (Author: Daniel Povey)
+// 2013 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_KALDI_FST_IO_INL_H_
+#define KALDI_FSTEXT_KALDI_FST_IO_INL_H_
+
+#include "util/text-utils.h"
+
+namespace fst {
+
+
+template <class Arc>
+void WriteFstKaldi(std::ostream &os, bool binary,
+ const VectorFst<Arc> &t) {
+ bool ok;
+ if (binary) {
+ // Binary-mode writing.
+ ok = t.Write(os, FstWriteOptions());
+ } else {
+ // Text-mode output. Note: we expect that t.InputSymbols() and
+ // t.OutputSymbols() would always return NULL. The corresponding input
+ // routine would not work if the FST actually had symbols attached. Write a
+ // newline to start the FST; in a table, the first line of the FST will
+ // appear on its own line.
+ os << '\n';
+ bool acceptor = false, write_one = false;
+ FstPrinter<Arc> printer(t, t.InputSymbols(), t.OutputSymbols(),
+ NULL, acceptor, write_one, "\t");
+ printer.Print(&os, "<unknown>");
+ if (os.fail())
+ KALDI_ERR << "Stream failure detected writing FST to stream";
+ // Write another newline as a terminating character. The read routine will
+ // detect this [this is a Kaldi mechanism, not something in the original
+ // OpenFst code].
+ os << '\n';
+ ok = os.good();
+ }
+ if (!ok) {
+ KALDI_ERR << "Error writing FST to stream";
+ }
+}
+
+// Utility function used in ReadFstKaldi
+template <class W>
+inline bool StrToWeight(const std::string &s, bool allow_zero, W *w) {
+ std::istringstream strm(s);
+ strm >> *w;
+ if (strm.fail() || (!allow_zero && *w == W::Zero())) {
+ return false;
+ }
+ return true;
+}
+
+template <class Arc>
+void ReadFstKaldi(std::istream &is, bool binary,
+ VectorFst<Arc> *fst) {
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId StateId;
+ if (binary) {
+ // We don't have access to the filename here, so write [unknown].
+ VectorFst<Arc> *ans =
+ VectorFst<Arc>::Read(is, fst::FstReadOptions(std::string("[unknown]")));
+ if (ans == NULL) {
+ KALDI_ERR << "Error reading FST from stream.";
+ }
+ *fst = *ans; // shallow copy.
+ delete ans;
+ } else {
+ // Consume the \r on Windows, the \n that the text-form FST format starts
+ // with, and any extra spaces that might have got in there somehow.
+ while (std::isspace(is.peek()) && is.peek() != '\n') is.get();
+ if (is.peek() == '\n') is.get(); // consume the newline.
+ else { // saw spaces but no newline.. this is not expected.
+ KALDI_ERR << "Reading FST: unexpected sequence of spaces "
+ << " at file position " << is.tellg();
+ }
+ using std::string;
+ using std::vector;
+ using kaldi::SplitStringToIntegers;
+ using kaldi::ConvertStringToInteger;
+ fst->DeleteStates();
+ string line;
+ size_t nline = 0;
+ string separator = FLAGS_fst_field_separator + "\r\n";
+ while (std::getline(is, line)) {
+ nline++;
+ vector<string> col;
+ // on Windows we'll write in text and read in binary mode.
+ kaldi::SplitStringToVector(line, separator.c_str(), true, &col);
+ if (col.size() == 0) break; // Empty line is a signal to stop, in our
+ // archive format.
+ if (col.size() > 5) {
+ KALDI_ERR << "Bad line in FST: " << line;
+ }
+ StateId s;
+ if (!ConvertStringToInteger(col[0], &s)) {
+ KALDI_ERR << "Bad line in FST: " << line;
+ }
+ while (s >= fst->NumStates())
+ fst->AddState();
+ if (nline == 1) fst->SetStart(s);
+
+ bool ok = true;
+ Arc arc;
+ Weight w;
+ StateId d = s;
+ switch (col.size()) {
+ case 1:
+ fst->SetFinal(s, Weight::One());
+ break;
+ case 2:
+ if (!StrToWeight(col[1], true, &w)) ok = false;
+ else fst->SetFinal(s, w);
+ break;
+ case 3: // 3 columns not ok for Lattice format; it's not an acceptor.
+ ok = false;
+ break;
+ case 4:
+ ok = ConvertStringToInteger(col[1], &arc.nextstate) &&
+ ConvertStringToInteger(col[2], &arc.ilabel) &&
+ ConvertStringToInteger(col[3], &arc.olabel);
+ if (ok) {
+ d = arc.nextstate;
+ arc.weight = Weight::One();
+ fst->AddArc(s, arc);
+ }
+ break;
+ case 5:
+ ok = ConvertStringToInteger(col[1], &arc.nextstate) &&
+ ConvertStringToInteger(col[2], &arc.ilabel) &&
+ ConvertStringToInteger(col[3], &arc.olabel) &&
+ StrToWeight(col[4], false, &arc.weight);
+ if (ok) {
+ d = arc.nextstate;
+ fst->AddArc(s, arc);
+ }
+ break;
+ default:
+ ok = false;
+ }
+ while (d >= fst->NumStates()) fst->AddState();
+ if (!ok)
+ KALDI_ERR << "Bad line in FST: " << line;
+ }
+ }
+}
+
+
+
+
+template<class Arc> // static
+bool VectorFstTplHolder<Arc>::Write(std::ostream &os, bool binary, const T &t) {
+ try {
+ WriteFstKaldi(os, binary, t);
+ return true;
+ } catch (...) {
+ return false;
+ }
+}
+
+template<class Arc> // static
+bool VectorFstTplHolder<Arc>::Read(std::istream &is) {
+ Clear();
+ int c = is.peek();
+ if (c == -1) {
+ KALDI_WARN << "End of stream detected reading Fst";
+ return false;
+ } else if (isspace(c)) { // The text form of the FST begins
+ // with space (normally, '\n'), so this means it's text (the binary form
+ // cannot begin with space because it starts with the FST Type() which is not
+ // space).
+ try {
+ t_ = new VectorFst<Arc>();
+ ReadFstKaldi(is, false, t_);
+ } catch (...) {
+ Clear();
+ return false;
+ }
+ } else { // reading a binary FST.
+ try {
+ t_ = new VectorFst<Arc>();
+ ReadFstKaldi(is, true, t_);
+ } catch (...) {
+ Clear();
+ return false;
+ }
+ }
+ return true;
+}
+
+} // namespace fst.
+
+#endif // KALDI_FSTEXT_KALDI_FST_IO_INL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/kaldi-fst-io.cc b/runtime/onnxruntime/third_party/kaldi/fstext/kaldi-fst-io.cc
new file mode 100644
index 000000000..61d6cc747
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/kaldi-fst-io.cc
@@ -0,0 +1,145 @@
+// fstext/kaldi-fst-io.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2012-2015 Johns Hopkins University (Author: Daniel Povey)
+// 2013 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "fstext/kaldi-fst-io.h"
+#include "base/kaldi-error.h"
+#include "base/kaldi-math.h"
+#include "util/kaldi-io.h"
+
+namespace fst {
+
+VectorFst<StdArc> *ReadFstKaldi(std::string rxfilename) {
+ if (rxfilename == "") rxfilename = "-"; // interpret "" as stdin,
+ // for compatibility with OpenFst conventions.
+ kaldi::Input ki(rxfilename);
+ fst::FstHeader hdr;
+ if (!hdr.Read(ki.Stream(), rxfilename))
+ KALDI_ERR << "Reading FST: error reading FST header from "
+ << kaldi::PrintableRxfilename(rxfilename);
+ FstReadOptions ropts("<unspecified>", &hdr);
+ VectorFst<StdArc> *fst = VectorFst<StdArc>::Read(ki.Stream(), ropts);
+ if (!fst)
+ KALDI_ERR << "Could not read fst from "
+ << kaldi::PrintableRxfilename(rxfilename);
+ return fst;
+}
+
+// Register const fst to load it automatically. Other types like
+// olabel_lookahead or ngram or compact_fst should be registered
+// through OpenFst registration API.
+static fst::FstRegisterer<VectorFst<StdArc>> VectorFst_StdArc_registerer;
+static fst::FstRegisterer<ConstFst<StdArc>> ConstFst_StdArc_registerer;
+
+Fst<StdArc> *ReadFstKaldiGeneric(std::string rxfilename, bool throw_on_err) {
+ if (rxfilename == "") rxfilename = "-"; // interpret "" as stdin,
+ // for compatibility with OpenFst conventions.
+ kaldi::Input ki(rxfilename);
+ fst::FstHeader hdr;
+ // Read FstHeader which contains the type of FST
+ if (!hdr.Read(ki.Stream(), rxfilename)) {
+ if(throw_on_err) {
+ KALDI_ERR << "Reading FST: error reading FST header from "
+ << kaldi::PrintableRxfilename(rxfilename);
+ } else {
+ KALDI_WARN << "We fail to read FST header from "
+ << kaldi::PrintableRxfilename(rxfilename)
+ << ". A NULL pointer is returned.";
+ return NULL;
+ }
+ }
+ // Check the type of Arc
+ if (hdr.ArcType() != fst::StdArc::Type()) {
+ if(throw_on_err) {
+ KALDI_ERR << "FST with arc type " << hdr.ArcType() << " is not supported.";
+ } else {
+ KALDI_WARN << "Fst with arc type" << hdr.ArcType()
+ << " is not supported. A NULL pointer is returned.";
+ return NULL;
+ }
+ }
+ // Read the FST
+ FstReadOptions ropts("<unspecified>", &hdr);
+ Fst<StdArc> *fst = Fst<StdArc>::Read(ki.Stream(), ropts);
+ if (!fst) {
+ if(throw_on_err) {
+ KALDI_ERR << "Could not read fst from "
+ << kaldi::PrintableRxfilename(rxfilename);
+ } else {
+ KALDI_WARN << "Could not read fst from "
+ << kaldi::PrintableRxfilename(rxfilename)
+ << ". A NULL pointer is returned.";
+ return NULL;
+ }
+ }
+ return fst;
+}
+
+VectorFst<StdArc> *CastOrConvertToVectorFst(Fst<StdArc> *fst) {
+ // This version currently supports ConstFst<StdArc> or VectorFst<StdArc>
+ std::string real_type = fst->Type();
+ KALDI_ASSERT(real_type == "vector" || real_type == "const");
+ if (real_type == "vector") {
+ return dynamic_cast<VectorFst<StdArc> *>(fst);
+ } else {
+ // As the 'fst' can't cast to VectorFst, we create a new
+ // VectorFst<StdArc> initialized by 'fst', and delete 'fst'.
+ VectorFst<StdArc> *new_fst = new VectorFst<StdArc>(*fst);
+ delete fst;
+ return new_fst;
+ }
+}
+
+void ReadFstKaldi(std::string rxfilename, fst::StdVectorFst *ofst) {
+ fst::StdVectorFst *fst = ReadFstKaldi(rxfilename);
+ *ofst = *fst;
+ delete fst;
+}
+
+void WriteFstKaldi(const VectorFst<StdArc> &fst,
+ std::string wxfilename) {
+ if (wxfilename == "") wxfilename = "-"; // interpret "" as stdout,
+ // for compatibility with OpenFst conventions.
+ bool write_binary = true, write_header = false;
+ kaldi::Output ko(wxfilename, write_binary, write_header);
+ FstWriteOptions wopts(kaldi::PrintableWxfilename(wxfilename));
+ fst.Write(ko.Stream(), wopts);
+}
+
+fst::VectorFst<fst::StdArc> *ReadAndPrepareLmFst(std::string rxfilename) {
+ // ReadFstKaldi() will die with exception on failure.
+ fst::VectorFst<fst::StdArc> *ans = fst::ReadFstKaldi(rxfilename);
+ if (ans->Properties(fst::kAcceptor, true) == 0) {
+ // If it's not already an acceptor, project on the output, i.e. copy olabels
+ // to ilabels. Generally the G.fst's on disk will have the disambiguation
+ // symbol #0 on the input symbols of the backoff arc, and projection will
+ // replace them with epsilons which is what is on the output symbols of
+ // those arcs.
+ fst::Project(ans, fst::PROJECT_OUTPUT);
+ }
+ if (ans->Properties(fst::kILabelSorted, true) == 0) {
+ // Make sure LM is sorted on ilabel.
+ fst::ILabelCompare<fst::StdArc> ilabel_comp;
+ fst::ArcSort(ans, ilabel_comp);
+ }
+ return ans;
+}
+
+} // end namespace fst
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/kaldi-fst-io.h b/runtime/onnxruntime/third_party/kaldi/fstext/kaldi-fst-io.h
new file mode 100644
index 000000000..a45920936
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/kaldi-fst-io.h
@@ -0,0 +1,158 @@
+// fstext/kaldi-fst-io.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2012-2015 Johns Hopkins University (Author: Daniel Povey)
+// 2013 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_KALDI_FST_IO_H_
+#define KALDI_FSTEXT_KALDI_FST_IO_H_
+
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+#include <fst/script/print-impl.h>
+#include "base/kaldi-common.h"
+
+// Some functions for writing Fsts.
+// I/O for FSTs is a bit of a mess, and not very well integrated with Kaldi's
+// generic I/O mechanisms, because we want files containing just FSTs to
+// be readable by OpenFST's native binaries, which is not compatible
+// with the normal \0B header that identifies Kaldi files as containing
+// binary data.
+// So use the functions here with your eyes open, and with caution!
+namespace fst {
+
+// Read a binary FST using Kaldi I/O mechanisms (pipes, etc.)
+// On error returns NULL. Only supports VectorFst and exists
+// mainly for backward code compabibility.
+VectorFst<StdArc> *ReadFstKaldi(std::string rxfilename);
+
+// Read a binary FST using Kaldi I/O mechanisms (pipes, etc.)
+// If it can't read the FST, if throw_on_err == true it throws using KALDI_ERR;
+// otherwise it prints a warning and returns. Note:this
+// doesn't support the text-mode option that we generally like to support.
+// This version currently supports ConstFst<StdArc> or VectorFst<StdArc>
+// (const-fst can give better performance for decoding). Other
+// types could be also loaded if registered inside OpenFst.
+Fst<StdArc> *ReadFstKaldiGeneric(std::string rxfilename,
+ bool throw_on_err = true);
+
+// This function attempts to dynamic_cast the pointer 'fst' (which will likely
+// have been returned by ReadFstGeneric()), to the more derived
+// type VectorFst<StdArc>. If this succeeds, it returns the same pointer;
+// if it fails, it converts the FST type (by creating a new VectorFst<stdArc>
+// initialized by 'fst'), prints a warning, and deletes 'fst'.
+VectorFst<StdArc> *CastOrConvertToVectorFst(Fst<StdArc> *fst);
+
+// Version of ReadFstKaldi() that writes to a pointer. Assumes
+// the FST is binary with no binary marker. Crashes on error.
+void ReadFstKaldi(std::string rxfilename, VectorFst<StdArc> *ofst);
+
+// Write an FST using Kaldi I/O mechanisms (pipes, etc.)
+// On error, throws using KALDI_ERR. For use only in code in fstbin/,
+// as it doesn't support the text-mode option.
+void WriteFstKaldi(const VectorFst<StdArc> &fst,
+ std::string wxfilename);
+
+// This is a more general Kaldi-type-IO mechanism of writing FSTs to
+// streams, supporting binary or text-mode writing. (note: we just
+// write the integers, symbol tables are not supported).
+// On error, throws using KALDI_ERR.
+template <class Arc>
+void WriteFstKaldi(std::ostream &os, bool binary,
+ const VectorFst<Arc> &fst);
+
+// A generic Kaldi-type-IO mechanism of reading FSTs from streams,
+// supporting binary or text-mode reading/writing.
+template <class Arc>
+void ReadFstKaldi(std::istream &is, bool binary,
+ VectorFst<Arc> *fst);
+
+// Read an FST file for LM (G.fst) and make it an acceptor,
+// and make sure it is sorted on labels
+fst::VectorFst<fst::StdArc> *ReadAndPrepareLmFst(std::string rxfilename);
+
+// This is a Holder class with T = VectorFst<Arc>, that meets the requirements
+// of a Holder class as described in ../util/kaldi-holder.h. This enables us to
+// read/write collections of FSTs indexed by strings, using the Table concept (
+// see ../util/kaldi-table.h).
+// Originally it was only templated on T = VectorFst<StdArc>, but as the keyword
+// spotting stuff introduced more types of FSTs, we made it also templated on
+// the arc.
+template<class Arc>
+class VectorFstTplHolder {
+ public:
+ typedef VectorFst<Arc> T;
+
+ VectorFstTplHolder(): t_(NULL) { }
+
+ static bool Write(std::ostream &os, bool binary, const T &t);
+
+ void Copy(const T &t) { // copies it into the holder.
+ Clear();
+ t_ = new T(t);
+ }
+
+ // Reads into the holder.
+ bool Read(std::istream &is);
+
+ // It's potentially a binary format, so must read in binary mode (linefeed
+ // translation will corrupt the file. We don't know till we open the file if
+ // it's really binary, so we need to read in binary mode to be on the safe
+ // side. Extra linefeeds won't matter, the text-mode reading code ignores
+ // them.
+ static bool IsReadInBinary() { return true; }
+
+ T &Value() {
+ // code error if !t_.
+ if (!t_) KALDI_ERR << "VectorFstTplHolder::Value() called wrongly.";
+ return *t_;
+ }
+
+ void Clear() {
+ if (t_) {
+ delete t_;
+ t_ = NULL;
+ }
+ }
+
+ void Swap(VectorFstTplHolder<Arc> *other) {
+ std::swap(t_, other->t_);
+ }
+
+ bool ExtractRange(const VectorFstTplHolder<Arc> &other,
+ const std::string &range) {
+ KALDI_ERR << "ExtractRange is not defined for this type of holder.";
+ return false;
+ }
+
+ ~VectorFstTplHolder() { Clear(); }
+ // No destructor. Assignment and
+ // copy constructor take their default implementations.
+ private:
+ KALDI_DISALLOW_COPY_AND_ASSIGN(VectorFstTplHolder);
+ T *t_;
+};
+
+// Now make the original VectorFstHolder as the typedef of VectorFstHolder<StdArc>.
+typedef VectorFstTplHolder<StdArc> VectorFstHolder;
+
+
+} // end namespace fst
+
+#include "fstext/kaldi-fst-io-inl.h"
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/lattice-utils-inl.h b/runtime/onnxruntime/third_party/kaldi/fstext/lattice-utils-inl.h
new file mode 100644
index 000000000..c97a538dd
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/lattice-utils-inl.h
@@ -0,0 +1,282 @@
+// fstext/lattice-utils-inl.h
+
+// Copyright 2009-2012 Microsoft Corporation Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_LATTICE_UTILS_INL_H_
+#define KALDI_FSTEXT_LATTICE_UTILS_INL_H_
+// Do not include this file directly. It is included by lattice-utils.h
+
+
+namespace fst {
+
+
+/* Convert from FST with arc-type Weight, to one with arc-type
+ CompactLatticeWeight. Uses FactorFst to identify chains
+ of states which can be turned into a single output arc. */
+
+template<class Weight, class Int>
+void ConvertLattice(
+ const ExpandedFst<ArcTpl<Weight> > &ifst,
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, Int> > > *ofst,
+ bool invert) {
+ typedef ArcTpl<Weight> Arc;
+ typedef typename Arc::StateId StateId;
+ typedef CompactLatticeWeightTpl<Weight, Int> CompactWeight;
+ typedef ArcTpl<CompactWeight> CompactArc;
+
+ VectorFst<ArcTpl<Weight> > ffst;
+ std::vector<std::vector<Int> > labels;
+ if (invert) // normal case: want the ilabels as sequences on the arcs of
+ Factor(ifst, &ffst, &labels); // the output... Factor makes seqs of
+ // ilabels.
+ else {
+ VectorFst<ArcTpl<Weight> > invfst(ifst);
+ Invert(&invfst);
+ Factor(invfst, &ffst, &labels);
+ }
+
+ TopSort(&ffst); // Put the states in ffst in topological order, which is
+ // easier on the eye when reading the text-form lattices and corresponds to
+ // what we get when we generate the lattices in the decoder.
+
+ ofst->DeleteStates();
+
+ // The states will be numbered exactly the same as the original FST.
+ // Add the states to the new FST.
+ StateId num_states = ffst.NumStates();
+ for (StateId s = 0; s < num_states; s++) {
+ StateId news = ofst->AddState();
+ assert(news == s);
+ }
+ ofst->SetStart(ffst.Start());
+ for (StateId s = 0; s < num_states; s++) {
+ Weight final_weight = ffst.Final(s);
+ if (final_weight != Weight::Zero()) {
+ CompactWeight final_compact_weight(final_weight, std::vector<Int>());
+ ofst->SetFinal(s, final_compact_weight);
+ }
+ for (ArcIterator<ExpandedFst<Arc> > iter(ffst, s);
+ !iter.Done();
+ iter.Next()) {
+ const Arc &arc = iter.Value();
+ KALDI_PARANOID_ASSERT(arc.weight != Weight::Zero());
+ // note: zero-weight arcs not allowed anyway so weight should not be zero,
+ // but no harm in checking.
+ CompactArc compact_arc(arc.olabel, arc.olabel,
+ CompactWeight(arc.weight, labels[arc.ilabel]),
+ arc.nextstate);
+ ofst->AddArc(s, compact_arc);
+ }
+ }
+}
+
+template<class Weight, class Int>
+void ConvertLattice(
+ const ExpandedFst<ArcTpl<CompactLatticeWeightTpl<Weight, Int> > > &ifst,
+ MutableFst<ArcTpl<Weight> > *ofst,
+ bool invert) {
+ typedef ArcTpl<Weight> Arc;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Label Label;
+ typedef CompactLatticeWeightTpl<Weight, Int> CompactWeight;
+ typedef ArcTpl<CompactWeight> CompactArc;
+ ofst->DeleteStates();
+ // make the states in the new FST have the same numbers as
+ // the original ones, and add chains of states as necessary
+ // to encode the string-valued weights.
+ StateId num_states = ifst.NumStates();
+ for (StateId s = 0; s < num_states; s++) {
+ StateId news = ofst->AddState();
+ assert(news == s);
+ }
+ ofst->SetStart(ifst.Start());
+ for (StateId s = 0; s < num_states; s++) {
+ CompactWeight final_weight = ifst.Final(s);
+ if (final_weight != CompactWeight::Zero()) {
+ StateId cur_state = s;
+ size_t string_length = final_weight.String().size();
+ for (size_t n = 0; n < string_length; n++) {
+ StateId next_state = ofst->AddState();
+ Label ilabel = 0;
+ Arc arc(ilabel, final_weight.String()[n],
+ (n == 0 ? final_weight.Weight() : Weight::One()),
+ next_state);
+ if (invert) std::swap(arc.ilabel, arc.olabel);
+ ofst->AddArc(cur_state, arc);
+ cur_state = next_state;
+ }
+ ofst->SetFinal(cur_state,
+ string_length > 0 ? Weight::One() : final_weight.Weight());
+ }
+ for (ArcIterator<ExpandedFst<CompactArc> > iter(ifst, s);
+ !iter.Done();
+ iter.Next()) {
+ const CompactArc &arc = iter.Value();
+ size_t string_length = arc.weight.String().size();
+ StateId cur_state = s;
+ // for all but the last element in the string--
+ // add a temporary state.
+ for (size_t n = 0 ; n+1 < string_length; n++) {
+ StateId next_state = ofst->AddState();
+ Label ilabel = (n == 0 ? arc.ilabel : 0),
+ olabel = static_cast<Label>(arc.weight.String()[n]);
+ Weight weight = (n == 0 ? arc.weight.Weight() : Weight::One());
+ Arc new_arc(ilabel, olabel, weight, next_state);
+ if (invert) std::swap(new_arc.ilabel, new_arc.olabel);
+ ofst->AddArc(cur_state, new_arc);
+ cur_state = next_state;
+ }
+ Label ilabel = (string_length <= 1 ? arc.ilabel : 0),
+ olabel = (string_length > 0 ? arc.weight.String()[string_length-1] : 0);
+ Weight weight = (string_length <= 1 ? arc.weight.Weight() : Weight::One());
+ Arc new_arc(ilabel, olabel, weight, arc.nextstate);
+ if (invert) std::swap(new_arc.ilabel, new_arc.olabel);
+ ofst->AddArc(cur_state, new_arc);
+ }
+ }
+}
+
+// This function converts lattices between float and double;
+// it works for both CompactLatticeWeight and LatticeWeight.
+template<class WeightIn, class WeightOut>
+void ConvertLattice(
+ const ExpandedFst<ArcTpl<WeightIn> > &ifst,
+ MutableFst<ArcTpl<WeightOut> > *ofst) {
+ typedef ArcTpl<WeightIn> ArcIn;
+ typedef ArcTpl<WeightOut> ArcOut;
+ typedef typename ArcIn::StateId StateId;
+ ofst->DeleteStates();
+ // The states will be numbered exactly the same as the original FST.
+ // Add the states to the new FST.
+ StateId num_states = ifst.NumStates();
+ for (StateId s = 0; s < num_states; s++) {
+ StateId news = ofst->AddState();
+ assert(news == s);
+ }
+ ofst->SetStart(ifst.Start());
+ for (StateId s = 0; s < num_states; s++) {
+ WeightIn final_iweight = ifst.Final(s);
+ if (final_iweight != WeightIn::Zero()) {
+ WeightOut final_oweight;
+ ConvertLatticeWeight(final_iweight, &final_oweight);
+ ofst->SetFinal(s, final_oweight);
+ }
+ for (ArcIterator<ExpandedFst<ArcIn> > iter(ifst, s);
+ !iter.Done();
+ iter.Next()) {
+ ArcIn arc = iter.Value();
+ KALDI_PARANOID_ASSERT(arc.weight != WeightIn::Zero());
+ ArcOut oarc;
+ ConvertLatticeWeight(arc.weight, &oarc.weight);
+ oarc.ilabel = arc.ilabel;
+ oarc.olabel = arc.olabel;
+ oarc.nextstate = arc.nextstate;
+ ofst->AddArc(s, oarc);
+ }
+ }
+}
+
+
+
+template<class Weight, class ScaleFloat>
+void ScaleLattice(
+ const std::vector<std::vector<ScaleFloat> > &scale,
+ MutableFst<ArcTpl<Weight> > *fst) {
+ assert(scale.size() == 2 && scale[0].size() == 2 && scale[1].size() == 2);
+ if (scale == DefaultLatticeScale()) // nothing to do.
+ return;
+ typedef ArcTpl<Weight> Arc;
+ typedef MutableFst<Arc> Fst;
+ typedef typename Arc::StateId StateId;
+ StateId num_states = fst->NumStates();
+ for (StateId s = 0; s < num_states; s++) {
+ for (MutableArcIterator<Fst> aiter(fst, s);
+ !aiter.Done();
+ aiter.Next()) {
+ Arc arc = aiter.Value();
+ arc.weight = Weight(ScaleTupleWeight(arc.weight, scale));
+ aiter.SetValue(arc);
+ }
+ Weight final_weight = fst->Final(s);
+ if (final_weight != Weight::Zero())
+ fst->SetFinal(s, Weight(ScaleTupleWeight(final_weight, scale)));
+ }
+}
+
+template<class Weight, class Int>
+void RemoveAlignmentsFromCompactLattice(
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, Int> > > *fst) {
+ typedef CompactLatticeWeightTpl<Weight, Int> W;
+ typedef ArcTpl<W> Arc;
+ typedef MutableFst<Arc> Fst;
+ typedef typename Arc::StateId StateId;
+ StateId num_states = fst->NumStates();
+ for (StateId s = 0; s < num_states; s++) {
+ for (MutableArcIterator<Fst> aiter(fst, s);
+ !aiter.Done();
+ aiter.Next()) {
+ Arc arc = aiter.Value();
+ arc.weight = W(arc.weight.Weight(), std::vector<Int>());
+ aiter.SetValue(arc);
+ }
+ W final_weight = fst->Final(s);
+ if (final_weight != W::Zero())
+ fst->SetFinal(s, W(final_weight.Weight(), std::vector<Int>()));
+ }
+}
+
+template<class Weight, class Int>
+bool CompactLatticeHasAlignment(
+ const ExpandedFst<ArcTpl<CompactLatticeWeightTpl<Weight, Int> > > &fst) {
+ typedef CompactLatticeWeightTpl<Weight, Int> W;
+ typedef ArcTpl<W> Arc;
+ typedef ExpandedFst<Arc> Fst;
+ typedef typename Arc::StateId StateId;
+ StateId num_states = fst.NumStates();
+ for (StateId s = 0; s < num_states; s++) {
+ for (ArcIterator<Fst> aiter(fst, s);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (!arc.weight.String().empty()) return true;
+ }
+ W final_weight = fst.Final(s);
+ if (!final_weight.String().empty()) return true;
+ }
+ return false;
+}
+
+
+template <class Real>
+void ConvertFstToLattice(
+ const ExpandedFst<ArcTpl<TropicalWeight> > &ifst,
+ MutableFst<ArcTpl<LatticeWeightTpl<Real> > > *ofst) {
+ int32 num_states_cache = 50000;
+ fst::CacheOptions cache_opts(true, num_states_cache);
+ fst::MapFstOptions mapfst_opts(cache_opts);
+ StdToLatticeMapper<Real> mapper;
+ MapFst<StdArc, ArcTpl<LatticeWeightTpl<Real> >,
+ StdToLatticeMapper<Real> > map_fst(ifst, mapper, mapfst_opts);
+ *ofst = map_fst;
+}
+
+
+}
+
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/lattice-utils-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/lattice-utils-test.cc
new file mode 100644
index 000000000..aa931d47d
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/lattice-utils-test.cc
@@ -0,0 +1,331 @@
+// fstext/lattice-utils-test.cc
+
+// Copyright 2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "fstext/lattice-utils.h"
+#include "fstext/fst-test-utils.h"
+#include "base/kaldi-math.h"
+
+namespace fst {
+
+template<class Weight, class Int> void TestConvert(bool invert) {
+ typedef ArcTpl<Weight> Arc;
+ typedef ArcTpl<CompactLatticeWeightTpl<Weight, Int> > CompactArc;
+ for(int i = 0; i < 5; i++) {
+ VectorFst<Arc> *fst = RandFst<Arc>();
+ std::cout << "FST before converting to compact-arc is:\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ VectorFst<CompactArc> ofst;
+ ConvertLattice<Weight, Int>(*fst, &ofst, invert);
+
+ std::cout << "FST after converting is:\n";
+ {
+ FstPrinter<CompactArc> fstprinter(ofst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ VectorFst<Arc> origfst;
+ ConvertLattice<Weight, Int>(ofst, &origfst, invert);
+ std::cout << "FST after back conversion is:\n";
+ {
+ FstPrinter<Arc> fstprinter(origfst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ assert(RandEquivalent(*fst, origfst, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst;
+ }
+}
+
+// This tests the ShortestPath algorithm, and by proxy, tests the
+// NaturalLess template etc.
+
+template<class Weight, class Int> void TestShortestPath() {
+ for (int p = 0; p < 10; p++) {
+ typedef ArcTpl<Weight> Arc;
+ typedef ArcTpl<CompactLatticeWeightTpl<Weight, Int> > CompactArc;
+ for(int i = 0; i < 5; i++) {
+ VectorFst<Arc> *fst = RandPairFst<Arc>();
+ std::cout << "Testing shortest path\n";
+ std::cout << "FST before converting to compact-arc is:\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ VectorFst<CompactArc> cfst;
+ ConvertLattice<Weight, Int>(*fst, &cfst, false); // invert == false
+
+
+ {
+ VectorFst<Arc> nbest_fst_1;
+ ShortestPath(*fst, &nbest_fst_1, 1);
+ VectorFst<Arc> nbest_fst_2;
+ ShortestPath(*fst, &nbest_fst_2, 3);
+ VectorFst<Arc> nbest_fst_1b;
+ ShortestPath(nbest_fst_2, &nbest_fst_1b, 1);
+
+
+ assert(ApproxEqual(ShortestDistance(nbest_fst_1),
+ ShortestDistance(nbest_fst_1b)));
+
+ // since semiring is idempotent, this should succeed too.
+ assert(ApproxEqual(ShortestDistance(*fst),
+ ShortestDistance(nbest_fst_1b)));
+ }
+ {
+ VectorFst<CompactArc> nbest_fst_1;
+ ShortestPath(cfst, &nbest_fst_1, 1);
+ VectorFst<CompactArc> nbest_fst_2;
+ ShortestPath(cfst, &nbest_fst_2, 3);
+ VectorFst<CompactArc> nbest_fst_1b;
+ ShortestPath(nbest_fst_2, &nbest_fst_1b, 1);
+
+ assert(ApproxEqual(ShortestDistance(nbest_fst_1),
+ ShortestDistance(nbest_fst_1b)));
+ // since semiring is idempotent, this should succeed too.
+ assert(ApproxEqual(ShortestDistance(cfst),
+ ShortestDistance(nbest_fst_1b)));
+ }
+
+ delete fst;
+ }
+ }
+}
+
+
+
+template<class Int> void TestConvert2() {
+ typedef ArcTpl<LatticeWeightTpl<float> > ArcF;
+ typedef ArcTpl<LatticeWeightTpl<double> > ArcD;
+ typedef ArcTpl<CompactLatticeWeightTpl<LatticeWeightTpl<float>, Int> > CArcF;
+ typedef ArcTpl<CompactLatticeWeightTpl<LatticeWeightTpl<double>, Int> > CArcD;
+
+ for(int i = 0; i < 2; i++) {
+ {
+ VectorFst<ArcF> *fst1 = RandPairFst<ArcF>();
+ VectorFst<ArcD> fst2;
+ VectorFst<ArcF> fst3;
+ ConvertLattice(*fst1, &fst2);
+ ConvertLattice(fst2, &fst3);
+
+ assert(RandEquivalent(*fst1, fst3, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst1;
+ }
+
+ {
+ VectorFst<ArcF> *fst1 = RandPairFst<ArcF>();
+ VectorFst<CArcF> cfst1, cfst3;
+ ConvertLattice(*fst1, &cfst1);
+ VectorFst<CArcD> cfst2;
+ ConvertLattice(cfst1, &cfst2);
+ ConvertLattice(cfst2, &cfst3);
+ assert(RandEquivalent(cfst1, cfst3, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst1;
+ }
+
+ {
+ VectorFst<ArcF> *fst1 = RandPairFst<ArcF>();
+ VectorFst<CArcD> cfst1, cfst3;
+ ConvertLattice(*fst1, &cfst1);
+ VectorFst<CArcF> cfst2;
+ ConvertLattice(cfst1, &cfst2);
+ ConvertLattice(cfst2, &cfst3);
+ assert(RandEquivalent(cfst1, cfst3, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst1;
+ }
+
+ {
+ VectorFst<ArcD> *fst1 = RandPairFst<ArcD>();
+ VectorFst<CArcD> cfst1, cfst3;
+ ConvertLattice(*fst1, &cfst1);
+ VectorFst<CArcF> cfst2;
+ ConvertLattice(cfst1, &cfst2);
+ ConvertLattice(cfst2, &cfst3);
+ assert(RandEquivalent(cfst1, cfst3, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst1;
+ }
+
+ {
+ VectorFst<ArcD> *fst1 = RandPairFst<ArcD>();
+ VectorFst<CArcF> cfst1;
+ ConvertLattice(*fst1, &cfst1);
+ VectorFst<ArcD> fst2;
+ ConvertLattice(cfst1, &fst2);
+ assert(RandEquivalent(*fst1, fst2, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst1;
+ }
+
+ {
+ VectorFst<ArcF> *fst1 = RandPairFst<ArcF>();
+ VectorFst<CArcD> cfst1;
+ ConvertLattice(*fst1, &cfst1);
+ VectorFst<ArcF> fst2;
+ ConvertLattice(cfst1, &fst2);
+ assert(RandEquivalent(*fst1, fst2, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst1;
+ }
+
+ {
+ VectorFst<ArcD> *fst1 = RandPairFst<ArcD>();
+ VectorFst<CArcF> cfst1;
+ ConvertLattice(*fst1, &cfst1);
+ VectorFst<ArcD> fst2;
+ ConvertLattice(cfst1, &fst2);
+ assert(RandEquivalent(*fst1, fst2, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst1;
+ }
+ }
+}
+
+
+// use TestConvertPair when the Weight can be constructed from
+// a pair of floats.
+template<class Weight, class Int> void TestConvertPair(bool invert) {
+ typedef ArcTpl<Weight> Arc;
+ typedef ArcTpl<CompactLatticeWeightTpl<Weight, Int> > CompactArc;
+ for(int i = 0; i < 2; i++) {
+ VectorFst<Arc> *fst = RandPairFst<Arc>();
+ /*std::cout << "FST before converting to compact-arc is:\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, NULL, NULL, NULL, false, true);
+ fstprinter.Print(&std::cout, "standard output");
+ }*/
+ VectorFst<CompactArc> ofst;
+ ConvertLattice<Weight, Int>(*fst, &ofst, invert);
+
+ /*std::cout << "FST after converting is:\n";
+ {
+ FstPrinter<CompactArc> fstprinter(ofst, NULL, NULL, NULL, false, true);
+ fstprinter.Print(&std::cout, "standard output");
+ }*/
+ VectorFst<Arc> origfst;
+ ConvertLattice<Weight, Int>(ofst, &origfst, invert);
+ /*std::cout << "FST after back conversion is:\n";
+ {
+ FstPrinter<Arc> fstprinter(origfst, NULL, NULL, NULL, false, true);
+ fstprinter.Print(&std::cout, "standard output");
+ }*/
+
+ assert(RandEquivalent(*fst, origfst, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst;
+ }
+}
+
+
+// use TestConvertPair when the Weight can be constructed from
+// a pair of floats.
+template<class Weight, class Int> void TestScalePair(bool invert) {
+ std::vector<std::vector<double> > scale1 = DefaultLatticeScale(),
+ scale2 = DefaultLatticeScale();
+ // important that all these numbers exactly representable as floats..
+ // exact floating-point comparisons are used in LatticeWeight, and
+ // this exactness is being tested here.. this test will fail for
+ // other types of number.
+ if (kaldi::Rand() % 4 == 0) {
+ scale1[0][0] = 2.0;
+ scale2[0][0] = 0.5;
+ scale1[1][1] = 4.0;
+ scale2[1][1] = 0.25;
+ } else if (kaldi::Rand() % 3 == 0) {
+ // use that [1 0.25; 0 1] [ 1 -0.25; 0 1] is the unit matrix.
+ scale1[0][1] = 0.25;
+ scale2[0][1] = -0.25;
+ } else if (kaldi::Rand() % 2 == 0) {
+ scale1[1][0] = 0.25;
+ scale2[1][0] = -0.25;
+ }
+
+
+ typedef ArcTpl<Weight> Arc;
+ typedef ArcTpl<CompactLatticeWeightTpl<Weight, Int> > CompactArc;
+ for(int i = 0; i < 2; i++) {
+ VectorFst<Arc> *fst = RandPairFst<Arc>();
+ /*std::cout << "FST before converting to compact-arc is:\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, NULL, NULL, NULL, false, true);
+ fstprinter.Print(&std::cout, "standard output");
+ }*/
+ VectorFst<CompactArc> ofst;
+ ConvertLattice<Weight, Int>(*fst, &ofst, invert);
+ ScaleLattice(scale1, &ofst);
+ /*std::cout << "FST after converting and scaling is:\n";
+ {
+ FstPrinter<CompactArc> fstprinter(ofst, NULL, NULL, NULL, false, true);
+ fstprinter.Print(&std::cout, "standard output");
+ }*/
+ VectorFst<Arc> origfst;
+ ConvertLattice<Weight, Int>(ofst, &origfst, invert);
+ ScaleLattice(scale2, &origfst);
+ /*std::cout << "FST after back conversion and scaling is:\n";
+ {
+ FstPrinter<Arc> fstprinter(origfst, NULL, NULL, NULL, false, true);
+ fstprinter.Print(&std::cout, "standard output");
+ }*/
+ // If RandEquivalent doesn't work, it could be due to a nasty issue related to the use
+ // of exact floating-point comparisons in the Plus function of LatticeWeight.
+ if (!RandEquivalent(*fst, origfst, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/)) {
+ std::cerr << "Warn, randequivalent returned false. Checking equivalence another way.\n";
+ assert(Equal(*fst, origfst));
+ }
+ delete fst;
+ }
+}
+
+
+
+} // end namespace fst
+
+int main() {
+ using namespace fst;
+
+ typedef ::int64 int64;
+ typedef ::uint64 uint64;
+ typedef ::int32 int32;
+ typedef ::uint32 uint32;
+
+ {
+ typedef LatticeWeightTpl<float> LatticeWeight;
+ for(int i = 0; i < 2; i++) {
+ bool invert = (i % 2);
+ TestConvert<TropicalWeight, int32>(invert);
+ TestConvertPair<LatticeWeight, int32>(invert);
+ TestConvertPair<LatticeWeight, size_t>(invert);
+ TestConvertPair<LexicographicWeight<TropicalWeight, TropicalWeight>, size_t>(invert);
+ TestScalePair<LatticeWeight, int32>(invert);
+ TestScalePair<LatticeWeight, size_t>(invert);
+ TestScalePair<LexicographicWeight<TropicalWeight, TropicalWeight>, size_t>(invert);
+ }
+ }
+ {
+ typedef LatticeWeightTpl<double> LatticeWeight;
+ TestShortestPath<LatticeWeight, int32>();
+ TestConvert2<int32>();
+ for(int i = 0; i < 2; i++) {
+ bool invert = (i % 2);
+ TestConvertPair<LatticeWeight, int32>(invert);
+ TestConvertPair<LatticeWeight, size_t>(invert);
+ TestConvertPair<LexicographicWeight<TropicalWeight, TropicalWeight>, size_t>(invert);
+ TestScalePair<LatticeWeight, int32>(invert);
+ TestScalePair<LatticeWeight, size_t>(invert);
+ TestScalePair<LexicographicWeight<TropicalWeight, TropicalWeight>, size_t>(invert);
+ }
+ }
+ std::cout << "Tests succeeded\n";
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/lattice-utils.h b/runtime/onnxruntime/third_party/kaldi/fstext/lattice-utils.h
new file mode 100644
index 000000000..489fcac47
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/lattice-utils.h
@@ -0,0 +1,256 @@
+// fstext/lattice-utils.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_FSTEXT_LATTICE_UTILS_H_
+#define KALDI_FSTEXT_LATTICE_UTILS_H_
+
+#include "fst/fstlib.h"
+#include "fstext/lattice-weight.h"
+#include "fstext/factor.h"
+
+namespace fst {
+
+// The template ConvertLattice does conversions to and from
+// LatticeWeight FSTs and CompactLatticeWeight FSTs, and
+// between float and double, and to convert from LatticeWeight
+// to TropicalWeight. It's used in the I/O code for lattices,
+// and for converting lattices to standard FSTs (e.g. for creating
+// decoding graphs from lattices).
+
+
+/**
+ Convert lattice from a normal FST to a CompactLattice FST.
+ This is a bit like converting to the Gallic semiring, except
+ the semiring behaves in a different way (designed to take
+ the best path).
+ Note: the ilabels end up as the symbols on the arcs of the
+ output acceptor, and the olabels go to the strings. To make
+ it the other way around (useful for the speech-recognition
+ application), set invert=true [the default].
+*/
+template<class Weight, class Int>
+void ConvertLattice(
+ const ExpandedFst<ArcTpl<Weight> > &ifst,
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, Int> > > *ofst,
+ bool invert = true);
+
+/**
+ Convert lattice CompactLattice format to Lattice. This is a bit
+ like converting from the Gallic semiring. As for any CompactLattice, "ifst"
+ must be an acceptor (i.e., ilabels and olabels should be identical). If
+ invert=false, the labels on "ifst" become the ilabels on "ofst" and the
+ strings in the weights of "ifst" becomes the olabels. If invert=true
+ [default], this is reversed (useful for speech recognition lattices; our
+ standard non-compact format has the words on the output side to match HCLG).
+ */
+template<class Weight, class Int>
+void ConvertLattice(
+ const ExpandedFst<ArcTpl<CompactLatticeWeightTpl<Weight, Int> > > &ifst,
+ MutableFst<ArcTpl<Weight> > *ofst,
+ bool invert = true);
+
+
+/**
+ Convert between CompactLattices and Lattices of different floating point types...
+ this works between any pair of weight types for which ConvertLatticeWeight
+ is defined (c.f. lattice-weight.h), and also includes conversion from
+ LatticeWeight to TropicalWeight.
+ */
+template<class WeightIn, class WeightOut>
+void ConvertLattice(
+ const ExpandedFst<ArcTpl<WeightIn> > &ifst,
+ MutableFst<ArcTpl<WeightOut> > *ofst);
+
+
+// Now define some ConvertLattice functions that require two phases of conversion (don't
+// bother coding these separately as they will be used rarely.
+
+// Lattice with float to CompactLattice with double.
+template<class Int>
+void ConvertLattice(const ExpandedFst<ArcTpl<LatticeWeightTpl<float> > > &ifst,
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<LatticeWeightTpl<double>, Int> > > *ofst) {
+ VectorFst<ArcTpl<CompactLatticeWeightTpl<LatticeWeightTpl<float>, Int> > > fst;
+ ConvertLattice(ifst, &fst);
+ ConvertLattice(fst, ofst);
+}
+
+// Lattice with double to CompactLattice with float.
+template<class Int>
+void ConvertLattice(const ExpandedFst<ArcTpl<LatticeWeightTpl<double> > > &ifst,
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<LatticeWeightTpl<float>, Int> > > *ofst) {
+ VectorFst<ArcTpl<CompactLatticeWeightTpl<LatticeWeightTpl<double>, Int> > > fst;
+ ConvertLattice(ifst, &fst);
+ ConvertLattice(fst, ofst);
+}
+
+/// Converts CompactLattice with double to Lattice with float.
+template<class Int>
+void ConvertLattice(const ExpandedFst<ArcTpl<CompactLatticeWeightTpl<LatticeWeightTpl<double>, Int> > > &ifst,
+ MutableFst<ArcTpl<LatticeWeightTpl<float> > > *ofst) {
+ VectorFst<ArcTpl<CompactLatticeWeightTpl<LatticeWeightTpl<float>, Int> > > fst;
+ ConvertLattice(ifst, &fst);
+ ConvertLattice(fst, ofst);
+}
+
+/// Converts CompactLattice with float to Lattice with double.
+template<class Int>
+void ConvertLattice(const ExpandedFst<ArcTpl<CompactLatticeWeightTpl<LatticeWeightTpl<float>, Int> > > &ifst,
+ MutableFst<ArcTpl<LatticeWeightTpl<double> > > *ofst) {
+ VectorFst<ArcTpl<CompactLatticeWeightTpl<LatticeWeightTpl<double>, Int> > > fst;
+ ConvertLattice(ifst, &fst);
+ ConvertLattice(fst, ofst);
+}
+
+/// Converts TropicalWeight to LatticeWeight (puts all the weight on
+/// the first float in the lattice's pair).
+template <class Real>
+void ConvertFstToLattice(
+ const ExpandedFst<ArcTpl<TropicalWeight> > &ifst,
+ MutableFst<ArcTpl<LatticeWeightTpl<Real> > > *ofst);
+
+
+/** Returns a default 2x2 matrix scaling factor for LatticeWeight */
+inline std::vector<std::vector<double> > DefaultLatticeScale() {
+ std::vector<std::vector<double> > ans(2);
+ ans[0].resize(2, 0.0);
+ ans[1].resize(2, 0.0);
+ ans[0][0] = ans[1][1] = 1.0;
+ return ans;
+}
+
+inline std::vector<std::vector<double> > AcousticLatticeScale(double acwt) {
+ std::vector<std::vector<double> > ans(2);
+ ans[0].resize(2, 0.0);
+ ans[1].resize(2, 0.0);
+ ans[0][0] = 1.0;
+ ans[1][1] = acwt;
+ return ans;
+}
+
+inline std::vector<std::vector<double> > GraphLatticeScale(double lmwt) {
+ std::vector<std::vector<double> > ans(2);
+ ans[0].resize(2, 0.0);
+ ans[1].resize(2, 0.0);
+ ans[0][0] = lmwt;
+ ans[1][1] = 1.0;
+ return ans;
+}
+
+inline std::vector<std::vector<double> > LatticeScale(double lmwt, double acwt) {
+ std::vector<std::vector<double> > ans(2);
+ ans[0].resize(2, 0.0);
+ ans[1].resize(2, 0.0);
+ ans[0][0] = lmwt;
+ ans[1][1] = acwt;
+ return ans;
+}
+
+
+/** Scales the pairs of weights in LatticeWeight or CompactLatticeWeight by
+ viewing the pair (a, b) as a 2-vector and pre-multiplying by the 2x2 matrix
+ in "scale". E.g. typically scale would equal
+ [ 1 0;
+ 0 acwt ]
+ if we want to scale the acoustics by "acwt".
+ */
+template<class Weight, class ScaleFloat>
+void ScaleLattice(
+ const std::vector<std::vector<ScaleFloat> > &scale,
+ MutableFst<ArcTpl<Weight> > *fst);
+
+/// Removes state-level alignments (the strings that are
+/// part of the weights).
+template<class Weight, class Int>
+void RemoveAlignmentsFromCompactLattice(
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, Int> > > *fst);
+
+/// Returns true if lattice has alignments, i.e. it has
+/// any nonempty strings inside its weights.
+template<class Weight, class Int>
+bool CompactLatticeHasAlignment(
+ const ExpandedFst<ArcTpl<CompactLatticeWeightTpl<Weight, Int> > > &fst);
+
+
+/// Class StdToLatticeMapper maps a normal arc (StdArc)
+/// to a LatticeArc by putting the StdArc weight as the first
+/// element of the LatticeWeight. Useful when doing LM
+/// rescoring.
+template<class Real>
+class StdToLatticeMapper {
+ typedef LatticeWeightTpl<Real> LatticeWeight;
+ typedef ArcTpl<LatticeWeight> LatticeArc;
+ public:
+ LatticeArc operator()(const StdArc &arc) {
+ // Note: we have to check whether the arc's weight is zero below,
+ // and if so return (infinity, infinity) and not (infinity, zero),
+ // because (infinity, zero) is not a valid LatticeWeight, which should
+ // either be both finite, or both infinite (i.e. Zero()).
+ return LatticeArc(arc.ilabel, arc.olabel,
+ LatticeWeight(arc.weight.Value(),
+ arc.weight == StdArc::Weight::Zero() ?
+ arc.weight.Value() : 0.0),
+ arc.nextstate);
+ }
+ MapFinalAction FinalAction() { return MAP_NO_SUPERFINAL; }
+
+ MapSymbolsAction InputSymbolsAction() { return MAP_COPY_SYMBOLS; }
+
+ MapSymbolsAction OutputSymbolsAction() { return MAP_COPY_SYMBOLS; }
+
+ // I believe all properties are preserved.
+ uint64 Properties(uint64 props) { return props; }
+};
+
+
+/// Class LatticeToStdMapper maps a LatticeArc to a normal arc (StdArc)
+/// by adding the elements of the LatticeArc weight.
+
+template<class Real>
+class LatticeToStdMapper {
+ typedef LatticeWeightTpl<Real> LatticeWeight;
+ typedef ArcTpl<LatticeWeight> LatticeArc;
+ public:
+ StdArc operator()(const LatticeArc &arc) {
+ return StdArc(arc.ilabel, arc.olabel,
+ StdArc::Weight(arc.weight.Value1() + arc.weight.Value2()),
+ arc.nextstate);
+ }
+ MapFinalAction FinalAction() { return MAP_NO_SUPERFINAL; }
+
+ MapSymbolsAction InputSymbolsAction() { return MAP_COPY_SYMBOLS; }
+
+ MapSymbolsAction OutputSymbolsAction() { return MAP_COPY_SYMBOLS; }
+
+ // I believe all properties are preserved.
+ uint64 Properties(uint64 props) { return props; }
+};
+
+
+template<class Weight, class Int>
+void PruneCompactLattice(
+ Weight beam,
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, Int> > > *fst);
+
+
+} // end namespace fst
+
+#include "fstext/lattice-utils-inl.h"
+
+#endif // KALDI_FSTEXT_LATTICE_UTILS_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/lattice-weight-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/lattice-weight-test.cc
new file mode 100644
index 000000000..55229675f
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/lattice-weight-test.cc
@@ -0,0 +1,197 @@
+// fstext/lattice-weight-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#include "base/kaldi-math.h"
+#include "fstext/lattice-weight.h"
+
+namespace fst {
+using std::vector;
+using std::cout;
+// these typedefs are the same as in ../lat/kaldi-lattice.h, but
+// just used here for testing (doesn't matter if they get out of
+// sync).
+typedef float BaseFloat;
+
+typedef LatticeWeightTpl<BaseFloat> LatticeWeight;
+
+typedef CompactLatticeWeightTpl<LatticeWeight, int32> CompactLatticeWeight;
+
+typedef CompactLatticeWeightCommonDivisorTpl<LatticeWeight, int32>
+ CompactLatticeWeightCommonDivisor;
+
+
+LatticeWeight RandomLatticeWeight() {
+ int tmp = kaldi::Rand() % 4;
+ if (tmp == 0) {
+ return LatticeWeight::Zero();
+ } else if (tmp == 1) {
+ return LatticeWeight( 1, 2); // sometimes return special values..
+ } else if (tmp == 2) {
+ return LatticeWeight( 2, 1); // this tests more thoroughly certain properties...
+ } else {
+ return LatticeWeight( 100 * kaldi::RandGauss(), 100 * kaldi::RandGauss());
+ }
+}
+
+CompactLatticeWeight RandomCompactLatticeWeight() {
+ LatticeWeight w = RandomLatticeWeight();
+ if (w == LatticeWeight::Zero()) {
+ return CompactLatticeWeight(w, vector<int32>());
+ } else {
+ int32 len = kaldi::Rand() % 4;
+ vector<int32> str;
+ for(int32 i = 0; i < len; i++)
+ str.push_back(kaldi::Rand() % 10 + 1);
+ return CompactLatticeWeight(w, str);
+ }
+}
+
+void LatticeWeightTest() {
+ for(int32 i = 0; i < 100; i++) {
+ LatticeWeight l1 = RandomLatticeWeight(), l2 = RandomLatticeWeight();
+ LatticeWeight l3 = Plus(l1, l2);
+ LatticeWeight l4 = Times(l1, l2);
+ BaseFloat f1 = l1.Value1() + l1.Value2(), f2 = l2.Value1() + l2.Value2(), f3 = l3.Value1() + l3.Value2(),
+ f4 = l4.Value1() + l4.Value2();
+ kaldi::AssertEqual(std::min(f1, f2), f3);
+ kaldi::AssertEqual(f1 + f2, f4);
+
+ KALDI_ASSERT(Plus(l3, l3) == l3);
+ KALDI_ASSERT(Plus(l1, l2) == Plus(l2, l1)); // commutativity of plus
+ KALDI_ASSERT(Times(l1, l2) == Times(l2, l1)); // commutativity of Times (true for this semiring, not always)
+ KALDI_ASSERT(Plus(l3, LatticeWeight::Zero()) == l3); // x + 0 = x
+ KALDI_ASSERT(Times(l3, LatticeWeight::One()) == l3); // x * 1 = x
+ KALDI_ASSERT(Times(l3, LatticeWeight::Zero()) == LatticeWeight::Zero()); // x * 0 = 0
+
+ KALDI_ASSERT(l3.Reverse().Reverse() == l3);
+
+ NaturalLess<LatticeWeight> nl;
+ bool a = nl(l1, l2);
+ bool b = (Plus(l1, l2) == l1 && l1 != l2);
+ KALDI_ASSERT(a == b);
+
+ KALDI_ASSERT(Compare(l1, Plus(l1, l2)) != 1); // so do not have l1 > l1 + l2
+ LatticeWeight l5 = RandomLatticeWeight(), l6 = RandomLatticeWeight();
+ {
+ LatticeWeight wa = Times(Plus(l1, l2), Plus(l5, l6)),
+ wb = Plus(Times(l1, l5), Plus(Times(l1, l6),
+ Plus(Times(l2, l5), Times(l2, l6))));
+ if (!ApproxEqual(wa, wb)) {
+ std::cout << "l1 = " << l1 << ", l2 = " << l2
+ << ", l5 = " << l5 << ", l6 = " << l6 << "\n";
+ std::cout << "ERROR: " << wa << " != " << wb << "\n";
+ }
+ // KALDI_ASSERT(Times(Plus(l1, l2), Plus(l5, l6))
+ // == Plus(Times(l1, l5), Plus(Times(l1,l6),
+ // Plus(Times(l2, l5), Times(l2, l6))))); // * distributes over +
+ }
+ KALDI_ASSERT(l1.Member() && l2.Member() && l3.Member() && l4.Member()
+ && l5.Member() && l6.Member());
+ if (l2 != LatticeWeight::Zero())
+ KALDI_ASSERT(ApproxEqual(Divide(Times(l1, l2), l2), l1)); // (a*b) / b = a if b != 0
+ KALDI_ASSERT(ApproxEqual(l1, l1.Quantize()));
+
+ std::ostringstream s1;
+ s1 << l1;
+ std::istringstream s2(s1.str());
+ s2 >> l2;
+ KALDI_ASSERT(ApproxEqual(l1, l2, 0.001));
+ std::cout << s1.str() << '\n';
+ {
+ std::ostringstream s1b;
+ l1.Write(s1b);
+ std::istringstream s2b(s1b.str());
+ l3.Read(s2b);
+ KALDI_ASSERT(l1 == l3);
+ }
+ }
+}
+
+
+void CompactLatticeWeightTest() {
+ for(int32 i = 0; i < 100; i++) {
+ CompactLatticeWeight l1 = RandomCompactLatticeWeight(), l2 = RandomCompactLatticeWeight();
+ CompactLatticeWeight l3 = Plus(l1, l2);
+ CompactLatticeWeight l4 = Times(l1, l2);
+
+ KALDI_ASSERT(Plus(l3, l3) == l3);
+ KALDI_ASSERT(Plus(l1, l2) == Plus(l2, l1)); // commutativity of plus
+ KALDI_ASSERT(Plus(l3, CompactLatticeWeight::Zero()) == l3); // x + 0 = x
+ KALDI_ASSERT(Times(l3, CompactLatticeWeight::One()) == l3); // x * 1 = x
+ KALDI_ASSERT(Times(l3, CompactLatticeWeight::Zero()) == CompactLatticeWeight::Zero()); // x * 0 = 0
+ NaturalLess<CompactLatticeWeight> nl;
+ bool a = nl(l1, l2);
+ bool b = (Plus(l1, l2) == l1 && l1 != l2);
+ KALDI_ASSERT(a == b);
+
+ KALDI_ASSERT(Compare(l1, Plus(l1, l2)) != 1); // so do not have l1 > l1 + l2
+ CompactLatticeWeight l5 = RandomCompactLatticeWeight(), l6 = RandomCompactLatticeWeight();
+ KALDI_ASSERT(Times(Plus(l1, l2), Plus(l5, l6)) ==
+ Plus(Times(l1, l5), Plus(Times(l1, l6),
+ Plus(Times(l2, l5), Times(l2, l6))))); // * distributes over +
+ KALDI_ASSERT(l1.Member() && l2.Member() && l3.Member() && l4.Member()
+ && l5.Member() && l6.Member());
+ if (l2 != CompactLatticeWeight::Zero()) {
+ KALDI_ASSERT(ApproxEqual(Divide(Times(l1, l2), l2, DIVIDE_RIGHT), l1)); // (a*b) / b = a if b != 0
+ KALDI_ASSERT(ApproxEqual(Divide(Times(l2, l1), l2, DIVIDE_LEFT), l1)); // (a*b) / b = a if b != 0
+ }
+ KALDI_ASSERT(ApproxEqual(l1, l1.Quantize()));
+
+ std::ostringstream s1;
+ s1 << l1;
+ std::istringstream s2(s1.str());
+ s2 >> l2;
+ KALDI_ASSERT(ApproxEqual(l1, l2));
+ std::cout << s1.str() << '\n';
+
+ {
+ std::ostringstream s1b;
+ l1.Write(s1b);
+ std::istringstream s2b(s1b.str());
+ l3.Read(s2b);
+ KALDI_ASSERT(l1 == l3);
+ }
+
+ CompactLatticeWeightCommonDivisor divisor;
+ std::cout << "l5 = " << l5 << '\n';
+ std::cout << "l6 = " << l6 << '\n';
+ l1 = divisor(l5, l6);
+ std::cout << "div = " << l1 << '\n';
+ if (l1 != CompactLatticeWeight::Zero()) {
+ l2 = Divide(l5, l1, DIVIDE_LEFT);
+ l3 = Divide(l6, l1, DIVIDE_LEFT);
+ std::cout << "l2 = " << l2 << '\n';
+ std::cout << "l3 = " << l3 << '\n';
+ l4 = divisor(l2, l3); // make sure l2 is now one.
+ std::cout << "l4 = " << l4 << '\n';
+ KALDI_ASSERT(ApproxEqual(l4, CompactLatticeWeight::One()));
+ } else {
+ KALDI_ASSERT(l5 == CompactLatticeWeight::Zero()
+ && l6 == CompactLatticeWeight::Zero());
+ }
+ }
+}
+
+
+}
+
+int main() {
+ fst::LatticeWeightTest();
+ fst::CompactLatticeWeightTest();
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/lattice-weight.h b/runtime/onnxruntime/third_party/kaldi/fstext/lattice-weight.h
new file mode 100644
index 000000000..6e7737a19
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/lattice-weight.h
@@ -0,0 +1,862 @@
+// fstext/lattice-weight.h
+// Copyright 2009-2012 Microsoft Corporation
+// Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_FSTEXT_LATTICE_WEIGHT_H_
+#define KALDI_FSTEXT_LATTICE_WEIGHT_H_
+
+#include "fst/fstlib.h"
+#include "base/kaldi-common.h"
+
+namespace fst {
+
+// Declare weight type for lattice... will import to namespace kaldi. has two
+// members, value1_ and value2_, of type BaseFloat (normally equals float). It
+// is basically the same as the tropical semiring on value1_+value2_, except it
+// keeps track of a and b separately. More precisely, it is equivalent to the
+// lexicographic semiring on (value1_+value2_), (value1_-value2_)
+
+
+template<class FloatType>
+class LatticeWeightTpl;
+
+template <class FloatType>
+inline std::ostream &operator <<(std::ostream &strm, const LatticeWeightTpl<FloatType> &w);
+
+template <class FloatType>
+inline std::istream &operator >>(std::istream &strm, LatticeWeightTpl<FloatType> &w);
+
+
+template<class FloatType>
+class LatticeWeightTpl {
+ public:
+ typedef FloatType T; // normally float.
+ typedef LatticeWeightTpl ReverseWeight;
+
+ inline T Value1() const { return value1_; }
+
+ inline T Value2() const { return value2_; }
+
+ inline void SetValue1(T f) { value1_ = f; }
+
+ inline void SetValue2(T f) { value2_ = f; }
+
+ LatticeWeightTpl(): value1_{}, value2_{} { }
+
+ LatticeWeightTpl(T a, T b): value1_(a), value2_(b) {}
+
+ LatticeWeightTpl(const LatticeWeightTpl &other): value1_(other.value1_), value2_(other.value2_) { }
+
+ LatticeWeightTpl &operator=(const LatticeWeightTpl &w) {
+ value1_ = w.value1_;
+ value2_ = w.value2_;
+ return *this;
+ }
+
+ LatticeWeightTpl<FloatType> Reverse() const {
+ return *this;
+ }
+
+ static const LatticeWeightTpl Zero() {
+ return LatticeWeightTpl(std::numeric_limits<T>::infinity(),
+ std::numeric_limits<T>::infinity());
+ }
+
+ static const LatticeWeightTpl One() {
+ return LatticeWeightTpl(0.0, 0.0);
+ }
+
+ static const std::string &Type() {
+ static const std::string type = (sizeof(T) == 4 ? "lattice4" : "lattice8") ;
+ return type;
+ }
+
+ static const LatticeWeightTpl NoWeight() {
+ return LatticeWeightTpl(std::numeric_limits<FloatType>::quiet_NaN(),
+ std::numeric_limits<FloatType>::quiet_NaN());
+ }
+
+ bool Member() const {
+ // value1_ == value1_ tests for NaN.
+ // also test for no -inf, and either both or neither
+ // must be +inf, and
+ if (value1_ != value1_ || value2_ != value2_) return false; // NaN
+ if (value1_ == -std::numeric_limits<T>::infinity() ||
+ value2_ == -std::numeric_limits<T>::infinity()) return false; // -infty not allowed
+ if (value1_ == std::numeric_limits<T>::infinity() ||
+ value2_ == std::numeric_limits<T>::infinity()) {
+ if (value1_ != std::numeric_limits<T>::infinity() ||
+ value2_ != std::numeric_limits<T>::infinity()) return false; // both must be +infty;
+ // this is necessary so that the semiring has only one zero.
+ }
+ return true;
+ }
+
+ LatticeWeightTpl Quantize(float delta = kDelta) const {
+ if (value1_ + value2_ == -std::numeric_limits<T>::infinity()) {
+ return LatticeWeightTpl(-std::numeric_limits<T>::infinity(), -std::numeric_limits<T>::infinity());
+ } else if (value1_ + value2_ == std::numeric_limits<T>::infinity()) {
+ return LatticeWeightTpl(std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity());
+ } else if (value1_ + value2_ != value1_ + value2_) { // NaN
+ return LatticeWeightTpl(value1_ + value2_, value1_ + value2_);
+ } else {
+ return LatticeWeightTpl(floor(value1_/delta + 0.5F)*delta, floor(value2_/delta + 0.5F) * delta);
+ }
+ }
+ static constexpr uint64 Properties() {
+ return kLeftSemiring | kRightSemiring | kCommutative |
+ kPath | kIdempotent;
+ }
+
+ // This is used in OpenFst for binary I/O. This is OpenFst-style,
+ // not Kaldi-style, I/O.
+ std::istream &Read(std::istream &strm) {
+ // Always read/write as float, even if T is double,
+ // so we can use OpenFst-style read/write and still maintain
+ // compatibility when compiling with different FloatTypes
+ ReadType(strm, &value1_);
+ ReadType(strm, &value2_);
+ return strm;
+ }
+
+
+ // This is used in OpenFst for binary I/O. This is OpenFst-style,
+ // not Kaldi-style, I/O.
+ std::ostream &Write(std::ostream &strm) const {
+ WriteType(strm, value1_);
+ WriteType(strm, value2_);
+ return strm;
+ }
+
+ size_t Hash() const {
+ size_t ans;
+ union {
+ T f;
+ size_t s;
+ } u;
+ u.s = 0;
+ u.f = value1_;
+ ans = u.s;
+ u.f = value2_;
+ ans += u.s;
+ return ans;
+ }
+
+ protected:
+ inline static void WriteFloatType(std::ostream &strm, const T &f) {
+ if (f == std::numeric_limits<T>::infinity())
+ strm << "Infinity";
+ else if (f == -std::numeric_limits<T>::infinity())
+ strm << "-Infinity";
+ else if (f != f)
+ strm << "BadNumber";
+ else
+ strm << f;
+ }
+
+ // Internal helper function, used in ReadNoParen.
+ inline static void ReadFloatType(std::istream &strm, T &f) {
+ std::string s;
+ strm >> s;
+ if (s == "Infinity") {
+ f = std::numeric_limits<T>::infinity();
+ } else if (s == "-Infinity") {
+ f = -std::numeric_limits<T>::infinity();
+ } else if (s == "BadNumber") {
+ f = std::numeric_limits<T>::quiet_NaN();
+ } else {
+ char *p;
+ f = strtod(s.c_str(), &p);
+ if (p < s.c_str() + s.size())
+ strm.clear(std::ios::badbit);
+ }
+ }
+
+ // Reads LatticeWeight when there are no parentheses around pair terms...
+ // currently the only form supported.
+ inline std::istream &ReadNoParen(
+ std::istream &strm, char separator) {
+ int c;
+ do {
+ c = strm.get();
+ } while (isspace(c));
+
+ std::string s1;
+ while (c != separator) {
+ if (c == EOF) {
+ strm.clear(std::ios::badbit);
+ return strm;
+ }
+ s1 += c;
+ c = strm.get();
+ }
+ std::istringstream strm1(s1);
+ ReadFloatType(strm1, value1_); // ReadFloatType is class member function
+ // read second element
+ ReadFloatType(strm, value2_);
+ return strm;
+ }
+
+ friend std::istream &operator>> <FloatType>(std::istream&, LatticeWeightTpl<FloatType>&);
+ friend std::ostream &operator<< <FloatType>(std::ostream&, const LatticeWeightTpl<FloatType>&);
+
+ private:
+ T value1_;
+ T value2_;
+
+
+};
+
+
+/* ScaleTupleWeight is a function defined for LatticeWeightTpl and
+ CompactLatticeWeightTpl that mutliplies the pair (value1_, value2_) by a 2x2
+ matrix. Used, for example, in applying acoustic scaling.
+ */
+template<class FloatType, class ScaleFloatType>
+inline LatticeWeightTpl<FloatType> ScaleTupleWeight(
+ const LatticeWeightTpl<FloatType> &w,
+ const std::vector<std::vector<ScaleFloatType> > &scale) {
+ // Without the next special case we'd get NaNs from infinity * 0
+ if (w.Value1() == std::numeric_limits<FloatType>::infinity())
+ return LatticeWeightTpl<FloatType>::Zero();
+ return LatticeWeightTpl<FloatType>(scale[0][0] * w.Value1() + scale[0][1] * w.Value2(),
+ scale[1][0] * w.Value1() + scale[1][1] * w.Value2());
+}
+
+/* For testing purposes and in case it's ever useful, we define a similar
+ function to apply to LexicographicWeight and the like, templated on
+ TropicalWeight<float> etc.; we use PairWeight which is the base class of
+ LexicographicWeight.
+*/
+template<class FloatType, class ScaleFloatType>
+inline PairWeight<TropicalWeightTpl<FloatType>,
+ TropicalWeightTpl<FloatType> > ScaleTupleWeight(
+ const PairWeight<TropicalWeightTpl<FloatType>,
+ TropicalWeightTpl<FloatType> > &w,
+ const std::vector<std::vector<ScaleFloatType> > &scale) {
+ typedef TropicalWeightTpl<FloatType> BaseType;
+ typedef PairWeight<BaseType, BaseType> PairType;
+ const BaseType zero = BaseType::Zero();
+ // Without the next special case we'd get NaNs from infinity * 0
+ if (w.Value1() == zero || w.Value2() == zero)
+ return PairType(zero, zero);
+ FloatType f1 = w.Value1().Value(), f2 = w.Value2().Value();
+ return PairType(BaseType(scale[0][0] * f1 + scale[0][1] * f2),
+ BaseType(scale[1][0] * f1 + scale[1][1] * f2));
+}
+
+
+
+template<class FloatType>
+inline bool operator==(const LatticeWeightTpl<FloatType> &wa,
+ const LatticeWeightTpl<FloatType> &wb) {
+ // Volatile qualifier thwarts over-aggressive compiler optimizations
+ // that lead to problems esp. with NaturalLess().
+ volatile FloatType va1 = wa.Value1(), va2 = wa.Value2(),
+ vb1 = wb.Value1(), vb2 = wb.Value2();
+ return (va1 == vb1 && va2 == vb2);
+}
+
+template<class FloatType>
+inline bool operator!=(const LatticeWeightTpl<FloatType> &wa,
+ const LatticeWeightTpl<FloatType> &wb) {
+ // Volatile qualifier thwarts over-aggressive compiler optimizations
+ // that lead to problems esp. with NaturalLess().
+ volatile FloatType va1 = wa.Value1(), va2 = wa.Value2(),
+ vb1 = wb.Value1(), vb2 = wb.Value2();
+ return (va1 != vb1 || va2 != vb2);
+}
+
+
+// We define a Compare function LatticeWeightTpl even though it's
+// not required by the semiring standard-- it's just more efficient
+// to do it this way rather than using the NaturalLess template.
+
+/// Compare returns -1 if w1 < w2, +1 if w1 > w2, and 0 if w1 == w2.
+
+template<class FloatType>
+inline int Compare (const LatticeWeightTpl<FloatType> &w1,
+ const LatticeWeightTpl<FloatType> &w2) {
+ FloatType f1 = w1.Value1() + w1.Value2(),
+ f2 = w2.Value1() + w2.Value2();
+ if (f1 < f2) { return 1; } // having smaller cost means you're larger
+ // in the semiring [higher probability]
+ else if (f1 > f2) { return -1; }
+ // mathematically we should be comparing (w1.value1_-w1.value2_ < w2.value1_-w2.value2_)
+ // in the next line, but add w1.value1_+w1.value2_ = w2.value1_+w2.value2_ to both sides and
+ // divide by two, and we get the simpler equivalent form w1.value1_ < w2.value1_.
+ else if (w1.Value1() < w2.Value1()) { return 1; }
+ else if (w1.Value1() > w2.Value1()) { return -1; }
+ else { return 0; }
+}
+
+
+template<class FloatType>
+inline LatticeWeightTpl<FloatType> Plus(const LatticeWeightTpl<FloatType> &w1,
+ const LatticeWeightTpl<FloatType> &w2) {
+ return (Compare(w1, w2) >= 0 ? w1 : w2);
+}
+
+
+// For efficiency, override the NaturalLess template class.
+template<class FloatType>
+class NaturalLess<LatticeWeightTpl<FloatType> > {
+ public:
+ typedef LatticeWeightTpl<FloatType> Weight;
+
+ NaturalLess() {}
+
+ bool operator()(const Weight &w1, const Weight &w2) const {
+ // NaturalLess is a negative order (opposite to normal ordering).
+ // This operator () corresponds to "<" in the negative order, which
+ // corresponds to the ">" in the normal order.
+ return (Compare(w1, w2) == 1);
+ }
+};
+template<>
+class NaturalLess<LatticeWeightTpl<float> > {
+ public:
+ typedef LatticeWeightTpl<float> Weight;
+
+ NaturalLess() {}
+
+ bool operator()(const Weight &w1, const Weight &w2) const {
+ // NaturalLess is a negative order (opposite to normal ordering).
+ // This operator () corresponds to "<" in the negative order, which
+ // corresponds to the ">" in the normal order.
+ return (Compare(w1, w2) == 1);
+ }
+};
+template<>
+class NaturalLess<LatticeWeightTpl<double> > {
+ public:
+ typedef LatticeWeightTpl<double> Weight;
+
+ NaturalLess() {}
+
+ bool operator()(const Weight &w1, const Weight &w2) const {
+ // NaturalLess is a negative order (opposite to normal ordering).
+ // This operator () corresponds to "<" in the negative order, which
+ // corresponds to the ">" in the normal order.
+ return (Compare(w1, w2) == 1);
+ }
+};
+
+template<class FloatType>
+inline LatticeWeightTpl<FloatType> Times(const LatticeWeightTpl<FloatType> &w1,
+ const LatticeWeightTpl<FloatType> &w2) {
+ return LatticeWeightTpl<FloatType>(w1.Value1()+w2.Value1(), w1.Value2()+w2.Value2());
+}
+
+// divide w1 by w2 (on left/right/any doesn't matter as
+// commutative).
+template<class FloatType>
+inline LatticeWeightTpl<FloatType> Divide(const LatticeWeightTpl<FloatType> &w1,
+ const LatticeWeightTpl<FloatType> &w2,
+ DivideType typ = DIVIDE_ANY) {
+ typedef FloatType T;
+ T a = w1.Value1() - w2.Value1(), b = w1.Value2() - w2.Value2();
+ if (a != a || b != b || a == -std::numeric_limits<T>::infinity()
+ || b == -std::numeric_limits<T>::infinity()) {
+ KALDI_WARN << "LatticeWeightTpl::Divide, NaN or invalid number produced. "
+ << "[dividing by zero?] Returning zero";
+ return LatticeWeightTpl<T>::Zero();
+ }
+ if (a == std::numeric_limits<T>::infinity() ||
+ b == std::numeric_limits<T>::infinity())
+ return LatticeWeightTpl<T>::Zero(); // not a valid number if only one is infinite.
+ return LatticeWeightTpl<T>(a, b);
+}
+
+
+template<class FloatType>
+inline bool ApproxEqual(const LatticeWeightTpl<FloatType> &w1,
+ const LatticeWeightTpl<FloatType> &w2,
+ float delta = kDelta) {
+ if (w1.Value1() == w2.Value1() && w1.Value2() == w2.Value2()) return true; // handles Zero().
+ return (fabs((w1.Value1() + w1.Value2()) - (w2.Value1() + w2.Value2())) <= delta);
+}
+
+template <class FloatType>
+inline std::ostream &operator <<(std::ostream &strm, const LatticeWeightTpl<FloatType> &w) {
+ LatticeWeightTpl<FloatType>::WriteFloatType(strm, w.Value1());
+ CHECK(FLAGS_fst_weight_separator.size() == 1);
+ strm << FLAGS_fst_weight_separator[0]; // comma by default;
+ // may or may not be settable from Kaldi programs.
+ LatticeWeightTpl<FloatType>::WriteFloatType(strm, w.Value2());
+ return strm;
+}
+
+template <class FloatType>
+inline std::istream &operator >>(std::istream &strm, LatticeWeightTpl<FloatType> &w1) {
+ CHECK(FLAGS_fst_weight_separator.size() == 1);
+ // separator defaults to ','
+ return w1.ReadNoParen(strm, FLAGS_fst_weight_separator[0]);
+}
+
+
+
+// CompactLattice will be an acceptor (accepting the words/output-symbols),
+// with the weights and input-symbol-seqs on the arcs.
+// There must be a total order on W. We assume for the sake of efficiency
+// that there is a function
+// Compare(W w1, W w2) that returns -1 if w1 < w2, +1 if w1 > w2, and
+// zero if w1 == w2, and Plus for type W returns (Compare(w1,w2) >= 0 ? w1 : w2).
+
+template<class WeightType, class IntType>
+class CompactLatticeWeightTpl {
+ public:
+ typedef WeightType W;
+
+ typedef CompactLatticeWeightTpl<WeightType, IntType> ReverseWeight;
+
+ // Plus is like LexicographicWeight on the pair (weight_, string_), but where we
+ // use standard lexicographic order on string_ [this is not the same as
+ // NaturalLess on the StringWeight equivalent, which does not define a
+ // total order].
+ // Times, Divide obvious... (support both left & right division..)
+ // CommonDivisor would need to be coded separately.
+
+ CompactLatticeWeightTpl() { }
+
+ CompactLatticeWeightTpl(const WeightType &w, const std::vector<IntType> &s):
+ weight_(w), string_(s) { }
+
+ CompactLatticeWeightTpl(const CompactLatticeWeightTpl &compactLatticeWeightTpl) = default;
+
+ CompactLatticeWeightTpl &operator=(const CompactLatticeWeightTpl &w) = default;
+
+ const W &Weight() const { return weight_; }
+
+ const std::vector<IntType> &String() const { return string_; }
+
+ void SetWeight(const W &w) { weight_ = w; }
+
+ void SetString(const std::vector<IntType> &s) { string_ = s; }
+
+ static const CompactLatticeWeightTpl<WeightType, IntType> Zero() {
+ return CompactLatticeWeightTpl<WeightType, IntType>(
+ WeightType::Zero(), std::vector<IntType>());
+ }
+
+ static const CompactLatticeWeightTpl<WeightType, IntType> One() {
+ return CompactLatticeWeightTpl<WeightType, IntType>(
+ WeightType::One(), std::vector<IntType>());
+ }
+
+ inline static std::string GetIntSizeString() {
+ char buf[2];
+ buf[0] = '0' + sizeof(IntType);
+ buf[1] = '\0';
+ return buf;
+ }
+ static const std::string &Type() {
+ static const std::string type = "compact" + WeightType::Type()
+ + GetIntSizeString();
+ return type;
+ }
+
+ static const CompactLatticeWeightTpl<WeightType, IntType> NoWeight() {
+ return CompactLatticeWeightTpl<WeightType, IntType>(
+ WeightType::NoWeight(), std::vector<IntType>());
+ }
+
+
+ CompactLatticeWeightTpl<WeightType, IntType> Reverse() const {
+ size_t s = string_.size();
+ std::vector<IntType> v(s);
+ for(size_t i = 0; i < s; i++)
+ v[i] = string_[s-i-1];
+ return CompactLatticeWeightTpl<WeightType, IntType>(weight_, v);
+ }
+
+ bool Member() const {
+ // a semiring has only one zero, this is the important property
+ // we're trying to maintain here. So force string_ to be empty if
+ // w_ == zero.
+ if (!weight_.Member()) return false;
+ if (weight_ == WeightType::Zero())
+ return string_.empty();
+ else
+ return true;
+ }
+
+ CompactLatticeWeightTpl Quantize(float delta = kDelta) const {
+ return CompactLatticeWeightTpl(weight_.Quantize(delta), string_);
+ }
+
+ static constexpr uint64 Properties() {
+ return kLeftSemiring | kRightSemiring | kPath | kIdempotent;
+ }
+
+ // This is used in OpenFst for binary I/O. This is OpenFst-style,
+ // not Kaldi-style, I/O.
+ std::istream &Read(std::istream &strm) {
+ weight_.Read(strm);
+ if (strm.fail()){ return strm; }
+ int32 sz;
+ ReadType(strm, &sz);
+ if (strm.fail()){ return strm; }
+ if (sz < 0) {
+ KALDI_WARN << "Negative string size! Read failure";
+ strm.clear(std::ios::badbit);
+ return strm;
+ }
+ string_.resize(sz);
+ for(int32 i = 0; i < sz; i++) {
+ ReadType(strm, &(string_[i]));
+ }
+ return strm;
+ }
+
+ // This is used in OpenFst for binary I/O. This is OpenFst-style,
+ // not Kaldi-style, I/O.
+ std::ostream &Write(std::ostream &strm) const {
+ weight_.Write(strm);
+ if (strm.fail()){ return strm; }
+ int32 sz = static_cast<int32>(string_.size());
+ WriteType(strm, sz);
+ for(int32 i = 0; i < sz; i++)
+ WriteType(strm, string_[i]);
+ return strm;
+ }
+ size_t Hash() const {
+ size_t ans = weight_.Hash();
+ // any weird numbers here are largish primes
+ size_t sz = string_.size(), mult = 6967;
+ for(size_t i = 0; i < sz; i++) {
+ ans += string_[i] * mult;
+ mult *= 7499;
+ }
+ return ans;
+ }
+ private:
+ W weight_;
+ std::vector<IntType> string_;
+
+};
+
+template<class WeightType, class IntType>
+inline bool operator==(const CompactLatticeWeightTpl<WeightType, IntType> &w1,
+ const CompactLatticeWeightTpl<WeightType, IntType> &w2) {
+ return (w1.Weight() == w2.Weight() && w1.String() == w2.String());
+}
+
+template<class WeightType, class IntType>
+inline bool operator!=(const CompactLatticeWeightTpl<WeightType, IntType> &w1,
+ const CompactLatticeWeightTpl<WeightType, IntType> &w2) {
+ return (w1.Weight() != w2.Weight() || w1.String() != w2.String());
+}
+
+template<class WeightType, class IntType>
+inline bool ApproxEqual(const CompactLatticeWeightTpl<WeightType, IntType> &w1,
+ const CompactLatticeWeightTpl<WeightType, IntType> &w2,
+ float delta = kDelta) {
+ return (ApproxEqual(w1.Weight(), w2.Weight(), delta) && w1.String() == w2.String());
+}
+
+
+
+// Compare is not part of the standard for weight types, but used internally for
+// efficiency. The comparison here first compares the weight; if this is the
+// same, it compares the string. The comparison on strings is: first compare
+// the length, if this is the same, use lexicographical order. We can't just
+// use the lexicographical order because this would destroy the distributive
+// property of multiplication over addition, taking into account that addition
+// uses Compare. The string element of "Compare" isn't super-important in
+// practical terms; it's only needed to ensure that Plus always give consistent
+// answers and is symmetric. It's essentially for tie-breaking, but we need to
+// make sure all the semiring axioms are satisfied otherwise OpenFst might
+// break.
+
+template<class WeightType, class IntType>
+inline int Compare(const CompactLatticeWeightTpl<WeightType, IntType> &w1,
+ const CompactLatticeWeightTpl<WeightType, IntType> &w2) {
+ int c1 = Compare(w1.Weight(), w2.Weight());
+ if (c1 != 0) return c1;
+ int l1 = w1.String().size(), l2 = w2.String().size();
+ // Use opposite order on the string lengths, so that if the costs are the same,
+ // the shorter string wins.
+ if (l1 > l2) return -1;
+ else if (l1 < l2) return 1;
+ for(int i = 0; i < l1; i++) {
+ if (w1.String()[i] < w2.String()[i]) return -1;
+ else if (w1.String()[i] > w2.String()[i]) return 1;
+ }
+ return 0;
+}
+
+// For efficiency, override the NaturalLess template class.
+template<class FloatType, class IntType>
+class NaturalLess<CompactLatticeWeightTpl<LatticeWeightTpl<FloatType>, IntType> > {
+ public:
+ typedef CompactLatticeWeightTpl<LatticeWeightTpl<FloatType>, IntType> Weight;
+
+ NaturalLess() {}
+
+ bool operator()(const Weight &w1, const Weight &w2) const {
+ // NaturalLess is a negative order (opposite to normal ordering).
+ // This operator () corresponds to "<" in the negative order, which
+ // corresponds to the ">" in the normal order.
+ return (Compare(w1, w2) == 1);
+ }
+};
+template<>
+class NaturalLess<CompactLatticeWeightTpl<LatticeWeightTpl<float>, int32> > {
+ public:
+ typedef CompactLatticeWeightTpl<LatticeWeightTpl<float>, int32> Weight;
+
+ NaturalLess() {}
+
+ bool operator()(const Weight &w1, const Weight &w2) const {
+ // NaturalLess is a negative order (opposite to normal ordering).
+ // This operator () corresponds to "<" in the negative order, which
+ // corresponds to the ">" in the normal order.
+ return (Compare(w1, w2) == 1);
+ }
+};
+template<>
+class NaturalLess<CompactLatticeWeightTpl<LatticeWeightTpl<double>, int32> > {
+ public:
+ typedef CompactLatticeWeightTpl<LatticeWeightTpl<double>, int32> Weight;
+
+ NaturalLess() {}
+
+ bool operator()(const Weight &w1, const Weight &w2) const {
+ // NaturalLess is a negative order (opposite to normal ordering).
+ // This operator () corresponds to "<" in the negative order, which
+ // corresponds to the ">" in the normal order.
+ return (Compare(w1, w2) == 1);
+ }
+};
+
+// Make sure Compare is defined for TropicalWeight, so everything works
+// if we substitute LatticeWeight for TropicalWeight.
+inline int Compare(const TropicalWeight &w1,
+ const TropicalWeight &w2) {
+ float f1 = w1.Value(), f2 = w2.Value();
+ if (f1 == f2) return 0;
+ else if (f1 > f2) return -1;
+ else return 1;
+}
+
+
+
+template<class WeightType, class IntType>
+inline CompactLatticeWeightTpl<WeightType, IntType> Plus(
+ const CompactLatticeWeightTpl<WeightType, IntType> &w1,
+ const CompactLatticeWeightTpl<WeightType, IntType> &w2) {
+ return (Compare(w1, w2) >= 0 ? w1 : w2);
+}
+
+template<class WeightType, class IntType>
+inline CompactLatticeWeightTpl<WeightType, IntType> Times(
+ const CompactLatticeWeightTpl<WeightType, IntType> &w1,
+ const CompactLatticeWeightTpl<WeightType, IntType> &w2) {
+ WeightType w = Times(w1.Weight(), w2.Weight());
+ if (w == WeightType::Zero()) {
+ return CompactLatticeWeightTpl<WeightType, IntType>::Zero();
+ // special case to ensure zero is unique
+ } else {
+ std::vector<IntType> v;
+ v.resize(w1.String().size() + w2.String().size());
+ typename std::vector<IntType>::iterator iter = v.begin();
+ iter = std::copy(w1.String().begin(), w1.String().end(), iter); // returns end of first range.
+ std::copy(w2.String().begin(), w2.String().end(), iter);
+ return CompactLatticeWeightTpl<WeightType, IntType>(w, v);
+ }
+}
+
+template<class WeightType, class IntType>
+inline CompactLatticeWeightTpl<WeightType, IntType> Divide(const CompactLatticeWeightTpl<WeightType, IntType> &w1,
+ const CompactLatticeWeightTpl<WeightType, IntType> &w2,
+ DivideType div = DIVIDE_ANY) {
+ if (w1.Weight() == WeightType::Zero()) {
+ if (w2.Weight() != WeightType::Zero()) {
+ return CompactLatticeWeightTpl<WeightType, IntType>::Zero();
+ } else {
+ KALDI_ERR << "Division by zero [0/0]";
+ }
+ } else if (w2.Weight() == WeightType::Zero()) {
+ KALDI_ERR << "Error: division by zero";
+ }
+ WeightType w = Divide(w1.Weight(), w2.Weight());
+
+ const std::vector<IntType> v1 = w1.String(), v2 = w2.String();
+ if (v2.size() > v1.size()) {
+ KALDI_ERR << "Cannot divide, length mismatch";
+ }
+ typename std::vector<IntType>::const_iterator v1b = v1.begin(),
+ v1e = v1.end(), v2b = v2.begin(), v2e = v2.end();
+ if (div == DIVIDE_LEFT) {
+ if (!std::equal(v2b, v2e, v1b)) { // v2 must be identical to first part of v1.
+ KALDI_ERR << "Cannot divide, data mismatch";
+ }
+ return CompactLatticeWeightTpl<WeightType, IntType>(
+ w, std::vector<IntType>(v1b+(v2e-v2b), v1e)); // return last part of v1.
+ } else if (div == DIVIDE_RIGHT) {
+ if (!std::equal(v2b, v2e, v1e-(v2e-v2b))) { // v2 must be identical to last part of v1.
+ KALDI_ERR << "Cannot divide, data mismatch";
+ }
+ return CompactLatticeWeightTpl<WeightType, IntType>(
+ w, std::vector<IntType>(v1b, v1e-(v2e-v2b))); // return first part of v1.
+
+ } else {
+ KALDI_ERR << "Cannot divide CompactLatticeWeightTpl with DIVIDE_ANY";
+ }
+ return CompactLatticeWeightTpl<WeightType,IntType>::Zero(); // keep compiler happy.
+}
+
+template <class WeightType, class IntType>
+inline std::ostream &operator <<(std::ostream &strm, const CompactLatticeWeightTpl<WeightType, IntType> &w) {
+ strm << w.Weight();
+ CHECK(FLAGS_fst_weight_separator.size() == 1);
+ strm << FLAGS_fst_weight_separator[0]; // comma by default.
+ for(size_t i = 0; i < w.String().size(); i++) {
+ strm << w.String()[i];
+ if (i+1 < w.String().size())
+ strm << kStringSeparator; // '_'; defined in string-weight.h in OpenFst code.
+ }
+ return strm;
+}
+
+template <class WeightType, class IntType>
+inline std::istream &operator >>(std::istream &strm, CompactLatticeWeightTpl<WeightType, IntType> &w) {
+ std::string s;
+ strm >> s;
+ if (strm.fail()) {
+ return strm;
+ }
+ CHECK(FLAGS_fst_weight_separator.size() == 1);
+ size_t pos = s.find_last_of(FLAGS_fst_weight_separator); // normally ","
+ if (pos == std::string::npos) {
+ strm.clear(std::ios::badbit);
+ return strm;
+ }
+ // get parts of str before and after the separator (default: ',');
+ std::string s1(s, 0, pos), s2(s, pos+1);
+ std::istringstream strm1(s1);
+ WeightType weight;
+ strm1 >> weight;
+ w.SetWeight(weight);
+ if (strm1.fail() || !strm1.eof()) {
+ strm.clear(std::ios::badbit);
+ return strm;
+ }
+ // read string part.
+ std::vector<IntType> string;
+ const char *c = s2.c_str();
+ while(*c != '\0') {
+ if (*c == kStringSeparator) // '_'
+ c++;
+ char *c2;
+ long int i = strtol(c, &c2, 10);
+ if (c2 == c || static_cast<long int>(static_cast<IntType>(i)) != i) {
+ strm.clear(std::ios::badbit);
+ return strm;
+ }
+ c = c2;
+ string.push_back(static_cast<IntType>(i));
+ }
+ w.SetString(string);
+ return strm;
+}
+
+template<class BaseWeightType, class IntType>
+class CompactLatticeWeightCommonDivisorTpl {
+ public:
+ typedef CompactLatticeWeightTpl<BaseWeightType, IntType> Weight;
+
+ Weight operator()(const Weight &w1, const Weight &w2) const {
+ // First find longest common prefix of the strings.
+ typename std::vector<IntType>::const_iterator s1b = w1.String().begin(),
+ s1e = w1.String().end(), s2b = w2.String().begin(), s2e = w2.String().end();
+ while (s1b < s1e && s2b < s2e && *s1b == *s2b) {
+ s1b++;
+ s2b++;
+ }
+ return Weight(Plus(w1.Weight(), w2.Weight()), std::vector<IntType>(w1.String().begin(), s1b));
+ }
+};
+
+/** Scales the pair (a, b) of floating-point weights inside a
+ CompactLatticeWeight by premultiplying it (viewed as a vector)
+ by a 2x2 matrix "scale".
+ Assumes there is a ScaleTupleWeight function that applies to "Weight";
+ this currently only works if Weight equals LatticeWeightTpl<FloatType>
+ for some FloatType.
+*/
+template<class Weight, class IntType, class ScaleFloatType>
+inline CompactLatticeWeightTpl<Weight, IntType> ScaleTupleWeight(
+ const CompactLatticeWeightTpl<Weight, IntType> &w,
+ const std::vector<std::vector<ScaleFloatType> > &scale) {
+ return CompactLatticeWeightTpl<Weight, IntType>(
+ Weight(ScaleTupleWeight(w.Weight(), scale)), w.String());
+}
+
+/** Define some ConvertLatticeWeight functions that are used in various lattice
+ conversions... make them all templates, some with no arguments, since some
+ must be templates.*/
+template<class Float1, class Float2>
+inline void ConvertLatticeWeight(
+ const LatticeWeightTpl<Float1> &w_in,
+ LatticeWeightTpl<Float2> *w_out) {
+ w_out->SetValue1(w_in.Value1());
+ w_out->SetValue2(w_in.Value2());
+}
+
+template<class Float1, class Float2, class Int>
+inline void ConvertLatticeWeight(
+ const CompactLatticeWeightTpl<LatticeWeightTpl<Float1>, Int> &w_in,
+ CompactLatticeWeightTpl<LatticeWeightTpl<Float2>, Int> *w_out) {
+ LatticeWeightTpl<Float2> weight2(w_in.Weight().Value1(),
+ w_in.Weight().Value2());
+ w_out->SetWeight(weight2);
+ w_out->SetString(w_in.String());
+}
+
+// to convert from Lattice to standard FST
+template<class Float1, class Float2>
+inline void ConvertLatticeWeight(
+ const LatticeWeightTpl<Float1> &w_in,
+ TropicalWeightTpl<Float2> *w_out) {
+ TropicalWeightTpl<Float2> w1(w_in.Value1());
+ TropicalWeightTpl<Float2> w2(w_in.Value2());
+ *w_out = Times(w1, w2);
+}
+
+template<class Float>
+inline double ConvertToCost(const LatticeWeightTpl<Float> &w) {
+ return static_cast<double>(w.Value1()) + static_cast<double>(w.Value2());
+}
+
+template<class Float, class Int>
+inline double ConvertToCost(const CompactLatticeWeightTpl<LatticeWeightTpl<Float>, Int> &w) {
+ return static_cast<double>(w.Weight().Value1()) + static_cast<double>(w.Weight().Value2());
+}
+
+template<class Float>
+inline double ConvertToCost(const TropicalWeightTpl<Float> &w) {
+ return w.Value();
+}
+
+
+} // namespace fst
+
+#endif // KALDI_FSTEXT_LATTICE_WEIGHT_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/pre-determinize-inl.h b/runtime/onnxruntime/third_party/kaldi/fstext/pre-determinize-inl.h
new file mode 100644
index 000000000..b67b0ba6f
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/pre-determinize-inl.h
@@ -0,0 +1,728 @@
+// fstext/pre-determinize-inl.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_PRE_DETERMINIZE_INL_H_
+#define KALDI_FSTEXT_PRE_DETERMINIZE_INL_H_
+
+
+/* Do not include this file directly. It is an implementation file included by PreDeterminize.h */
+
+/*
+ Predeterminization
+
+ This is a function that makes an FST compactly determinizable by inserting symbols on the input
+ side as necessary for disambiguation. Note that we do not treat epsilon as a real symbol
+ when measuring determinizability in this sense. The extra symbols are added to the vocabulary,
+ on the input side; these are of the form (prefix)1, (prefix)2, and so on without limit, where
+ (prefix) is some prefix the user provides, e.g. '#' (the function checks that this will not
+ lead to conflicts with symbols already in the FST). The function tells us how many such
+ symbols it created.
+
+ Note that there is a paper "Generalized optimization algorithm for speech recognition
+ transducers" by Allauzen and Mohri, that deals with a similar issue, but this is a very
+ different algorithm that only aims to ensure determinizability, but not *compact*
+ determinizability.
+
+ Our algorithm is slightly heuristic, and probably not optimal, but does ensure that the
+ output is compactly determinizable, possibly at the expense of inserting unnecessary
+ symbols. We considered more sophisticated algorithms, but these were extremely
+ complicated and would give the same output for the kinds of inputs that we envisage.
+
+ Suppose the input FST is T. We want to ensure that in det(T), if we consider the
+ states of det(T) as weighted subsets of states of T, each state of T only appears once
+ in any given subset. This ensures that det(T) is no larger than T in an appropriate
+ sense. The way we do this is as follows. We identify all states in T that have
+ multiple input transitions (counting "being an initial state" as an input transition).
+ Let's call these "problematic" states. For a problematic state p we stipulate that it
+ can never appear in any state of det(T) unless that state equals (p, \bar{1}) [i.e. p,
+ unweighted]. In order to ensure this, we insert input symbols on the transitions to these
+ problematic states (this may necessitate adding extra states).
+ We also stipulate that the path through det(T) should always be sufficient to tell us
+ the path through T (and we insert extra symbols sufficient to make this so). This is to
+ simplify the algorithm, so that we don't have to consider the output symbols or weights
+ when predeterminizing.
+
+ The algorithm is as follows.
+
+ (A) Definitions
+
+ (i) Define a *problematic state* as a state that either has multiple input transitions,
+ or is an initial state and has at least one input transition.
+
+ (ii) For an arc a, define:
+ i[a] = input symbol on a
+ o[a] = output symbol on a
+ n[a] = dest-state of a
+ p[a] = origin-state of a
+
+ For a state q, define
+ E[q] = set of transitions leaving q.
+ For a set of states Q, define
+ E[Q] = set of transitions leaving some q in Q
+
+ (iii) For a state s, define Closure(s) as the union of state s, and all states t
+ that are reachable via sequences of arcs a such that i[a]=epsilon and n[a] is
+ not problematic.
+
+ For a set of states S, define Closure(S) as the union of the closures of
+ states s in S.
+
+ (B) Inputs and outputs.
+
+ (i) Inputs and preconditions. Input is an FST, which should have a symbol table compiled into
+ it, and a prefix (e.g. #) for symbols to be added. We check that the input FST is trim,
+ and that it does not have any symbols that appear on its arcs, that are equal to the prefix
+ followed by digits.
+
+ (ii) Outputs: The algorithm modifies the FST that is given to it, and returns the number of
+ the highest numbered "extra symbol" inserted. The extra symbols are numbered #1, #2 and
+ so on without limit (as integers). They are inserted into the symbol table in a sequential
+ way by calling AvailableKey()
+ for each in turn (this is stipulated in case we need to keep other symbol tables in sync).
+
+ (C) Sub-algorithm: Closure(S). This requires the array p(s), defined below, which is true
+ if s is problematic. This also requires, for efficiency, that the arcs be sorted on input
+ label.
+ Input: a set of states S. [plus, the fst and the array p].
+ Output: a set of states T.
+ Algorithm:
+ set T <-- S, Q <-- S.
+ while Q is nonempty:
+ pop a state s from Q.
+ for each transition a from state s with epsilon on the input label [we can
+ find these efficiently using the sorting on arcs]:
+ If p(n[a]) is false and n[a] is not in T:
+ Insert n[a] into T.
+ Add n[a] to Q.
+ return T.
+
+
+ (D) Main algorithm.
+
+
+ (i) (a) Check preconditions (FST is trim)
+ (b) Make sure there is just one final state (insert epsilon transitions as necessary).
+ (c) Sort arcs on input label (so epsilon arcs are at the start of arc lists).
+
+
+ (ii) Work out the set of problematic states by constructing a boolean array indexed by
+ states, i.e.
+ p(s)
+ which is true if the state is problematic. We can do this by constructing an array
+ t(s) to store the number of transitions into each state [adding one for the initial state],
+ and then setting p(s) = true if t(s) > 1.
+
+ Also create a boolean array d(s), defined for states, and set d(s) = false.
+ This array is purely for sanity-checking that we are processing each state exactly once.
+
+ (iii) Set up an array of integers m(a), indexed by arcs (how exactly we store these is
+ implementation-dependent, but this will probably be a hash from (state, arc-index) to
+ integers. m(a) will store the extra symbol, if any, to be added to that arc (or -1
+ if no such symbol; we can also simply have the arc not present in the hash). The
+ initial value of m(a) is -1 (if array), or undefined (if hash).
+
+ (iv) Initialize a set of sets-of-states S, and a queue of pairs Q, as follows.
+ The pairs in Q are a pair of (set-of-states, integer), where the integer
+ is the number of "special symbols" already used up for that state.
+
+ Note that we use a special indexing for the sets in both S and Q, rather than
+ using std::set. We use a sorted vector of StateId's. And in S, we index them
+ by the lowest-numbered state-id. Because each state is supposed to only ever
+ be a member of one set, if there is an attempt to add another, different set
+ with the same lowest-numbered state-id, we detect an error.
+
+ Let I be the single initial state (OpenFST only supports one).
+ We set:
+ S = { Closure(I) }
+ Push (Closure(I), 0) onto Q.
+ Then for each state s such that p(s) = true, and s is not an initial state:
+ S <-- S u { Closure(s) }
+ Push (Closure(s), 0) onto Q.
+
+ (v) While Q is nonempty:
+
+ (a) Pop pair (A, n) from Q (queue discipline is arbitrary).
+
+ (b) For each state s in A, check that d(s) is false, and set d(s) to true.
+ This is for sanity checking only.
+
+ (c)
+ Let S_\eps be the set of epsilon-transitions from members of A to problematic
+ states (i.e. S_\eps = \{ a \in E[A]: i[a]=\epsilon, p(n[a]) = true \}).
+
+ Next, we will define, for each t \neq \epsilon, S_t as the set of
+ transitions from some state s in S with t as the input label, i.e.:
+ S_t = \{ a \in E[A]: i[a] = t \}
+ We further define T_t and U_t as the subsets of S where the destination
+ state is problematic and non-problematic respectively, i.e:
+ T_t = \{ a \in E[A]: i[a] = t, p(n[a]) = true \}
+ U_t = \{ a \in E[A]: i[a] = t, p(n[a]) = false \}
+
+ The easiest way to obtain these sets is probably to have a hash indexed by
+ t that maps to a list of pairs (state, arc-offset) that stores S_t.
+ From this we can work out the sizes of T_t and U_t on the fly.
+
+ (d)
+ for each transition a in S_\eps:
+ m(a) <-- n # Will put symbol n on this transition.
+ n <-- n+1 # Note, same n as in pair (A, n)
+
+ (e)
+ next,
+ for each t\neq epsilon s.t. S_t is nonempty,
+
+ if |S_t| > 1 #if-statement is because if |S_t|=|T_t|=1, no need for prefix.
+ k = 0
+ for each transition a in T_t:
+ set m(a) to k.
+ set k = k+1
+
+ if |U_t| > 0
+ Let V_t be the set of destination-states of arcs in U_t.
+ if Closure(V_t) is not in S:
+ insert Closure(V_t) into S, and add the pair (Closure(V_t), k) to Q.
+
+ (vi) Check that for each state in the FST, d(s) = true.
+
+ (vii) Let n = max_a m(a). This is the highest-numbered extra symbol (extra symbols
+ start from zero, in this numbering which doesn't correspond to the symbol-table
+ numbering). Here we add n+1 extra symbols to the symbol table and store
+ the mappings from 0, 1, ... n to the symbol-id.
+
+ (viii) Set up a hash h from (state, int) to (state-id) such that
+ t = h(s, k)
+ will be the state-id of a newly-created state that has a transition to state s
+ with input-label #k.
+
+ (ix) For each arc a such that m(a) != 0:
+ If i[a] = epsilon (the input label is epsilon):
+ Change i[a] to #m(a). [i.e. prefix then digit m(a)]
+ Otherwise:
+ If t = h(n[a], m(a)) is not defined [where n[a] is the dest-state]:
+ create a new state t with a transition to n[a], with input-label #m(a) and
+ no output-label or weight. Set h(n[a], m(a)) = t.
+ Change n[a] to h(n[a], m(a)).
+
+
+*/
+namespace fst {
+
+namespace pre_determinize_helpers {
+
+// make it inline to avoid having to put it in a .cc file which most functions here
+// could not go in.
+inline bool HasBannedPrefixPlusDigits(SymbolTable *symTable, std::string prefix, std::string *bad_sym) {
+ // returns true if the symbol table contains any string consisting of this
+ // (possibly empty) prefix followed by a nonempty sequence of digits (0 to 9).
+ // requires symTable to be non-NULL.
+ // if bad_sym != NULL, puts the first bad symbol it finds in *bad_sym.
+ assert(symTable != NULL);
+ const char *prefix_ptr = prefix.c_str();
+ size_t prefix_len = strlen(prefix_ptr); // allowed to be zero but not encouraged.
+ for (SymbolTableIterator siter(*symTable); !siter.Done(); siter.Next()) {
+ const std::string &sym = siter.Symbol();
+ if (!strncmp(prefix_ptr, sym.c_str(), prefix_len)) { // has prefix.
+ if (isdigit(sym[prefix_len])) { // we don't allow prefix followed by a digit, as a symbol.
+ // Has at least one digit.
+ size_t pos;
+ for (pos = prefix_len;sym[pos] != '\0'; pos++)
+ if (!isdigit(sym[pos])) break;
+ if (sym[pos] == '\0') { // All remaining characters were digits.
+ if (bad_sym != NULL) *bad_sym = sym;
+ return true;
+ }
+ } // else OK because prefix was followed by '\0' or a non-digit.
+ }
+ }
+ return false; // doesn't have banned symbol.
+}
+
+template<class T> void CopySetToVector(const std::set<T> s, std::vector<T> *v) {
+ // adds members of s to v, in sorted order from lowest to highest
+ // (because the set was in sorted order).
+ assert(v != NULL);
+ v->resize(s.size());
+ typename std::set<T>::const_iterator siter = s.begin();
+ typename std::vector<T>::iterator viter = v->begin();
+ for (; siter != s.end(); ++siter, ++viter) {
+ assert(viter != v->end());
+ *viter = *siter;
+ }
+}
+
+// Warning. This function calls 'new'.
+template<class T>
+std::vector<T>* InsertMember(const std::vector<T> m, std::vector<std::vector<T>*> *S) {
+ assert(m.size() > 0);
+ T idx = m[0];
+ assert(idx>=(T)0 && idx < (T)S->size());
+ if ( (*S)[idx] != NULL) {
+ assert( *((*S)[idx]) == m );
+ // The vectors should be the same. Otherwise this is a bug in the algorithm.
+ // It could either be a programming error or a deeper conceptual bug.
+ return NULL; // nothing was inserted.
+ } else {
+ std::vector<T> *ret = (*S)[idx] = new std::vector<T>(m); // New copy of m.
+ return ret; // was inserted.
+ }
+}
+
+
+// See definition of Closure(S) in item A(iii) in the comment above. it's the set of states
+// that are reachable from S via sequences of arcs a such that i[a]=epsilon and n[a] is
+// not problematic. We assume that the fst is sorted on input label (so epsilon arcs first)
+// The algorithm is described in section (C) above. We use the same variable for S and T.
+template<class Arc> void Closure(MutableFst<Arc> *fst, std::set<typename Arc::StateId> *S,
+ const std::vector<bool> &pVec) {
+ typedef typename Arc::StateId StateId;
+ std::vector<StateId> Q;
+ CopySetToVector(*S, &Q);
+ while (Q.size() != 0) {
+ StateId s = Q.back();
+ Q.pop_back();
+ for (ArcIterator<MutableFst<Arc> > aiter(*fst, s); ! aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0) break; // Break from the loop: due to sorting there will be no
+ // more transitions with epsilons as input labels.
+ if (!pVec[arc.nextstate]) { // Next state is not problematic -> we can use this transition.
+ std::pair< typename std::set<StateId>::iterator, bool > p = S->insert(arc.nextstate);
+ if (p.second) { // True means: was inserted into S (wasn't already there).
+ Q.push_back(arc.nextstate);
+ }
+ }
+ }
+ }
+} // end function Closure.
+
+} // end namespace pre_determinize_helpers.
+
+
+template<class Arc, class Int>
+void PreDeterminize(MutableFst<Arc> *fst,
+ typename Arc::Label first_new_sym,
+ std::vector<Int> *symsOut) {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef size_t ArcId; // Our own typedef, not standard OpenFst. Use size_t
+ // for compatibility with argument of ArcIterator::Seek().
+ typedef typename Arc::Weight Weight;
+ assert(first_new_sym > 0);
+ assert(fst != NULL);
+ if (fst->Start() == kNoStateId) return; // for empty FST, nothing to do.
+ assert(symsOut != NULL && symsOut->size() == 0); // we will output the symbols we add into this.
+
+ { // (D)(i)(a): check is trim (i.e. connected, in OpenFST parlance).
+ KALDI_VLOG(2) << "PreDeterminize: Checking FST properties";
+ uint64 props = fst->Properties(kAccessible|kCoAccessible, true); // true-> computes properties if unknown at time when called.
+ if (props != (kAccessible|kCoAccessible)) { // All states are not both accessible and co-accessible...
+ KALDI_ERR << "PreDeterminize: FST is not trim";
+ }
+ }
+
+ { // (D)(i)(b): make single final state.
+ KALDI_VLOG(2) << "PreDeterminize: creating single final state";
+ CreateSuperFinal(fst);
+ }
+
+ { // (D)(i)(c): sort arcs on input.
+ KALDI_VLOG(2) << "PreDeterminize: sorting arcs on input";
+ ILabelCompare<Arc> icomp;
+ ArcSort(fst, icomp);
+ }
+
+ StateId n_states = 0, max_state = 0; // Compute n_states, max_state = highest-numbered state.
+ { // compute nStates, maxStates.
+ for (StateIterator<MutableFst<Arc> > iter(*fst); ! iter.Done(); iter.Next()) {
+ StateId state = iter.Value();
+ assert(state>=0);
+ n_states++;
+ if (state > max_state) max_state = state;
+ }
+ KALDI_VLOG(2) << "PreDeterminize: n_states = "<<(n_states)<<", max_state ="<<(max_state);
+ }
+
+ std::vector<bool> p_vec(max_state+1, false); // compute this next.
+ { // D(ii): computing the array p. ["problematic states, i.e. states with >1 input transition,
+ // counting being the initial state as an input transition"].
+ std::vector<bool> seen_vec(max_state+1, false); // rather than counting incoming transitions we just have a bool that says we saw at least one.
+
+ seen_vec[fst->Start()] = true;
+ for (StateIterator<MutableFst<Arc> > siter(*fst); ! siter.Done(); siter.Next()) {
+ for (ArcIterator<MutableFst<Arc> > aiter(*fst, siter.Value()); ! aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ assert(arc.nextstate>=0&&arc.nextstate<max_state+1);
+ if (seen_vec[arc.nextstate])
+ p_vec[arc.nextstate] = true; // now have >1 transition in, so problematic.
+ else
+ seen_vec[arc.nextstate] = true;
+ }
+ }
+ }
+ // D(iii): set up m(a)
+ std::map<std::pair<StateId, ArcId>, size_t> m_map;
+ // This is the array m, indexed by arcs. It maps to the index of the symbol we add.
+
+
+ // WARNING: we should be sure to clean up this memory before exiting. Do not return
+ // or throw an exception from this function, later than this point, without cleaning up!
+ // Note that the vectors are shared between Q and S (they "belong to" S.
+ std::vector<std::vector<StateId>* > S(max_state+1, (std::vector<StateId>*)(void*)0);
+ std::vector<std::pair<std::vector<StateId>*, size_t> > Q;
+
+ // D(iv): initialize S and Q.
+ {
+ std::vector<StateId> all_seed_states; // all "problematic" states, plus initial state (if not problematic).
+ if (!p_vec[fst->Start()])
+ all_seed_states.push_back(fst->Start());
+ for (StateId s = 0;s<=max_state; s++)
+ if (p_vec[s]) all_seed_states.push_back(s);
+
+ for (size_t idx = 0;idx < all_seed_states.size(); idx++) {
+ StateId s = all_seed_states[idx];
+ std::set<StateId> closure_s;
+ closure_s.insert(s); // insert "seed" state.
+ pre_determinize_helpers::Closure(fst, &closure_s, p_vec); // follow epsilons to non-problematic states.
+ // Closure in this case whis will usually not add anything, for typical topologies in speech
+ std::vector<StateId> closure_s_vec;
+ pre_determinize_helpers::CopySetToVector(closure_s, &closure_s_vec);
+ KALDI_ASSERT(closure_s_vec.size() != 0);
+ std::vector<StateId> *ptr = pre_determinize_helpers::InsertMember(closure_s_vec, &S);
+ KALDI_ASSERT(ptr != NULL); // Or conceptual bug or programming error.
+ Q.push_back(std::pair<std::vector<StateId>*, size_t>(ptr, 0));
+ }
+ }
+
+ std::vector<bool> d_vec(max_state+1, false); // "done vector". Purely for debugging.
+
+
+ size_t num_extra_det_states = 0;
+
+ // (D)(v)
+ while (Q.size() != 0) {
+
+ // (D)(v)(a)
+ std::pair<std::vector<StateId>*, size_t> cur_pair(Q.back());
+ Q.pop_back();
+ const std::vector<StateId> &A(*cur_pair.first);
+ size_t n =cur_pair.second; // next special symbol to add.
+
+ // (D)(v)(b)
+ for (size_t idx = 0;idx < A.size(); idx++) {
+ assert(d_vec[A[idx]] == false && "This state has been seen before. Algorithm error.");
+ d_vec[A[idx]] = true;
+ }
+
+ // From here is (D)(v)(c). We work out S_\eps and S_t (for t\neq eps)
+ // simultaneously at first.
+ std::map<Label, std::set<std::pair<std::pair<StateId, ArcId>, StateId> > > arc_hash;
+ // arc_hash is a hash with info of all arcs from states in the set A to
+ // non-problematic states.
+ // It is a map from ilabel to pair(pair(start-state, arc-offset), end-state).
+ // Here, arc-offset reflects the order in which we accessed the arc using the
+ // ArcIterator (zero for the first arc).
+
+
+ { // This block sets up arc_hash
+ for (size_t idx = 0;idx < A.size(); idx++) {
+ StateId s = A[idx];
+ assert(s>=0 && s<=max_state);
+ ArcId arc_id = 0;
+ for (ArcIterator<MutableFst<Arc> > aiter(*fst, s); ! aiter.Done(); aiter.Next(), ++arc_id) {
+ const Arc &arc = aiter.Value();
+
+ std::pair<std::pair<StateId, ArcId>, StateId>
+ this_pair(std::pair<StateId, ArcId>(s, arc_id), arc.nextstate);
+ bool inserted = (arc_hash[arc.ilabel].insert(this_pair)).second;
+ assert(inserted); // Otherwise we had a duplicate.
+ }
+ }
+ }
+
+ // (D)(v)(d)
+ if (arc_hash.count(0) == 1) { // We have epsilon transitions out.
+ std::set<std::pair<std::pair<StateId, ArcId>, StateId> > &eps_set = arc_hash[0];
+ typedef typename std::set<std::pair<std::pair<StateId, ArcId>, StateId> >::iterator set_iter_t;
+ for (set_iter_t siter = eps_set.begin(); siter != eps_set.end(); ++siter) {
+ const std::pair<std::pair<StateId, ArcId>, StateId> &this_pr = *siter;
+ if (p_vec[this_pr.second]) { // Eps-transition to problematic state.
+ assert(m_map.count(this_pr.first) == 0);
+ m_map[this_pr.first] = n;
+ n++;
+ }
+ }
+ }
+
+ // (D)(v)(e)
+ {
+ typedef typename std::map<Label, std::set<std::pair<std::pair<StateId, ArcId>, StateId> > >::iterator map_iter_t;
+ typedef typename std::set<std::pair<std::pair<StateId, ArcId>, StateId> >::iterator set_iter_t2;
+ for (map_iter_t miter = arc_hash.begin(); miter != arc_hash.end(); ++miter) {
+ Label t = miter->first;
+ std::set<std::pair<std::pair<StateId, ArcId>, StateId> > &S_t = miter->second;
+ if (t != 0) { // For t != epsilon,
+ std::set<StateId> V_t; // set of destination non-problem states. Will create this set now.
+
+ // exists_noproblem is true iff |U_t| > 0.
+ size_t k = 0;
+
+ // First loop "for each transition a in T_t" (i.e. transitions to problematic states)
+ // The if-statement if (|S_t|>1) is pushed inside the loop, as the loop also computes
+ // the set V_t.
+ for (set_iter_t2 siter = S_t.begin(); siter != S_t.end(); ++siter) {
+ const std::pair<std::pair<StateId, ArcId>, StateId> &this_pr = *siter;
+ if (p_vec[this_pr.second]) { // only consider problematic states (just set T_t)
+ if (S_t.size() > 1) { // This is where we pushed the if-statement in.
+ assert(m_map.count(this_pr.first) == 0);
+ m_map[this_pr.first] = k;
+ k++;
+ num_extra_det_states++;
+ }
+ } else { // Create the set V_t.
+ V_t.insert(this_pr.second);
+ }
+ }
+ if (V_t.size() != 0) {
+ pre_determinize_helpers::Closure(fst, &V_t, p_vec); // follow epsilons to non-problematic states.
+ std::vector<StateId> closure_V_t_vec;
+ pre_determinize_helpers::CopySetToVector(V_t, &closure_V_t_vec);
+ std::vector<StateId> *ptr = pre_determinize_helpers::InsertMember(closure_V_t_vec, &S);
+ if (ptr != NULL) { // was inserted.
+ Q.push_back(std::pair<std::vector<StateId>*, size_t>(ptr, k));
+ }
+ }
+ }
+ }
+ }
+ } // end while (Q.size() != 0)
+
+
+ { // (D)(vi): Check that for each state in the FST, d(s) = true.
+ for (StateIterator<MutableFst<Arc> > siter(*fst); ! siter.Done(); siter.Next()) {
+ StateId val = siter.Value();
+ assert(d_vec[val] == true);
+ }
+ }
+
+ { // (D)(vii): compute symbol-table ID's.
+ // sets up symsOut array.
+ int64 n = -1;
+ for (typename std::map<std::pair<StateId, ArcId>, size_t>::iterator m_iter = m_map.begin();
+ m_iter != m_map.end();
+ ++m_iter) {
+ n = std::max(n, (int64) m_iter->second); // m_iter->second is of type size_t.
+ }
+ // At this point n is the highest symbol-id (type size_t) of symbols we must add.
+ n++; // This is now the number of symbols we must add.
+ for (size_t i = 0;static_cast<int64>(i)<n;i++) symsOut->push_back(first_new_sym + i);
+ }
+
+ // (D)(viii): set up hash.
+ std::map<std::pair<StateId, size_t>, StateId> h_map;
+
+ { // D(ix): add extra symbols! This is where the work gets done.
+
+ // Core part of this is below, search for (*)
+ size_t n_states_added = 0;
+
+ for (typename std::map<std::pair<StateId, ArcId>, size_t>::iterator m_iter = m_map.begin();
+ m_iter != m_map.end();
+ ++m_iter) {
+ StateId state = m_iter->first.first;
+ ArcId arcpos = m_iter->first.second;
+ size_t m_a = m_iter->second;
+
+ MutableArcIterator<MutableFst<Arc> > aiter(fst, state);
+ aiter.Seek(arcpos);
+ Arc arc = aiter.Value();
+
+ // (*) core part here.
+ if (arc.ilabel == 0)
+ arc.ilabel = (*symsOut)[m_a];
+ else {
+ std::pair<StateId, size_t> pr(arc.nextstate, m_a);
+ if (!h_map.count(pr)) {
+ n_states_added++;
+ StateId newstate = fst->AddState();
+ assert(newstate>=0);
+ Arc new_arc( (*symsOut)[m_a], (Label)0, Weight::One(), arc.nextstate);
+ fst->AddArc(newstate, new_arc);
+ h_map[pr] = newstate;
+ }
+ arc.nextstate = h_map[pr];
+ }
+ aiter.SetValue(arc);
+ }
+
+ KALDI_VLOG(2) << "Added " <<(n_states_added)<<" new states and added/changed "<<(m_map.size())<<" arcs";
+
+ }
+ // Now free up memory.
+ for (size_t i = 0;i < S.size();i++)
+ delete S[i];
+} // end function PreDeterminize
+
+
+template<class Label> void CreateNewSymbols(SymbolTable *input_sym_table, int nSym,
+ std::string prefix, std::vector<Label> *symsOut) {
+ // Creates nSym new symbols named (prefix)0, (prefix)1 and so on.
+ // Crashes if it cannot create them because one or more of them were in the symbol
+ // table already.
+ assert(symsOut && symsOut->size() == 0);
+ for (int i = 0;i < nSym;i++) {
+ std::stringstream ss; ss << prefix << i;
+ std::string str = ss.str();
+ if (input_sym_table->Find(str) != -1) { // should not be present.
+ }
+ assert(symsOut);
+ symsOut->push_back( (Label) input_sym_table->AddSymbol(str));
+ }
+}
+
+
+// see pre-determinize.h for documentation.
+template<class Arc> void AddSelfLoops(MutableFst<Arc> *fst, std::vector<typename Arc::Label> &isyms,
+ std::vector<typename Arc::Label> &osyms) {
+ assert(fst != NULL);
+ assert(isyms.size() == osyms.size());
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ size_t n = isyms.size();
+ if (n == 0) return; // Nothing to do.
+
+ // {
+ // the following declarations and statements are for quick detection of these
+ // symbols, which is purely for debugging/checking purposes.
+ Label isyms_min = *std::min_element(isyms.begin(), isyms.end()),
+ isyms_max = *std::max_element(isyms.begin(), isyms.end()),
+ osyms_min = *std::min_element(osyms.begin(), osyms.end()),
+ osyms_max = *std::max_element(osyms.begin(), osyms.end());
+ std::set<Label> isyms_set, osyms_set;
+ for (size_t i = 0; i < isyms.size(); i++) {
+ assert(isyms[i] > 0 && osyms[i] > 0); // should not have epsilon or invalid symbols.
+ isyms_set.insert(isyms[i]);
+ osyms_set.insert(osyms[i]);
+ }
+ assert(isyms_set.size() == n && osyms_set.size() == n);
+ // } end block.
+
+ for (StateIterator<MutableFst<Arc> > siter(*fst); ! siter.Done(); siter.Next()) {
+ StateId state = siter.Value();
+ bool this_state_needs_self_loops = (fst->Final(state) != Weight::Zero());
+ for (ArcIterator<MutableFst<Arc> > aiter(*fst, state); ! aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ // If one of the following asserts fails, it means that the input FST already had the symbols
+ // we are inserting. This is contrary to the preconditions of this algorithm.
+ assert(!(arc.ilabel>=isyms_min && arc.ilabel<=isyms_max && isyms_set.count(arc.ilabel) != 0));
+ assert(!(arc.olabel>=osyms_min && arc.olabel<=osyms_max && osyms_set.count(arc.olabel) != 0));
+ if (arc.olabel != 0) // Has non-epsilon output label -> need self loops.
+ this_state_needs_self_loops = true;
+ }
+ if (this_state_needs_self_loops) {
+ for (size_t i = 0;i < n;i++) {
+ Arc arc;
+ arc.ilabel = isyms[i];
+ arc.olabel = osyms[i];
+ arc.weight = Weight::One();
+ arc.nextstate = state;
+ fst->AddArc(state, arc);
+ }
+ }
+ }
+}
+
+template<class Arc>
+int64 DeleteISymbols(MutableFst<Arc> *fst, std::vector<typename Arc::Label> isyms) {
+
+ // We could do this using the Mapper concept, but this is much easier to understand.
+
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+
+ int64 num_deleted = 0;
+
+ if (isyms.size() == 0) return 0;
+ Label isyms_min = *std::min_element(isyms.begin(), isyms.end()),
+ isyms_max = *std::max_element(isyms.begin(), isyms.end());
+ bool isyms_consecutive = (isyms_max+1-isyms_min == static_cast<Label>(isyms.size()));
+ std::set<Label> isyms_set;
+ if (!isyms_consecutive)
+ for (size_t i = 0;i < isyms.size();i++)
+ isyms_set.insert(isyms[i]);
+
+ for (StateIterator<MutableFst<Arc> > siter(*fst); ! siter.Done(); siter.Next()) {
+ StateId state = siter.Value();
+ for (MutableArcIterator<MutableFst<Arc> > aiter(fst, state); ! aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel >= isyms_min && arc.ilabel <= isyms_max) {
+ if (isyms_consecutive || isyms_set.count(arc.ilabel) != 0) {
+ num_deleted++;
+ Arc mod_arc (arc);
+ mod_arc.ilabel = 0; // change label to epsilon.
+ aiter.SetValue(mod_arc);
+ }
+ }
+ }
+ }
+ return num_deleted;
+}
+
+template<class Arc>
+typename Arc::StateId CreateSuperFinal(MutableFst<Arc> *fst) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+ assert(fst != NULL);
+ StateId num_states = fst->NumStates();
+ std::vector<StateId> final_states;
+ for (StateId s = 0; s < num_states; s++) {
+ if (fst->Final(s) != Weight::Zero()) {
+ final_states.push_back(s);
+ }
+ }
+ if (final_states.size() == 1) {
+ if (fst->Final(final_states[0]) == Weight::One()) {
+ ArcIterator<MutableFst<Arc> > iter(*fst, final_states[0]);
+ if (iter.Done()) {
+ // We already have a final state w/ no transitions out and unit weight.
+ // So we're done.
+ return final_states[0];
+ }
+ }
+ }
+
+ StateId final_state = fst->AddState();
+ fst->SetFinal(final_state, Weight::One());
+ for (size_t idx = 0; idx < final_states.size(); idx++) {
+ StateId s = final_states[idx];
+ Weight weight = fst->Final(s);
+ fst->SetFinal(s, Weight::Zero());
+ Arc arc;
+ arc.ilabel = 0;
+ arc.olabel = 0;
+ arc.nextstate = final_state;
+ arc.weight = weight;
+ fst->AddArc(s, arc);
+ }
+ return final_state;
+}
+
+
+} // namespace fst
+
+#endif // KALDI_FSTEXT_PRE_DETERMINIZE_INL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/pre-determinize-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/pre-determinize-test.cc
new file mode 100644
index 000000000..7210e4554
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/pre-determinize-test.cc
@@ -0,0 +1,220 @@
+// fstext/pre-determinize-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "base/kaldi-math.h"
+#include "fstext/pre-determinize.h"
+#include "fstext/fst-test-utils.h"
+#include "fstext/fstext-utils.h"
+
+// Just check that it compiles, for now.
+
+namespace fst
+{
+ using std::vector;
+ using std::cout;
+
+// Don't instantiate with log semiring, as RandEquivalent may fail.
+template<class Arc> void TestPreDeterminize() {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = new VectorFst<Arc>();
+ int n_syms = 2 + kaldi::Rand() % 5, n_states = 3 + kaldi::Rand() % 10, n_arcs = 5 + kaldi::Rand() % 30, n_final = 1 + kaldi::Rand()%3; // Up to 2 unique symbols.
+ cout << "Testing pre-determinize with "<<n_syms<<" symbols, "<<n_states<<" states and "<<n_arcs<<" arcs and "<<n_final<<" final states.\n";
+ SymbolTable *sptr = NULL;
+
+ vector<Label> all_syms; // including epsilon.
+ // Put symbols in the symbol table from 1..n_syms-1.
+ for (size_t i = 0;i < (size_t)n_syms;i++)
+ all_syms.push_back(i);
+
+ // Create states.
+ vector<StateId> all_states;
+ for (size_t i = 0;i < (size_t)n_states;i++) {
+ StateId this_state = fst->AddState();
+ if (i == 0) fst->SetStart(i);
+ all_states.push_back(this_state);
+ }
+ // Set final states.
+ for (size_t j = 0;j < (size_t)n_final;j++) {
+ StateId id = all_states[kaldi::Rand() % n_states];
+ Weight weight = (Weight)(0.33*(kaldi::Rand() % 5) );
+ printf("calling SetFinal with %d and %f\n", id, weight.Value());
+ fst->SetFinal(id, weight);
+ }
+ // Create arcs.
+ for (size_t i = 0;i < (size_t)n_arcs;i++) {
+ Arc a;
+ a.nextstate = all_states[kaldi::Rand() % n_states];
+ a.ilabel = all_syms[kaldi::Rand() % n_syms];
+ a.olabel = all_syms[kaldi::Rand() % n_syms]; // same input+output vocab.
+ a.weight = (Weight) (0.33*(kaldi::Rand() % 2));
+ StateId start_state = all_states[kaldi::Rand() % n_states];
+ fst->AddArc(start_state, a);
+ }
+
+ std::cout <<" printing before trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ // Trim resulting FST.
+ Connect(fst);
+
+ std::cout <<" printing after trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ VectorFst<Arc> *fst_copy_orig = new VectorFst<Arc>(*fst);
+
+ vector<Label> extra_syms;
+ if (fst->Start() != kNoStateId) { // "Connect" did not make it empty....
+ typename Arc::Label highest_sym = HighestNumberedInputSymbol(*fst);
+ PreDeterminize(fst, highest_sym+1, &extra_syms);
+ }
+
+ std::cout <<" printing after predeterminization\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ { // Remove epsilon. All default args.
+ bool connect = true;
+ Weight weight_threshold = Weight::Zero();
+ int64 nstate = -1; // Relates to pruning.
+ double delta = kDelta; // I think a small weight value. Relates to some kind of pruning,
+ // I guess. But with no epsilon cycles, probably doensn't matter.
+ RmEpsilon(fst, connect, weight_threshold, nstate, delta);
+ }
+
+ std::cout <<" printing after epsilon removal\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ VectorFst<Arc> ofst;
+ DeterminizeOptions<Arc> opts; // Default options.
+ Determinize(*fst, &ofst, opts);
+ std::cout <<" printing after determinization\n";
+ {
+ FstPrinter<Arc> fstprinter(ofst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ int64 num_removed = DeleteISymbols(&ofst, extra_syms);
+ std::cout <<" printing after removing "<<num_removed<<" instances of extra symbols\n";
+ {
+ FstPrinter<Arc> fstprinter(ofst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ std::cout <<" Checking equivalent to original FST.\n";
+ // giving Rand() as a seed stops the random number generator from always being reset to
+ // the same point each time, while maintaining determinism of the test.
+ assert(RandEquivalent(ofst, *fst_copy_orig, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ delete fst;
+ delete fst_copy_orig;
+}
+
+template<class Arc> void TestAddSelfLoops() {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = new VectorFst<Arc>();
+ SymbolTable *ilabels = new SymbolTable("my-symbol-table");
+ SymbolTable *olabels = new SymbolTable("my-symbol-table-2");
+ Label i0 = ilabels->AddSymbol("<eps>");
+ Label i1 = ilabels->AddSymbol("1");
+ Label i2 = ilabels->AddSymbol("2");
+
+ Label o0 = olabels->AddSymbol("<eps>");
+ Label o1 = olabels->AddSymbol("1");
+
+ assert(i0 == 0 && o0 == 0);
+ StateId s0 = fst->AddState(), s1 = fst->AddState(), s2 = fst->AddState();
+ fst->SetStart(s0);
+ assert(s0 == 0);
+
+ fst->SetFinal(s2, (Weight)2); // state 2 is final.
+ {
+ Arc arc;
+ arc.ilabel = i1;
+ arc.olabel = o0;
+ arc.nextstate = 1;
+ arc.weight = (Weight)1;
+ fst->AddArc(s0, arc); // arc from 0 to 1 with epsilon out.
+ }
+ {
+ Arc arc;
+ arc.ilabel = i2;
+ arc.olabel = o1;
+ arc.nextstate = 2;
+ arc.weight = (Weight)2;
+ fst->AddArc(s1, arc); // arc from 1 to 2 with "1" out.
+ }
+ std::cout <<" printing before adding self-loops\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, ilabels, olabels, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ // So states 1 and 2 should have self-loops on.
+ size_t num_extra = kaldi::Rand() % 5;
+ vector<Label> extra_ilabels, extra_olabels;
+ CreateNewSymbols(ilabels, num_extra, "in#", &extra_ilabels);
+ CreateNewSymbols(olabels, num_extra, "out#", &extra_olabels);
+
+ AddSelfLoops(fst, extra_ilabels, extra_olabels);
+
+ assert(fst->NumArcs(0) == 1);
+ assert(fst->NumArcs(1) == 1 + num_extra);
+ assert(fst->NumArcs(2) == num_extra);
+
+ std::cout <<" printing after adding self-loops\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, ilabels, olabels, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ delete fst;
+ delete ilabels;
+ delete olabels;
+}
+
+} // end namespace fst.
+
+
+int main() {
+ for (int i = 0;i < 10;i++) { // run it multiple times; it's a randomized testing algorithm.
+ fst::TestPreDeterminize<fst::StdArc>();
+ }
+ for (int i = 0;i < 5;i++) {
+ fst::TestAddSelfLoops<fst::StdArc>();
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/pre-determinize.h b/runtime/onnxruntime/third_party/kaldi/fstext/pre-determinize.h
new file mode 100644
index 000000000..7ead946bf
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/pre-determinize.h
@@ -0,0 +1,96 @@
+// fstext/pre-determinize.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_PRE_DETERMINIZE_H_
+#define KALDI_FSTEXT_PRE_DETERMINIZE_H_
+#include <algorithm>
+#include <map>
+#include <set>
+#include <vector>
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+#include "base/kaldi-common.h"
+
+namespace fst {
+
+/* PreDeterminize inserts extra symbols on the input side of an FST as necessary to
+ ensure that, after epsilon removal, it will be compactly determinizable by the
+ determinize* algorithm. By compactly determinizable we mean that
+ no original FST state is represented in more than one determinized state).
+
+ Caution: this code is now only used in testing.
+
+ The new symbols start from the value "first_new_symbol", which should be
+ higher than the largest-numbered symbol currently in the FST. The new
+ symbols added are put in the array syms_out, which should be empty at start.
+*/
+
+template<class Arc, class Int>
+void PreDeterminize(MutableFst<Arc> *fst,
+ typename Arc::Label first_new_symbol,
+ std::vector<Int> *syms_out);
+
+
+/* CreateNewSymbols is a helper function used inside PreDeterminize, and is also useful
+ when you need to add a number of extra symbols to a different vocabulary from the one
+ modified by PreDeterminize. */
+
+template<class Label>
+void CreateNewSymbols(SymbolTable *inputSymTable, int nSym,
+ std::string prefix, std::vector<Label> *syms_out);
+
+/** AddSelfLoops is a function you will probably want to use alongside PreDeterminize,
+ to add self-loops to any FSTs that you compose on the left hand side of the one
+ modified by PreDeterminize.
+
+ This function inserts loops with "special symbols" [e.g. \#0, \#1] into an FST.
+ This is done at each final state and each state with non-epsilon output symbols on
+ at least one arc out of it. This is to ensure that these symbols, when inserted into
+ the input side of an FST we will compose with on the right, can "pass through" this
+ FST.
+
+ At input, isyms and osyms must be vectors of the same size n, corresponding
+ to symbols that currently do not exist in 'fst'. For each state in n that has
+ non-epsilon symbols on the output side of arcs leaving it, or which is a final state,
+ this function inserts n self-loops with unit weight and one of the n pairs
+ of symbols on its input and output.
+*/
+template<class Arc>
+void AddSelfLoops(MutableFst<Arc> *fst, std::vector<typename Arc::Label> &isyms,
+ std::vector<typename Arc::Label> &osyms);
+
+
+/* DeleteSymbols replaces any instances of symbols in the vector symsIn, appearing
+ on the input side, with epsilon. */
+/* It returns the number of instances of symbols deleted. */
+template<class Arc>
+int64 DeleteISymbols(MutableFst<Arc> *fst, std::vector<typename Arc::Label> symsIn);
+
+/* CreateSuperFinal takes an FST, and creates an equivalent FST with a single final
+ state with no transitions out and unit final weight, by inserting epsilon transitions
+ as necessary. */
+template<class Arc>
+typename Arc::StateId CreateSuperFinal(MutableFst<Arc> *fst);
+
+
+} // end namespace fst
+
+#include "fstext/pre-determinize-inl.h"
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/prune-special-inl.h b/runtime/onnxruntime/third_party/kaldi/fstext/prune-special-inl.h
new file mode 100644
index 000000000..61aa732f3
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/prune-special-inl.h
@@ -0,0 +1,173 @@
+// fstext/prune-special-inl.h
+
+// Copyright 2014 Johns Hopkins University (Author: Daniel Povey)
+// Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_PRUNE_SPECIAL_INL_H_
+#define KALDI_FSTEXT_PRUNE_SPECIAL_INL_H_
+// Do not include this file directly. It is included by prune-special.h
+
+#include "fstext/prune-special.h"
+#include "base/kaldi-error.h"
+
+namespace fst {
+
+
+/// This class is used to implement the function PruneSpecial.
+template<class Arc> class PruneSpecialClass {
+ public:
+ typedef typename Arc::StateId InputStateId;
+ typedef typename Arc::StateId OutputStateId;
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::Label Label;
+
+ PruneSpecialClass(const Fst<Arc> &ifst,
+ VectorFst<Arc> *ofst,
+ Weight beam,
+ size_t max_states):
+ ifst_(ifst), ofst_(ofst), beam_(beam), max_states_(max_states),
+ best_weight_(Weight::Zero()) {
+ KALDI_ASSERT(beam != Weight::One());
+ KALDI_ASSERT(queue_.size() == 0);
+ ofst_->DeleteStates(); // make sure it's empty.
+ if (ifst_.Start() == kNoStateId)
+ return;
+ ofst_->SetStart(ProcessState(ifst_.Start(), Weight::One()));
+
+ while (!queue_.empty()) {
+ Task task = queue_.top();
+ queue_.pop();
+ if (Done(task)) break;
+ else ProcessTask(task);
+ }
+ Connect(ofst);
+ if (beam_ != Weight::One())
+ Prune(ofst, beam_);
+ }
+
+ struct Task {
+ InputStateId istate;
+ OutputStateId ostate; // could be looked up; this is for speed.
+ size_t position; // arc position, or -1 if final-prob.
+ Weight weight;
+
+ Task(InputStateId istate, OutputStateId ostate, size_t position,
+ Weight weight): istate(istate), ostate(ostate), position(position),
+ weight(weight) { }
+ bool operator < (const Task &other) const {
+ return Compare(weight, other.weight) < 0;
+ }
+ };
+
+ bool Done(const Task &task) {
+ if (beam_ != Weight::One() && best_weight_ != Weight::Zero() &&
+ Compare(task.weight, Times(best_weight_, beam_)) < 0)
+ return true;
+ if (max_states_ > 0 &&
+ static_cast<size_t>(ofst_->NumStates()) > max_states_)
+ return true;
+ return false;
+ }
+
+
+ // This function assumes "state" has not been seen before, so we need to
+ // create a new output-state for it and add tasks. It returns the
+ // output-state id. "weight" is the best cost from the start-state to this
+ // state.
+ inline OutputStateId ProcessState(InputStateId istate, const Weight &weight) {
+ OutputStateId ostate = ofst_->AddState();
+ state_map_[istate] = ostate;
+ for (ArcIterator<Fst<Arc> > aiter(ifst_, istate); !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ Task new_task(istate, ostate, aiter.Position(),
+ Times(weight, arc.weight));
+ KALDI_ASSERT(Compare(arc.weight, Weight::One()) != 1);
+ queue_.push(new_task);
+ }
+ Weight final = ifst_.Final(istate);
+ if (final != Weight::Zero()) {
+ Task final_task(istate, ostate, static_cast<size_t>(-1),
+ Times(weight, final));
+ KALDI_ASSERT(Compare(final, Weight::One()) != 1);
+ queue_.push(final_task);
+ }
+ return ostate;
+ }
+
+ // Returns the output-state id corresponding to "istate". This assumes we are
+ // processing a task corresponding to an arc to "istate", and the cost from
+ // the start-state to this state is "weight". Since we process tasks in
+ // order, if this is the first time we see this istate, then this is the best
+ // cost from the start-state to this state, and it can be used in setting the
+ // priority costs in ProcessState().
+ inline OutputStateId GetOutputStateId(InputStateId istate,
+ const Weight &weight) {
+ typedef typename unordered_map<InputStateId, OutputStateId>::iterator IterType;
+ IterType iter = state_map_.find(istate);
+ if (iter == state_map_.end())
+ return ProcessState(istate, weight);
+ else
+ return iter->second;
+ }
+
+ void ProcessTask(const Task &task) {
+ if (task.position == static_cast<size_t>(-1)) {
+ ofst_->SetFinal(task.ostate, ifst_.Final(task.istate));
+ if (best_weight_ == Weight::Zero())
+ best_weight_ = task.weight; // best-path cost through FST, used for
+ // beam-pruning.
+ } else {
+ ArcIterator<Fst<Arc> > aiter(ifst_, task.istate);
+ aiter.Seek(task.position); // if we spend most of our time here, we may
+ // need to store the arc in the Task.
+ const Arc &arc = aiter.Value();
+ InputStateId next_istate = arc.nextstate;
+ OutputStateId next_ostate = GetOutputStateId(next_istate, task.weight);
+ Arc oarc(arc.ilabel, arc.olabel, arc.weight, next_ostate);
+ ofst_->AddArc(task.ostate, oarc);
+ }
+ }
+
+ private:
+ const Fst<Arc> &ifst_;
+ VectorFst<Arc> *ofst_;
+ Weight beam_;
+ size_t max_states_;
+
+ unordered_map<InputStateId, OutputStateId> state_map_;
+ std::priority_queue<Task> queue_;
+ Weight best_weight_; // if not Zero(), then we have now processed a successful path
+ // through ifst_, and this is the weight.
+
+};
+
+template<class Arc>
+void PruneSpecial(const Fst<Arc> &ifst,
+ VectorFst<Arc> *ofst,
+ typename Arc::Weight beam,
+ size_t max_states) {
+ PruneSpecialClass<Arc> c(ifst, ofst, beam, max_states);
+}
+
+
+
+}
+
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/prune-special-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/prune-special-test.cc
new file mode 100644
index 000000000..5d8c40b6a
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/prune-special-test.cc
@@ -0,0 +1,79 @@
+// fstext/prune-special-test.cc
+
+// Copyright 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "fstext/prune-special.h"
+#include "fstext/rand-fst.h"
+#include "fstext/fstext-utils.h"
+
+namespace fst {
+
+static void TestPruneSpecial() {
+ typedef StdArc Arc;
+ typedef Arc::Label Label;
+ typedef Arc::StateId StateId;
+ typedef Arc::Weight Weight;
+
+ RandFstOptions opts;
+ opts.acyclic = false;
+ VectorFst<Arc> *ifst = RandFst<StdArc>(opts);
+
+ float beam = 0.55;
+
+ {
+ FstPrinter<Arc> fstprinter(*ifst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ std::cout << std::endl;
+ }
+
+ // Do the special pruning.
+ VectorFst<Arc> ofst1;
+ PruneSpecial<StdArc>(*ifst, &ofst1, beam);
+ {
+ FstPrinter<Arc> fstprinter(ofst1, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ std::cout << std::endl;
+ }
+
+ // Do the normal pruning.
+ VectorFst<Arc> ofst2;
+ Prune(*ifst, &ofst2, beam);
+ {
+ FstPrinter<Arc> fstprinter(ofst2, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ std::cout << std::endl;
+ }
+
+ KALDI_ASSERT(RandEquivalent(ofst1, ofst2,
+ 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/,
+ 100/*path length-- max?*/));
+
+ delete ifst;
+}
+
+
+} // namespace fst
+
+int main() {
+ kaldi::g_kaldi_verbose_level = 4;
+ using namespace fst;
+ for (int i = 0; i < 25; i++) {
+ TestPruneSpecial();
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/prune-special.h b/runtime/onnxruntime/third_party/kaldi/fstext/prune-special.h
new file mode 100644
index 000000000..62cf280fc
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/prune-special.h
@@ -0,0 +1,60 @@
+// fstext/prune-special.h
+
+// Copyright 2014 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_FSTEXT_PRUNE_SPECIAL_H_
+#define KALDI_FSTEXT_PRUNE_SPECIAL_H_
+
+#include "fst/fstlib.h"
+#include "fstext/lattice-weight.h"
+#include "fstext/factor.h"
+
+namespace fst {
+
+
+
+/**
+ The function PruneSpecial is like the standard OpenFst function "prune",
+ except it does not expand the entire "ifst"- this is useful for cases where
+ ifst is an on-demand FST such as a ComposeFst and we don't want to visit
+ it all. It supports pruning either to a specified beam (if beam is
+ not One()), or to a specified max_states (if max_states is > 0). One of the
+ two must be specified.
+
+ Requirements:
+ - Costs must be non-negative (equivalently, weights must not be greater than One()).
+ - There must be a Compare(a, b) function that compares two weights and returns (-1,0,1)
+ if (a<b, a=b, a>b). We define this in Kaldi, for TropicalWeight, LogWeight (I think),
+ and LatticeWeight... also CompactLatticeWeight, but we doubt that will be used here;
+ better to use PruneCompactLattice().
+ */
+
+template<class Arc>
+void PruneSpecial(const Fst<Arc> &ifst,
+ VectorFst<Arc> *ofst,
+ typename Arc::Weight beam,
+ size_t max_states = 0);
+
+
+
+} // end namespace fst
+
+#include "fstext/prune-special-inl.h"
+
+#endif // KALDI_FSTEXT_PRUNE_SPECIAL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/push-special-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/push-special-test.cc
new file mode 100644
index 000000000..557b43d30
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/push-special-test.cc
@@ -0,0 +1,81 @@
+// fstext/push-special-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "fstext/push-special.h"
+#include "fstext/rand-fst.h"
+#include "fstext/fstext-utils.h"
+#include "base/kaldi-math.h"
+
+namespace fst
+{
+
+
+// Don't instantiate with log semiring, as RandEquivalent may fail.
+static void TestPushSpecial() {
+ typedef StdArc Arc;
+ typedef Arc::Label Label;
+ typedef Arc::StateId StateId;
+ typedef Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = RandFst<StdArc>();
+
+ {
+ FstPrinter<Arc> fstprinter(*fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ VectorFst<Arc> fst_copy(*fst);
+
+ float delta = kDelta;
+ PushSpecial(&fst_copy, delta);
+
+ Weight min, max;
+ float delta_dontcare = 0.1;
+ IsStochasticFstInLog(fst_copy, delta_dontcare, &min, &max);
+ // the per-state normalizers are allowed to deviate from the average by delta
+ // up and down, so the difference from the min to max weight should be 2*delta
+ // or less. We give it a bit of wiggle room (->2.5) due to numerical roundoff.
+
+
+ {
+ FstPrinter<Arc> fstprinter(fst_copy, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ KALDI_LOG << "Min value is " << min.Value() << ", max value is " << max.Value();
+
+ // below, should be <= delta but different pieces of code compute this in this
+ // part vs. push-special, so the roundoff may be different.
+ KALDI_ASSERT(std::abs(min.Value() - max.Value()) <= 1.2 * delta);
+
+ KALDI_ASSERT(RandEquivalent(*fst, fst_copy,
+ 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ delete fst;
+}
+
+
+} // namespace fst
+
+int main() {
+ kaldi::g_kaldi_verbose_level = 4;
+ using namespace fst;
+ for (int i = 0; i < 25; i++) {
+ TestPushSpecial();
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/push-special.cc b/runtime/onnxruntime/third_party/kaldi/fstext/push-special.cc
new file mode 100644
index 000000000..91207ca1c
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/push-special.cc
@@ -0,0 +1,269 @@
+// fstext/push-special.cc
+
+// Copyright 2012 Johns Hopkins University (author: Daniel Povey)
+// 2012 Ehsan Variani, Pegah Ghahrmani
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "fstext/push-special.h"
+#include "base/kaldi-error.h"
+#include "base/kaldi-math.h"
+
+namespace fst {
+
+
+/*
+
+ This algorithm was briefly described in "COMBINING FORWARD AND BACKWARD SEARCH
+ IN DECODING" by Hannemann and Povey, ICASSP 2013,
+ http://www.danielpovey.com/files/2013_icassp_pingpong.pdf
+
+ Below is the most relevant excerpt of the LaTeX source.
+
+Real backoff language models represented as WFSTs (\cite{Mohri:08}) will not
+exactly sum to one because the backoff structure leads to duplicate paths for
+some word sequences. In fact, such language models cannot be pushed at all in
+the general case, because the total weight of the entire WFST may not be finite.
+For our language model reversal we need a suitable pushing operation that will
+always succeed.
+
+Our solution is to require a modified pushing operation such that each state
+``sums to'' the same quantity.
+We were able to find an iterative algorithm that does this very efficiently in practice;
+it is based on the power method for finding the top eigenvalue of a matrix.
+Both for the math and the implementation, we find it more convenient to
+use the probability semiring, i.e. we represent the transition-probabilities
+as actual probabilities, not negative logs.
+Let the transitions be written as a sparse matrix $\mathbf{P}$,
+where $p_{ij}$ is the sum of all the probabilities of transitions between state $i$ and state $j$.
+As a special case, if $j$ is the initial state,
+then $p_{ij}$ is the final-probability of state $i$.
+In our method we find the dominant eigenvector $\mathbf{v}$ of the matrix $\mathbf{P}$,
+by starting from a random positive vector and iterating with the power method:
+each time we let $\mathbf{v} \leftarrow \mathbf{P} \mathbf{v}$
+and then renormalize the length of $\mathbf{v}$.
+It is convenient to renormalize $\mathbf{v}$ so that $v_I$ is 1,
+where $I$ is the initial state of the WFST\footnote{Note: in order to correctly
+deal with the case of linear WFSTs, which have different eigenvalues
+with the same magnitude but different complex phase,
+we modify the iteration to $\mathbf{v} \leftarrow \mathbf{P} \mathbf{v} + 0.1 \mathbf{v}$.}.
+This generally converges within several tens of iterations.
+At the end we have a vector $\mathbf{v}$ with $v_I = 1$, and a scalar $\lambda > 0$, such that
+\begin{equation}
+ \lambda \mathbf{v} = \mathbf{P} \mathbf{v} . \label{eqn:lambdav}
+\end{equation}
+Suppose we compute a modified transition matrix $\mathbf{P}'$, by letting
+\begin{equation}
+ p'_{ij} = p_{ij} v_j / v_i .
+\end{equation}
+Then it is easy to show each row of $\mathbf{P}'$ sums to $\lambda$:
+writing one element of Eq.~\ref{eqn:lambdav} as
+\begin{equation}
+ \lambda v_i = \sum_j p_{ij} v_j,
+\end{equation}
+it easily follows that $\lambda = \sum_j p'_{ij}$.
+We need to perform a similar transformation on the transition-probabilities and
+final-probabilities of the WFST; the details are quite obvious, and the
+equivalence with the original WFST is easy to show. Our algorithm is in
+practice an order of magnitude faster than the more generic algorithm for
+conventional weight-pushing of \cite{Mohri:02}, when applied to cyclic WFSTs.
+
+ */
+
+class PushSpecialClass {
+ typedef StdArc Arc;
+ typedef Arc::Weight Weight;
+ typedef Arc::StateId StateId;
+
+ public:
+ // Everything happens in the initializer.
+ PushSpecialClass(VectorFst<StdArc> *fst,
+ float delta): fst_(fst) {
+ num_states_ = fst_->NumStates();
+ initial_state_ = fst_->Start();
+ occ_.resize(num_states_, 1.0 / sqrt(num_states_)); // unit length
+
+ pred_.resize(num_states_);
+ for (StateId s = 0; s < num_states_; s++) {
+ for (ArcIterator<VectorFst<StdArc> > aiter(*fst, s);
+ !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ StateId t = arc.nextstate;
+ double weight = kaldi::Exp(-arc.weight.Value());
+ pred_[t].push_back(std::make_pair(s, weight));
+ }
+ double final = kaldi::Exp(-fst_->Final(s).Value());
+ if (final != 0.0)
+ pred_[initial_state_].push_back(std::make_pair(s, final));
+ }
+ Iterate(delta);
+ ModifyFst();
+ }
+ private:
+ double TestAccuracy() { // returns the error (the difference
+ // between the min and max weights).
+ double min_sum = 0, max_sum = 0;
+ for (StateId s = 0; s < num_states_; s++) {
+ double sum = 0.0;
+ for (ArcIterator<VectorFst<StdArc> > aiter(*fst_, s);
+ !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ StateId t = arc.nextstate;
+ sum += kaldi::Exp(-arc.weight.Value()) * occ_[t] / occ_[s];
+ }
+ sum += kaldi::Exp(-(fst_->Final(s).Value())) * occ_[initial_state_] / occ_[s];
+ if (s == 0) {
+ min_sum = sum;
+ max_sum = sum;
+ } else {
+ min_sum = std::min(min_sum, sum);
+ max_sum = std::max(max_sum, sum);
+ }
+ }
+ KALDI_VLOG(4) << "min,max is " << min_sum << " " << max_sum;
+ return kaldi::Log(max_sum / min_sum); // In FST world we'll actually
+ // dealing with logs, so the log of the ratio is more suitable
+ // to compare with delta (makes testing the algorithm easier).
+ }
+
+
+ void Iterate(float delta) {
+ // This is like the power method to find the top eigenvalue of a matrix.
+ // We limit it to 200 iters max, just in case something unanticipated
+ // happens, but we should exit due to the "delta" thing, usually after
+ // several tens of iterations.
+ int iter, max_iter = 200;
+
+ for (iter = 0; iter < max_iter; iter++) {
+ std::vector<double> new_occ(num_states_);
+ // We initialize new_occ to 0.1 * occ. A simpler algorithm would
+ // initialize them to zero, so it's like the pure power method. This is
+ // like the power method on (M + 0.1 I), and we do it this way to avoid a
+ // problem we encountered with certain very simple linear FSTs where the
+ // eigenvalues of the weight matrix (including negative and imaginary
+ // ones) all have the same magnitude.
+ for (int i = 0; i < num_states_; i++)
+ new_occ[i] = 0.1 * occ_[i];
+
+ for (int i = 0; i < num_states_; i++) {
+ std::vector<std::pair<StateId, double> >::const_iterator iter,
+ end = pred_[i].end();
+ for (iter = pred_[i].begin(); iter != end; ++iter) {
+ StateId j = iter->first;
+ double p = iter->second;
+ new_occ[j] += occ_[i] * p;
+ }
+ }
+ double sumsq = 0.0;
+ for (int i = 0; i < num_states_; i++) sumsq += new_occ[i] * new_occ[i];
+ lambda_ = std::sqrt(sumsq);
+ double inv_lambda = 1.0 / lambda_;
+ for (int i = 0; i < num_states_; i++) occ_[i] = new_occ[i] * inv_lambda;
+ KALDI_VLOG(4) << "Lambda is " << lambda_;
+ if (iter % 5 == 0 && iter > 0 && TestAccuracy() <= delta) {
+ KALDI_VLOG(3) << "Weight-pushing converged after " << iter
+ << " iterations.";
+ return;
+ }
+ }
+ KALDI_WARN << "push-special: finished " << iter
+ << " iterations without converging. Output will be inaccurate.";
+ }
+
+
+ // Modifies the FST weights and the final-prob to take account of these potentials.
+ void ModifyFst() {
+ // First get the potentials as negative-logs, like the values
+ // in the FST.
+ for (StateId s = 0; s < num_states_; s++) {
+ occ_[s] = -kaldi::Log(occ_[s]);
+ if (KALDI_ISNAN(occ_[s]) || KALDI_ISINF(occ_[s]))
+ KALDI_WARN << "NaN or inf found: " << occ_[s];
+ }
+ for (StateId s = 0; s < num_states_; s++) {
+ for (MutableArcIterator<VectorFst<StdArc> > aiter(fst_, s);
+ !aiter.Done(); aiter.Next()) {
+ Arc arc = aiter.Value();
+ StateId t = arc.nextstate;
+ arc.weight = Weight(arc.weight.Value() + occ_[t] - occ_[s]);
+ aiter.SetValue(arc);
+ }
+ fst_->SetFinal(s, Times(fst_->Final(s).Value(),
+ Weight(occ_[initial_state_] - occ_[s])));
+ }
+ }
+
+ private:
+ StateId num_states_;
+ StateId initial_state_;
+ std::vector<double> occ_; // the top eigenvector of (matrix of weights) transposed.
+ double lambda_; // our current estimate of the top eigenvalue.
+
+ std::vector<std::vector<std::pair<StateId, double> > > pred_; // List of transitions
+ // into each state. For the start state, this list consists of the list of
+ // states with final-probs, each with their final prob.
+
+ VectorFst<StdArc> *fst_;
+
+};
+
+
+
+
+void PushSpecial(VectorFst<StdArc> *fst, float delta) {
+ if (fst->NumStates() > 0)
+ PushSpecialClass c(fst, delta); // all the work
+ // gets done in the initializer.
+}
+
+
+} // end namespace fst.
+
+
+/*
+ Note: in testing an earlier, simpler
+ version of this method (without the 0.1 * old_occ) we had a problem with the following FST.
+0 2 3 3 0
+1 3 1 4 0.5
+2 1 0 0 0.5
+3 0.25
+
+ Corresponds to the following matrix [or maybe its transpose, doesn't matter
+ probably]
+
+ a=exp(-0.5)
+ b=exp(-0.25)
+M = [ 0 1 0 0
+ 0 0 a 0
+ 0 0 0 a
+ b 0 0 0 ]
+
+eigs(M)
+eigs(M)
+
+ans =
+
+ -0.0000 - 0.7316i
+ -0.0000 + 0.7316i
+ 0.7316
+ -0.7316
+
+ OK, so the issue appears to be that all the eigenvalues of this matrix
+ have the same magnitude. The solution is to work with the eigenvalues
+ of M + alpha I, for some small alpha such as 0.1 (so as not to slow down
+ convergence in the normal case).
+
+*/
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/push-special.h b/runtime/onnxruntime/third_party/kaldi/fstext/push-special.h
new file mode 100644
index 000000000..49e1babd4
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/push-special.h
@@ -0,0 +1,42 @@
+// fstext/push-special.h
+
+// Copyright 2012-2015 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_PUSH_SPECIAL_H_
+#define KALDI_FSTEXT_PUSH_SPECIAL_H_
+
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+#include "util/const-integer-set.h"
+
+namespace fst {
+
+/*
+ This function does weight-pushing, in the log semiring,
+ but in a special way, such that any "leftover weight" after pushing
+ gets distributed evenly along the FST, and doesn't end up either
+ at the start or at the end. Basically it pushes the weights such
+ that the total weight of each state (i.e. the sum of the arc
+ probabilities plus the final-prob) is the same for all states.
+*/
+void PushSpecial(VectorFst<StdArc> *fst,
+ float delta = kDelta);
+
+}
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/rand-fst.h b/runtime/onnxruntime/third_party/kaldi/fstext/rand-fst.h
new file mode 100644
index 000000000..56ba250e1
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/rand-fst.h
@@ -0,0 +1,162 @@
+// fstext/rand-fst.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_RAND_FST_H_
+#define KALDI_FSTEXT_RAND_FST_H_
+
+#include <sstream>
+#include <string>
+
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+#include "base/kaldi-math.h"
+
+namespace fst {
+
+// Note: all weights are constructed from nonnegative floats.
+// (so no "negative costs").
+struct RandFstOptions {
+ size_t n_syms;
+ size_t n_states;
+ size_t n_arcs;
+ size_t n_final;
+ bool allow_empty;
+ bool acyclic;
+ float weight_multiplier;
+ RandFstOptions() { // Initializes the options randomly.
+ n_syms = 2 + kaldi::Rand() % 5;
+ n_states = 3 + kaldi::Rand() % 10;
+ n_arcs = 5 + kaldi::Rand() % 30;
+ n_final = 1 + kaldi::Rand()%3;
+ allow_empty = true;
+ acyclic = false;
+ weight_multiplier = 0.25;
+ }
+};
+
+
+/// Returns a random FST. Useful for randomized algorithm testing.
+/// Only works if weight can be constructed from float.
+template<class Arc> VectorFst<Arc>* RandFst(RandFstOptions opts = RandFstOptions() ) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = new VectorFst<Arc>();
+
+ start:
+
+ // Create states.
+ std::vector<StateId> all_states;
+ for (size_t i = 0;i < (size_t)opts.n_states;i++) {
+ StateId this_state = fst->AddState();
+ if (i == 0) fst->SetStart(i);
+ all_states.push_back(this_state);
+ }
+ // Set final states.
+ for (size_t j = 0;j < (size_t)opts.n_final;j++) {
+ StateId id = all_states[kaldi::Rand() % opts.n_states];
+ Weight weight = (Weight)(opts.weight_multiplier*(kaldi::Rand() % 5));
+ fst->SetFinal(id, weight);
+ }
+ // Create arcs.
+ for (size_t i = 0;i < (size_t)opts.n_arcs;i++) {
+ Arc a;
+ StateId start_state;
+ if(!opts.acyclic) { // no restriction on arcs.
+ start_state = all_states[kaldi::Rand() % opts.n_states];
+ a.nextstate = all_states[kaldi::Rand() % opts.n_states];
+ } else {
+ start_state = all_states[kaldi::Rand() % (opts.n_states-1)];
+ a.nextstate = start_state + 1 + (kaldi::Rand() % (opts.n_states-start_state-1));
+ }
+ a.ilabel = kaldi::Rand() % opts.n_syms;
+ a.olabel = kaldi::Rand() % opts.n_syms; // same input+output vocab.
+ a.weight = (Weight) (opts.weight_multiplier*(kaldi::Rand() % 4));
+
+ fst->AddArc(start_state, a);
+ }
+
+ // Trim resulting FST.
+ Connect(fst);
+ if (opts.acyclic)
+ assert(fst->Properties(kAcyclic, true) & kAcyclic);
+ if (fst->Start() == kNoStateId && !opts.allow_empty) {
+ goto start;
+ }
+ return fst;
+}
+
+
+/// Returns a random FST. Useful for randomized algorithm testing.
+/// Only works if weight can be constructed from a pair of floats
+template<class Arc> VectorFst<Arc>* RandPairFst(RandFstOptions opts = RandFstOptions() ) {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = new VectorFst<Arc>();
+
+ start:
+
+ // Create states.
+ std::vector<StateId> all_states;
+ for (size_t i = 0;i < (size_t)opts.n_states;i++) {
+ StateId this_state = fst->AddState();
+ if (i == 0) fst->SetStart(i);
+ all_states.push_back(this_state);
+ }
+ // Set final states.
+ for (size_t j = 0; j < (size_t)opts.n_final;j++) {
+ StateId id = all_states[kaldi::Rand() % opts.n_states];
+ Weight weight (opts.weight_multiplier*(kaldi::Rand() % 5), opts.weight_multiplier*(kaldi::Rand() % 5));
+ fst->SetFinal(id, weight);
+ }
+ // Create arcs.
+ for (size_t i = 0;i < (size_t)opts.n_arcs;i++) {
+ Arc a;
+ StateId start_state;
+ if(!opts.acyclic) { // no restriction on arcs.
+ start_state = all_states[kaldi::Rand() % opts.n_states];
+ a.nextstate = all_states[kaldi::Rand() % opts.n_states];
+ } else {
+ start_state = all_states[kaldi::Rand() % (opts.n_states-1)];
+ a.nextstate = start_state + 1 + (kaldi::Rand() % (opts.n_states-start_state-1));
+ }
+ a.ilabel = kaldi::Rand() % opts.n_syms;
+ a.olabel = kaldi::Rand() % opts.n_syms; // same input+output vocab.
+ a.weight = Weight (opts.weight_multiplier*(kaldi::Rand() % 4), opts.weight_multiplier*(kaldi::Rand() % 4));
+
+ fst->AddArc(start_state, a);
+ }
+
+ // Trim resulting FST.
+ Connect(fst);
+ if (opts.acyclic)
+ assert(fst->Properties(kAcyclic, true) & kAcyclic);
+ if (fst->Start() == kNoStateId && !opts.allow_empty) {
+ goto start;
+ }
+ return fst;
+}
+
+
+} // end namespace fst.
+
+
+#endif
+
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/remove-eps-local-inl.h b/runtime/onnxruntime/third_party/kaldi/fstext/remove-eps-local-inl.h
new file mode 100644
index 000000000..8590bab22
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/remove-eps-local-inl.h
@@ -0,0 +1,321 @@
+// fstext/remove-eps-local-inl.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2014 Johns Hopkins University (author: Daniel Povey
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_REMOVE_EPS_LOCAL_INL_H_
+#define KALDI_FSTEXT_REMOVE_EPS_LOCAL_INL_H_
+
+
+namespace fst {
+
+
+template<class Weight>
+struct ReweightPlusDefault {
+ inline Weight operator () (const Weight &a, const Weight &b) {
+ return Plus(a, b);
+ }
+};
+
+struct ReweightPlusLogArc {
+ inline TropicalWeight operator () (const TropicalWeight &a,
+ const TropicalWeight &b) {
+ LogWeight a_log(a.Value()), b_log(b.Value());
+ return TropicalWeight(Plus(a_log, b_log).Value());
+ }
+};
+
+
+
+template<class Arc, class ReweightPlus = ReweightPlusDefault<typename Arc::Weight> >
+class RemoveEpsLocalClass {
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Label Label;
+ typedef typename Arc::Weight Weight;
+
+ public:
+ RemoveEpsLocalClass(MutableFst<Arc> *fst):
+ fst_(fst) {
+ if (fst_->Start() == kNoStateId) return; // empty.
+ non_coacc_state_ = fst_->AddState();
+ InitNumArcs();
+ StateId num_states = fst_->NumStates();
+ for (StateId s = 0; s < num_states; s++)
+ for (size_t pos = 0; pos < fst_->NumArcs(s); pos++)
+ RemoveEps(s, pos);
+ assert(CheckNumArcs());
+ Connect(fst); // remove inaccessible states.
+ }
+ private:
+ MutableFst<Arc> *fst_;
+ StateId non_coacc_state_; // use this to delete arcs: make it nextstate
+ std::vector<StateId> num_arcs_in_; // The number of arcs into the state, plus one
+ // if it's the start state.
+ std::vector<StateId> num_arcs_out_; // The number of arcs out of the state, plus
+ // one if it's a final state.
+ ReweightPlus reweight_plus_;
+
+ bool CanCombineArcs(const Arc &a, const Arc &b, Arc *c) {
+ if (a.ilabel != 0 && b.ilabel != 0) return false;
+ if (a.olabel != 0 && b.olabel != 0) return false;
+ c->weight = Times(a.weight, b.weight);
+ c->ilabel = (a.ilabel != 0 ? a.ilabel : b.ilabel);
+ c->olabel = (a.olabel != 0 ? a.olabel : b.olabel);
+ c->nextstate = b.nextstate;
+ return true;
+ }
+
+ static bool CanCombineFinal(const Arc &a, Weight final_prob, Weight *final_prob_out) {
+ if (a.ilabel != 0 || a.olabel != 0) return false;
+ else {
+ *final_prob_out = Times(a.weight, final_prob);
+ return true;
+ }
+ }
+
+ void InitNumArcs() { // init num transitions in/out of each state.
+ StateId num_states = fst_->NumStates();
+ num_arcs_in_.resize(num_states);
+ num_arcs_out_.resize(num_states);
+ num_arcs_in_[fst_->Start()]++; // count start as trans in.
+ for (StateId s = 0; s < num_states; s++) {
+ if (fst_->Final(s) != Weight::Zero())
+ num_arcs_out_[s]++; // count final as transition.
+ for (ArcIterator<MutableFst<Arc> > aiter(*fst_, s); !aiter.Done(); aiter.Next()) {
+ num_arcs_in_[aiter.Value().nextstate]++;
+ num_arcs_out_[s]++;
+ }
+ }
+ }
+
+ bool CheckNumArcs() { // check num arcs in/out of each state, at end. Debug.
+ num_arcs_in_[fst_->Start()]--; // count start as trans in.
+ StateId num_states = fst_->NumStates();
+ for (StateId s = 0; s < num_states; s++) {
+ if (s == non_coacc_state_) continue;
+ if (fst_->Final(s) != Weight::Zero())
+ num_arcs_out_[s]--; // count final as transition.
+ for (ArcIterator<MutableFst<Arc> > aiter(*fst_, s); !aiter.Done(); aiter.Next()) {
+ if (aiter.Value().nextstate == non_coacc_state_) continue;
+ num_arcs_in_[aiter.Value().nextstate]--;
+ num_arcs_out_[s]--;
+ }
+ }
+ for (StateId s = 0; s < num_states; s++) {
+ assert(num_arcs_in_[s] == 0);
+ assert(num_arcs_out_[s] == 0);
+ }
+ return true; // always does this. so we can assert it w/o warnings.
+ }
+
+ inline void GetArc(StateId s, size_t pos, Arc *arc) const {
+ ArcIterator<MutableFst<Arc> > aiter(*fst_, s);
+ aiter.Seek(pos);
+ *arc = aiter.Value();
+ }
+
+ inline void SetArc(StateId s, size_t pos, const Arc &arc) {
+ MutableArcIterator<MutableFst<Arc> > aiter(fst_, s);
+ aiter.Seek(pos);
+ aiter.SetValue(arc);
+ }
+
+
+ void Reweight(StateId s, size_t pos, Weight reweight) {
+ // Reweight is called from RemoveEpsPattern1; it is a step we
+ // do to preserve stochasticity. This function multiplies the
+ // arc at (s, pos) by reweight and divides all the arcs [+final-prob]
+ // out of the next state by the same. This is only valid if
+ // the next state has only one arc in and is not the start state.
+ assert(reweight != Weight::Zero());
+ MutableArcIterator<MutableFst<Arc> > aiter(fst_, s);
+ aiter.Seek(pos);
+ Arc arc = aiter.Value();
+ assert(num_arcs_in_[arc.nextstate] == 1);
+ arc.weight = Times(arc.weight, reweight);
+ aiter.SetValue(arc);
+
+ for (MutableArcIterator<MutableFst<Arc> > aiter_next(fst_, arc.nextstate);
+ !aiter_next.Done();
+ aiter_next.Next()) {
+ Arc nextarc = aiter_next.Value();
+ if (nextarc.nextstate != non_coacc_state_) {
+ nextarc.weight = Divide(nextarc.weight, reweight, DIVIDE_LEFT);
+ aiter_next.SetValue(nextarc);
+ }
+ }
+ Weight final = fst_->Final(arc.nextstate);
+ if (final != Weight::Zero()) {
+ fst_->SetFinal(arc.nextstate, Divide(final, reweight, DIVIDE_LEFT));
+ }
+ }
+
+ // RemoveEpsPattern1 applies where this arc, which is not a
+ // self-loop, enters a state which has only one input transition
+ // [and is not the start state], and has multiple output
+ // transitions [counting being the final-state as a final-transition].
+
+ void RemoveEpsPattern1(StateId s, size_t pos, Arc arc) {
+ const StateId nextstate = arc.nextstate;
+ Weight total_removed = Weight::Zero(),
+ total_kept = Weight::Zero(); // totals out of nextstate.
+ std::vector<Arc> arcs_to_add; // to add to state s.
+ for (MutableArcIterator<MutableFst<Arc> > aiter_next(fst_, nextstate);
+ !aiter_next.Done();
+ aiter_next.Next()) {
+ Arc nextarc = aiter_next.Value();
+ if (nextarc.nextstate == non_coacc_state_) continue; // deleted.
+ Arc combined;
+ if (CanCombineArcs(arc, nextarc, &combined)) {
+ total_removed = reweight_plus_(total_removed, nextarc.weight);
+ num_arcs_out_[nextstate]--;
+ num_arcs_in_[nextarc.nextstate]--;
+ nextarc.nextstate = non_coacc_state_;
+ aiter_next.SetValue(nextarc);
+ arcs_to_add.push_back(combined);
+ } else {
+ total_kept = reweight_plus_(total_kept, nextarc.weight);
+ }
+ }
+
+ { // now final-state.
+ Weight next_final = fst_->Final(nextstate);
+ if (next_final != Weight::Zero()) {
+ Weight new_final;
+ if (CanCombineFinal(arc, next_final, &new_final)) {
+ total_removed = reweight_plus_(total_removed, next_final);
+ if (fst_->Final(s) == Weight::Zero())
+ num_arcs_out_[s]++; // final is counted as arc.
+ fst_->SetFinal(s, Plus(fst_->Final(s), new_final));
+ num_arcs_out_[nextstate]--;
+ fst_->SetFinal(nextstate, Weight::Zero());
+ } else {
+ total_kept = reweight_plus_(total_kept, next_final);
+ }
+ }
+ }
+
+ if (total_removed != Weight::Zero()) { // did something...
+ if (total_kept == Weight::Zero()) { // removed everything: remove arc.
+ num_arcs_out_[s]--;
+ num_arcs_in_[arc.nextstate]--;
+ arc.nextstate = non_coacc_state_;
+ SetArc(s, pos, arc);
+ } else {
+ // Have to reweight.
+ Weight total = reweight_plus_(total_removed, total_kept);
+ Weight reweight = Divide(total_kept, total, DIVIDE_LEFT); // <=1
+ Reweight(s, pos, reweight);
+ }
+ }
+ // Now add the arcs we were going to add.
+ for (size_t i = 0; i < arcs_to_add.size(); i++) {
+ num_arcs_out_[s]++;
+ num_arcs_in_[arcs_to_add[i].nextstate]++;
+ fst_->AddArc(s, arcs_to_add[i]);
+ }
+ }
+
+ void RemoveEpsPattern2(StateId s, size_t pos, Arc arc) {
+
+ // Pattern 2 is where "nextstate" has only one arc out, counting
+ // being-the-final-state as an arc, but possibly multiple arcs in.
+ // Also, nextstate != s.
+
+ const StateId nextstate = arc.nextstate;
+ bool can_delete_next = (num_arcs_in_[nextstate] == 1); // if
+ // we combine, can delete the corresponding out-arc/final-prob
+ // of nextstate.
+ bool delete_arc = false; // set to true if this arc to be deleted.
+
+ Weight next_final = fst_->Final(arc.nextstate);
+ if (next_final != Weight::Zero()) { // nextstate has no actual arcs out, only final-prob.
+ Weight new_final;
+ if (CanCombineFinal(arc, next_final, &new_final)) {
+ if (fst_->Final(s) == Weight::Zero())
+ num_arcs_out_[s]++; // final is counted as arc.
+ fst_->SetFinal(s, Plus(fst_->Final(s), new_final));
+ delete_arc = true; // will delete "arc".
+ if (can_delete_next) {
+ num_arcs_out_[nextstate]--;
+ fst_->SetFinal(nextstate, Weight::Zero());
+ }
+ }
+ } else { // has an arc but no final prob.
+ MutableArcIterator<MutableFst<Arc> > aiter_next(fst_, nextstate);
+ assert(!aiter_next.Done());
+ while (aiter_next.Value().nextstate == non_coacc_state_) {
+ aiter_next.Next();
+ assert(!aiter_next.Done());
+ }
+ // now aiter_next points to a real arc out of nextstate.
+ Arc nextarc = aiter_next.Value();
+ Arc combined;
+ if (CanCombineArcs(arc, nextarc, &combined)) {
+ delete_arc = true;
+ if (can_delete_next) { // do it before we invalidate iterators
+ num_arcs_out_[nextstate]--;
+ num_arcs_in_[nextarc.nextstate]--;
+ nextarc.nextstate = non_coacc_state_;
+ aiter_next.SetValue(nextarc);
+ }
+ num_arcs_out_[s]++;
+ num_arcs_in_[combined.nextstate]++;
+ fst_->AddArc(s, combined);
+ }
+ }
+ if (delete_arc) {
+ num_arcs_out_[s]--;
+ num_arcs_in_[nextstate]--;
+ arc.nextstate = non_coacc_state_;
+ SetArc(s, pos, arc);
+ }
+ }
+
+ void RemoveEps(StateId s, size_t pos) {
+ // Tries to do local epsilon-removal for arc sequences starting with this arc
+ Arc arc;
+ GetArc(s, pos, &arc);
+ StateId nextstate = arc.nextstate;
+ if (nextstate == non_coacc_state_) return; // deleted arc.
+ if (nextstate == s) return; // don't handle self-loops: too complex.
+
+ if (num_arcs_in_[nextstate] == 1 && num_arcs_out_[nextstate] > 1) {
+ RemoveEpsPattern1(s, pos, arc);
+ } else if (num_arcs_out_[nextstate] == 1) {
+ RemoveEpsPattern2(s, pos, arc);
+ }
+ }
+
+};
+
+
+template<class Arc>
+void RemoveEpsLocal(MutableFst<Arc> *fst) {
+ RemoveEpsLocalClass<Arc> c(fst); // work gets done in initializer.
+}
+
+
+void RemoveEpsLocalSpecial(MutableFst<StdArc> *fst) {
+ // work gets done in initializer.
+ RemoveEpsLocalClass<StdArc, ReweightPlusLogArc> c(fst);
+}
+
+} // end namespace fst.
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/remove-eps-local-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/remove-eps-local-test.cc
new file mode 100644
index 000000000..80cca875f
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/remove-eps-local-test.cc
@@ -0,0 +1,178 @@
+// fstext/remove-eps-local-test.cc
+
+// Copyright 2009-2012 Microsoft Corporation Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "fstext/remove-eps-local.h"
+#include "fstext/fstext-utils.h"
+#include "fstext/fst-test-utils.h"
+#include "base/kaldi-math.h"
+
+
+namespace fst
+{
+using std::vector;
+using std::cout;
+
+// Don't instantiate with log semiring, as RandEquivalent may fail.
+template<class Arc> static void TestRemoveEpsLocal() {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> fst;
+ int n_syms = 2 + kaldi::Rand() % 5, n_arcs = 5 + kaldi::Rand() % 30, n_final = 1 + kaldi::Rand()%10;
+
+ SymbolTable symtab("my-symbol-table"), *sptr = &symtab;
+
+ vector<Label> all_syms; // including epsilon.
+ // Put symbols in the symbol table from 1..n_syms-1.
+ for (size_t i = 0;i < (size_t)n_syms;i++) {
+ std::stringstream ss;
+ if (i == 0) ss << "<eps>";
+ else ss<<i;
+ Label cur_lab = sptr->AddSymbol(ss.str());
+ assert(cur_lab == (Label)i);
+ all_syms.push_back(cur_lab);
+ }
+ assert(all_syms[0] == 0);
+
+ fst.AddState();
+ int cur_num_states = 1;
+ for (int i = 0; i < n_arcs; i++) {
+ StateId src_state = kaldi::Rand() % cur_num_states;
+ StateId dst_state;
+ if (kaldi::RandUniform() < 0.1) dst_state = kaldi::Rand() % cur_num_states;
+ else {
+ dst_state = cur_num_states++; fst.AddState();
+ }
+ Arc arc;
+ if (kaldi::RandUniform() < 0.3) arc.ilabel = all_syms[kaldi::Rand()%all_syms.size()];
+ else arc.ilabel = 0;
+ if (kaldi::RandUniform() < 0.3) arc.olabel = all_syms[kaldi::Rand()%all_syms.size()];
+ else arc.olabel = 0;
+ arc.weight = (Weight) (0 + 0.1*(kaldi::Rand() % 5));
+ arc.nextstate = dst_state;
+ fst.AddArc(src_state, arc);
+ }
+ for (int i = 0; i < n_final; i++) {
+ fst.SetFinal(kaldi::Rand() % cur_num_states, (Weight) (0 + 0.1*(kaldi::Rand() % 5)));
+ }
+
+ if (kaldi::RandUniform() < 0.8) fst.SetStart(0); // usually leads to nicer examples.
+ else fst.SetStart(kaldi::Rand() % cur_num_states);
+
+ Connect(&fst);
+ if (fst.Start() == kNoStateId) return; // "Connect" made it empty.
+
+ std::cout <<" printing after trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ VectorFst<Arc> fst_copy1(fst);
+
+
+ RemoveEpsLocal(&fst_copy1);
+
+
+
+ {
+ std::cout << "copy1 = \n";
+ FstPrinter<Arc> fstprinter(fst_copy1, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ int num_states_0 = fst.NumStates();
+ int num_states_1 = fst_copy1.NumStates();
+
+
+ std::cout << "Number of states 0 = "<<num_states_0<<", 1 = "<<num_states_1<<'\n';
+
+ assert(RandEquivalent(fst, fst_copy1, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+}
+
+
+static void TestRemoveEpsLocalSpecial() {
+ // test that RemoveEpsLocalSpecial preserves equivalence in tropical while
+ // maintaining stochasticity in log.
+ typedef VectorFst<LogArc> Fst;
+ typedef LogArc::Weight Weight;
+ typedef LogArc::StateId StateId;
+ typedef LogArc Arc;
+ VectorFst<LogArc> *logfst = RandFst<LogArc>();
+
+ { // Make the FST stochastic.
+ for (StateId s = 0; s < logfst->NumStates(); s++) {
+ Weight w = logfst->Final(s);
+ for (ArcIterator<Fst> aiter(*logfst, s); !aiter.Done(); aiter.Next()) {
+ w = Plus(w, aiter.Value().weight);
+ }
+ if (w != Weight::Zero()) {
+ logfst->SetFinal(s, Divide(logfst->Final(s), w, DIVIDE_ANY));
+ for (MutableArcIterator<Fst> aiter(logfst, s); !aiter.Done(); aiter.Next()) {
+ Arc a = aiter.Value();
+ a.weight = Divide(a.weight, w, DIVIDE_ANY);
+ aiter.SetValue(a);
+ }
+ }
+ }
+ }
+#ifndef _MSC_VER
+ assert(IsStochasticFst(*logfst, kDelta*10));
+#endif
+ {
+ std::cout << "logfst = \n";
+ FstPrinter<LogArc> fstprinter(*logfst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ VectorFst<StdArc> fst;
+ Cast(*logfst, &fst);
+ VectorFst<StdArc> fst_copy(fst);
+ RemoveEpsLocalSpecial(&fst); // removes eps in std-arc but keep stochastic in log-arc
+ // make sure equivalent.
+ assert(RandEquivalent(fst, fst_copy, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+ VectorFst<LogArc> logfst2;
+ Cast(fst, &logfst2);
+
+ {
+ std::cout << "logfst2 = \n";
+ FstPrinter<LogArc> fstprinter(logfst2, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ if (ApproxEqual(ShortestDistance(*logfst), ShortestDistance(logfst2))) {
+ // make sure we preserved stochasticity in cases where doing so was
+ // possible... if the log-semiring total weight changed, then it is
+ // not possible so don't assert this.
+ assert(IsStochasticFst(logfst2, kDelta*10));
+ }
+ delete logfst;
+}
+
+} // namespace fst
+
+int main() {
+ using namespace fst;
+ for (int i = 0; i < 10; i++) {
+ TestRemoveEpsLocal<fst::StdArc>();
+ TestRemoveEpsLocalSpecial();
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/remove-eps-local.h b/runtime/onnxruntime/third_party/kaldi/fstext/remove-eps-local.h
new file mode 100644
index 000000000..c45226c11
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/remove-eps-local.h
@@ -0,0 +1,60 @@
+// fstext/remove-eps-local.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2014 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_REMOVE_EPS_LOCAL_H_
+#define KALDI_FSTEXT_REMOVE_EPS_LOCAL_H_
+
+
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+
+namespace fst {
+
+
+/// RemoveEpsLocal remove some (but not necessarily all) epsilons in an FST,
+/// using an algorithm that is guaranteed to never increase the number of arcs
+/// in the FST (and will also never increase the number of states). The
+/// algorithm is not optimal but is reasonably clever. It does not just remove
+/// epsilon arcs;it also combines pairs of input-epsilon and output-epsilon arcs
+/// into one.
+/// The algorithm preserves equivalence and stochasticity in the given semiring.
+/// If you want to preserve stochasticity in a different semiring (e.g. log),
+/// then use RemoveEpsLocalSpecial, which only works for StdArc but which
+/// preserves stochasticity, where possible (*) in the LogArc sense. The reason that we can't
+/// just cast to a different semiring is that in that case we would no longer
+/// be able to guarantee equivalence in the original semiring (this arises from
+/// what happens when we combine identical arcs).
+/// (*) by "where possible".. there are situations where we wouldn't be able to
+/// preserve stochasticity in the LogArc sense while maintaining equivalence in
+/// the StdArc sense, so in these situations we maintain equivalence.
+
+template<class Arc>
+void RemoveEpsLocal(MutableFst<Arc> *fst);
+
+/// As RemoveEpsLocal but takes care to preserve stochasticity
+/// when cast to LogArc.
+inline void RemoveEpsLocalSpecial(MutableFst<StdArc> *fst);
+
+
+} // namespace fst
+
+#include "remove-eps-local-inl.h"
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/table-matcher-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/table-matcher-test.cc
new file mode 100644
index 000000000..2d39fe957
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/table-matcher-test.cc
@@ -0,0 +1,257 @@
+// fstext/table-matcher-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "fstext/table-matcher.h"
+#include "fstext/fst-test-utils.h"
+#include "base/kaldi-math.h"
+
+namespace fst{
+
+
+// Don't instantiate with log semiring, as RandEquivalent may fail.
+template<class Arc> void TestTableMatcher(bool connect, bool left) {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+
+ VectorFst<Arc> *fst1 = RandFst<Arc>();
+
+ VectorFst<Arc> *fst2 = RandFst<Arc>();
+
+ ILabelCompare<Arc> ilabel_comp;
+ OLabelCompare<Arc> olabel_comp;
+
+ TableComposeOptions opts;
+ if (left) opts.table_match_type = MATCH_OUTPUT;
+ else opts.table_match_type = MATCH_INPUT;
+ opts.min_table_size = 1 + kaldi::Rand() % 5;
+ opts.table_ratio = 0.25 * (kaldi::Rand() % 5);
+ opts.connect = connect;
+
+ ArcSort(fst1, olabel_comp);
+ ArcSort(fst2, ilabel_comp);
+
+ VectorFst<Arc> composed;
+
+ TableCompose(*fst1, *fst2, &composed, opts);
+
+ if (!connect) Connect(&composed);
+
+ VectorFst<Arc> composed_baseline;
+
+ Compose(*fst1, *fst2, &composed_baseline);
+
+
+ std::cout << "Connect = "<< (connect?"True\n":"False\n");
+
+ std::cout <<"Table-Composed FST\n";
+ {
+ FstPrinter<Arc> fstprinter(composed, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ std::cout <<" Baseline-Composed FST\n";
+ {
+ FstPrinter<Arc> fstprinter(composed_baseline, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ if ( !RandEquivalent(composed, composed_baseline, 3/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 20/*path length-- max?*/)) {
+ VectorFst<Arc> diff1;
+ Difference(composed, composed_baseline, &diff1);
+ std::cout <<" Diff1 (composed - baseline) \n";
+ {
+ FstPrinter<Arc> fstprinter(diff1, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ VectorFst<Arc> diff2;
+ Difference(composed_baseline, composed, &diff2);
+ std::cout <<" Diff2 (baseline - composed) \n";
+ {
+ FstPrinter<Arc> fstprinter(diff2, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ assert(0);
+ }
+
+ delete fst1;
+ delete fst2;
+}
+
+
+
+// Don't instantiate with log semiring, as RandEquivalent may fail.
+template<class Arc> void TestTableMatcherCacheLeft(bool connect) {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+
+ VectorFst<Arc> *fst1 = RandFst<Arc>();
+
+
+ TableComposeOptions opts;
+ opts.table_match_type = MATCH_OUTPUT;
+ opts.min_table_size = 1 + kaldi::Rand() % 5;
+ opts.table_ratio = 0.25 * (kaldi::Rand() % 5);
+ opts.connect = connect;
+
+ TableComposeCache<Fst<Arc> > cache(opts);
+
+ for (size_t i = 0; i < 3; i++) {
+
+ VectorFst<Arc> *fst2 = RandFst<Arc>();
+
+ ILabelCompare<Arc> ilabel_comp;
+ OLabelCompare<Arc> olabel_comp;
+
+
+ ArcSort(fst1, olabel_comp);
+ ArcSort(fst2, ilabel_comp);
+
+ VectorFst<Arc> composed;
+
+ TableCompose(*fst1, *fst2, &composed, &cache);
+
+ if (!connect) Connect(&composed);
+
+ VectorFst<Arc> composed_baseline;
+
+ Compose(*fst1, *fst2, &composed_baseline);
+
+
+ std::cout << "Connect = "<< (connect?"True\n":"False\n");
+
+
+ if ( !RandEquivalent(composed, composed_baseline, 3/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/)) {
+ VectorFst<Arc> diff1;
+ Difference(composed, composed_baseline, &diff1);
+ std::cout <<" Diff1 (composed - baseline) \n";
+ {
+ FstPrinter<Arc> fstprinter(diff1, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ VectorFst<Arc> diff2;
+ Difference(composed_baseline, composed, &diff2);
+ std::cout <<" Diff2 (baseline - composed) \n";
+ {
+ FstPrinter<Arc> fstprinter(diff2, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ assert(0);
+ }
+ delete fst2;
+ }
+
+ delete fst1;
+}
+
+
+template<class Arc> void TestTableMatcherCacheRight(bool connect) {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+
+ VectorFst<Arc> *fst2 = RandFst<Arc>();
+ ILabelCompare<Arc> ilabel_comp;
+ ArcSort(fst2, ilabel_comp);
+
+
+ TableComposeOptions opts;
+ opts.table_match_type = MATCH_INPUT;
+ opts.min_table_size = 1 + kaldi::Rand() % 5;
+ opts.table_ratio = 0.25 * (kaldi::Rand() % 5);
+ opts.connect = connect;
+
+ TableComposeCache<Fst<Arc> > cache(opts);
+
+ for (size_t i = 0; i < 2; i++) {
+
+ VectorFst<Arc> *fst1 = RandFst<Arc>();
+
+
+ OLabelCompare<Arc> olabel_comp;
+
+
+ ArcSort(fst1, olabel_comp);
+
+ VectorFst<Arc> composed;
+
+ TableCompose(*fst1, *fst2, &composed, &cache);
+
+ if (!connect) Connect(&composed);
+
+ VectorFst<Arc> composed_baseline;
+
+ Compose(*fst1, *fst2, &composed_baseline);
+
+
+ std::cout << "Connect = "<< (connect?"True\n":"False\n");
+
+
+ if ( !RandEquivalent(composed, composed_baseline, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 20/*path length-- max?*/)) {
+ VectorFst<Arc> diff1;
+ Difference(composed, composed_baseline, &diff1);
+ std::cout <<" Diff1 (composed - baseline) \n";
+ {
+ FstPrinter<Arc> fstprinter(diff1, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ VectorFst<Arc> diff2;
+ Difference(composed_baseline, composed, &diff2);
+ std::cout <<" Diff2 (baseline - composed) \n";
+ {
+ FstPrinter<Arc> fstprinter(diff2, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ assert(0);
+ }
+ delete fst1;
+ }
+
+ delete fst2;
+}
+
+
+} // namespace fst
+
+int main() {
+ using namespace fst;
+ for (int i = 0;i < 1;i++) {
+ TestTableMatcher<fst::StdArc>(true, true);
+ TestTableMatcher<fst::StdArc>(false, true);
+ TestTableMatcher<fst::StdArc>(true, false);
+ TestTableMatcher<fst::StdArc>(false, false);
+ TestTableMatcherCacheLeft<fst::StdArc>(true);
+ TestTableMatcherCacheLeft<fst::StdArc>(false);
+ TestTableMatcherCacheRight<fst::StdArc>(true);
+ TestTableMatcherCacheRight<fst::StdArc>(false);
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/table-matcher.h b/runtime/onnxruntime/third_party/kaldi/fstext/table-matcher.h
new file mode 100644
index 000000000..290a4f8bc
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/table-matcher.h
@@ -0,0 +1,376 @@
+// fstext/table-matcher.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_FSTEXT_TABLE_MATCHER_H_
+#define KALDI_FSTEXT_TABLE_MATCHER_H_
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+
+
+
+namespace fst {
+
+
+/// TableMatcher is a matcher specialized for the case where the output
+/// side of the left FST always has either all-epsilons coming out of
+/// a state, or a majority of the symbol table. Therefore we can
+/// either store nothing (for the all-epsilon case) or store a lookup
+/// table from Labels to arc offsets. Since the TableMatcher has to
+/// iterate over all arcs in each left-hand state the first time it sees
+/// it, this matcher type is not efficient if you compose with
+/// something very small on the right-- unless you do it multiple
+/// times and keep the matcher around. To do this requires using the
+/// most advanced form of ComposeFst in Compose.h, that initializes
+/// with ComposeFstImplOptions.
+
+struct TableMatcherOptions {
+ float table_ratio; // we construct the table if it would be at least this full.
+ int min_table_size;
+ TableMatcherOptions(): table_ratio(0.25), min_table_size(4) { }
+};
+
+
+// Introducing an "impl" class for TableMatcher because
+// we need to do a shallow copy of the Matcher for when
+// we want to cache tables for multiple compositions.
+template<class F, class BackoffMatcher = SortedMatcher<F> >
+class TableMatcherImpl : public MatcherBase<typename F::Arc> {
+ public:
+ typedef F FST;
+ typedef typename F::Arc Arc;
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef StateId ArcId; // Use this type to store arc offsets [it's actually size_t
+ // in the Seek function of ArcIterator, but StateId should be big enough].
+ typedef typename Arc::Weight Weight;
+
+
+ public:
+
+ TableMatcherImpl(const FST &fst, MatchType match_type,
+ const TableMatcherOptions &opts = TableMatcherOptions()):
+ match_type_(match_type),
+ fst_(fst.Copy()),
+ loop_(match_type == MATCH_INPUT ?
+ Arc(kNoLabel, 0, Weight::One(), kNoStateId) :
+ Arc(0, kNoLabel, Weight::One(), kNoStateId)),
+ aiter_(NULL),
+ s_(kNoStateId), opts_(opts),
+ backoff_matcher_(fst, match_type)
+ {
+ assert(opts_.min_table_size > 0);
+ if (match_type == MATCH_INPUT)
+ assert(fst_->Properties(kILabelSorted, true) == kILabelSorted);
+ else if (match_type == MATCH_OUTPUT)
+ assert(fst_->Properties(kOLabelSorted, true) == kOLabelSorted);
+ else
+ assert(0 && "Invalid FST properties");
+ }
+
+ virtual const FST &GetFst() const { return *fst_; }
+
+ virtual ~TableMatcherImpl() {
+ std::vector<ArcId> *const empty = ((std::vector<ArcId>*)(NULL)) + 1; // special marker.
+ for (size_t i = 0; i < tables_.size(); i++) {
+ if (tables_[i] != NULL && tables_[i] != empty)
+ delete tables_[i];
+ }
+ delete aiter_;
+ delete fst_;
+ }
+
+ virtual MatchType Type(bool test) const {
+ return match_type_;
+ }
+
+ void SetState(StateId s) {
+ if (aiter_) {
+ delete aiter_;
+ aiter_ = NULL;
+ }
+ if (match_type_ == MATCH_NONE)
+ LOG(FATAL) << "TableMatcher: bad match type";
+ s_ = s;
+ std::vector<ArcId> *const empty = ((std::vector<ArcId>*)(NULL)) + 1; // special marker.
+ if (static_cast<size_t>(s) >= tables_.size()) {
+ assert(s>=0);
+ tables_.resize(s+1, NULL);
+ }
+ std::vector<ArcId>* &this_table_ = tables_[s]; // note: ref to ptr.
+ if (this_table_ == empty) {
+ backoff_matcher_.SetState(s);
+ return;
+ } else if (this_table_ == NULL) { // NULL means has not been set.
+ ArcId num_arcs = fst_->NumArcs(s);
+ if (num_arcs == 0 || num_arcs < opts_.min_table_size) {
+ this_table_ = empty;
+ backoff_matcher_.SetState(s);
+ return;
+ }
+ ArcIterator<FST> aiter(*fst_, s);
+ aiter.SetFlags(kArcNoCache|(match_type_ == MATCH_OUTPUT?kArcOLabelValue:kArcILabelValue),
+ kArcNoCache|kArcValueFlags);
+ // the statement above, says: "Don't cache stuff; and I only need the ilabel/olabel
+ // to be computed.
+ aiter.Seek(num_arcs - 1);
+ Label highest_label = (match_type_ == MATCH_OUTPUT ?
+ aiter.Value().olabel : aiter.Value().ilabel);
+ if ((highest_label+1) * opts_.table_ratio > num_arcs) {
+ this_table_ = empty;
+ backoff_matcher_.SetState(s);
+ return; // table would be too sparse.
+ }
+ // OK, now we are creating the table.
+ this_table_ = new std::vector<ArcId> (highest_label+1, kNoStateId);
+ ArcId pos = 0;
+ for (aiter.Seek(0); !aiter.Done(); aiter.Next(), pos++) {
+ Label label = (match_type_ == MATCH_OUTPUT ?
+ aiter.Value().olabel : aiter.Value().ilabel);
+ assert((size_t)label <= (size_t)highest_label); // also checks >= 0.
+ if ((*this_table_)[label] == kNoStateId) (*this_table_)[label] = pos;
+ // set this_table_[label] to first position where arc has this
+ // label.
+ }
+ }
+ // At this point in the code, this_table_ != NULL and != empty.
+ aiter_ = new ArcIterator<FST>(*fst_, s);
+ aiter_->SetFlags(kArcNoCache, kArcNoCache); // don't need to cache arcs as may only
+ // need a small subset.
+ loop_.nextstate = s;
+ // aiter_ = NULL;
+ // backoff_matcher_.SetState(s);
+ }
+
+ bool Find(Label match_label) {
+ if (!aiter_) return backoff_matcher_.Find(match_label);
+ else {
+ match_label_ = match_label;
+ current_loop_ = (match_label == 0);
+ // kNoLabel means the implicit loop on the other FST --
+ // matches real epsilons but not the self-loop.
+ match_label_ = (match_label_ == kNoLabel ? 0 : match_label_);
+ if (static_cast<size_t>(match_label_) < tables_[s_]->size() &&
+ (*(tables_[s_]))[match_label_] != kNoStateId) {
+ aiter_->Seek( (*(tables_[s_]))[match_label_] ); // label exists.
+ return true;
+ }
+ return current_loop_;
+ }
+ }
+ const Arc& Value() const {
+ if (aiter_)
+ return current_loop_ ? loop_ : aiter_->Value();
+ else
+ return backoff_matcher_.Value();
+ }
+
+ void Next() {
+ if (aiter_) {
+ if (current_loop_)
+ current_loop_ = false;
+ else
+ aiter_->Next();
+ } else
+ backoff_matcher_.Next();
+ }
+
+ bool Done() const {
+ if (aiter_ != NULL) {
+ if (current_loop_)
+ return false;
+ if (aiter_->Done())
+ return true;
+ Label label = (match_type_ == MATCH_OUTPUT ?
+ aiter_->Value().olabel : aiter_->Value().ilabel);
+ return (label != match_label_);
+ } else
+ return backoff_matcher_.Done();
+ }
+ const Arc &Value() {
+ if (aiter_ != NULL) {
+ return (current_loop_ ? loop_ : aiter_->Value() );
+ } else
+ return backoff_matcher_.Value();
+ }
+
+ virtual TableMatcherImpl<FST> *Copy(bool safe = false) const {
+ assert(0); // shouldn't be called. This is not a "real" matcher,
+ // although we derive from MatcherBase for convenience.
+ return NULL;
+ }
+
+ virtual uint64 Properties(uint64 props) const { return props; } // simple matcher that does
+ // not change its FST, so properties are properties of FST it is applied to
+
+ private:
+ virtual void SetState_(StateId s) { SetState(s); }
+ virtual bool Find_(Label label) { return Find(label); }
+ virtual bool Done_() const { return Done(); }
+ virtual const Arc& Value_() const { return Value(); }
+ virtual void Next_() { Next(); }
+
+ MatchType match_type_;
+ FST *fst_;
+ bool current_loop_;
+ Label match_label_;
+ Arc loop_;
+ ArcIterator<FST> *aiter_;
+ StateId s_;
+ std::vector<std::vector<ArcId> *> tables_;
+ TableMatcherOptions opts_;
+ BackoffMatcher backoff_matcher_;
+
+};
+
+
+template<class F, class BackoffMatcher = SortedMatcher<F> >
+class TableMatcher : public MatcherBase<typename F::Arc> {
+ public:
+ typedef F FST;
+ typedef typename F::Arc Arc;
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef StateId ArcId; // Use this type to store arc offsets [it's actually size_t
+ // in the Seek function of ArcIterator, but StateId should be big enough].
+ typedef typename Arc::Weight Weight;
+ typedef TableMatcherImpl<F, BackoffMatcher> Impl;
+
+ TableMatcher(const FST &fst, MatchType match_type,
+ const TableMatcherOptions &opts = TableMatcherOptions())
+ : impl_(std::make_shared<Impl>(fst, match_type, opts)) { }
+
+ TableMatcher(const TableMatcher<FST, BackoffMatcher> &matcher,
+ bool safe = false)
+ : impl_(matcher.impl_) {
+ if (safe == true) {
+ LOG(FATAL) << "TableMatcher: Safe copy not supported";
+ }
+ }
+
+ virtual const FST &GetFst() const { return impl_->GetFst(); }
+
+ virtual MatchType Type(bool test) const { return impl_->Type(test); }
+
+ void SetState(StateId s) { return impl_->SetState(s); }
+
+ bool Find(Label match_label) { return impl_->Find(match_label); }
+
+ const Arc& Value() const { return impl_->Value(); }
+
+ void Next() { return impl_->Next(); }
+
+ bool Done() const { return impl_->Done(); }
+
+ const Arc &Value() { return impl_->Value(); }
+
+ virtual TableMatcher<FST, BackoffMatcher> *Copy(bool safe = false) const {
+ return new TableMatcher<FST, BackoffMatcher> (*this, safe);
+ }
+
+ virtual uint64 Properties(uint64 props) const { return impl_->Properties(props); } // simple matcher that does
+ // not change its FST, so properties are properties of FST it is applied to
+ private:
+ std::shared_ptr<Impl> impl_;
+
+ virtual void SetState_(StateId s) { impl_->SetState(s); }
+ virtual bool Find_(Label label) { return impl_->Find(label); }
+ virtual bool Done_() const { return impl_->Done(); }
+ virtual const Arc& Value_() const { return impl_->Value(); }
+ virtual void Next_() { impl_->Next(); }
+
+ TableMatcher &operator=(const TableMatcher &) = delete;
+};
+
+struct TableComposeOptions: public TableMatcherOptions {
+ bool connect; // Connect output
+ ComposeFilter filter_type; // Which pre-defined filter to use
+ MatchType table_match_type;
+
+ explicit TableComposeOptions(const TableMatcherOptions &mo,
+ bool c = true, ComposeFilter ft = SEQUENCE_FILTER,
+ MatchType tms = MATCH_OUTPUT)
+ : TableMatcherOptions(mo), connect(c), filter_type(ft), table_match_type(tms) { }
+ TableComposeOptions() : connect(true), filter_type(SEQUENCE_FILTER),
+ table_match_type(MATCH_OUTPUT) { }
+};
+
+
+template<class Arc>
+void TableCompose(const Fst<Arc> &ifst1, const Fst<Arc> &ifst2,
+ MutableFst<Arc> *ofst,
+ const TableComposeOptions &opts = TableComposeOptions()) {
+ typedef Fst<Arc> F;
+ CacheOptions nopts;
+ nopts.gc_limit = 0; // Cache only the last state for fastest copy.
+ if (opts.table_match_type == MATCH_OUTPUT) {
+ // ComposeFstImplOptions templated on matcher for fst1, matcher for fst2.
+ ComposeFstImplOptions<TableMatcher<F>, SortedMatcher<F> > impl_opts(nopts);
+ impl_opts.matcher1 = new TableMatcher<F>(ifst1, MATCH_OUTPUT, opts);
+ *ofst = ComposeFst<Arc>(ifst1, ifst2, impl_opts);
+ } else {
+ assert(opts.table_match_type == MATCH_INPUT) ;
+ // ComposeFstImplOptions templated on matcher for fst1, matcher for fst2.
+ ComposeFstImplOptions<SortedMatcher<F>, TableMatcher<F> > impl_opts(nopts);
+ impl_opts.matcher2 = new TableMatcher<F>(ifst2, MATCH_INPUT, opts);
+ *ofst = ComposeFst<Arc>(ifst1, ifst2, impl_opts);
+ }
+ if (opts.connect) Connect(ofst);
+}
+
+
+/// TableComposeCache lets us do multiple compositions while caching the same
+/// matcher.
+template<class F>
+struct TableComposeCache {
+ TableMatcher<F> *matcher;
+ TableComposeOptions opts;
+ TableComposeCache(const TableComposeOptions &opts = TableComposeOptions()): matcher (NULL), opts(opts) {}
+ ~TableComposeCache() { delete(matcher); }
+};
+
+template<class Arc>
+void TableCompose(const Fst<Arc> &ifst1, const Fst<Arc> &ifst2,
+ MutableFst<Arc> *ofst,
+ TableComposeCache<Fst<Arc> > *cache) {
+ typedef Fst<Arc> F;
+ assert(cache != NULL);
+ CacheOptions nopts;
+ nopts.gc_limit = 0; // Cache only the last state for fastest copy.
+ if (cache->opts.table_match_type == MATCH_OUTPUT) {
+ ComposeFstImplOptions<TableMatcher<F>, SortedMatcher<F> > impl_opts(nopts);
+ if (cache->matcher == NULL)
+ cache->matcher = new TableMatcher<F>(ifst1, MATCH_OUTPUT, cache->opts);
+ impl_opts.matcher1 = cache->matcher->Copy(); // not passing "safe": may not
+ // be thread-safe-- anway I don't understand this part.
+ *ofst = ComposeFst<Arc>(ifst1, ifst2, impl_opts);
+ } else {
+ assert(cache->opts.table_match_type == MATCH_INPUT) ;
+ ComposeFstImplOptions<SortedMatcher<F>, TableMatcher<F> > impl_opts(nopts);
+ if (cache->matcher == NULL)
+ cache->matcher = new TableMatcher<F>(ifst2, MATCH_INPUT, cache->opts);
+ impl_opts.matcher2 = cache->matcher->Copy();
+ *ofst = ComposeFst<Arc>(ifst1, ifst2, impl_opts);
+ }
+ if (cache->opts.connect) Connect(ofst);
+}
+
+
+
+} // end namespace fst
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/trivial-factor-weight-test.cc b/runtime/onnxruntime/third_party/kaldi/fstext/trivial-factor-weight-test.cc
new file mode 100644
index 000000000..b4682443d
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/trivial-factor-weight-test.cc
@@ -0,0 +1,214 @@
+// fstext/trivial-factor-weight-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "base/kaldi-math.h"
+#include "fstext/pre-determinize.h"
+#include "fstext/determinize-star.h"
+#include "fstext/trivial-factor-weight.h"
+#include "fstext/fst-test-utils.h"
+// Just check that it compiles, for now.
+
+namespace fst
+{
+ using std::cout;
+ using std::vector;
+
+// Don't instantiate with log semiring, as RandEquivalent may fail.
+template<class Arc> void TestFactor() {
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Weight Weight;
+
+ VectorFst<Arc> *fst = new VectorFst<Arc>();
+ int n_syms = 2 + kaldi::Rand() % 5, n_states = 3 + kaldi::Rand() % 10, n_arcs = 5 + kaldi::Rand() % 30, n_final = 1 + kaldi::Rand()%3; // Up to 2 unique symbols.
+ cout << "Testing pre-determinize with "<<n_syms<<" symbols, "<<n_states<<" states and "<<n_arcs<<" arcs and "<<n_final<<" final states.\n";
+ SymbolTable *sptr = NULL;
+
+ vector<Label> all_syms; // including epsilon.
+ // Put symbols in the symbol table from 1..n_syms-1.
+ for (size_t i = 0;i < (size_t)n_syms;i++)
+ all_syms.push_back(i);
+
+ // Create states.
+ vector<StateId> all_states;
+ for (size_t i = 0;i < (size_t)n_states;i++) {
+ StateId this_state = fst->AddState();
+ if (i == 0) fst->SetStart(i);
+ all_states.push_back(this_state);
+ }
+ // Set final states.
+ for (size_t j = 0;j < (size_t)n_final;j++) {
+ StateId id = all_states[kaldi::Rand() % n_states];
+ Weight weight = (Weight)(0.33*(kaldi::Rand() % 5) );
+ printf("calling SetFinal with %d and %f\n", id, weight.Value());
+ fst->SetFinal(id, weight);
+ }
+ // Create arcs.
+ for (size_t i = 0;i < (size_t)n_arcs;i++) {
+ Arc a;
+ a.nextstate = all_states[kaldi::Rand() % n_states];
+ a.ilabel = all_syms[kaldi::Rand() % n_syms];
+ a.olabel = all_syms[kaldi::Rand() % n_syms]; // same input+output vocab.
+ a.weight = (Weight) (0.33*(kaldi::Rand() % 2));
+ StateId start_state = all_states[kaldi::Rand() % n_states];
+ fst->AddArc(start_state, a);
+ }
+
+ std::cout <<" printing before trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ // Trim resulting FST.
+ Connect(fst);
+
+ std::cout <<" printing after trimming\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ vector<Label> extra_syms;
+ if (fst->Start() != kNoStateId) { // "Connect" did not make it empty....
+ PreDeterminize(fst, 1000, &extra_syms);
+ }
+
+ std::cout <<" printing after predeterminization\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ { // Remove epsilon. All default args.
+ bool connect = true;
+ Weight weight_threshold = Weight::Zero();
+ int64 nstate = -1; // Relates to pruning.
+ double delta = kDelta; // I think a small weight value. Relates to some kind of pruning,
+ // I guess. But with no epsilon cycles, probably doensn't matter.
+ RmEpsilon(fst, connect, weight_threshold, nstate, delta);
+ }
+
+ std::cout <<" printing after double-epsilon removal\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ VectorFst<Arc> ofst_star;
+
+ {
+ printf("Converting to Gallic semiring");
+ VectorFst<GallicArc<Arc> > gallic_fst;
+ VectorFst<GallicArc<Arc> > gallic_fst_noeps;
+ VectorFst<GallicArc<Arc> > gallic_fst_det;
+
+
+ {
+ printf("Determinizing with DeterminizeStar, converting to Gallic\n");
+ DeterminizeStar(*fst, &gallic_fst);
+ }
+
+ {
+ std::cout <<" printing gallic FST\n";
+ FstPrinter<GallicArc<Arc> > fstprinter(gallic_fst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ // Map(ofst_star, &gallic_fst, ToGallicMapper<Arc, STRING_LEFT>());
+
+ printf("Converting gallic back to regular\n");
+ TrivialFactorWeightFst< GallicArc<Arc, GALLIC_LEFT>, GallicFactor<typename Arc::Label,
+ typename Arc::Weight, GALLIC_LEFT> > fwfst(gallic_fst);
+ {
+ std::cout <<" printing factor-weight FST\n";
+ FstPrinter<GallicArc<Arc> > fstprinter(fwfst, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ Map(fwfst, &ofst_star, FromGallicMapper<Arc, GALLIC_LEFT>());
+
+ {
+ std::cout <<" printing after converting back to regular FST\n";
+ FstPrinter<Arc> fstprinter(ofst_star, sptr, sptr, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+
+ VectorFst<GallicArc<Arc> > new_gallic_fst;
+ Map(ofst_star, &new_gallic_fst, ToGallicMapper<Arc, GALLIC_LEFT>());
+
+ assert(RandEquivalent(gallic_fst, new_gallic_fst, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length-- max?*/));
+
+ }
+
+ delete fst;
+}
+
+
+template<class Arc, class inttype> void TestStringRepository() {
+ typedef typename Arc::Label Label;
+
+ StringRepository<Label, inttype> sr;
+
+ int N = 1000;
+ if (sizeof(inttype) == 1) N = 64;
+ vector<vector<Label> > strings(N);
+ vector<inttype> ids(N);
+
+ for (size_t i = 0;i < N;i++) {
+ size_t len = kaldi::Rand() % 4;
+ vector<Label> vec;
+ for (size_t j = 0;j < len;j++) vec.push_back( (kaldi::Rand()%10) + 150*(kaldi::Rand()%2)); // make it have reasonable range.
+ if (i < 500 && vec.size() == 0) ids[i] = sr.IdOfEmpty();
+ else if (i < 500 && vec.size() == 1) ids[i] = sr.IdOfLabel(vec[0]);
+ else ids[i] = sr.IdOfSeq(vec);
+
+ strings[i] = vec;
+ }
+
+ for (size_t i = 0;i < N;i++) {
+ vector<Label> tmpv;
+ tmpv.push_back(10); // just put in garbage.
+ sr.SeqOfId(ids[i], &tmpv);
+ assert(tmpv == strings[i]);
+ assert(sr.IdOfSeq(strings[i]) == ids[i]);
+ if (strings[i].size() == 0) assert(ids[i] == sr.IdOfEmpty());
+ if (strings[i].size() == 1) assert(ids[i] == sr.IdOfLabel(strings[i][0]));
+
+ if (sizeof(inttype) != 1) {
+ size_t prefix_len = kaldi::Rand() % (strings[i].size() + 1);
+ inttype s2 = sr.RemovePrefix(ids[i], prefix_len);
+ vector<Label> vec2;
+ sr.SeqOfId(s2, &vec2);
+ for (size_t j = 0;j < strings[i].size()-prefix_len;j++) {
+ assert(vec2[j] == strings[i][j+prefix_len]);
+ }
+ }
+
+ }
+}
+
+} // end namespace fst
+
+int main() {
+ for (int i = 0;i < 25;i++) {
+ fst::TestFactor<fst::StdArc>();
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/fstext/trivial-factor-weight.h b/runtime/onnxruntime/third_party/kaldi/fstext/trivial-factor-weight.h
new file mode 100644
index 000000000..044e83b1f
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/fstext/trivial-factor-weight.h
@@ -0,0 +1,401 @@
+// fstext/trivial-factor-weight.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+//
+//
+// This is a modified file from the OpenFST Library v1.2.7 available at
+// http://www.openfst.org and released under the Apache License Version 2.0.
+//
+//
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// Copyright 2005-2010 Google, Inc.
+// Author: [email protected] (Cyril Allauzen)
+
+
+#ifndef KALDI_FSTEXT_TRIVIAL_FACTOR_WEIGHT_H_
+#define KALDI_FSTEXT_TRIVIAL_FACTOR_WEIGHT_H_
+
+
+// TrivialFactorWeight.h This is an extension to factor-weight.h in the OpenFst
+// code. It is a version of FactorWeight that creates separate states (with
+// input epsilons) rather than pushing the factors forward. This is for
+// converting from Gallic FSTs, where you want the result to be a bit more
+// trivial with input epsilons inserted where there are multiple output symbols.
+// This has the advantage that it always works, for any input (also I just
+// prefer this approach).
+
+#include <unordered_map>
+using std::unordered_map;
+
+#include <algorithm>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include <fst/cache.h>
+#include <fst/test-properties.h>
+
+namespace fst {
+
+
+template <class Arc>
+struct TrivialFactorWeightOptions : CacheOptions {
+ typedef typename Arc::Label Label;
+ float delta;
+ Label extra_ilabel; // input label of extra arcs
+ Label extra_olabel; // output label of extra arcs
+
+ TrivialFactorWeightOptions(const CacheOptions &opts, float d,
+ Label il = 0, Label ol = 0)
+ : CacheOptions(opts), delta(d), extra_ilabel(il), extra_olabel(ol) {}
+
+ explicit TrivialFactorWeightOptions(
+ float d, Label il = 0, Label ol = 0)
+ : delta(d), extra_ilabel(il), extra_olabel(ol) {}
+
+ TrivialFactorWeightOptions(): delta(kDelta), extra_ilabel(0), extra_olabel(0) {}
+
+};
+
+namespace internal {
+
+// Implementation class for TrivialFactorWeight
+template <class A, class F>
+class TrivialFactorWeightFstImpl
+ : public CacheImpl<A> {
+ public:
+ using CacheImpl<A>::PushArc;
+ using FstImpl<A>::SetType;
+ using FstImpl<A>::SetProperties;
+ using FstImpl<A>::Properties;
+ using FstImpl<A>::SetInputSymbols;
+ using FstImpl<A>::SetOutputSymbols;
+
+ using CacheBaseImpl< CacheState<A> >::HasStart;
+ using CacheBaseImpl< CacheState<A> >::HasFinal;
+ using CacheBaseImpl< CacheState<A> >::HasArcs;
+
+ typedef A Arc;
+ typedef typename A::Label Label;
+ typedef typename A::Weight Weight;
+ typedef typename A::StateId StateId;
+ typedef F FactorIterator;
+
+ typedef DefaultCacheStore<A> Store;
+ typedef typename Store::State State;
+
+ struct Element {
+ Element() {}
+
+ Element(StateId s, Weight w) : state(s), weight(w) {}
+
+ StateId state; // Input state Id
+ Weight weight; // Residual weight
+ };
+
+ TrivialFactorWeightFstImpl(const Fst<A> &fst, const TrivialFactorWeightOptions<A> &opts)
+ : CacheImpl<A>(opts),
+ fst_(fst.Copy()),
+ delta_(opts.delta),
+ extra_ilabel_(opts.extra_ilabel),
+ extra_olabel_(opts.extra_olabel) {
+ SetType("factor-weight");
+ uint64 props = fst.Properties(kFstProperties, false);
+ SetProperties(FactorWeightProperties(props), kCopyProperties);
+
+ SetInputSymbols(fst.InputSymbols());
+ SetOutputSymbols(fst.OutputSymbols());
+ }
+
+ TrivialFactorWeightFstImpl(const TrivialFactorWeightFstImpl<A, F> &impl)
+ : CacheImpl<A>(impl),
+ fst_(impl.fst_->Copy(true)),
+ delta_(impl.delta_),
+ extra_ilabel_(impl.extra_ilabel_),
+ extra_olabel_(impl.extra_olabel_) {
+ SetType("factor-weight");
+ SetProperties(impl.Properties(), kCopyProperties);
+ SetInputSymbols(impl.InputSymbols());
+ SetOutputSymbols(impl.OutputSymbols());
+ }
+
+ StateId Start() {
+ if (!HasStart()) {
+ StateId s = fst_->Start();
+ if (s == kNoStateId)
+ return kNoStateId;
+ StateId start = this->FindState(Element(fst_->Start(), Weight::One()));
+ this->SetStart(start);
+ }
+ return CacheImpl<A>::Start();
+ }
+
+ Weight Final(StateId s) {
+ if (!HasFinal(s)) {
+ const Element &e = elements_[s];
+ Weight w;
+ if (e.state == kNoStateId) { // extra state inserted to represent final weights.
+ FactorIterator fit(e.weight);
+ if (fit.Done()) { // cannot be factored.
+ w = e.weight; // so it's final
+ } else {
+ w = Weight::Zero(); // need another transition.
+ }
+ } else {
+ if (e.weight != Weight::One()) { // Not a real state.
+ w = Weight::Zero();
+ } else { // corresponds to a "real" state.
+ w = fst_->Final(e.state);
+ FactorIterator fit(w);
+ if (!fit.Done()) // we would have intermediate states representing this final state.
+ w = Weight::Zero();
+ }
+ }
+ this->SetFinal(s, w);
+ return w;
+ } else {
+ return CacheImpl<A>::Final(s);
+ }
+ }
+
+ size_t NumArcs(StateId s) {
+ if (!HasArcs(s))
+ Expand(s);
+ return CacheImpl<A>::NumArcs(s);
+ }
+
+ size_t NumInputEpsilons(StateId s) {
+ if (!HasArcs(s))
+ Expand(s);
+ return CacheImpl<A>::NumInputEpsilons(s);
+ }
+
+ size_t NumOutputEpsilons(StateId s) {
+ if (!HasArcs(s))
+ Expand(s);
+ return CacheImpl<A>::NumOutputEpsilons(s);
+ }
+
+ void InitArcIterator(StateId s, ArcIteratorData<A> *data) {
+ if (!HasArcs(s))
+ Expand(s);
+ CacheImpl<A>::InitArcIterator(s, data);
+ }
+
+
+ // Find state corresponding to an element. Create new state
+ // if element not found.
+ StateId FindState(const Element &e) {
+ typename ElementMap::iterator eit = element_map_.find(e);
+ if (eit != element_map_.end()) {
+ return (*eit).second;
+ } else {
+ StateId s = elements_.size();
+ elements_.push_back(e);
+ element_map_.insert(std::pair<const Element, StateId>(e, s));
+ return s;
+ }
+ }
+
+ // Computes the outgoing transitions from a state, creating new destination
+ // states as needed.
+ void Expand(StateId s) {
+ CHECK(static_cast<size_t>(s) < elements_.size());
+ Element e = elements_[s];
+ if (e.weight != Weight::One()) {
+ FactorIterator fit(e.weight);
+ if (fit.Done()) { // Cannot be factored-> create a link to dest state directly
+ if (e.state != kNoStateId) {
+ StateId dest = FindState(Element(e.state, Weight::One()));
+ PushArc(s, Arc(extra_ilabel_, extra_olabel_, e.weight, dest));
+ } // else we're done. This is a final state.
+ } else { // Can be factored.
+ const std::pair<Weight, Weight> &p = fit.Value();
+ StateId dest = FindState(Element(e.state, p.second.Quantize(delta_)));
+ PushArc(s, Arc(extra_ilabel_, extra_olabel_, p.first, dest));
+ }
+ } else { // Unit weight. This corresponds to a "real" state.
+ CHECK(e.state != kNoStateId);
+ for (ArcIterator< Fst<A> > ait(*fst_, e.state);
+ !ait.Done();
+ ait.Next()) {
+ const A &arc = ait.Value();
+ FactorIterator fit(arc.weight);
+ if (fit.Done()) { // cannot be factored->just link directly to dest.
+ StateId dest = FindState(Element(arc.nextstate, Weight::One()));
+ PushArc(s, Arc(arc.ilabel, arc.olabel, arc.weight, dest));
+ } else {
+ const std::pair<Weight, Weight> &p = fit.Value();
+ StateId dest = FindState(Element(arc.nextstate, p.second.Quantize(delta_)));
+ PushArc(s, Arc(arc.ilabel, arc.olabel, p.first, dest));
+ }
+ }
+ // See if we have to add arcs for final-states [only if final-weight is factorable].
+ Weight final_w = fst_->Final(e.state);
+ if (final_w != Weight::Zero()) {
+ FactorIterator fit(final_w);
+ if (!fit.Done()) {
+ const std::pair<Weight, Weight> &p = fit.Value();
+ StateId dest = FindState(Element(kNoStateId, p.second.Quantize(delta_)));
+ PushArc(s, Arc(extra_ilabel_, extra_olabel_, p.first, dest));
+ }
+ }
+ }
+ this->SetArcs(s);
+ }
+
+ private:
+ // Equality function for Elements, assume weights have been quantized.
+ class ElementEqual {
+ public:
+ bool operator()(const Element &x, const Element &y) const {
+ return x.state == y.state && x.weight == y.weight;
+ }
+ };
+
+ // Hash function for Elements to Fst states.
+ class ElementKey {
+ public:
+ size_t operator()(const Element &x) const {
+ return static_cast<size_t>(x.state * kPrime + x.weight.Hash());
+ }
+ private:
+ static const int kPrime = 7853;
+ };
+
+ typedef unordered_map<Element, StateId, ElementKey, ElementEqual> ElementMap;
+
+ std::unique_ptr<const Fst<A>> fst_;
+ float delta_;
+ uint32 mode_; // factoring arc and/or final weights
+ Label extra_ilabel_; // ilabel of arc created when factoring final w's
+ Label extra_olabel_; // olabel of arc created when factoring final w's
+ std::vector<Element> elements_; // mapping Fst state to Elements
+ ElementMap element_map_; // mapping Elements to Fst state
+
+};
+
+} // namespace internal
+
+/// TrivialFactorWeightFst takes as template parameter a FactorIterator as
+/// defined above. The result of weight factoring is a transducer
+/// equivalent to the input whose path weights have been factored
+/// according to the FactorIterator. States and transitions will be
+/// added as necessary.
+/// This algorithm differs from the one implemented in FactorWeightFst
+/// in that it does not attempt to push the extra weight forward to the
+/// next state: it uses a sequence of "extra" intermediate state, and
+/// outputs the remaining weight right away. This ensures that it will
+/// always succeed, even for Gallic representations of FSTs that have cycles
+/// with more output than input symbols.
+
+/// Note that the code below was modified from factor-weight.h by just
+/// search-and-replacing "FactorWeight" by "TrivialFactorWeight".
+
+
+template <class A, class F>
+class TrivialFactorWeightFst :
+ public ImplToFst<internal::TrivialFactorWeightFstImpl<A, F>> {
+ public:
+ friend class ArcIterator< TrivialFactorWeightFst<A, F> >;
+ friend class StateIterator< TrivialFactorWeightFst<A, F> >;
+
+ typedef A Arc;
+ typedef typename A::Weight Weight;
+ typedef typename A::StateId StateId;
+ typedef DefaultCacheStore<Arc> Store;
+ typedef typename Store::State State;
+ typedef internal::TrivialFactorWeightFstImpl<A, F> Impl;
+
+ explicit TrivialFactorWeightFst(const Fst<A> &fst)
+ : ImplToFst<Impl>(std::make_shared<Impl>(fst, TrivialFactorWeightOptions<A>())) {}
+
+ TrivialFactorWeightFst(const Fst<A> &fst, const TrivialFactorWeightOptions<A> &opts)
+ : ImplToFst<Impl>(std::make_shared<Impl>(fst, opts)) {}
+
+ // See Fst<>::Copy() for doc.
+ TrivialFactorWeightFst(const TrivialFactorWeightFst<A, F> &fst, bool copy)
+ : ImplToFst<Impl>(fst, copy) {}
+
+ // Get a copy of this TrivialFactorWeightFst. See Fst<>::Copy() for further doc.
+ TrivialFactorWeightFst<A, F> *Copy(bool copy = false) const override {
+ return new TrivialFactorWeightFst<A, F>(*this, copy);
+ }
+
+ inline void InitStateIterator(StateIteratorData<A> *data) const override;
+
+ void InitArcIterator(StateId s, ArcIteratorData<A> *data) const override {
+ GetMutableImpl()->InitArcIterator(s, data);
+ }
+
+ private:
+ using ImplToFst<Impl>::GetImpl;
+ using ImplToFst<Impl>::GetMutableImpl;
+
+ TrivialFactorWeightFst &operator=(const TrivialFactorWeightFst &fst) = delete;
+};
+
+
+// Specialization for TrivialFactorWeightFst.
+template<class A, class F>
+class StateIterator< TrivialFactorWeightFst<A, F> >
+ : public CacheStateIterator< TrivialFactorWeightFst<A, F> > {
+ public:
+ explicit StateIterator(const TrivialFactorWeightFst<A, F> &fst)
+ : CacheStateIterator< TrivialFactorWeightFst<A, F> >(fst, fst.GetMutableImpl()) {}
+};
+
+
+// Specialization for TrivialFactorWeightFst.
+template <class A, class F>
+class ArcIterator< TrivialFactorWeightFst<A, F> >
+ : public CacheArcIterator< TrivialFactorWeightFst<A, F> > {
+ public:
+ typedef typename A::StateId StateId;
+
+ ArcIterator(const TrivialFactorWeightFst<A, F> &fst, StateId s)
+ : CacheArcIterator< TrivialFactorWeightFst<A, F>>(fst.GetMutableImpl(), s) {
+ if (!fst.GetImpl()->HasArcs(s)) fst.GetMutableImpl()->Expand(s);
+ }
+};
+
+template <class A, class F>
+inline void TrivialFactorWeightFst<A, F>::InitStateIterator(
+ StateIteratorData<A> *data) const {
+ data->base = new StateIterator< TrivialFactorWeightFst<A, F> >(*this);
+}
+
+
+
+
+} // namespace fst
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/itf/clusterable-itf.h b/runtime/onnxruntime/third_party/kaldi/itf/clusterable-itf.h
new file mode 100644
index 000000000..7ef9ae0ec
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/itf/clusterable-itf.h
@@ -0,0 +1,97 @@
+// itf/clusterable-itf.h
+
+// Copyright 2009-2011 Microsoft Corporation; Go Vivace Inc.
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_ITF_CLUSTERABLE_ITF_H_
+#define KALDI_ITF_CLUSTERABLE_ITF_H_ 1
+
+#include <string>
+#include "base/kaldi-common.h"
+
+namespace kaldi {
+
+
+/** \addtogroup clustering_group
+ @{
+ A virtual class for clusterable objects; see \ref clustering for an
+ explanation if its function.
+*/
+
+
+
+class Clusterable {
+ public:
+ /// \name Functions that must be overridden
+ /// @{
+
+ /// Return a copy of this object.
+ virtual Clusterable *Copy() const = 0;
+ /// Return the objective function associated with the stats
+ /// [assuming ML estimation]
+ virtual BaseFloat Objf() const = 0;
+ /// Return the normalizer (typically, count) associated with the stats
+ virtual BaseFloat Normalizer() const = 0;
+ /// Set stats to empty.
+ virtual void SetZero() = 0;
+ /// Add other stats.
+ virtual void Add(const Clusterable &other) = 0;
+ /// Subtract other stats.
+ virtual void Sub(const Clusterable &other) = 0;
+ /// Scale the stats by a positive number f [not mandatory to supply this].
+ virtual void Scale(BaseFloat f) {
+ KALDI_ERR << "This Clusterable object does not implement Scale().";
+ }
+
+ /// Return a string that describes the inherited type.
+ virtual std::string Type() const = 0;
+
+ /// Write data to stream.
+ virtual void Write(std::ostream &os, bool binary) const = 0;
+
+ /// Read data from a stream and return the corresponding object (const
+ /// function; it's a class member because we need access to the vtable
+ /// so generic code can read derived types).
+ virtual Clusterable* ReadNew(std::istream &os, bool binary) const = 0;
+
+ virtual ~Clusterable() {}
+
+ /// @}
+
+ /// \name Functions that have default implementations
+ /// @{
+
+ // These functions have default implementations (but may be overridden for
+ // speed). Implementatons in tree/clusterable-classes.cc
+
+ /// Return the objective function of the combined object this + other.
+ virtual BaseFloat ObjfPlus(const Clusterable &other) const;
+ /// Return the objective function of the subtracted object this - other.
+ virtual BaseFloat ObjfMinus(const Clusterable &other) const;
+ /// Return the objective function decrease from merging the two
+ /// clusters, negated to be a positive number (or zero).
+ virtual BaseFloat Distance(const Clusterable &other) const;
+ /// @}
+
+};
+/// @} end of "ingroup clustering_group"
+
+} // end namespace kaldi
+
+#endif // KALDI_ITF_CLUSTERABLE_ITF_H_
+
diff --git a/runtime/onnxruntime/third_party/kaldi/itf/context-dep-itf.h b/runtime/onnxruntime/third_party/kaldi/itf/context-dep-itf.h
new file mode 100644
index 000000000..b62bd11e1
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/itf/context-dep-itf.h
@@ -0,0 +1,114 @@
+// itf/context-dep-itf.h
+
+// Copyright 2009-2011 Microsoft Corporation; Go Vivace Inc.
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_ITF_CONTEXT_DEP_ITF_H_
+#define KALDI_ITF_CONTEXT_DEP_ITF_H_
+#include "base/kaldi-common.h"
+
+namespace kaldi {
+/// @ingroup tree_group
+/// @{
+
+/// context-dep-itf.h provides a link between
+/// the tree-building code in ../tree/, and the FST code in ../fstext/
+/// (particularly, ../fstext/context-dep.h). It is an abstract
+/// interface that describes an object that can map from a
+/// phone-in-context to a sequence of integer leaf-ids.
+class ContextDependencyInterface {
+ public:
+ /// ContextWidth() returns the value N (e.g. 3 for triphone models) that says how many phones
+ /// are considered for computing context.
+ virtual int ContextWidth() const = 0;
+
+ /// Central position P of the phone context, in 0-based numbering, e.g. P = 1 for typical
+ /// triphone system. We have to see if we can do without this function.
+ virtual int CentralPosition() const = 0;
+
+ /// The "new" Compute interface. For typical topologies,
+ /// pdf_class would be 0, 1, 2.
+ /// Returns success or failure; outputs the pdf-id.
+ ///
+ /// "Compute" is the main function of this interface, that takes a
+ /// sequence of N phones (and it must be N phones), possibly
+ /// including epsilons (symbol id zero) but only at positions other
+ /// than P [these represent unknown phone context due to end or
+ /// begin of sequence]. We do not insist that Compute must always
+ /// output (into stateseq) a nonempty sequence of states, but we
+ /// anticipate that stateseq will always be nonempty at output in
+ /// typical use cases. "Compute" returns false if expansion somehow
+ /// failed. Normally the calling code should raise an exception if
+ /// this happens. We can define a different interface later in
+ /// order to handle other kinds of information-- the underlying
+ /// data-structures from event-map.h are very flexible.
+ virtual bool Compute(const std::vector<int32> &phoneseq, int32 pdf_class,
+ int32 *pdf_id) const = 0;
+
+ /// GetPdfInfo returns a vector indexed by pdf-id, saying for each pdf which
+ /// pairs of (phone, pdf-class) it can correspond to. (Usually just one).
+ /// c.f. hmm/hmm-topology.h for meaning of pdf-class.
+ /// This is the old, simpler interface of GetPdfInfo(), and that this one can
+ /// only be called if the HmmTopology object's IsHmm() function call returns
+ /// true.
+ virtual void GetPdfInfo(
+ const std::vector<int32> &phones, // list of phones
+ const std::vector<int32> &num_pdf_classes, // indexed by phone,
+ std::vector<std::vector<std::pair<int32, int32> > > *pdf_info)
+ const = 0;
+
+ /// This function outputs information about what possible pdf-ids can
+ /// be generated for HMM-states; it covers the general case where
+ /// the self-loop pdf-class may be different from the forward-transition
+ /// pdf-class, so we are asking not about the set of possible pdf-ids
+ /// for a given (phone, pdf-class), but the set of possible ordered pairs
+ /// (forward-transition-pdf, self-loop-pdf) for a given (phone,
+ /// forward-transition-pdf-class, self-loop-pdf-class).
+ /// Note: 'phones' is a list of integer ids of phones, and
+ /// 'pdf-class-pairs', indexed by phone, is a list of pairs
+ /// (forward-transition-pdf-class, self-loop-pdf-class) that we can have for
+ /// that phone.
+ /// The output 'pdf_info' is indexed first by phone and then by the
+ /// same index that indexes each element of 'pdf_class_pairs',
+ /// and tells us for each pair in 'pdf_class_pairs', what is the
+ /// list of possible (forward-transition-pdf-id, self-loop-pdf-id) that
+ /// we can have.
+ /// This is less efficient than the other version of GetPdfInfo().
+ virtual void GetPdfInfo(
+ const std::vector<int32> &phones,
+ const std::vector<std::vector<std::pair<int32, int32> > > &pdf_class_pairs,
+ std::vector<std::vector<std::vector<std::pair<int32, int32> > > > *pdf_info)
+ const = 0;
+
+
+ /// NumPdfs() returns the number of acoustic pdfs (they are numbered 0.. NumPdfs()-1).
+ virtual int32 NumPdfs() const = 0;
+
+ virtual ~ContextDependencyInterface() {};
+ ContextDependencyInterface() {}
+
+ /// Returns pointer to new object which is copy of current one.
+ virtual ContextDependencyInterface *Copy() const = 0;
+ private:
+ KALDI_DISALLOW_COPY_AND_ASSIGN(ContextDependencyInterface);
+};
+/// @}
+} // namespace Kaldi
+
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/itf/decodable-itf.h b/runtime/onnxruntime/third_party/kaldi/itf/decodable-itf.h
new file mode 100644
index 000000000..20934dde8
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/itf/decodable-itf.h
@@ -0,0 +1,122 @@
+// itf/decodable-itf.h
+
+// Copyright 2009-2011 Microsoft Corporation; Saarland University;
+// Mirko Hannemann; Go Vivace Inc.;
+// 2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_ITF_DECODABLE_ITF_H_
+#define KALDI_ITF_DECODABLE_ITF_H_ 1
+#include "base/kaldi-common.h"
+
+namespace kaldi {
+/// @ingroup Interfaces
+/// @{
+
+
+/**
+ DecodableInterface provides a link between the (acoustic-modeling and
+ feature-processing) code and the decoder. The idea is to make this
+ interface as small as possible, and to make it as agnostic as possible about
+ the form of the acoustic model (e.g. don't assume the probabilities are a
+ function of just a vector of floats), and about the decoder (e.g. don't
+ assume it accesses frames in strict left-to-right order). For normal
+ models, without on-line operation, the "decodable" sub-class will just be a
+ wrapper around a matrix of features and an acoustic model, and it will
+ answer the question 'what is the acoustic likelihood for this index and this
+ frame?'.
+
+ For online decoding, where the features are coming in in real time, it is
+ important to understand the IsLastFrame() and NumFramesReady() functions.
+ There are two ways these are used: the old online-decoding code, in ../online/,
+ and the new online-decoding code, in ../online2/. In the old online-decoding
+ code, the decoder would do:
+ \code{.cc}
+ for (int frame = 0; !decodable.IsLastFrame(frame); frame++) {
+ // Process this frame
+ }
+ \endcode
+ and the call to IsLastFrame would block if the features had not arrived yet.
+ The decodable object would have to know when to terminate the decoding. This
+ online-decoding mode is still supported, it is what happens when you call, for
+ example, LatticeFasterDecoder::Decode().
+
+ We realized that this "blocking" mode of decoding is not very convenient
+ because it forces the program to be multi-threaded and makes it complex to
+ control endpointing. In the "new" decoding code, you don't call (for example)
+ LatticeFasterDecoder::Decode(), you call LatticeFasterDecoder::InitDecoding(),
+ and then each time you get more features, you provide them to the decodable
+ object, and you call LatticeFasterDecoder::AdvanceDecoding(), which does
+ something like this:
+ \code{.cc}
+ while (num_frames_decoded_ < decodable.NumFramesReady()) {
+ // Decode one more frame [increments num_frames_decoded_]
+ }
+ \endcode
+ So the decodable object never has IsLastFrame() called. For decoding where
+ you are starting with a matrix of features, the NumFramesReady() function will
+ always just return the number of frames in the file, and IsLastFrame() will
+ return true for the last frame.
+
+ For truly online decoding, the "old" online decodable objects in ../online/
+ have a "blocking" IsLastFrame() and will crash if you call NumFramesReady().
+ The "new" online decodable objects in ../online2/ return the number of frames
+ currently accessible if you call NumFramesReady(). You will likely not need
+ to call IsLastFrame(), but we implement it to only return true for the last
+ frame of the file once we've decided to terminate decoding.
+*/
+class DecodableInterface {
+ public:
+ /// Returns the log likelihood, which will be negated in the decoder.
+ /// The "frame" starts from zero. You should verify that NumFramesReady() > frame
+ /// before calling this.
+ virtual BaseFloat LogLikelihood(int32 frame, int32 index) = 0;
+
+ /// Returns true if this is the last frame. Frames are zero-based, so the
+ /// first frame is zero. IsLastFrame(-1) will return false, unless the file
+ /// is empty (which is a case that I'm not sure all the code will handle, so
+ /// be careful). Caution: the behavior of this function in an online setting
+ /// is being changed somewhat. In future it may return false in cases where
+ /// we haven't yet decided to terminate decoding, but later true if we decide
+ /// to terminate decoding. The plan in future is to rely more on
+ /// NumFramesReady(), and in future, IsLastFrame() would always return false
+ /// in an online-decoding setting, and would only return true in a
+ /// decoding-from-matrix setting where we want to allow the last delta or LDA
+ /// features to be flushed out for compatibility with the baseline setup.
+ virtual bool IsLastFrame(int32 frame) const = 0;
+
+ /// The call NumFramesReady() will return the number of frames currently available
+ /// for this decodable object. This is for use in setups where you don't want the
+ /// decoder to block while waiting for input. This is newly added as of Jan 2014,
+ /// and I hope, going forward, to rely on this mechanism more than IsLastFrame to
+ /// know when to stop decoding.
+ virtual int32 NumFramesReady() const {
+ KALDI_ERR << "NumFramesReady() not implemented for this decodable type.";
+ return -1;
+ }
+
+ /// Returns the number of states in the acoustic model
+ /// (they will be indexed one-based, i.e. from 1 to NumIndices();
+ /// this is for compatibility with OpenFst).
+ virtual int32 NumIndices() const = 0;
+
+ virtual ~DecodableInterface() {}
+};
+/// @}
+} // namespace Kaldi
+
+#endif // KALDI_ITF_DECODABLE_ITF_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/itf/online-feature-itf.h b/runtime/onnxruntime/third_party/kaldi/itf/online-feature-itf.h
new file mode 100644
index 000000000..3d139b461
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/itf/online-feature-itf.h
@@ -0,0 +1,125 @@
+// itf/online-feature-itf.h
+
+// Copyright 2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_ITF_ONLINE_FEATURE_ITF_H_
+#define KALDI_ITF_ONLINE_FEATURE_ITF_H_ 1
+#include "base/kaldi-common.h"
+#include "matrix/matrix-lib.h"
+
+namespace kaldi {
+/// @ingroup Interfaces
+/// @{
+
+/**
+ OnlineFeatureInterface is an interface for online feature processing (it is
+ also usable in the offline setting, but currently we're not using it for
+ that). This is for use in the online2/ directory, and it supersedes the
+ interface in ../online/online-feat-input.h. We have a slightly different
+ model that puts more control in the hands of the calling thread, and won't
+ involve waiting on semaphores in the decoding thread.
+
+ This interface only specifies how the object *outputs* the features.
+ How it obtains the features, e.g. from a previous object or objects of type
+ OnlineFeatureInterface, is not specified in the interface and you will
+ likely define new constructors or methods in the derived type to do that.
+
+ You should appreciate that this interface is designed to allow random
+ access to features, as long as they are ready. That is, the user
+ can call GetFrame for any frame less than NumFramesReady(), and when
+ implementing a child class you must not make assumptions about the
+ order in which the user makes these calls.
+*/
+
+class OnlineFeatureInterface {
+ public:
+ virtual int32 Dim() const = 0; /// returns the feature dimension.
+
+ /// Returns the total number of frames, since the start of the utterance, that
+ /// are now available. In an online-decoding context, this will likely
+ /// increase with time as more data becomes available.
+ virtual int32 NumFramesReady() const = 0;
+
+ /// Returns true if this is the last frame. Frame indices are zero-based, so the
+ /// first frame is zero. IsLastFrame(-1) will return false, unless the file
+ /// is empty (which is a case that I'm not sure all the code will handle, so
+ /// be careful). This function may return false for some frame if
+ /// we haven't yet decided to terminate decoding, but later true if we decide
+ /// to terminate decoding. This function exists mainly to correctly handle
+ /// end effects in feature extraction, and is not a mechanism to determine how
+ /// many frames are in the decodable object (as it used to be, and for backward
+ /// compatibility, still is, in the Decodable interface).
+ virtual bool IsLastFrame(int32 frame) const = 0;
+
+ /// Gets the feature vector for this frame. Before calling this for a given
+ /// frame, it is assumed that you called NumFramesReady() and it returned a
+ /// number greater than "frame". Otherwise this call will likely crash with
+ /// an assert failure. This function is not declared const, in case there is
+ /// some kind of caching going on, but most of the time it shouldn't modify
+ /// the class.
+ virtual void GetFrame(int32 frame, VectorBase<BaseFloat> *feat) = 0;
+
+
+ /// This is like GetFrame() but for a collection of frames. There is a
+ /// default implementation that just gets the frames one by one, but it
+ /// may be overridden for efficiency by child classes (since sometimes
+ /// it's more efficient to do things in a batch).
+ virtual void GetFrames(const std::vector<int32> &frames,
+ MatrixBase<BaseFloat> *feats) {
+ KALDI_ASSERT(static_cast<int32>(frames.size()) == feats->NumRows());
+ for (size_t i = 0; i < frames.size(); i++) {
+ SubVector<BaseFloat> feat(*feats, i);
+ GetFrame(frames[i], &feat);
+ }
+ }
+
+
+ // Returns frame shift in seconds. Helps to estimate duration from frame
+ // counts.
+ virtual BaseFloat FrameShiftInSeconds() const = 0;
+
+ /// Virtual destructor. Note: constructors that take another member of
+ /// type OnlineFeatureInterface are not expected to take ownership of
+ /// that pointer; the caller needs to keep track of that manually.
+ virtual ~OnlineFeatureInterface() { }
+
+};
+
+
+/// Add a virtual class for "source" features such as MFCC or PLP or pitch
+/// features.
+class OnlineBaseFeature: public OnlineFeatureInterface {
+ public:
+ /// This would be called from the application, when you get more wave data.
+ /// Note: the sampling_rate is typically only provided so the code can assert
+ /// that it matches the sampling rate expected in the options.
+ virtual void AcceptWaveform(BaseFloat sampling_rate,
+ const VectorBase<BaseFloat> &waveform) = 0;
+
+ /// InputFinished() tells the class you won't be providing any
+ /// more waveform. This will help flush out the last few frames
+ /// of delta or LDA features (it will typically affect the return value
+ /// of IsLastFrame.
+ virtual void InputFinished() = 0;
+};
+
+
+/// @}
+} // namespace Kaldi
+
+#endif // KALDI_ITF_ONLINE_FEATURE_ITF_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/itf/optimizable-itf.h b/runtime/onnxruntime/third_party/kaldi/itf/optimizable-itf.h
new file mode 100644
index 000000000..1b8f54b4f
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/itf/optimizable-itf.h
@@ -0,0 +1,51 @@
+// itf/optimizable-itf.h
+
+// Copyright 2009-2011 Go Vivace Inc.; Microsoft Corporation; Georg Stemmer
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#ifndef KALDI_ITF_OPTIMIZABLE_ITF_H_
+#define KALDI_ITF_OPTIMIZABLE_ITF_H_
+
+#include "base/kaldi-common.h"
+#include "matrix/matrix-lib.h"
+
+namespace kaldi {
+/// @ingroup Interfaces
+/// @{
+
+/// OptimizableInterface provides
+/// a virtual class for optimizable objects.
+/// E.g. a class that computed a likelihood function and
+/// its gradient using some parameter
+/// that has to be optimized on data
+/// could inherit from it.
+template<class Real>
+class OptimizableInterface {
+ public:
+ /// computes gradient for a parameter params and returns it
+ /// in gradient_out
+ virtual void ComputeGradient(const Vector<Real> &params,
+ Vector<Real> *gradient_out) = 0;
+ /// computes the function value for a parameter params
+ /// and returns it
+ virtual Real ComputeValue(const Vector<Real> &params) = 0;
+
+ virtual ~OptimizableInterface() {}
+};
+/// @} end of "Interfaces"
+} // end namespace kaldi
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/itf/options-itf.h b/runtime/onnxruntime/third_party/kaldi/itf/options-itf.h
new file mode 100644
index 000000000..204f46d66
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/itf/options-itf.h
@@ -0,0 +1,49 @@
+// itf/options-itf.h
+
+// Copyright 2013 Tanel Alumae, Tallinn University of Technology
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_ITF_OPTIONS_ITF_H_
+#define KALDI_ITF_OPTIONS_ITF_H_ 1
+#include "base/kaldi-common.h"
+
+namespace kaldi {
+
+class OptionsItf {
+ public:
+
+ virtual void Register(const std::string &name,
+ bool *ptr, const std::string &doc) = 0;
+ virtual void Register(const std::string &name,
+ int32 *ptr, const std::string &doc) = 0;
+ virtual void Register(const std::string &name,
+ uint32 *ptr, const std::string &doc) = 0;
+ virtual void Register(const std::string &name,
+ float *ptr, const std::string &doc) = 0;
+ virtual void Register(const std::string &name,
+ double *ptr, const std::string &doc) = 0;
+ virtual void Register(const std::string &name,
+ std::string *ptr, const std::string &doc) = 0;
+
+ virtual ~OptionsItf() {}
+};
+
+} // namespace Kaldi
+
+#endif // KALDI_ITF_OPTIONS_ITF_H_
+
+
diff --git a/runtime/onnxruntime/third_party/kaldi/itf/transition-information.h b/runtime/onnxruntime/third_party/kaldi/itf/transition-information.h
new file mode 100644
index 000000000..4592e8c54
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/itf/transition-information.h
@@ -0,0 +1,108 @@
+// itf/transition-information.h
+
+// Copyright 2021 NVIDIA (author: Daniel Galvez)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_ITF_TRANSITION_INFORMATION_H_
+#define KALDI_ITF_TRANSITION_INFORMATION_H_
+
+#include <stdint.h>
+#include <vector>
+
+namespace kaldi {
+
+/**
+ * Class that abstracts out TransitionModel's methods originally used
+ * in the lat/ directory. By instantiating a subclass of this abstract
+ * class other than TransitionModel, you can use kaldi's lattice tools
+ * without a dependency on the hmm/ and tree/ directories. For
+ * example, you can consider creating a subclass that implements these
+ * via extracting information from Eesen's CTC T.fst object.
+ *
+ * TransitionId values must be contiguous, and starting from 1, rather
+ * than 0, since 0 corresponds to epsilon in OpenFST.
+ */
+class TransitionInformation {
+ public:
+ virtual ~TransitionInformation() {};
+ /**
+ * Returns true if trans_id1 and trans_id2 can correspond to the
+ * same phone when trans_id1 immediately precedes trans_id2 (i.e.,
+ * trans_id1 occurss at timestep t, and trans_id2 ocurs at timestep
+ * 2) (possibly with epsilons between trans_id1 and trans_id2) OR
+ * trans_id1 ocurs before trans_id2, with some number of
+ * trans_id_{k} values, all of which fulfill
+ * TransitionIdsEquivalent(trans_id1, trans_id_{k})
+ *
+ * If trans_id1 == trans_id2, it must be the case that
+ * TransitionIdsEquivalent(trans_id1, trans_id2) == true
+ */
+ virtual bool TransitionIdsEquivalent(int32_t trans_id1, int32_t trans_id2) const = 0;
+ /**
+ * Returns true if this trans_id corresponds to the start of a
+ * phone.
+ */
+ virtual bool TransitionIdIsStartOfPhone(int32_t trans_id) const = 0;
+ /**
+ * Phone is a historical term, and should be understood in a wider
+ * sense that also includes graphemes, word pieces, etc.: any
+ * minimal entity in your problem domain which is represented by a
+ * sequence of transitions with a PDF assigned to each of them by
+ * the model. In this sense, Token is a better word. Since
+ * TransitionInformation was added to subsume TransitionModel, we
+ * did not want to change the call site of every
+ * TransitionModel::TransitionIdToPhone to
+ * TransitionInformation::TransitionIdToToken.
+ */
+ virtual int32_t TransitionIdToPhone(int32_t trans_id) const = 0;
+ /**
+ * Returns true if the destination of any edge with this trans_id
+ * as its ilabel is a final state (or if a final state is
+ * epsilon-reachable from its destination state).
+ */
+ virtual bool IsFinal(int32_t trans_id) const = 0;
+ /**
+ * Returns true if *all* of the FST edge labeled by this trans_id
+ * have the same start and end states.
+ */
+ virtual bool IsSelfLoop(int32_t trans_id) const = 0;
+ int32_t TransitionIdToPdf(int32_t trans_id) const {
+ return TransitionIdToPdfArray()[trans_id];
+ }
+ /**
+ * Returns the contiguous array that backs calls to
+ * TransitionIdToPdf().
+ *
+ * Ideally, this would return a std::span, but it doesn't because
+ * kaldi doesn't support C++20 at the time this interface was
+ * written.
+ */
+ virtual const std::vector<int32_t>& TransitionIdToPdfArray() const = 0;
+ int32_t NumTransitionIds() const {
+ return TransitionIdToPdfArray().size() - 1;
+ }
+ /**
+ * Return the number of distinct outputs from
+ * TransitionIdToPdf(). Another way to look at this is as the number
+ * of outputs over which your acoustic model does a softmax.
+ */
+ virtual int32_t NumPdfs() const = 0;
+};
+
+} // namespace kaldi
+
+#endif // KALDI_TRANSITION_INFORMATION_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/Makefile b/runtime/onnxruntime/third_party/kaldi/lat/Makefile
new file mode 100644
index 000000000..7718f47f0
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/Makefile
@@ -0,0 +1,24 @@
+
+all:
+
+include ../kaldi.mk
+
+EXTRA_CXXFLAGS += -Wno-sign-compare
+
+TESTFILES = kaldi-lattice-test push-lattice-test minimize-lattice-test \
+ determinize-lattice-pruned-test word-align-lattice-lexicon-test
+
+OBJFILES = kaldi-lattice.o lattice-functions.o \
+ lattice-functions-transition-model.o word-align-lattice.o \
+ phone-align-lattice.o word-align-lattice-lexicon.o sausages.o \
+ push-lattice.o minimize-lattice.o determinize-lattice-pruned.o \
+ confidence.o compose-lattice-pruned.o
+
+LIBNAME = kaldi-lat
+
+ADDLIBS = ../hmm/kaldi-hmm.a ../tree/kaldi-tree.a ../util/kaldi-util.a \
+ ../matrix/kaldi-matrix.a ../base/kaldi-base.a
+
+
+include ../makefiles/default_rules.mk
+
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/arctic-weight.h b/runtime/onnxruntime/third_party/kaldi/lat/arctic-weight.h
new file mode 100644
index 000000000..5c0c6d3c4
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/arctic-weight.h
@@ -0,0 +1,153 @@
+// lat/arctic-weight.h
+
+// Copyright 2012 Johns Hopkins University (Author: Guoguo Chen)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_LAT_ARCTIC_WEIGHT_H_
+#define KALDI_LAT_ARCTIC_WEIGHT_H_
+
+#include "fst/float-weight.h"
+
+namespace fst {
+
+// Arctic semiring: (max, +, inf, 0)
+// We define the Arctic semiring T' = (R \cup {-inf, +inf}, max, +, -inf, 0).
+// The term "Arctic" came from Keith Kintzley ([email protected]), as opposite
+// to the Tropical semiring.
+template <class T>
+class ArcticWeightTpl : public FloatWeightTpl<T> {
+ public:
+ using FloatWeightTpl<T>::Value;
+
+ typedef ArcticWeightTpl<T> ReverseWeight;
+
+ ArcticWeightTpl() : FloatWeightTpl<T>() {}
+
+ ArcticWeightTpl(T f) : FloatWeightTpl<T>(f) {}
+
+ ArcticWeightTpl(const ArcticWeightTpl<T> &w) : FloatWeightTpl<T>(w) {}
+
+ static const ArcticWeightTpl<T> Zero() {
+ return ArcticWeightTpl<T>(-std::numeric_limits<T>::infinity()); }
+
+ static const ArcticWeightTpl<T> One() {
+ return ArcticWeightTpl<T>(0.0F); }
+
+ static const std::string &Type() {
+ static const std::string type = std::string("arctic") +
+ FloatWeightTpl<T>::GetPrecisionString();
+ return type;
+ }
+
+ static ArcticWeightTpl<T> NoWeight() {
+ return ArcticWeightTpl<T>(std::numeric_limits<T>::infinity());
+ }
+
+ bool Member() const {
+ // First part fails for IEEE NaN
+ return Value() == Value() && Value() != std::numeric_limits<T>::infinity();
+ }
+
+ ArcticWeightTpl<T> Quantize(float delta = kDelta) const {
+ if (Value() == -std::numeric_limits<T>::infinity() ||
+ Value() == std::numeric_limits<T>::infinity() ||
+ Value() != Value())
+ return *this;
+ else
+ return ArcticWeightTpl<T>(floor(Value()/delta + 0.5F) * delta);
+ }
+
+ ArcticWeightTpl<T> Reverse() const { return *this; }
+
+ static uint64 Properties() {
+ return kLeftSemiring | kRightSemiring | kCommutative |
+ kPath | kIdempotent;
+ }
+};
+
+// Single precision arctic weight
+typedef ArcticWeightTpl<float> ArcticWeight;
+
+template <class T>
+inline ArcticWeightTpl<T> Plus(const ArcticWeightTpl<T> &w1,
+ const ArcticWeightTpl<T> &w2) {
+ return w1.Value() > w2.Value() ? w1 : w2;
+}
+
+inline ArcticWeightTpl<float> Plus(const ArcticWeightTpl<float> &w1,
+ const ArcticWeightTpl<float> &w2) {
+ return Plus<float>(w1, w2);
+}
+
+inline ArcticWeightTpl<double> Plus(const ArcticWeightTpl<double> &w1,
+ const ArcticWeightTpl<double> &w2) {
+ return Plus<double>(w1, w2);
+}
+
+template <class T>
+inline ArcticWeightTpl<T> Times(const ArcticWeightTpl<T> &w1,
+ const ArcticWeightTpl<T> &w2) {
+ T f1 = w1.Value(), f2 = w2.Value();
+ if (f1 == -std::numeric_limits<T>::infinity())
+ return w1;
+ else if (f2 == -std::numeric_limits<T>::infinity())
+ return w2;
+ else
+ return ArcticWeightTpl<T>(f1 + f2);
+}
+
+inline ArcticWeightTpl<float> Times(const ArcticWeightTpl<float> &w1,
+ const ArcticWeightTpl<float> &w2) {
+ return Times<float>(w1, w2);
+}
+
+inline ArcticWeightTpl<double> Times(const ArcticWeightTpl<double> &w1,
+ const ArcticWeightTpl<double> &w2) {
+ return Times<double>(w1, w2);
+}
+
+template <class T>
+inline ArcticWeightTpl<T> Divide(const ArcticWeightTpl<T> &w1,
+ const ArcticWeightTpl<T> &w2,
+ DivideType typ = DIVIDE_ANY) {
+ T f1 = w1.Value(), f2 = w2.Value();
+ if (f2 == -std::numeric_limits<T>::infinity())
+ return std::numeric_limits<T>::quiet_NaN();
+ else if (f1 == -std::numeric_limits<T>::infinity())
+ return -std::numeric_limits<T>::infinity();
+ else
+ return ArcticWeightTpl<T>(f1 - f2);
+}
+
+inline ArcticWeightTpl<float> Divide(const ArcticWeightTpl<float> &w1,
+ const ArcticWeightTpl<float> &w2,
+ DivideType typ = DIVIDE_ANY) {
+ return Divide<float>(w1, w2, typ);
+}
+
+inline ArcticWeightTpl<double> Divide(const ArcticWeightTpl<double> &w1,
+ const ArcticWeightTpl<double> &w2,
+ DivideType typ = DIVIDE_ANY) {
+ return Divide<double>(w1, w2, typ);
+}
+
+
+
+} // namespace fst
+
+#endif // KALDI_LAT_ARCTIC_WEIGHT_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/compose-lattice-pruned.cc b/runtime/onnxruntime/third_party/kaldi/lat/compose-lattice-pruned.cc
new file mode 100644
index 000000000..cc71db38e
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/compose-lattice-pruned.cc
@@ -0,0 +1,955 @@
+// lat/compose-lattice-pruned.cc
+
+// Copyright 2009-2012 Microsoft Corporation
+// 2012-2013 Johns Hopkins University (Author: Daniel Povey)
+// 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "lat/compose-lattice-pruned.h"
+#include "lat/lattice-functions.h"
+
+namespace kaldi {
+
+/**
+ PrunedCompactLatticeComposer implements an algorithm for pruned composition.
+ It uses a heuristic (like the heuristics used in A*) to estimate the
+ cost to the end of a graph, of the best path that we might get if
+ we expand a particular transition out of a particular state. This enables
+ us to use a priority queue to expand arcs in the composed result in an
+ order roughly from most promising to least promising.
+
+ Because some of the quantities used in the heuristic are hard to efficiently
+ keep updated as the composed output is incrementally added to, we
+ periodically recompute these quantities (c.f. RecomputePruningInfo()).
+ In order to prevent this periodic recomputation from dominating the time
+ taken to produce the lattice, we recompute these things on a schedule where,
+ between each computation, we allow the size of the output to grow by
+ a constant factor (default: 1.5). Since the time taken to do the
+ recomputation of quantities used in the heuristic takes time linear in the
+ size of the so-far existing composed output, doing so on this type of schedule
+ will add no more than a constant factor to the runtime.
+
+ */
+class PrunedCompactLatticeComposer {
+ public:
+ PrunedCompactLatticeComposer(
+ const ComposeLatticePrunedOptions &opts,
+ const CompactLattice &clat,
+ fst::DeterministicOnDemandFst<fst::StdArc> *det_fst,
+ CompactLattice* composed_clat);
+
+ // Does the composition. You must call this just once per object.
+ void Compose();
+
+ private:
+
+ // Gets the num-arcs limit for this iteration of the algorithm, which will be
+ // opts_.initial_num_arcs if there are currently no arcs; or otherwise
+ // opts_.growth_ration * the current number of arcs (subject to the
+ // opts_.max_arcs limit if we have already reached a final-state). This helps
+ // ensure that we call RecomputePruningInfo() on an appropriate schedule.
+ int32 GetCurrentArcLimit() const;
+
+ // This function, called just once at the start, computes all the static
+ // information about the input lattice 'clat', in lat_state_info_. (however,
+ // the 'composed_states' members are just set to the empty vector for now.
+ void ComputeLatticeStateInfo();
+
+ // Called just once at the start, this sets up the first state in the
+ // composed output.
+ void AddFirstState();
+
+ // This function processes the next un-expanded transition (or final-state)
+ // out of the composed state numbered 'composed_state_to_expand'.
+ void ProcessQueueElement(int32 composed_state_to_expand);
+
+ // This is a part of ProcessQueueElements() that has been broken out
+ // for clarity. it process the arc_index'th arc out of this source state.
+ void ProcessTransition(int32 composed_src_state,
+ int32 arc_index);
+
+ // This function recomputes certain members of the ComposedStateInfo relating
+ // to the output states: namely, 'forward_cost', 'backward_cost' and
+ // 'delta_backward_cost'. In between calls to this function, we try to
+ // keep those quantities as accurate as possible, but they aren't
+ // completely accurate (see comments by their declarations for more info).
+ void RecomputePruningInfo();
+
+ // Sets '*composed_states' to a list of the states that currently
+ // exist in the composed output, in topologically sorted order.
+ // At exit, *composed_states will be a permutation of numbers
+ // [0, 1, ... clat_out_->NumStates() - 1], beginning with the
+ // start-state 0.
+ void GetTopsortedStateList(std::vector<int32> *composed_states) const;
+
+ // Called from RecomputePruningInfo(), this computes all the 'forward_cost'
+ // and 'prev_composed_state' members of the ComposedStateInfo.
+ // @param [in] composed_states This is expected to be a list,
+ // in topological order, of all currently existing composed states,
+ // as produced by GetTopsortedStateList().
+ void ComputeForwardCosts(const std::vector<int32> &composed_states);
+
+ // Called from RecomputePruningInfo(), this computes all the 'backward_cost'
+ // members of the ComposedStateInfo. It also sets 'output_best_cost_'.
+ // 'composed_states' is expected to be a list, in topological order, of all
+ // currently existing composed states, as produced by GetTopsortedStateList().
+ void ComputeBackwardCosts(const std::vector<int32> &composed_states);
+
+ // Called from RecomputePruningInfo(), this computes all the
+ // 'delta_backward_cost' members of the ComposedStateInfo. 'composed_states'
+ // is expected to be a list, in topological order, of all currently existing
+ // composed states, as produced by GetTopsortedStateList(). It also computes
+ // the 'expected_cost_offset' values for all states, and uses them recreate
+ // 'composed_state_queue_'.
+ void ComputeDeltaBackwardCosts(const std::vector<int32> &composed_states);
+
+
+ // This struct contains information about a state of the input lattice.
+ struct LatticeStateInfo {
+ // 'backward_cost' is the total cost of the best path from this state to
+ // the final state in the source lattice, including the final-prob.
+ double backward_cost;
+
+ // 'arc_delta_costs' is an array, one for each arc (and the final-prob, if
+ // present), showing how much the cost to the final-state for the best path
+ // starting in this state and exiting through each arc (or final-prob),
+ // differs from 'backward_cost'. Specifically, it contains pairs
+ // (delta_cost, arc_index), where delta_cost >= 0 and arc_index is
+ // either the index into this state's array of arcs (for arcs), or -1
+ // if this represents the final-prob.
+ //
+ // 'arc_delta_costs' will be sorted, so that the first element has
+ // .first=0.0 and the delta-costs will be increasing order. This means that
+ // we expand them from the start of the array, in order to process the best
+ // arcs first.
+ // lat_state_info_[i].arc_delta_costs.size() will equal will equal
+ // clat_.NumStates(i), plus one if clat_.Final(i) != Zero().
+ std::vector<std::pair<BaseFloat, int32> > arc_delta_costs;
+
+
+ // 'composed_states' is a list of the state-ids in the composed output
+ // that correspond to this state in the lattice, so we expect
+ // that composed_state_info_[composed_states[i]].lat_state
+ // equals the index of this lattice state. This is helpful in
+ // accessing the states in the output lattice in topological
+ // order.
+ std::vector<int32> composed_states;
+ };
+
+ // This struct contains information about a state of the composed
+ // output.
+ struct ComposedStateInfo {
+ // 'lat_state' and 'lm_state' form the pair of states in the two FSTs
+ // that this state corresponds to. The unordered map 'pair_to_state_' maps these
+ // state-pairs to the index of the composed state (the state-index in clat_out_).
+ int32 lat_state;
+ int32 lm_state;
+
+ // the number of arcs on the path from the start state to this state, in the
+ // composed lattice, by which this state was first reached.
+ int32 depth;
+
+ // If you have just called RecomputePruningInfo(), then
+ // 'forward_cost' will equal the cost of the best path from the start-state
+ // to this state, in the composed output.
+ //
+ // In between calls to RecomputePruningInfo() it may not always be fully up
+ // to date; instead it will be an upper bound on what it would be if you had
+ // just called RecomputePruningInfo(); it will be the cost of some path but
+ // not necessarily the best path.
+ double forward_cost;
+
+ // 'backward_cost' relates to the cost from this state to the final-state in
+ // the composed FST. (By this we mean, more precisely, the cost of the best
+ // path from this state to any final state, including the final-prob in that
+ // final state).
+ //
+ // If we have just called RecomputePruningInfo(), then the following rules
+ // specify what the value of 'backward_cost' will be:
+ // - If a final state is reachable from this state, backward_cost
+ // will contain the cost of the best path from this state to the
+ // final state (including the corresponding final-prob).
+ // - Otherwise, it will contain +infinity.
+ //
+ // If RecomputePruningInfo() has not just been called), it may contain any
+ // value that is >= the value the the rules above specify (since, for
+ // existing states, we don't modify it between calls to
+ // RecomputePruningInfo()). For states that have been added since
+ // RecomputePruningInfo() was last called, it will be infinity.
+ double backward_cost;
+
+ // 'delta_backward_cost' is a quantity that is used in our heuristic of the
+ // cost to an end-state from expanding a previously un-expanded arc. It is
+ // an estimate of the difference between the backward cost in this struct
+ // (this->backward_cost) and the backward cost in the input lattice
+ // (LatticeStateInfo::backward_cost). This term reflects the anticipated
+ // extra costs from 'det_fst_', which, while fairly close to zero, may be
+ // substantial enough to want to correct for.
+ //
+ // The following is the value that 'delta_backward_cost' will have if
+ // RecomputePruningInfo() has just been called:
+ // - If backward_cost is finite (this state in the composed result can
+ // reach the final state via currently expanded states), then
+ // delta_backward_cost is this->backward_cost minus
+ // lat_state_info_[lat_state].backward_cost. (It will mostly, but
+ // not always, be <= 0, reflecting that the new LM is better than
+ // the old LM).
+ // - On the other hand, if backward_cost is infinite: delta_backward_cost
+ // is set to the delta_backward_cost of the previous state on the best
+ // path from the start state of the composed result to this state (or
+ // zero if this is the start state).
+ //
+ // If RecomputePruningInfo() has not just been called, then:
+ // - For states created since RecomputePruningInfo() was last called,
+ // delta_backward_cost will be inherited from the source state from
+ // which the new state was expanded.
+ // - For other states, delta_backward_cost will be unchanged since
+ // RecomputePruningInfo() was last called.
+ // The above rules may make the delta_backward_cost a less accurate, but
+ // still probably reasonable, heuristic. What it is a heuristic for,
+ // is: if we were to successfully reach an end-state of the composed output
+ // from this state, what would be the resulting backward_cost
+ // minus lat_state_info_[lat_state].backward_cost.
+ BaseFloat delta_backward_cost;
+
+ // 'prev_composed_state' is the previous state on the best path from
+ // the start-state to the current state (or -1 if this is the start state).
+ // It is computed in RecomputePruningInfo() when setting up 'forward_cost',
+ // and then used to compute delta_backward_cost. It is not otherwise
+ // used.
+ int32 prev_composed_state;
+
+ // 'sorted_arc_index' is an index into the 'arc_delta_costs' array which is
+ // a member of the LatticeStateInfo object corresponding to the lattice
+ // state 'lat_state'. It corresponds to the next arc (or final-prob) out of
+ // the input lattice that we have yet to expand in the composition; or -1 if
+ // we have expanded all of them. When we first reach a composed state,
+ // 'sorted_arc_index' will be zero; then it will increase one at a time as
+ // we expand arcs until either the composition terminates or we have
+ // expanded all the arcs and it becomes -1.
+ int32 sorted_arc_index;
+
+ // 'arc_delta_cost' is a derived quantity that we store here for easier
+ // access. Suppose this_lat_info is lat_state_info_[lat_state]; then
+ // if sorted_arc_index >= 0, then:
+ // arc_delta_cost == this_lat_info.arc_delta_costs[sorted_arc_index].first
+ // else: arc_delta_cost == +infinity.
+ //
+ // what 'arc_delta_cost' represents (or is a heuristic for), is the expected
+ // cost of a path to the final-state leaving through the arc we're about to
+ // expand, minus the expected cost of any path to the final-state starting
+ // from this state.
+ BaseFloat arc_delta_cost;
+
+ // view 'expected_cost_offset' a phantom field of this struct, that has
+ // been optimized out. It's clearer if we act like it's a field, but
+ // actually it's not stored.
+ //
+ // 'expected_cost_offset' is a derived quantity that reflects the expected
+ // cost (according to our heuristic) of the best path we might encounter
+ // when expanding the next previously unseen arc (or final-prob),
+ // corresponding to 'sorted_arc_index'. (This is the expected cost of a
+ // successful path, from the beginning to the end of the lattice, but
+ // constrained to be a path that contains the arc we're about to expand).
+ //
+ // The 'offset' part is about subtracting the best cost of the lattice, so we
+ // can cast to float without too much loss of accuracy:
+ // expected_cost_offset = expected_cost - lat_best_cost_.
+ //
+ // We define expected_cost_offset by defining the 'expected_cost' part;
+ // for clarity:
+ // First, let lat_backward_cost equal the backward_cost of the LatticeStateInfo
+ // corresponding to 'lat_state', i.e.
+ // lat_backward_cost = lat_state_info_[lat_state].backward_cost. Then:
+ // expected_cost = forward_cost + lat_backward_cost +
+ // delta_backward_cost + arc_delta_cost.
+ // expected_cost_offset will always equal the above minus lat_best_cost_.
+ //
+ // The formula for expected_cost above is a pretty good heuristic for what
+ // the cost to the end-state will be. If the costs in det_fst_ were zero,
+ // then the expression (forward_cost + lat_backward_cost + arc_delta_cost)
+ // would be exact, and we would expand things in the ideal, best-first
+ // order. "delta_backward_cost" is a reasonable approximation for the extra
+ // costs from 'det_fst_'.
+ // BaseFloat expected_cost_offset;
+ };
+
+ // This bool variable is initialized to false, and will be updated to true
+ // the first time a Final() function is called on the det_fst_. Then we will
+ // immediately call RecomputeRruningInfo() so that the output_best_cost_ is
+ // changed from +inf to a finite value, to be used in beam search. This is the
+ // only time the RecomputeRruningInfo() function is called manually; otherwise
+ // it always follows an automatic schedule based on the num-arcs of the output
+ // lattice.
+ bool output_reached_final_;
+
+ // This variable, which we set initially to -1000, makes sure that in the
+ // beginning of the algorithm, we always prioritize exploring the lattice
+ // in a depth-first way. Once we find a path reaching a final state, this
+ // variable will be reset to 0.
+ // The reason we do this is because the beam-search depends on a good estimate
+ // of the composed-best-cost, which before we reach a final state, we instead
+ // borrow the value from best-cost from the input lattice, which is usually
+ // systematically worse than the RNNLM scores, and makes the algorithm spend
+ // a lot of time before reaching any final state, especially if the input
+ // lattices are large.
+ float depth_penalty_;
+ const ComposeLatticePrunedOptions &opts_;
+ const CompactLattice &clat_in_;
+ fst::DeterministicOnDemandFst<fst::StdArc> *det_fst_;
+ CompactLattice *clat_out_;
+
+ // This counter keeps track of the number of arcs in the output lattice
+ // clat_out_. When it exceeds max_arcs,
+ int32 num_arcs_out_;
+
+ std::vector<LatticeStateInfo> lat_state_info_;
+
+ // 'lat_best_cost' is the cost of the best path in the input lattice,
+ // equal to lat_state_info_[0].backward_cost (we check that 0 is the
+ // start state in the input lattice).
+ double lat_best_cost_;
+
+ // 'output_best_cost_' is the cost of the best successful path in the output
+ // lattice 'clat_out_'; or +infinity if 'clat_out_' does not yet have any
+ // successful paths. It is updated only when RecomputePruningInfo() is
+ // called.
+ double output_best_cost_;
+
+
+ // current_cutoff_ is a value used in deciding which composed states
+ // need to be included in the queue. Each time RecomputePruningInfo()
+ // called, current_cutoff_ is set to
+ // (output_best_cost_ - lat_best_cost_ + opts_.lattice_compose_beam).
+ // It will be +infinity if the output lattice doesn't yet have any
+ // successful paths. It decreases with time. You can compare the
+ // phantom 'expected_cost_offset' members of ComposedStateInfo with this
+ // value; if they are more than this value, then there is no need
+ // to enter the corresponding state into the queue.
+ BaseFloat current_cutoff_;
+
+ typedef std::priority_queue<std::pair<BaseFloat, int32>,
+ std::vector<std::pair<BaseFloat, int32> >,
+ std::greater<std::pair<BaseFloat, int32> > > QueueType;
+
+ // composed_state_queue_ is a priority queue of the composed states
+ // that we are intending to expand. It contains pairs
+ // (expected_cost_offset, composed_state_index),
+ // where expected_cost_offset == the phantom variable
+ // composed_state_info_[composed_state_index].expected_cost_offset.
+ // We process the states from lowest cost first.
+ // Every time RecomputePruningInfo() is called, this is cleared and repopulated
+ // (since the states' expected_cost_offset values may change), and in between
+ // calls to RecomputePruningInfo(), we do insert elements for newly created
+ // states.
+ QueueType composed_state_queue_;
+
+
+ std::vector<ComposedStateInfo> composed_state_info_;
+
+ // This maps a pair (lat_state, lm_state) to the index of the
+ // state in the composed FST. That would correspond to a state-id in
+ // clat_out_, and also to an index into 'composed_state_info_'.
+ unordered_map<std::pair<int32,int32>,
+ int32, PairHasher<int32> > pair_to_state_;
+
+ // This contains the set of state-indexes of the input lattice that already
+ // have states in the composed output (i.e. is in accessed_lat_states_ if and
+ // only if !lat_state_info_[i].composed_states.empty(). The point is to be
+ // able to enumerate, in order or in reverse order, just those states in the
+ // lattice that appear in the composed output (it's an efficiency thing that
+ // will matter more for early iterations of the composition, when we need
+ // to access the output lattice in topological order).
+ std::set<int32> accessed_lat_states_;
+};
+
+
+void PrunedCompactLatticeComposer::GetTopsortedStateList(
+ std::vector<int32> *composed_states) const {
+ composed_states->clear();
+ composed_states->reserve(clat_out_->NumStates());
+ std::set<int32>::const_iterator iter = accessed_lat_states_.begin(),
+ end = accessed_lat_states_.end();
+ for (; iter != end; ++iter) {
+ int32 lat_state = *iter;
+ const LatticeStateInfo &input_lat_info = lat_state_info_[lat_state];
+ composed_states->insert(composed_states->end(),
+ input_lat_info.composed_states.begin(),
+ input_lat_info.composed_states.end());
+ }
+ KALDI_ASSERT((*composed_states)[0] == 0 &&
+ static_cast<int32>(composed_states->size()) ==
+ clat_out_->NumStates());
+}
+
+int32 PrunedCompactLatticeComposer::GetCurrentArcLimit() const {
+ int32 current_num_arcs = num_arcs_out_;
+ if (current_num_arcs == 0) {
+ return opts_.initial_num_arcs;
+ } else {
+ KALDI_ASSERT(opts_.growth_ratio > 1.0);
+ int32 ans = static_cast<int32>(current_num_arcs *
+ opts_.growth_ratio);
+ if (ans == current_num_arcs) // make sure the target increases.
+ ans = current_num_arcs + 1;
+ // if we have already reached a final state, then
+ // apply the max_arcs limit.
+ if (output_best_cost_ - output_best_cost_ == 0.0 &&
+ ans > opts_.max_arcs)
+ ans = opts_.max_arcs;
+ return ans;
+ }
+
+}
+
+
+void PrunedCompactLatticeComposer::RecomputePruningInfo() {
+ std::vector<int32> all_composed_states;
+ GetTopsortedStateList(&all_composed_states);
+ ComputeForwardCosts(all_composed_states);
+ ComputeBackwardCosts(all_composed_states);
+ ComputeDeltaBackwardCosts(all_composed_states);
+}
+
+void PrunedCompactLatticeComposer::ComputeForwardCosts(
+ const std::vector<int32> &composed_states) {
+ KALDI_ASSERT(composed_states[0] == 0);
+
+ // Note: when we initialized composed_state_info_[0]
+ // we set forward_cost = 0.0, prev_composed_state = -1.
+
+ std::vector<ComposedStateInfo>::iterator
+ state_iter = composed_state_info_.begin(),
+ state_end = composed_state_info_.end();
+
+ state_iter->depth = 0; // start state has depth 0
+ ++state_iter; // Skip over the start state.
+ // Set all other forward_cost fields to infinity and prev_composed_state to
+ // -1.
+ for (; state_iter != state_end; ++state_iter) {
+ state_iter->forward_cost = std::numeric_limits<double>::infinity();
+ state_iter->prev_composed_state = -1;
+ }
+
+ std::vector<int32>::const_iterator state_index_iter = composed_states.begin(),
+ state_index_end = composed_states.end();
+ for (; state_index_iter != state_index_end; ++state_index_iter) {
+ int32 composed_state_index = *state_index_iter;
+ const ComposedStateInfo &info = composed_state_info_[
+ composed_state_index];
+ double forward_cost = info.forward_cost;
+ // The next line is a check for infinity. If infinities have appeared, it
+ // either means there is a bug in the algorithm or there were infinities or
+ // NaN's in the lattice.
+ KALDI_ASSERT(forward_cost - forward_cost == 0.0);
+ fst::ArcIterator<CompactLattice> aiter(*clat_out_,
+ composed_state_index);
+ for (; !aiter.Done(); aiter.Next()) {
+ const CompactLatticeArc &arc = aiter.Value();
+ double arc_cost = ConvertToCost(arc.weight),
+ next_forward_cost = forward_cost + arc_cost;
+ ComposedStateInfo &next_info = composed_state_info_[arc.nextstate];
+ if (next_info.forward_cost > next_forward_cost) {
+ next_info.forward_cost = next_forward_cost;
+ next_info.prev_composed_state = composed_state_index;
+ next_info.depth = composed_state_info_[composed_state_index].depth + 1;
+ }
+ }
+ }
+}
+
+void PrunedCompactLatticeComposer::ComputeBackwardCosts(
+ const std::vector<int32> &composed_states) {
+ // Access the composed states in reverse topological order from latest to
+ // earliest.
+ std::vector<int32>::const_reverse_iterator iter = composed_states.rbegin(),
+ end = composed_states.rend();
+ for (; iter != end; ++iter) {
+ int32 composed_state_index = *iter;
+ ComposedStateInfo &info = composed_state_info_[composed_state_index];
+ double backward_cost =
+ ConvertToCost(clat_out_->Final(composed_state_index));
+ fst::ArcIterator<CompactLattice> aiter(*clat_out_,
+ composed_state_index);
+ for (; !aiter.Done(); aiter.Next()) {
+ const CompactLatticeArc &arc = aiter.Value();
+ double arc_cost = ConvertToCost(arc.weight),
+ next_backward_cost = composed_state_info_[arc.nextstate].backward_cost,
+ this_backward_cost = arc_cost + next_backward_cost;
+ if (this_backward_cost < backward_cost)
+ backward_cost = this_backward_cost;
+ }
+ // It's OK if at this point, backward_cost is still +infinity. This means
+ // that this state cannot reach the end yet, which means we have not yet
+ // expanded any path from this state all the way to a final-state of the
+ // output.
+ info.backward_cost = backward_cost;
+ }
+ output_best_cost_ = composed_state_info_[0].backward_cost;
+ // See the declaration of current_cutoff_ for more information. Note: on
+ // early iterations, before any path reaches a final state of the composed
+ // lattice, current_cutoff_ may be +infinity, and this is OK.
+ current_cutoff_ =
+ output_best_cost_ - lat_best_cost_ + opts_.lattice_compose_beam;
+}
+
+void PrunedCompactLatticeComposer::ComputeDeltaBackwardCosts(
+ const std::vector<int32> &composed_states) {
+
+ int32 num_states = clat_out_->NumStates();
+ for (int32 composed_state_index = 0; composed_state_index < num_states;
+ ++composed_state_index) {
+ ComposedStateInfo &info = composed_state_info_[composed_state_index];
+ int32 lat_state = info.lat_state;
+ // Note: delta_backward_cost will be +infinity at this stage if the
+ // backward_cost was +infinity. This is OK; we'll set them all to
+ // finite values later in this function.
+ info.delta_backward_cost =
+ info.backward_cost - lat_state_info_[lat_state].backward_cost + info.depth * depth_penalty_;
+ }
+
+ // 'queue_elements' is a list of items (expected_cost_offset,
+ // composed_state_index) that we are going to add to composed_state_queue_,
+ // after clearing it. It's more efficient to accumulate them as a vector
+ // and add them all at once, than adding them one by one (search online for
+ // "heapify" if this seems confusing).
+ std::vector<std::pair<BaseFloat, int32> > queue_elements;
+ queue_elements.reserve(num_states);
+
+ double lat_best_cost = lat_best_cost_;
+ BaseFloat current_cutoff = current_cutoff_;
+ std::vector<int32>::const_iterator iter = composed_states.begin(),
+ end = composed_states.end();
+ for (; iter != end; ++iter) {
+ int32 composed_state_index = *iter;
+ ComposedStateInfo &info = composed_state_info_[composed_state_index];
+ if (info.delta_backward_cost - info.delta_backward_cost != 0) {
+ // if info.delta_backward_cost is +infinity...
+ int32 prev_composed_state = info.prev_composed_state;
+ if (prev_composed_state < 0) {
+ KALDI_ASSERT(composed_state_index == 0);
+ info.delta_backward_cost = 0.0;
+ } else {
+ const ComposedStateInfo &prev_info =
+ composed_state_info_[prev_composed_state];
+ // Check that prev_info.delta_backward_cost is finite.
+ KALDI_ASSERT(prev_info.delta_backward_cost -
+ prev_info.delta_backward_cost == 0.0);
+ info.delta_backward_cost = prev_info.delta_backward_cost + depth_penalty_;
+ }
+ }
+ double lat_backward_cost = lat_state_info_[info.lat_state].backward_cost;
+ // See the formula by where expected_cost_offset is declared in the
+ // struct for explanation.
+ BaseFloat expected_cost_offset =
+ info.forward_cost + lat_backward_cost + info.delta_backward_cost +
+ info.arc_delta_cost - lat_best_cost;
+ // If info.expected_cost_offset were real, we'd set it here:
+ //info.expected_cost_offset = expected_cost_offset;
+
+ // At this point expected_cost_offset may be infinite, if arc_delta_cost was
+ // infinite (reflecting that we processed all the arcs, and the final-state
+ // if applicable, of the lattice state corresponding to this composed state.
+ if (expected_cost_offset < current_cutoff) {
+ queue_elements.push_back(std::pair<BaseFloat, int32>(
+ expected_cost_offset, composed_state_index));
+ }
+ }
+
+ // Reinitialize composed_state_queue_ from 'queue_elements'.
+ QueueType temp_queue(queue_elements.begin(), queue_elements.end());
+ composed_state_queue_.swap(temp_queue);
+}
+
+void PrunedCompactLatticeComposer::ComputeLatticeStateInfo() {
+ KALDI_ASSERT(clat_in_.Properties(fst::kTopSorted, true) ==
+ fst::kTopSorted && clat_in_.NumStates() > 0 &&
+ clat_in_.Start() == 0);
+ int32 num_lat_states = clat_in_.NumStates();
+ lat_state_info_.resize(num_lat_states);
+
+ for (int32 s = num_lat_states - 1; s >= 0; s--) {
+ LatticeStateInfo &info = lat_state_info_[s];
+ std::vector<std::pair<double, int32> > arc_costs;
+ double backward_cost = ConvertToCost(clat_in_.Final(s));
+ if (backward_cost != std::numeric_limits<double>::infinity())
+ arc_costs.push_back(std::pair<BaseFloat,int32>(backward_cost, -1));
+ fst::ArcIterator<CompactLattice> aiter(clat_in_, s);
+ int32 arc_index = 0;
+ for (; !aiter.Done(); aiter.Next(), ++arc_index) {
+ const CompactLatticeArc &arc = aiter.Value();
+ KALDI_ASSERT(arc.nextstate > s);
+ backward_cost = lat_state_info_[arc.nextstate].backward_cost +
+ ConvertToCost(arc.weight);
+ KALDI_ASSERT(backward_cost - backward_cost == 0.0 &&
+ "Possibly not all states of input lattice are co-accessible?");
+ arc_costs.push_back(std::pair<BaseFloat,int32>(backward_cost, arc_index));
+ }
+ std::sort(arc_costs.begin(), arc_costs.end());
+ KALDI_ASSERT(!arc_costs.empty() &&
+ "Possibly not all states of input lattice are co-accessible?");
+ backward_cost = arc_costs[0].first;
+ info.backward_cost = backward_cost; // this is the state's backward_cost,
+ // reflecting the best path to the end.
+ info.arc_delta_costs.resize(arc_costs.size());
+ std::vector<std::pair<double, int32> >::const_iterator
+ src_iter = arc_costs.begin(), src_end = arc_costs.end();
+ std::vector<std::pair<BaseFloat, int32> >::iterator
+ dest_iter = info.arc_delta_costs.begin();
+ for (; src_iter != src_end; ++src_iter, ++dest_iter) {
+ dest_iter->first = BaseFloat(src_iter->first - backward_cost);
+ dest_iter->second = src_iter->second;
+ }
+ }
+ lat_best_cost_ = lat_state_info_[0].backward_cost;
+}
+
+PrunedCompactLatticeComposer::PrunedCompactLatticeComposer(
+ const ComposeLatticePrunedOptions &opts,
+ const CompactLattice &clat_in,
+ fst::DeterministicOnDemandFst<fst::StdArc> *det_fst,
+ CompactLattice* composed_clat): output_reached_final_(false),
+ opts_(opts), clat_in_(clat_in), det_fst_(det_fst),
+ clat_out_(composed_clat),
+ num_arcs_out_(0),
+ output_best_cost_(std::numeric_limits<double>::infinity()),
+ current_cutoff_(std::numeric_limits<double>::infinity()) {
+ clat_out_->DeleteStates();
+ depth_penalty_ = -1000;
+}
+
+
+void PrunedCompactLatticeComposer::AddFirstState() {
+ int32 state_id = clat_out_->AddState();
+ clat_out_->SetStart(state_id);
+ KALDI_ASSERT(state_id == 0);
+ composed_state_info_.resize(1);
+ ComposedStateInfo &composed_state = composed_state_info_[0];
+ composed_state.lat_state = 0;
+ composed_state.lm_state = det_fst_->Start();
+ composed_state.depth = 0;
+ composed_state.forward_cost = 0.0;
+ composed_state.backward_cost = std::numeric_limits<double>::infinity();
+ composed_state.delta_backward_cost = 0.0;
+ composed_state.prev_composed_state = -1;
+ composed_state.sorted_arc_index = 0;
+ composed_state.arc_delta_cost = 0.0; // the first arc_delta_cost is always 0.0
+ // due to sorting; no need to look it up.
+ lat_state_info_[0].composed_states.push_back(state_id);
+ accessed_lat_states_.insert(state_id);
+ pair_to_state_[std::pair<int32, int32>(0, det_fst_->Start())] = state_id;
+
+ BaseFloat expected_cost_offset = 0.0; // the formula simplifies to zero
+ // in this case.
+ composed_state_queue_.push(
+ std::pair<BaseFloat, int32>(expected_cost_offset,
+ state_id)); // actually (0.0, 0).
+
+}
+
+
+void PrunedCompactLatticeComposer::ProcessQueueElement(
+ int32 src_composed_state) {
+ KALDI_ASSERT(static_cast<size_t>(src_composed_state) <
+ composed_state_info_.size());
+
+ ComposedStateInfo &src_composed_state_info = composed_state_info_[
+ src_composed_state];
+ int32 lat_state = src_composed_state_info.lat_state;
+ const LatticeStateInfo &lat_state_info =
+ lat_state_info_[lat_state];
+
+ int32 sorted_arc_index = src_composed_state_info.sorted_arc_index,
+ num_sorted_arcs = lat_state_info.arc_delta_costs.size();
+ // note: num_sorted_arcs will be the number of arcs from this
+ // lattice state; plus one if there is a final-prob.
+ KALDI_ASSERT(sorted_arc_index >= 0);
+
+ { // this block update the state's 'sorted_arc_index', 'arc_delta_cost' and
+ // 'expected_cost_offset' to reflect the fact that (by the time we exit from
+ // this function) we will have processed this arc (or the final-prob);
+ // it also re-inserts this state into the queue, if appropriate.
+ BaseFloat expected_cost_offset;
+ if (sorted_arc_index + 1 == num_sorted_arcs) {
+ src_composed_state_info.sorted_arc_index = -1;
+ src_composed_state_info.arc_delta_cost =
+ std::numeric_limits<BaseFloat>::infinity();
+ expected_cost_offset =
+ std::numeric_limits<BaseFloat>::infinity();
+ } else {
+ src_composed_state_info.sorted_arc_index = sorted_arc_index + 1;
+ src_composed_state_info.arc_delta_cost =
+ lat_state_info.arc_delta_costs[sorted_arc_index+1].first;
+ expected_cost_offset =
+ (src_composed_state_info.forward_cost +
+ lat_state_info.backward_cost +
+ src_composed_state_info.delta_backward_cost +
+ src_composed_state_info.arc_delta_cost - lat_best_cost_);
+ }
+ // We do '<' here rather than '<=', so that if current_cutoff_ is infinity
+ // and expected_cost_offset is infinity (because we've exhausted all the
+ // transitions from this state, and sorted_arc_index is now -1), we don't
+ // add this element to the queue.
+ if (expected_cost_offset < current_cutoff_) {
+ // this state has another exit arc (or final prob) that is good
+ // enough to re-enter into the queue. Note: if we are processing
+ // an arc out of this state and the destination state is new,
+ // we may also add something new to the queue at that time.
+
+ // the following call should be equivalent to
+ // composed_state_queue_.push(std::pair<BaseFloat,int32>(...)) with
+ // the same pair of args.
+ composed_state_queue_.emplace(
+ expected_cost_offset, src_composed_state);
+ }
+ }
+
+ int32 arc_index = lat_state_info.arc_delta_costs[sorted_arc_index].second;
+ if (arc_index < 0) { // This (arc_index == -1) means it is not really an arc
+ // index; it's a final-prob.
+ int32 lm_state = src_composed_state_info.lm_state;
+ BaseFloat lm_final_cost = det_fst_->Final(lm_state).Value();
+ if (lm_final_cost != std::numeric_limits<BaseFloat>::infinity()) {
+ // If there is a final-prob on this LM state (note: there always will be
+ // for conventional language models), then add the final-prob of this
+ // state...
+ CompactLattice::Weight final_weight = clat_in_.Final(lat_state);
+ // assume 'final_weight' is not Zero(); otherwise the final-prob should
+ // not have been present in 'arc_delta_costs'.
+ Lattice::Weight final_lat_weight = final_weight.Weight();
+ final_lat_weight.SetValue1(final_lat_weight.Value1() +
+ lm_final_cost);
+ final_weight.SetWeight(final_lat_weight);
+ clat_out_->SetFinal(src_composed_state, final_weight);
+ double final_cost = ConvertToCost(final_lat_weight);
+ if (final_cost < src_composed_state_info.backward_cost)
+ src_composed_state_info.backward_cost = final_cost;
+ if (!output_reached_final_) {
+ output_reached_final_ = true;
+ depth_penalty_ = 0.0;
+ RecomputePruningInfo();
+ }
+ }
+ } else {
+ // It really was an arc. This code is very complicated, so we make it its
+ // own function.
+ ProcessTransition(src_composed_state, arc_index);
+ }
+}
+
+void PrunedCompactLatticeComposer::ProcessTransition(int32 src_composed_state,
+ int32 arc_index) {
+ // Make src_composed_state a const pointer not a reference, as we may have to
+ // modify the pointer if composed_state_info_ is resized.
+ const ComposedStateInfo *src_info = &(composed_state_info_[
+ src_composed_state]);
+ int32 src_lat_state = src_info->lat_state;
+ // Get the arc we are going to expand.
+ fst::ArcIterator<CompactLattice> aiter(clat_in_, src_lat_state);
+ aiter.Seek(arc_index);
+ const CompactLatticeArc &lat_arc = aiter.Value();
+ // Note: this code is for CompactLatticeArc, in which the ilabel and olabel
+ // are the same, but we're writing it in such a way that it will naturally
+ // generalize to LatticeArc, so there are separate variables for the ilabel
+ // and the olabel.
+ int32 dest_lat_state = lat_arc.nextstate,
+ ilabel = lat_arc.ilabel,
+ olabel = lat_arc.olabel;
+ // Note: we expect that ilabel == olabel, since this is a CompactLattice, but this
+ // may not be so if we extend this to work with Lattice.
+ fst::StdArc lm_arc;
+
+ // the input lattice might have epsilons
+ if (olabel == 0) {
+ lm_arc.ilabel = 0;
+ lm_arc.olabel = 0;
+ lm_arc.nextstate = src_info->lm_state;
+ lm_arc.weight = fst::StdArc::Weight(0.0);
+ } else if (!det_fst_->GetArc(src_info->lm_state, olabel, &lm_arc)) {
+ // for normal language models we don't expect this to happen, but the
+ // appropriate behavior is to do nothing; the composed arc does not exist,
+ // so there is no arc to add and no new state to create.
+ return;
+ }
+ int32 dest_lm_state = lm_arc.nextstate;
+ // The following assertion is necessary because CompactLattice cannot support
+ // different ilabel vs. olabel; and also it's an expectation about
+ // language-models.
+ KALDI_ASSERT(lm_arc.ilabel == lm_arc.olabel);
+
+ LatticeStateInfo &dest_lat_state_info =
+ lat_state_info_[dest_lat_state];
+
+ int32 dest_composed_state;
+ ComposedStateInfo *dest_info;
+
+ { // The next block works out 'dest_composed_state' and
+ // 'dest_info', and if the destination state did not already
+ // exist, creates a new composed state.
+ typedef std::unordered_map<std::pair<int32,int32>, int32,
+ PairHasher<int32> > MapType;
+ int32 new_composed_state = clat_out_->NumStates();
+ std::pair<const std::pair<int32,int32>, int32> value(
+ std::pair<int32,int32>(dest_lat_state, dest_lm_state), new_composed_state);
+ std::pair<MapType::iterator, bool> ret =
+ pair_to_state_.insert(value);
+ if (ret.second) {
+ // Successfully inserted: this dest-state did not already exist. Most of
+ // the rest of this block deals with the consequences of adding a new
+ // state.
+ int32 ans = clat_out_->AddState();
+ KALDI_ASSERT(ans == new_composed_state);
+ dest_composed_state = new_composed_state;
+ composed_state_info_.resize(dest_composed_state + 1);
+ dest_info = &(composed_state_info_[dest_composed_state]);
+ // Re-assign src_composed_state as the vector might have been reallocated.
+ src_info = &(composed_state_info_[src_composed_state]);
+ if (dest_lat_state_info.composed_states.empty())
+ accessed_lat_states_.insert(dest_lat_state);
+ dest_lat_state_info.composed_states.push_back(new_composed_state);
+ dest_info->lat_state = dest_lat_state;
+ dest_info->lm_state = dest_lm_state;
+ dest_info->depth = src_info->depth + 1;
+ dest_info->forward_cost =
+ src_info->forward_cost +
+ ConvertToCost(lat_arc.weight) + lm_arc.weight.Value();
+ dest_info->backward_cost =
+ std::numeric_limits<double>::infinity();
+ dest_info->delta_backward_cost =
+ src_info->delta_backward_cost + dest_info->depth * depth_penalty_;
+ // The 'prev_composed_state' field will not be read again until after it's
+ // overwritten; we set it as below only for debugging purposes (the
+ // negation is also for debugging purposes).
+ dest_info->prev_composed_state = -src_composed_state;
+ dest_info->sorted_arc_index = 0;
+ dest_info->arc_delta_cost = 0.0;
+ // Note: in the expression below, which can be understood with reference
+ // to the comment by the declaration of the phantom variable
+ // 'expected_cost_offset', 'arc_delta_cost' is known to equal 0.0 so it
+ // has been removed.
+ BaseFloat expected_cost_offset =
+ (dest_info->forward_cost +
+ dest_lat_state_info.backward_cost +
+ dest_info->delta_backward_cost -
+ lat_best_cost_);
+ if (expected_cost_offset < current_cutoff_) {
+ // the following call should be equivalent to
+ // composed_state_queue_.push(std::pair<BaseFloat,int32>(...)) with
+ // the same pair of args.
+ composed_state_queue_.emplace(expected_cost_offset,
+ dest_composed_state);
+ }
+ } else { // the destination composed state already existed.
+ dest_composed_state = ret.first->second;
+ dest_info = &(composed_state_info_[dest_composed_state]);
+ }
+ }
+ // Add the arc from the src to dest state in the composed output.
+ CompactLatticeArc new_arc;
+ new_arc.nextstate = dest_composed_state;
+ // Actually the ilabel and olabel are the same, but writing it this way will
+ // generalize better to type Lattice if we need that later.
+ new_arc.ilabel = ilabel;
+ new_arc.olabel = olabel;
+ new_arc.weight = lat_arc.weight;
+ // 'weight' is the weight part, as opposed to the string part.
+ LatticeArc::Weight weight = new_arc.weight.Weight();
+ // include the LM-arc's weight in the weight of the new arc.
+ weight.SetValue1(fst::Times(weight.Value1(), lm_arc.weight).Value());
+ new_arc.weight.SetWeight(weight);
+ clat_out_->AddArc(src_composed_state, new_arc);
+ num_arcs_out_++;
+}
+
+static int32 TotalNumArcs(const CompactLattice &clat) {
+ int32 num_states = clat.NumStates(),
+ num_arcs = 0;
+ for (int32 s = 0; s < num_states; s++)
+ num_arcs += clat.NumArcs(s);
+ return num_arcs;
+}
+
+
+void PrunedCompactLatticeComposer::Compose() {
+ if (clat_in_.NumStates() == 0) {
+ KALDI_WARN << "Input lattice to composition is empty.";
+ return;
+ }
+ ComputeLatticeStateInfo();
+ AddFirstState();
+ // while (we have not reached final state ||
+ // num-arcs produced < target num-arcs) { ...
+ while (output_best_cost_ == std::numeric_limits<double>::infinity() ||
+ num_arcs_out_ < opts_.max_arcs) {
+ RecomputePruningInfo();
+ int32 this_iter_arc_limit = GetCurrentArcLimit();
+ while (num_arcs_out_ < this_iter_arc_limit &&
+ !composed_state_queue_.empty()) {
+ int32 src_composed_state = composed_state_queue_.top().second;
+ composed_state_queue_.pop();
+ ProcessQueueElement(src_composed_state);
+ }
+ if (composed_state_queue_.empty())
+ break;
+ }
+
+ fst::Connect(clat_out_);
+ TopSortCompactLatticeIfNeeded(clat_out_);
+
+ if (GetVerboseLevel() >= 2) {
+ int32 num_arcs_in = TotalNumArcs(clat_in_),
+ orig_num_arcs_out = num_arcs_out_,
+ num_arcs_out = TotalNumArcs(*clat_out_),
+ num_states_in = clat_in_.NumStates(),
+ orig_num_states_out = composed_state_info_.size(),
+ num_states_out = clat_out_->NumStates();
+ std::ostringstream os;
+ os << "Input lattice had " << num_arcs_in << '/' << num_states_in
+ << " arcs/states; output lattice has " << num_arcs_out << '/'
+ << num_states_out;
+ if (num_arcs_out != orig_num_arcs_out) {
+ os << " (before pruning: " << orig_num_arcs_out << '/'
+ << orig_num_states_out << ")";
+ }
+ if (!composed_state_queue_.empty()) {
+ // Below, composed_state_queue_.top().first + lat_best_cost is an
+ // expected-cost of the best path from the composed output that we *did
+ // not* expand. This, minus the best cost in the output compact lattice,
+ // can be interpreted as the beam that we effecctively pruned the output
+ // lattice to.
+ BaseFloat effective_beam =
+ composed_state_queue_.top().first + lat_best_cost_ - output_best_cost_;
+ os << ". Effective beam was " << effective_beam;
+ }
+ KALDI_VLOG(2) << os.str();
+ }
+
+ if (clat_out_->NumStates() == 0) {
+ KALDI_WARN << "Composed lattice has no states: something went wrong.";
+ }
+}
+
+void ComposeCompactLatticePruned(
+ const ComposeLatticePrunedOptions &opts,
+ const CompactLattice &clat,
+ fst::DeterministicOnDemandFst<fst::StdArc> *det_fst,
+ CompactLattice* composed_clat) {
+ PrunedCompactLatticeComposer composer(opts, clat, det_fst, composed_clat);
+ composer.Compose();
+}
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/compose-lattice-pruned.h b/runtime/onnxruntime/third_party/kaldi/lat/compose-lattice-pruned.h
new file mode 100644
index 000000000..160b9f3fe
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/compose-lattice-pruned.h
@@ -0,0 +1,179 @@
+// lat/compose-lattice-pruned.h
+
+// Copyright 2017 Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_LAT_COMPOSE_LATTICE_PRUNED_H_
+#define KALDI_LAT_COMPOSE_LATTICE_PRUNED_H_
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+#include <algorithm>
+#include <map>
+#include <set>
+#include <vector>
+#include "fstext/lattice-weight.h"
+#include "itf/options-itf.h"
+#include "lat/kaldi-lattice.h"
+
+namespace kaldi {
+
+
+/*
+ This header implements pruned lattice composition, via the functions
+ ComposeCompactLatticePruned (we may later add ComposeLatticePruned if
+ needed).
+
+ ComposeCompactLatticePruned does composition of a CompactLattice with a
+ DeterministicOnDemandFst<StdArc>, producing a CompactLattice. It's
+ intended for language model rescoring of lattices.
+
+ The scenario is that you have produced a Lattice or CompactLattice via
+ conventional decoding, and you want to replace (or partially replace) the
+ language model scores in the lattice (which will probably will come from the
+ LM used to generate the HCLG.fst) with the language model scores from a
+ larger language model.
+
+ The simpler alternative to using ComposeCompactLatticePruned is to use
+ ComposeCompactLatticeDeterministic. The advantages of ComposedCompactLatticePruned are:
+
+ (1) The alternative might be too slow, because when you compose a lattice
+ with a high-order n-gram language model (or an RNNLM with a high-order
+ n-gram approximation) it can generate a lot more arcs than were present
+ in the original lattice.
+
+ (2) For RNNLM rescoring, the n-gram approximation may not always
+ be choosing a very good history. In the n-gram approximation,
+ the LM score for a particular word given a history is taken
+ from a history that is the same as the desired history up to
+ the last, say, 4 words, but beyond that may differ. The
+ advantage of ComposeCompactLatticePruned functions over the alternative is
+ that it will often take, in a suitable sense, the "best" history
+ (instead of an arbitrary history); this happens simply because the
+ paths that are expected to be the best paths are visited first.
+
+
+ We now describe how you are expected to get the thing to compose with,
+ i.e. the DeterministicOnDemandFst<StdArc> that corrects the LM weights. It
+ will normally contain the LM used to create the original HCLG, with a
+ negative weight, composed with the LM you want to use, with a positive
+ weights (these weights might not be -1 and 1 if there is interpolation in the
+ picture). The LM we want to use will often be e.g. a 4-gram ARPA-type LM
+ (stored as a regular FST or, more compactly, as a .carpa file which is a
+ ConstArpaFst), or it will be some kind of RNNLM. You would use a
+ ComposeDeterministicOnDemandFst<StdArc> to combine the "base" language model
+ (with a negative weight, using either ConstArpaLm or
+ BackoffDeterministicOnDemandFst wrapped in ScaleDeterministicOnDemandFst)
+ with the RNNLM language model (the name of FST TBD, Hainan needs to write
+ this).
+*/
+
+
+
+
+// This options class is used for ComposeCompactLatticePruned,
+// and if in future we write a function ComposeLatticePruned, we'll
+// use the same options class.
+// Note: the binary that uses this may want to use an --acoustic-scale
+// option, in case the acoustics need to be scaled down before this
+// composition, because it will make a difference to which paths
+// are explored in the lattice.
+struct ComposeLatticePrunedOptions {
+ // 'lattice_compose_beam' is a beam that determines
+ // how much of a given composition space we will expand (at least,
+ // until we hit the limit imposed by 'max_arcs'.. This
+ // beam is applied using heuristically-estimated expected costs
+ // to the end of the lattice, so if you specify, for example,
+ // beam=5.0, it doesn't guarantee that all paths with best-cost
+ // within 5.0 of the best path in the composed output will be
+ // retained (However, this would be exact if the LM we were
+ // rescoring with had zero costs).
+ float lattice_compose_beam;
+
+ // 'max_arcs' is the maximum number of arcs that we are willing to expand per
+ // lattice; once this limit is reached, we terminate the composition (however,
+ // this limit is not applied until at least one path to a final-state has been
+ // produced).
+ int32 max_arcs;
+
+ // 'initial_num_arcs' is the number of arcs we use on the first outer
+ // iteration of the algorithm. This is so unimportant that we do not expose
+ // it on the command line.
+ int32 initial_num_arcs;
+
+ // 'growth_ratio' determines how much we allow the num-arcs to grow on each
+ // outer iteration of the algorithm. 1.5 is a reasonable value; if it is set
+ // too small, too much time will be taken in RecomputePruningInfo(), and if
+ // too large, the paths searched may be less optimal than they could be (the
+ // heuristics will be less accurate).
+ BaseFloat growth_ratio;
+
+ ComposeLatticePrunedOptions(): lattice_compose_beam(6.0),
+ max_arcs(100000),
+ initial_num_arcs(100),
+ growth_ratio(1.5) { }
+ void Register(OptionsItf *po) {
+ po->Register("lattice-compose-beam", &lattice_compose_beam,
+ "Beam used in pruned lattice composition, which determines how "
+ "large the composed lattice may be.");
+ po->Register("max-arcs", &max_arcs, "Maximum number of arcs we allow in "
+ "any given lattice, during pruned composition (limits max size "
+ "of lattices; also see lattice-compose-beam).");
+ po->Register("growth-ratio", &growth_ratio, "Factor used in the lattice "
+ "composition algorithm; must be >1.0. Affects speed vs. "
+ "the optimality of the best-first composition.");
+ }
+};
+
+
+/**
+ Does pruned composition of a lattice 'clat' with a DeterministicOnDemandFst
+ 'det_fst'; implements LM rescoring.
+
+ @param [in] opts Class containing options
+ @param [in] clat The input lattice, which is expected to already have a
+ reasonable acoustic scale applied (e.g. 0.1 if it's a normal
+ cross-entropy system, but 1.0 for a chain system); this scale
+ affects the pruning.
+ @param [in] det_fst The on-demand FST that we are composing with; its
+ ilabels will correspond to words and it should be an acceptor
+ in practice (ilabel == olabel). Will often contain a
+ weighted difference of language model scores, with scores
+ of the form alpha * new - alpha * old, where alpha
+ is the interpolation weight for the 'new' language model
+ (e.g. 0.5 or 0.8). It's non-const because 'det_fst' is
+ on-demand.
+ @param [out] composed_clat The output, which is a result of composing
+ 'clat' with '*det_fst'. Notionally, '*det_fst' is on the
+ right, although both are acceptors so it doesn't really
+ matter in practice.
+ Although the two FSTs are of different types, the code
+ manually does the conversion. The weights in '*det_fst'
+ will be interpreted as graph weights (Value1()) in the
+ lattice semiring.
+ */
+void ComposeCompactLatticePruned(
+ const ComposeLatticePrunedOptions &opts,
+ const CompactLattice &clat,
+ fst::DeterministicOnDemandFst<fst::StdArc> *det_fst,
+ CompactLattice* composed_clat);
+
+
+
+
+} // namespace kaldi
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/confidence.cc b/runtime/onnxruntime/third_party/kaldi/lat/confidence.cc
new file mode 100644
index 000000000..0700de32e
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/confidence.cc
@@ -0,0 +1,117 @@
+// lat/confidence.cc
+
+// Copyright 2013 Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "lat/confidence.h"
+#include "lat/lattice-functions.h"
+#include "lat/determinize-lattice-pruned.h"
+
+namespace kaldi {
+
+BaseFloat SentenceLevelConfidence(const CompactLattice &clat,
+ int32 *num_paths,
+ std::vector<int32> *best_sentence,
+ std::vector<int32> *second_best_sentence) {
+ /* It may seem strange that the first thing we do is to convert the
+ CompactLattice to a Lattice, given that we may have just created the
+ CompactLattice by determinizing a Lattice. However, this is not just
+ a circular conversion; "lat" will have the property that distinct
+ paths have distinct word sequences.
+ Below, we could run NbestAsFsts on a CompactLattice, but the time
+ taken would be quadratic in the length in words of the CompactLattice,
+ because of the alignment information getting appended as vectors.
+ That's why we convert back to Lattice.
+ */
+ Lattice lat;
+ ConvertLattice(clat, &lat);
+
+ std::vector<Lattice> lats;
+ NbestAsFsts(lat, 2, &lats);
+ int32 n = lats.size();
+ KALDI_ASSERT(n >= 0 && n <= 2);
+ if (num_paths != NULL) *num_paths = n;
+ if (best_sentence != NULL) best_sentence->clear();
+ if (second_best_sentence != NULL) second_best_sentence->clear();
+
+ LatticeWeight weight1, weight2;
+ if (n >= 1)
+ fst::GetLinearSymbolSequence<LatticeArc,int32>(lats[0], NULL,
+ best_sentence,
+ &weight1);
+ if (n >= 2)
+ fst::GetLinearSymbolSequence<LatticeArc,int32>(lats[1], NULL,
+ second_best_sentence,
+ &weight2);
+
+ if (n == 0) {
+ return 0; // this seems most appropriate because it will be interpreted as
+ // zero confidence, and something definitely went wrong for this
+ // to happen.
+ } else if (n == 1) {
+ // If there is only one sentence in the lattice, we interpret this as there
+ // being perfect confidence
+ return std::numeric_limits<BaseFloat>::infinity();
+ } else {
+ BaseFloat best_cost = ConvertToCost(weight1),
+ second_best_cost = ConvertToCost(weight2);
+ BaseFloat ans = second_best_cost - best_cost;
+ if (!(ans >= -0.001 * (fabs(best_cost) + fabs(second_best_cost)))) {
+ // Answer should be positive. Make sure it's at at least not
+ // substantially negative. This would be very strange.
+ KALDI_WARN << "Very negative difference." << ans;
+ }
+ if (ans < 0) ans = 0;
+ return ans;
+ }
+}
+
+
+
+BaseFloat SentenceLevelConfidence(const Lattice &lat,
+ int32 *num_paths,
+ std::vector<int32> *best_sentence,
+ std::vector<int32> *second_best_sentence) {
+ int32 max_sentence_length = LongestSentenceLength(lat);
+ fst::DeterminizeLatticePrunedOptions determinize_opts;
+ // The basic idea of expanding only up to "max_sentence_length * 2" arcs,
+ // is that that should be sufficient to get the best and second-best paths
+ // through the lattice, which is all we need for this particular application.
+ // "safety_term" is just in case there is some reason why we might need a few
+ // extra arcs, e.g. in case of a tie on the weights of the second-best path.
+ int32 safety_term = 4 + max_sentence_length;
+ determinize_opts.max_arcs = max_sentence_length * 2 + safety_term;
+ // set prune_beam to a large value... we don't really rely on the beam; we
+ // rely on the max_arcs variable to limit the size of the lattice.
+ double prune_beam = std::numeric_limits<double>::infinity();
+
+ CompactLattice clat;
+ // We ignore the return status of DeterminizeLatticePruned. It will likely
+ // return false, but this is expected because the expansion is limited
+ // by "max_arcs" not "prune_beam".
+ Lattice inverse_lat(lat);
+ fst::Invert(&inverse_lat); // Swap input and output symbols.
+ DeterminizeLatticePruned(inverse_lat, prune_beam, &clat, determinize_opts);
+
+ // Call the version of this function that takes a CompactLattice.
+ return SentenceLevelConfidence(clat, num_paths,
+ best_sentence, second_best_sentence);
+}
+
+
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/confidence.h b/runtime/onnxruntime/third_party/kaldi/lat/confidence.h
new file mode 100644
index 000000000..e1b1eaef0
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/confidence.h
@@ -0,0 +1,77 @@
+// lat/confidence.h
+
+// Copyright 2013 Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_LAT_CONFIDENCE_H_
+#define KALDI_LAT_CONFIDENCE_H_
+
+#include <vector>
+#include <map>
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fstext/fstext-lib.h"
+#include "lat/kaldi-lattice.h"
+
+namespace kaldi {
+
+/// Caution: this function is not the only way to get confidences in Kaldi.
+/// This only gives you sentence-level (utterance-level) confidence. You can
+/// get word-by-word confidence within a sentence, along with Minimum Bayes Risk
+/// decoding, by looking at sausages.h.
+/// Caution: confidences estimated using this type of method are not very
+/// accurate.
+/// This function will return the difference between the best path in clat and
+/// the second-best path in clat (a positive number), or zero if clat was
+/// equivalent to the empty FST (no successful paths), or infinity if there
+/// was only one path in "clat". It will output to "num_paths" (if non-NULL)
+/// a number n = 0, 1 or 2 saying how many n-best paths (up to two) were found.
+/// If n >= 1 it outputs to "best_sentence" (if non-NULL) the best word-sequence;
+/// if n == 2 it outputs to "second_best_sentence" (if non-NULL) the second best
+/// word-sequence (this may be useful for testing whether the two best word
+/// sequences are somehow equivalent for the task at hand). If you need more
+/// information than this or want to look deeper inside the n-best list, then
+/// look at the implementation of this function.
+/// This function requires that distinct paths in "lat" have distinct word
+/// sequences; this will automatically be the case if you generated "clat"
+/// in any normal way, such as from a decoder, because a deterministic FST
+/// has this property.
+/// This function assumes that any acoustic scaling you want to apply,
+/// has already been applied.
+BaseFloat SentenceLevelConfidence(const CompactLattice &clat,
+ int32 *num_paths,
+ std::vector<int32> *best_sentence,
+ std::vector<int32> *second_best_sentence);
+
+
+/// This version of SentenceLevelConfidence takes as input a state-level lattice.
+/// It needs to determinize it first, but it does so in a "smart" way that only generates
+/// about as many output paths as it needs.
+BaseFloat SentenceLevelConfidence(const Lattice &lat,
+ int32 *num_paths,
+ std::vector<int32> *best_sentence,
+ std::vector<int32> *second_best_sentence);
+
+
+
+
+
+} // namespace kaldi
+
+#endif // KALDI_LAT_CONFIDENCE_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/determinize-lattice-pruned-test.cc b/runtime/onnxruntime/third_party/kaldi/lat/determinize-lattice-pruned-test.cc
new file mode 100644
index 000000000..f6684f0b5
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/determinize-lattice-pruned-test.cc
@@ -0,0 +1,147 @@
+// lat/determinize-lattice-pruned-test.cc
+
+// Copyright 2009-2012 Microsoft Corporation
+// 2012-2013 Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "lat/determinize-lattice-pruned.h"
+#include "fstext/lattice-utils.h"
+#include "fstext/fst-test-utils.h"
+#include "lat/kaldi-lattice.h"
+#include "lat/lattice-functions.h"
+
+namespace fst {
+// Caution: these tests are not as generic as you might think from all the
+// templates in the code. They are basically only valid for LatticeArc.
+// This is partly due to the fact that certain templates need to be instantiated
+// in other .cc files in this directory.
+
+// test that determinization proceeds correctly on general
+// FSTs (not guaranteed determinzable, but we use the
+// max-states option to stop it getting out of control).
+template<class Arc> void TestDeterminizeLatticePruned() {
+ typedef kaldi::int32 Int;
+ typedef typename Arc::Weight Weight;
+ typedef ArcTpl<CompactLatticeWeightTpl<Weight, Int> > CompactArc;
+
+ for(int i = 0; i < 100; i++) {
+ RandFstOptions opts;
+ opts.n_states = 4;
+ opts.n_arcs = 10;
+ opts.n_final = 2;
+ opts.allow_empty = false;
+ opts.weight_multiplier = 0.5; // impt for the randomly generated weights
+ opts.acyclic = true;
+ // to be exactly representable in float,
+ // or this test fails because numerical differences can cause symmetry in
+ // weights to be broken, which causes the wrong path to be chosen as far
+ // as the string part is concerned.
+
+ VectorFst<Arc> *fst = RandPairFst<Arc>(opts);
+
+ bool sorted = TopSort(fst);
+ KALDI_ASSERT(sorted);
+
+ ILabelCompare<Arc> ilabel_comp;
+ if (kaldi::Rand() % 2 == 0)
+ ArcSort(fst, ilabel_comp);
+
+ std::cout << "FST before lattice-determinizing is:\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ VectorFst<Arc> det_fst;
+ try {
+ DeterminizeLatticePrunedOptions lat_opts;
+ lat_opts.max_mem = ((kaldi::Rand() % 2 == 0) ? 100 : 1000);
+ lat_opts.max_states = ((kaldi::Rand() % 2 == 0) ? -1 : 20);
+ lat_opts.max_arcs = ((kaldi::Rand() % 2 == 0) ? -1 : 30);
+ bool ans = DeterminizeLatticePruned<Weight>(*fst, 10.0, &det_fst, lat_opts);
+
+ std::cout << "FST after lattice-determinizing is:\n";
+ {
+ FstPrinter<Arc> fstprinter(det_fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ KALDI_ASSERT(det_fst.Properties(kIDeterministic, true) & kIDeterministic);
+ // OK, now determinize it a different way and check equivalence.
+ // [note: it's not normal determinization, it's taking the best path
+ // for any input-symbol sequence....
+
+
+ VectorFst<Arc> pruned_fst(*fst);
+ if (pruned_fst.NumStates() != 0)
+ kaldi::PruneLattice(10.0, &pruned_fst);
+
+ VectorFst<CompactArc> compact_pruned_fst, compact_pruned_det_fst;
+ ConvertLattice<Weight, Int>(pruned_fst, &compact_pruned_fst, false);
+ std::cout << "Compact pruned FST is:\n";
+ {
+ FstPrinter<CompactArc> fstprinter(compact_pruned_fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ ConvertLattice<Weight, Int>(det_fst, &compact_pruned_det_fst, false);
+
+ std::cout << "Compact version of determinized FST is:\n";
+ {
+ FstPrinter<CompactArc> fstprinter(compact_pruned_det_fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+
+ if (ans)
+ KALDI_ASSERT(RandEquivalent(compact_pruned_det_fst, compact_pruned_fst, 5/*paths*/, 0.01/*delta*/, kaldi::Rand()/*seed*/, 100/*path length, max*/));
+ } catch (...) {
+ std::cout << "Failed to lattice-determinize this FST (probably not determinizable)\n";
+ }
+ delete fst;
+ }
+}
+
+// test that determinization proceeds without crash on acyclic FSTs
+// (guaranteed determinizable in this sense).
+template<class Arc> void TestDeterminizeLatticePruned2() {
+ typedef typename Arc::Weight Weight;
+ RandFstOptions opts;
+ opts.acyclic = true;
+ for(int i = 0; i < 100; i++) {
+ VectorFst<Arc> *fst = RandPairFst<Arc>(opts);
+ std::cout << "FST before lattice-determinizing is:\n";
+ {
+ FstPrinter<Arc> fstprinter(*fst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ VectorFst<Arc> ofst;
+ DeterminizeLatticePruned<Weight>(*fst, 10.0, &ofst);
+ std::cout << "FST after lattice-determinizing is:\n";
+ {
+ FstPrinter<Arc> fstprinter(ofst, NULL, NULL, NULL, false, true, "\t");
+ fstprinter.Print(&std::cout, "standard output");
+ }
+ delete fst;
+ }
+}
+
+
+} // end namespace fst
+
+int main() {
+ using namespace fst;
+ TestDeterminizeLatticePruned<kaldi::LatticeArc>();
+ TestDeterminizeLatticePruned2<kaldi::LatticeArc>();
+ std::cout << "Tests succeeded\n";
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/determinize-lattice-pruned.cc b/runtime/onnxruntime/third_party/kaldi/lat/determinize-lattice-pruned.cc
new file mode 100644
index 000000000..c4aa2e7b9
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/determinize-lattice-pruned.cc
@@ -0,0 +1,1541 @@
+// lat/determinize-lattice-pruned.cc
+
+// Copyright 2009-2012 Microsoft Corporation
+// 2012-2013 Johns Hopkins University (Author: Daniel Povey)
+// 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include <vector>
+#include <climits>
+#include "fstext/determinize-lattice.h" // for LatticeStringRepository
+#include "fstext/fstext-utils.h"
+#include "lat/lattice-functions.h" // for PruneLattice
+//#include "lat/minimize-lattice.h" // for minimization
+//#include "lat/push-lattice.h" // for minimization
+#include "lat/determinize-lattice-pruned.h"
+
+namespace fst {
+
+using std::vector;
+using std::pair;
+using std::greater;
+
+// class LatticeDeterminizerPruned is templated on the same types that
+// CompactLatticeWeight is templated on: the base weight (Weight), typically
+// LatticeWeightTpl<float> etc. but could also be e.g. TropicalWeight, and the
+// IntType, typically int32, used for the output symbols in the compact
+// representation of strings [note: the output symbols would usually be
+// p.d.f. id's in the anticipated use of this code] It has a special requirement
+// on the Weight type: that there should be a Compare function on the weights
+// such that Compare(w1, w2) returns -1 if w1 < w2, 0 if w1 == w2, and +1 if w1 >
+// w2. This requires that there be a total order on the weights.
+
+template<class Weight, class IntType> class LatticeDeterminizerPruned {
+ public:
+ // Output to Gallic acceptor (so the strings go on weights, and there is a 1-1 correspondence
+ // between our states and the states in ofst. If destroy == true, release memory as we go
+ // (but we cannot output again).
+
+ typedef CompactLatticeWeightTpl<Weight, IntType> CompactWeight;
+ typedef ArcTpl<CompactWeight> CompactArc; // arc in compact, acceptor form of lattice
+ typedef ArcTpl<Weight> Arc; // arc in non-compact version of lattice
+
+ // Output to standard FST with CompactWeightTpl<Weight> as its weight type (the
+ // weight stores the original output-symbol strings). If destroy == true,
+ // release memory as we go (but we cannot output again).
+ void Output(MutableFst<CompactArc> *ofst, bool destroy = true) {
+ KALDI_ASSERT(determinized_);
+ typedef typename Arc::StateId StateId;
+ StateId nStates = static_cast<StateId>(output_states_.size());
+ if (destroy)
+ FreeMostMemory();
+ ofst->DeleteStates();
+ ofst->SetStart(kNoStateId);
+ if (nStates == 0) {
+ return;
+ }
+ for (StateId s = 0;s < nStates;s++) {
+ OutputStateId news = ofst->AddState();
+ KALDI_ASSERT(news == s);
+ }
+ ofst->SetStart(0);
+ // now process transitions.
+ for (StateId this_state_id = 0; this_state_id < nStates; this_state_id++) {
+ OutputState &this_state = *(output_states_[this_state_id]);
+ vector<TempArc> &this_vec(this_state.arcs);
+ typename vector<TempArc>::const_iterator iter = this_vec.begin(), end = this_vec.end();
+
+ for (;iter != end; ++iter) {
+ const TempArc &temp_arc(*iter);
+ CompactArc new_arc;
+ vector<Label> olabel_seq;
+ repository_.ConvertToVector(temp_arc.string, &olabel_seq);
+ CompactWeight weight(temp_arc.weight, olabel_seq);
+ if (temp_arc.nextstate == kNoStateId) { // is really final weight.
+ ofst->SetFinal(this_state_id, weight);
+ } else { // is really an arc.
+ new_arc.nextstate = temp_arc.nextstate;
+ new_arc.ilabel = temp_arc.ilabel;
+ new_arc.olabel = temp_arc.ilabel; // acceptor. input == output.
+ new_arc.weight = weight; // includes string and weight.
+ ofst->AddArc(this_state_id, new_arc);
+ }
+ }
+ // Free up memory. Do this inside the loop as ofst is also allocating memory,
+ // and we want to reduce the maximum amount ever allocated.
+ if (destroy) { vector<TempArc> temp; temp.swap(this_vec); }
+ }
+ if (destroy) {
+ FreeOutputStates();
+ repository_.Destroy();
+ }
+ }
+
+ // Output to standard FST with Weight as its weight type. We will create extra
+ // states to handle sequences of symbols on the output. If destroy == true,
+ // release memory as we go (but we cannot output again).
+ void Output(MutableFst<Arc> *ofst, bool destroy = true) {
+ // Outputs to standard fst.
+ OutputStateId nStates = static_cast<OutputStateId>(output_states_.size());
+ ofst->DeleteStates();
+ if (nStates == 0) {
+ ofst->SetStart(kNoStateId);
+ return;
+ }
+ if (destroy)
+ FreeMostMemory();
+ // Add basic states-- but we will add extra ones to account for strings on output.
+ for (OutputStateId s = 0; s< nStates;s++) {
+ OutputStateId news = ofst->AddState();
+ KALDI_ASSERT(news == s);
+ }
+ ofst->SetStart(0);
+ for (OutputStateId this_state_id = 0; this_state_id < nStates; this_state_id++) {
+ OutputState &this_state = *(output_states_[this_state_id]);
+ vector<TempArc> &this_vec(this_state.arcs);
+
+ typename vector<TempArc>::const_iterator iter = this_vec.begin(), end = this_vec.end();
+ for (; iter != end; ++iter) {
+ const TempArc &temp_arc(*iter);
+ vector<Label> seq;
+ repository_.ConvertToVector(temp_arc.string, &seq);
+
+ if (temp_arc.nextstate == kNoStateId) { // Really a final weight.
+ // Make a sequence of states going to a final state, with the strings
+ // as labels. Put the weight on the first arc.
+ OutputStateId cur_state = this_state_id;
+ for (size_t i = 0; i < seq.size(); i++) {
+ OutputStateId next_state = ofst->AddState();
+ Arc arc;
+ arc.nextstate = next_state;
+ arc.weight = (i == 0 ? temp_arc.weight : Weight::One());
+ arc.ilabel = 0; // epsilon.
+ arc.olabel = seq[i];
+ ofst->AddArc(cur_state, arc);
+ cur_state = next_state;
+ }
+ ofst->SetFinal(cur_state, (seq.size() == 0 ? temp_arc.weight : Weight::One()));
+ } else { // Really an arc.
+ OutputStateId cur_state = this_state_id;
+ // Have to be careful with this integer comparison (i+1 < seq.size()) because unsigned.
+ // i < seq.size()-1 could fail for zero-length sequences.
+ for (size_t i = 0; i+1 < seq.size();i++) {
+ // for all but the last element of seq, create new state.
+ OutputStateId next_state = ofst->AddState();
+ Arc arc;
+ arc.nextstate = next_state;
+ arc.weight = (i == 0 ? temp_arc.weight : Weight::One());
+ arc.ilabel = (i == 0 ? temp_arc.ilabel : 0); // put ilabel on first element of seq.
+ arc.olabel = seq[i];
+ ofst->AddArc(cur_state, arc);
+ cur_state = next_state;
+ }
+ // Add the final arc in the sequence.
+ Arc arc;
+ arc.nextstate = temp_arc.nextstate;
+ arc.weight = (seq.size() <= 1 ? temp_arc.weight : Weight::One());
+ arc.ilabel = (seq.size() <= 1 ? temp_arc.ilabel : 0);
+ arc.olabel = (seq.size() > 0 ? seq.back() : 0);
+ ofst->AddArc(cur_state, arc);
+ }
+ }
+ // Free up memory. Do this inside the loop as ofst is also allocating memory
+ if (destroy) { vector<TempArc> temp; temp.swap(this_vec); }
+ }
+ if (destroy) {
+ FreeOutputStates();
+ repository_.Destroy();
+ }
+ }
+
+
+ // Initializer. After initializing the object you will typically
+ // call Determinize() and then call one of the Output functions.
+ // Note: ifst.Copy() will generally do a
+ // shallow copy. We do it like this for memory safety, rather than
+ // keeping a reference or pointer to ifst_.
+ LatticeDeterminizerPruned(const ExpandedFst<Arc> &ifst,
+ double beam,
+ DeterminizeLatticePrunedOptions opts):
+ num_arcs_(0), num_elems_(0), ifst_(ifst.Copy()), beam_(beam), opts_(opts),
+ equal_(opts_.delta), determinized_(false),
+ minimal_hash_(3, hasher_, equal_), initial_hash_(3, hasher_, equal_) {
+ KALDI_ASSERT(Weight::Properties() & kIdempotent); // this algorithm won't
+ // work correctly otherwise.
+ }
+
+ void FreeOutputStates() {
+ for (size_t i = 0; i < output_states_.size(); i++)
+ delete output_states_[i];
+ vector<OutputState*> temp;
+ temp.swap(output_states_);
+ }
+
+ // frees all memory except the info (in output_states_[ ]->arcs)
+ // that we need to output the FST.
+ void FreeMostMemory() {
+ if (ifst_) {
+ delete ifst_;
+ ifst_ = NULL;
+ }
+ { MinimalSubsetHash tmp; tmp.swap(minimal_hash_); }
+
+ for (size_t i = 0; i < output_states_.size(); i++) {
+ vector<Element> empty_subset;
+ empty_subset.swap(output_states_[i]->minimal_subset);
+ }
+
+ for (typename InitialSubsetHash::iterator iter = initial_hash_.begin();
+ iter != initial_hash_.end(); ++iter)
+ delete iter->first;
+ { InitialSubsetHash tmp; tmp.swap(initial_hash_); }
+ { vector<char> tmp; tmp.swap(isymbol_or_final_); }
+ { // Free up the queue. I'm not sure how to make sure all
+ // the memory is really freed (no swap() function)... doesn't really
+ // matter much though.
+ while (!queue_.empty()) {
+ Task *t = queue_.top();
+ delete t;
+ queue_.pop();
+ }
+ }
+ { vector<pair<Label, Element> > tmp; tmp.swap(all_elems_tmp_); }
+ }
+
+ ~LatticeDeterminizerPruned() {
+ FreeMostMemory();
+ FreeOutputStates();
+ // rest is deleted by destructors.
+ }
+
+ void RebuildRepository() { // rebuild the string repository,
+ // freeing stuff we don't need.. we call this when memory usage
+ // passes a supplied threshold. We need to accumulate all the
+ // strings we need the repository to "remember", then tell it
+ // to clean the repository.
+ std::vector<StringId> needed_strings;
+ for (size_t i = 0; i < output_states_.size(); i++) {
+ AddStrings(output_states_[i]->minimal_subset, &needed_strings);
+ for (size_t j = 0; j < output_states_[i]->arcs.size(); j++)
+ needed_strings.push_back(output_states_[i]->arcs[j].string);
+ }
+
+ { // the queue doesn't allow us access to the underlying vector,
+ // so we have to resort to a temporary collection.
+ std::vector<Task*> tasks;
+ while (!queue_.empty()) {
+ Task *task = queue_.top();
+ queue_.pop();
+ tasks.push_back(task);
+ AddStrings(task->subset, &needed_strings);
+ }
+ for (size_t i = 0; i < tasks.size(); i++)
+ queue_.push(tasks[i]);
+ }
+
+ // the following loop covers strings present in initial_hash_.
+ for (typename InitialSubsetHash::const_iterator
+ iter = initial_hash_.begin();
+ iter != initial_hash_.end(); ++iter) {
+ const vector<Element> &vec = *(iter->first);
+ Element elem = iter->second;
+ AddStrings(vec, &needed_strings);
+ needed_strings.push_back(elem.string);
+ }
+ std::sort(needed_strings.begin(), needed_strings.end());
+ needed_strings.erase(std::unique(needed_strings.begin(),
+ needed_strings.end()),
+ needed_strings.end()); // uniq the strings.
+ KALDI_LOG << "Rebuilding repository.";
+
+ repository_.Rebuild(needed_strings);
+ }
+
+ bool CheckMemoryUsage() {
+ int32 repo_size = repository_.MemSize(),
+ arcs_size = num_arcs_ * sizeof(TempArc),
+ elems_size = num_elems_ * sizeof(Element),
+ total_size = repo_size + arcs_size + elems_size;
+ if (opts_.max_mem > 0 && total_size > opts_.max_mem) { // We passed the memory threshold.
+ // This is usually due to the repository getting large, so we
+ // clean this out.
+ RebuildRepository();
+ int32 new_repo_size = repository_.MemSize(),
+ new_total_size = new_repo_size + arcs_size + elems_size;
+
+ KALDI_VLOG(2) << "Rebuilt repository in determinize-lattice: repository shrank from "
+ << repo_size << " to " << new_repo_size << " bytes (approximately)";
+
+ if (new_total_size > static_cast<int32>(opts_.max_mem * 0.8)) {
+ // Rebuilding didn't help enough-- we need a margin to stop
+ // having to rebuild too often. We'll just return to the user at
+ // this point, with a partial lattice that's pruned tighter than
+ // the specified beam. Here we figure out what the effective
+ // beam was.
+ double effective_beam = beam_;
+ if (!queue_.empty()) { // Note: queue should probably not be empty; we're
+ // just being paranoid here.
+ Task *task = queue_.top();
+ double total_weight = backward_costs_[ifst_->Start()]; // best weight of FST.
+ effective_beam = task->priority_cost - total_weight;
+ }
+ KALDI_WARN << "Did not reach requested beam in determinize-lattice: "
+ << "size exceeds maximum " << opts_.max_mem
+ << " bytes; (repo,arcs,elems) = (" << repo_size << ","
+ << arcs_size << "," << elems_size
+ << "), after rebuilding, repo size was " << new_repo_size
+ << ", effective beam was " << effective_beam
+ << " vs. requested beam " << beam_;
+ return false;
+ }
+ }
+ return true;
+ }
+
+ bool Determinize(double *effective_beam) {
+ KALDI_ASSERT(!determinized_);
+ // This determinizes the input fst but leaves it in the "special format"
+ // in "output_arcs_". Must be called after Initialize(). To get the
+ // output, call one of the Output routines.
+
+ InitializeDeterminization(); // some start-up tasks.
+ while (!queue_.empty()) {
+ Task *task = queue_.top();
+ // Note: the queue contains only tasks that are "within the beam".
+ // We also have to check whether we have reached one of the user-specified
+ // maximums, of estimated memory, arcs, or states. The condition for
+ // ending is:
+ // num-states is more than user specified, OR
+ // num-arcs is more than user specified, OR
+ // memory passed a user-specified threshold and cleanup failed
+ // to get it below that threshold.
+ size_t num_states = output_states_.size();
+ if ((opts_.max_states > 0 && num_states > opts_.max_states) ||
+ (opts_.max_arcs > 0 && num_arcs_ > opts_.max_arcs) ||
+ (num_states % 10 == 0 && !CheckMemoryUsage())) { // note: at some point
+ // it was num_states % 100, not num_states % 10, but I encountered an example
+ // where memory was exhausted before we reached state #100.
+ KALDI_VLOG(1) << "Lattice determinization terminated but not "
+ << " because of lattice-beam. (#states, #arcs) is ( "
+ << output_states_.size() << ", " << num_arcs_
+ << " ), versus limits ( " << opts_.max_states << ", "
+ << opts_.max_arcs << " ) (else, may be memory limit).";
+ break;
+ // we terminate the determinization here-- whatever we already expanded is
+ // what we'll return... because we expanded stuff in order of total
+ // (forward-backward) weight, the stuff we returned first is the most
+ // important.
+ }
+ queue_.pop();
+ ProcessTransition(task->state, task->label, &(task->subset));
+ delete task;
+ }
+ determinized_ = true;
+ if (effective_beam != NULL) {
+ if (queue_.empty()) *effective_beam = beam_;
+ else
+ *effective_beam = queue_.top()->priority_cost -
+ backward_costs_[ifst_->Start()];
+ }
+ return (queue_.empty()); // return success if queue was empty, i.e. we processed
+ // all tasks and did not break out of the loop early due to reaching a memory,
+ // arc or state limit.
+ }
+ private:
+
+ typedef typename Arc::Label Label;
+ typedef typename Arc::StateId StateId; // use this when we don't know if it's input or output.
+ typedef typename Arc::StateId InputStateId; // state in the input FST.
+ typedef typename Arc::StateId OutputStateId; // same as above but distinguish
+ // states in output Fst.
+
+ typedef LatticeStringRepository<IntType> StringRepositoryType;
+ typedef const typename StringRepositoryType::Entry* StringId;
+
+ // Element of a subset [of original states]
+ struct Element {
+ StateId state; // use StateId as this is usually InputStateId but in one case
+ // OutputStateId.
+ StringId string;
+ Weight weight;
+ bool operator != (const Element &other) const {
+ return (state != other.state || string != other.string ||
+ weight != other.weight);
+ }
+ // This operator is only intended for the priority_queue in the function
+ // EpsilonClosure().
+ bool operator > (const Element &other) const {
+ return state > other.state;
+ }
+ // This operator is only intended to support sorting in EpsilonClosure()
+ bool operator < (const Element &other) const {
+ return state < other.state;
+ }
+ };
+
+ // Arcs in the format we temporarily create in this class (a representation, essentially of
+ // a Gallic Fst).
+ struct TempArc {
+ Label ilabel;
+ StringId string; // Look it up in the StringRepository, it's a sequence of Labels.
+ OutputStateId nextstate; // or kNoState for final weights.
+ Weight weight;
+ };
+
+ // Hashing function used in hash of subsets.
+ // A subset is a pointer to vector<Element>.
+ // The Elements are in sorted order on state id, and without repeated states.
+ // Because the order of Elements is fixed, we can use a hashing function that is
+ // order-dependent. However the weights are not included in the hashing function--
+ // we hash subsets that differ only in weight to the same key. This is not optimal
+ // in terms of the O(N) performance but typically if we have a lot of determinized
+ // states that differ only in weight then the input probably was pathological in some way,
+ // or even non-determinizable.
+ // We don't quantize the weights, in order to avoid inexactness in simple cases.
+ // Instead we apply the delta when comparing subsets for equality, and allow a small
+ // difference.
+
+ class SubsetKey {
+ public:
+ size_t operator ()(const vector<Element> * subset) const { // hashes only the state and string.
+ size_t hash = 0, factor = 1;
+ for (typename vector<Element>::const_iterator iter= subset->begin(); iter != subset->end(); ++iter) {
+ hash *= factor;
+ hash += iter->state + reinterpret_cast<size_t>(iter->string);
+ factor *= 23531; // these numbers are primes.
+ }
+ return hash;
+ }
+ };
+
+ // This is the equality operator on subsets. It checks for exact match on state-id
+ // and string, and approximate match on weights.
+ class SubsetEqual {
+ public:
+ bool operator ()(const vector<Element> * s1, const vector<Element> * s2) const {
+ size_t sz = s1->size();
+ KALDI_ASSERT(sz>=0);
+ if (sz != s2->size()) return false;
+ typename vector<Element>::const_iterator iter1 = s1->begin(),
+ iter1_end = s1->end(), iter2=s2->begin();
+ for (; iter1 < iter1_end; ++iter1, ++iter2) {
+ if (iter1->state != iter2->state ||
+ iter1->string != iter2->string ||
+ ! ApproxEqual(iter1->weight, iter2->weight, delta_)) return false;
+ }
+ return true;
+ }
+ float delta_;
+ SubsetEqual(float delta): delta_(delta) {}
+ SubsetEqual(): delta_(kDelta) {}
+ };
+
+ // Operator that says whether two Elements have the same states.
+ // Used only for debug.
+ class SubsetEqualStates {
+ public:
+ bool operator ()(const vector<Element> * s1, const vector<Element> * s2) const {
+ size_t sz = s1->size();
+ KALDI_ASSERT(sz>=0);
+ if (sz != s2->size()) return false;
+ typename vector<Element>::const_iterator iter1 = s1->begin(),
+ iter1_end = s1->end(), iter2=s2->begin();
+ for (; iter1 < iter1_end; ++iter1, ++iter2) {
+ if (iter1->state != iter2->state) return false;
+ }
+ return true;
+ }
+ };
+
+ // Define the hash type we use to map subsets (in minimal
+ // representation) to OutputStateId.
+ typedef unordered_map<const vector<Element>*, OutputStateId,
+ SubsetKey, SubsetEqual> MinimalSubsetHash;
+
+ // Define the hash type we use to map subsets (in initial
+ // representation) to OutputStateId, together with an
+ // extra weight. [note: we interpret the Element.state in here
+ // as an OutputStateId even though it's declared as InputStateId;
+ // these types are the same anyway].
+ typedef unordered_map<const vector<Element>*, Element,
+ SubsetKey, SubsetEqual> InitialSubsetHash;
+
+
+ // converts the representation of the subset from canonical (all states) to
+ // minimal (only states with output symbols on arcs leaving them, and final
+ // states). Output is not necessarily normalized, even if input_subset was.
+ void ConvertToMinimal(vector<Element> *subset) {
+ KALDI_ASSERT(!subset->empty());
+ typename vector<Element>::iterator cur_in = subset->begin(),
+ cur_out = subset->begin(), end = subset->end();
+ while (cur_in != end) {
+ if(IsIsymbolOrFinal(cur_in->state)) { // keep it...
+ *cur_out = *cur_in;
+ cur_out++;
+ }
+ cur_in++;
+ }
+ subset->resize(cur_out - subset->begin());
+ }
+
+ // Takes a minimal, normalized subset, and converts it to an OutputStateId.
+ // Involves a hash lookup, and possibly adding a new OutputStateId.
+ // If it creates a new OutputStateId, it creates a new record for it, works
+ // out its final-weight, and puts stuff on the queue relating to its
+ // transitions.
+ OutputStateId MinimalToStateId(const vector<Element> &subset,
+ const double forward_cost) {
+ typename MinimalSubsetHash::const_iterator iter
+ = minimal_hash_.find(&subset);
+ if (iter != minimal_hash_.end()) { // Found a matching subset.
+ OutputStateId state_id = iter->second;
+ const OutputState &state = *(output_states_[state_id]);
+ // Below is just a check that the algorithm is working...
+ if (forward_cost < state.forward_cost - 0.1) {
+ // for large weights, this check could fail due to roundoff.
+ KALDI_WARN << "New cost is less (check the difference is small) "
+ << forward_cost << ", "
+ << state.forward_cost;
+ }
+ return state_id;
+ }
+ OutputStateId state_id = static_cast<OutputStateId>(output_states_.size());
+ OutputState *new_state = new OutputState(subset, forward_cost);
+ minimal_hash_[&(new_state->minimal_subset)] = state_id;
+ output_states_.push_back(new_state);
+ num_elems_ += subset.size();
+ // Note: in the previous algorithm, we pushed the new state-id onto the queue
+ // at this point. Here, the queue happens elsewhere, and we directly process
+ // the state (which result in stuff getting added to the queue).
+ ProcessFinal(state_id); // will work out the final-prob.
+ ProcessTransitions(state_id); // will process transitions and add stuff to the queue.
+ return state_id;
+ }
+
+
+ // Given a normalized initial subset of elements (i.e. before epsilon closure),
+ // compute the corresponding output-state.
+ OutputStateId InitialToStateId(const vector<Element> &subset_in,
+ double forward_cost,
+ Weight *remaining_weight,
+ StringId *common_prefix) {
+ typename InitialSubsetHash::const_iterator iter
+ = initial_hash_.find(&subset_in);
+ if (iter != initial_hash_.end()) { // Found a matching subset.
+ const Element &elem = iter->second;
+ *remaining_weight = elem.weight;
+ *common_prefix = elem.string;
+ if (elem.weight == Weight::Zero())
+ KALDI_WARN << "Zero weight!";
+ return elem.state;
+ }
+ // else no matching subset-- have to work it out.
+ vector<Element> subset(subset_in);
+ // Follow through epsilons. Will add no duplicate states. note: after
+ // EpsilonClosure, it is the same as "canonical" subset, except not
+ // normalized (actually we never compute the normalized canonical subset,
+ // only the normalized minimal one).
+ EpsilonClosure(&subset); // follow epsilons.
+ ConvertToMinimal(&subset); // remove all but emitting and final states.
+
+ Element elem; // will be used to store remaining weight and string, and
+ // OutputStateId, in initial_hash_;
+ NormalizeSubset(&subset, &elem.weight, &elem.string); // normalize subset; put
+ // common string and weight in "elem". The subset is now a minimal,
+ // normalized subset.
+
+ forward_cost += ConvertToCost(elem.weight);
+ OutputStateId ans = MinimalToStateId(subset, forward_cost);
+ *remaining_weight = elem.weight;
+ *common_prefix = elem.string;
+ if (elem.weight == Weight::Zero())
+ KALDI_WARN << "Zero weight!";
+
+ // Before returning "ans", add the initial subset to the hash,
+ // so that we can bypass the epsilon-closure etc., next time
+ // we process the same initial subset.
+ vector<Element> *initial_subset_ptr = new vector<Element>(subset_in);
+ elem.state = ans;
+ initial_hash_[initial_subset_ptr] = elem;
+ num_elems_ += initial_subset_ptr->size(); // keep track of memory usage.
+ return ans;
+ }
+
+ // returns the Compare value (-1 if a < b, 0 if a == b, 1 if a > b) according
+ // to the ordering we defined on strings for the CompactLatticeWeightTpl.
+ // see function
+ // inline int Compare (const CompactLatticeWeightTpl<WeightType,IntType> &w1,
+ // const CompactLatticeWeightTpl<WeightType,IntType> &w2)
+ // in lattice-weight.h.
+ // this is the same as that, but optimized for our data structures.
+ inline int Compare(const Weight &a_w, StringId a_str,
+ const Weight &b_w, StringId b_str) const {
+ int weight_comp = fst::Compare(a_w, b_w);
+ if (weight_comp != 0) return weight_comp;
+ // now comparing strings.
+ if (a_str == b_str) return 0;
+ vector<IntType> a_vec, b_vec;
+ repository_.ConvertToVector(a_str, &a_vec);
+ repository_.ConvertToVector(b_str, &b_vec);
+ // First compare their lengths.
+ int a_len = a_vec.size(), b_len = b_vec.size();
+ // use opposite order on the string lengths (c.f. Compare in
+ // lattice-weight.h)
+ if (a_len > b_len) return -1;
+ else if (a_len < b_len) return 1;
+ for(int i = 0; i < a_len; i++) {
+ if (a_vec[i] < b_vec[i]) return -1;
+ else if (a_vec[i] > b_vec[i]) return 1;
+ }
+ KALDI_ASSERT(0); // because we checked if a_str == b_str above, shouldn't reach here
+ return 0;
+ }
+
+ // This function computes epsilon closure of subset of states by following epsilon links.
+ // Called by InitialToStateId and Initialize.
+ // Has no side effects except on the string repository. The "output_subset" is not
+ // necessarily normalized (in the sense of there being no common substring), unless
+ // input_subset was.
+ void EpsilonClosure(vector<Element> *subset) {
+ // at input, subset must have only one example of each StateId. [will still
+ // be so at output]. This function follows input-epsilons, and augments the
+ // subset accordingly.
+
+ std::priority_queue<Element, vector<Element>, greater<Element> > queue;
+ unordered_map<InputStateId, Element> cur_subset;
+ typedef typename unordered_map<InputStateId, Element>::iterator MapIter;
+ typedef typename vector<Element>::const_iterator VecIter;
+
+ for (VecIter iter = subset->begin(); iter != subset->end(); ++iter) {
+ queue.push(*iter);
+ cur_subset[iter->state] = *iter;
+ }
+
+ // find whether input fst is known to be sorted on input label.
+ bool sorted = ((ifst_->Properties(kILabelSorted, false) & kILabelSorted) != 0);
+ bool replaced_elems = false; // relates to an optimization, see below.
+ int counter = 0; // stops infinite loops here for non-lattice-determinizable input
+ // (e.g. input with negative-cost epsilon loops); useful in testing.
+ while (queue.size() != 0) {
+ Element elem = queue.top();
+ queue.pop();
+
+ // The next if-statement is a kind of optimization. It's to prevent us
+ // unnecessarily repeating the processing of a state. "cur_subset" always
+ // contains only one Element with a particular state. The issue is that
+ // whenever we modify the Element corresponding to that state in "cur_subset",
+ // both the new (optimal) and old (less-optimal) Element will still be in
+ // "queue". The next if-statement stops us from wasting compute by
+ // processing the old Element.
+ if (replaced_elems && cur_subset[elem.state] != elem)
+ continue;
+ if (opts_.max_loop > 0 && counter++ > opts_.max_loop) {
+ KALDI_ERR << "Lattice determinization aborted since looped more than "
+ << opts_.max_loop << " times during epsilon closure.";
+ }
+ for (ArcIterator<ExpandedFst<Arc> > aiter(*ifst_, elem.state); !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (sorted && arc.ilabel != 0) break; // Break from the loop: due to sorting there will be no
+ // more transitions with epsilons as input labels.
+ if (arc.ilabel == 0
+ && arc.weight != Weight::Zero()) { // Epsilon transition.
+ Element next_elem;
+ next_elem.state = arc.nextstate;
+ next_elem.weight = Times(elem.weight, arc.weight);
+ // next_elem.string is not set up yet... create it only
+ // when we know we need it (this is an optimization)
+
+ MapIter iter = cur_subset.find(next_elem.state);
+ if (iter == cur_subset.end()) {
+ // was no such StateId: insert and add to queue.
+ next_elem.string = (arc.olabel == 0 ? elem.string :
+ repository_.Successor(elem.string, arc.olabel));
+ cur_subset[next_elem.state] = next_elem;
+ queue.push(next_elem);
+ } else {
+ // was not inserted because one already there. In normal
+ // determinization we'd add the weights. Here, we find which one
+ // has the better weight, and keep its corresponding string.
+ int comp = fst::Compare(next_elem.weight, iter->second.weight);
+ if (comp == 0) { // A tie on weights. This should be a rare case;
+ // we don't optimize for it.
+ next_elem.string = (arc.olabel == 0 ? elem.string :
+ repository_.Successor(elem.string,
+ arc.olabel));
+ comp = Compare(next_elem.weight, next_elem.string,
+ iter->second.weight, iter->second.string);
+ }
+ if(comp == 1) { // next_elem is better, so use its (weight, string)
+ next_elem.string = (arc.olabel == 0 ? elem.string :
+ repository_.Successor(elem.string, arc.olabel));
+ iter->second.string = next_elem.string;
+ iter->second.weight = next_elem.weight;
+ queue.push(next_elem);
+ replaced_elems = true;
+ }
+ // else it is the same or worse, so use original one.
+ }
+ }
+ }
+ }
+
+ { // copy cur_subset to subset.
+ subset->clear();
+ subset->reserve(cur_subset.size());
+ MapIter iter = cur_subset.begin(), end = cur_subset.end();
+ for (; iter != end; ++iter) subset->push_back(iter->second);
+ // sort by state ID, because the subset hash function is order-dependent(see SubsetKey)
+ std::sort(subset->begin(), subset->end());
+ }
+ }
+
+
+ // This function works out the final-weight of the determinized state.
+ // called by ProcessSubset.
+ // Has no side effects except on the variable repository_, and
+ // output_states_[output_state_id].arcs
+
+ void ProcessFinal(OutputStateId output_state_id) {
+ OutputState &state = *(output_states_[output_state_id]);
+ const vector<Element> &minimal_subset = state.minimal_subset;
+ // processes final-weights for this subset. state.minimal_subset_ may be
+ // empty if the graphs is not connected/trimmed, I think, do don't check
+ // that it's nonempty.
+ StringId final_string = repository_.EmptyString(); // set it to keep the
+ // compiler happy; if it doesn't get set in the loop, we won't use the value anyway.
+ Weight final_weight = Weight::Zero();
+ bool is_final = false;
+ typename vector<Element>::const_iterator iter = minimal_subset.begin(), end = minimal_subset.end();
+ for (; iter != end; ++iter) {
+ const Element &elem = *iter;
+ Weight this_final_weight = Times(elem.weight, ifst_->Final(elem.state));
+ StringId this_final_string = elem.string;
+ if (this_final_weight != Weight::Zero() &&
+ (!is_final || Compare(this_final_weight, this_final_string,
+ final_weight, final_string) == 1)) { // the new
+ // (weight, string) pair is more in semiring than our current
+ // one.
+ is_final = true;
+ final_weight = this_final_weight;
+ final_string = this_final_string;
+ }
+ }
+ if (is_final &&
+ ConvertToCost(final_weight) + state.forward_cost <= cutoff_) {
+ // store final weights in TempArc structure, just like a transition.
+ // Note: we only store the final-weight if it's inside the pruning beam, hence
+ // the stuff with Compare.
+ TempArc temp_arc;
+ temp_arc.ilabel = 0;
+ temp_arc.nextstate = kNoStateId; // special marker meaning "final weight".
+ temp_arc.string = final_string;
+ temp_arc.weight = final_weight;
+ state.arcs.push_back(temp_arc);
+ num_arcs_++;
+ }
+ }
+
+ // NormalizeSubset normalizes the subset "elems" by
+ // removing any common string prefix (putting it in common_str),
+ // and dividing by the total weight (putting it in tot_weight).
+ void NormalizeSubset(vector<Element> *elems,
+ Weight *tot_weight,
+ StringId *common_str) {
+ if(elems->empty()) { // just set common_str, tot_weight
+ // to defaults and return...
+ KALDI_WARN << "empty subset";
+ *common_str = repository_.EmptyString();
+ *tot_weight = Weight::Zero();
+ return;
+ }
+ size_t size = elems->size();
+ vector<IntType> common_prefix;
+ repository_.ConvertToVector((*elems)[0].string, &common_prefix);
+ Weight weight = (*elems)[0].weight;
+ for(size_t i = 1; i < size; i++) {
+ weight = Plus(weight, (*elems)[i].weight);
+ repository_.ReduceToCommonPrefix((*elems)[i].string, &common_prefix);
+ }
+ KALDI_ASSERT(weight != Weight::Zero()); // we made sure to ignore arcs with zero
+ // weights on them, so we shouldn't have zero here.
+ size_t prefix_len = common_prefix.size();
+ for(size_t i = 0; i < size; i++) {
+ (*elems)[i].weight = Divide((*elems)[i].weight, weight, DIVIDE_LEFT);
+ (*elems)[i].string =
+ repository_.RemovePrefix((*elems)[i].string, prefix_len);
+ }
+ *common_str = repository_.ConvertFromVector(common_prefix);
+ *tot_weight = weight;
+ }
+
+ // Take a subset of Elements that is sorted on state, and
+ // merge any Elements that have the same state (taking the best
+ // (weight, string) pair in the semiring).
+ void MakeSubsetUnique(vector<Element> *subset) {
+ typedef typename vector<Element>::iterator IterType;
+
+ // This KALDI_ASSERT is designed to fail (usually) if the subset is not sorted on
+ // state.
+ KALDI_ASSERT(subset->size() < 2 || (*subset)[0].state <= (*subset)[1].state);
+
+ IterType cur_in = subset->begin(), cur_out = cur_in, end = subset->end();
+ size_t num_out = 0;
+ // Merge elements with same state-id
+ while (cur_in != end) { // while we have more elements to process.
+ // At this point, cur_out points to location of next place we want to put an element,
+ // cur_in points to location of next element we want to process.
+ if (cur_in != cur_out) *cur_out = *cur_in;
+ cur_in++;
+ while (cur_in != end && cur_in->state == cur_out->state) {
+ if (Compare(cur_in->weight, cur_in->string,
+ cur_out->weight, cur_out->string) == 1) {
+ // if *cur_in > *cur_out in semiring, then take *cur_in.
+ cur_out->string = cur_in->string;
+ cur_out->weight = cur_in->weight;
+ }
+ cur_in++;
+ }
+ cur_out++;
+ num_out++;
+ }
+ subset->resize(num_out);
+ }
+
+ // ProcessTransition was called from "ProcessTransitions" in the non-pruned
+ // code, but now we in effect put the calls to ProcessTransition on a priority
+ // queue, and it now gets called directly from Determinize(). This function
+ // processes a transition from state "ostate_id". The set "subset" of Elements
+ // represents a set of next-states with associated weights and strings, each
+ // one arising from an arc from some state in a determinized-state; the
+ // next-states are unique (there is only one Entry assocated with each)
+ void ProcessTransition(OutputStateId ostate_id, Label ilabel, vector<Element> *subset) {
+
+ double forward_cost = output_states_[ostate_id]->forward_cost;
+ StringId common_str;
+ Weight tot_weight;
+ NormalizeSubset(subset, &tot_weight, &common_str);
+ forward_cost += ConvertToCost(tot_weight);
+
+ OutputStateId nextstate;
+ {
+ Weight next_tot_weight;
+ StringId next_common_str;
+ nextstate = InitialToStateId(*subset,
+ forward_cost,
+ &next_tot_weight,
+ &next_common_str);
+ common_str = repository_.Concatenate(common_str, next_common_str);
+ tot_weight = Times(tot_weight, next_tot_weight);
+ }
+
+ // Now add an arc to the next state (would have been created if necessary by
+ // InitialToStateId).
+ TempArc temp_arc;
+ temp_arc.ilabel = ilabel;
+ temp_arc.nextstate = nextstate;
+ temp_arc.string = common_str;
+ temp_arc.weight = tot_weight;
+ output_states_[ostate_id]->arcs.push_back(temp_arc); // record the arc.
+ num_arcs_++;
+ }
+
+
+ // "less than" operator for pair<Label, Element>. Used in ProcessTransitions.
+ // Lexicographical order, which only compares the state when ordering the
+ // "Element" member of the pair.
+
+ class PairComparator {
+ public:
+ inline bool operator () (const pair<Label, Element> &p1, const pair<Label, Element> &p2) {
+ if (p1.first < p2.first) return true;
+ else if (p1.first > p2.first) return false;
+ else {
+ return p1.second.state < p2.second.state;
+ }
+ }
+ };
+
+
+ // ProcessTransitions processes emitting transitions (transitions with
+ // ilabels) out of this subset of states. It actualy only creates records
+ // ("Task") that get added to the queue. The transitions will be processed in
+ // priority order from Determinize(). This function soes not consider final
+ // states. Partitions the emitting transitions up by ilabel (by sorting on
+ // ilabel), and for each unique ilabel, it creates a Task record that contains
+ // the information we need to process the transition.
+
+ void ProcessTransitions(OutputStateId output_state_id) {
+ const vector<Element> &minimal_subset = output_states_[output_state_id]->minimal_subset;
+ // it's possible that minimal_subset could be empty if there are
+ // unreachable parts of the graph, so don't check that it's nonempty.
+ vector<pair<Label, Element> > &all_elems(all_elems_tmp_); // use class member
+ // to avoid memory allocation/deallocation.
+ {
+ // Push back into "all_elems", elements corresponding to all
+ // non-epsilon-input transitions out of all states in "minimal_subset".
+ typename vector<Element>::const_iterator iter = minimal_subset.begin(), end = minimal_subset.end();
+ for (;iter != end; ++iter) {
+ const Element &elem = *iter;
+ for (ArcIterator<ExpandedFst<Arc> > aiter(*ifst_, elem.state); ! aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0
+ && arc.weight != Weight::Zero()) { // Non-epsilon transition -- ignore epsilons here.
+ pair<Label, Element> this_pr;
+ this_pr.first = arc.ilabel;
+ Element &next_elem(this_pr.second);
+ next_elem.state = arc.nextstate;
+ next_elem.weight = Times(elem.weight, arc.weight);
+ if (arc.olabel == 0) // output epsilon
+ next_elem.string = elem.string;
+ else
+ next_elem.string = repository_.Successor(elem.string, arc.olabel);
+ all_elems.push_back(this_pr);
+ }
+ }
+ }
+ }
+ PairComparator pc;
+ std::sort(all_elems.begin(), all_elems.end(), pc);
+ // now sorted first on input label, then on state.
+ typedef typename vector<pair<Label, Element> >::const_iterator PairIter;
+ PairIter cur = all_elems.begin(), end = all_elems.end();
+ while (cur != end) {
+ // The old code (non-pruned) called ProcessTransition; here, instead,
+ // we'll put the calls into a priority queue.
+ Task *task = new Task;
+ // Process ranges that share the same input symbol.
+ Label ilabel = cur->first;
+ task->state = output_state_id;
+ task->priority_cost = std::numeric_limits<double>::infinity();
+ task->label = ilabel;
+ while (cur != end && cur->first == ilabel) {
+ task->subset.push_back(cur->second);
+ const Element &element = cur->second;
+ // Note: we'll later include the term "forward_cost" in the
+ // priority_cost.
+ task->priority_cost = std::min(task->priority_cost,
+ ConvertToCost(element.weight) +
+ backward_costs_[element.state]);
+ cur++;
+ }
+
+ // After the command below, the "priority_cost" is a value comparable to
+ // the total-weight of the input FST, like a total-path weight... of
+ // course, it will typically be less (in the semiring) than that.
+ // note: we represent it just as a double.
+ task->priority_cost += output_states_[output_state_id]->forward_cost;
+
+ if (task->priority_cost > cutoff_) {
+ // This task would never get done as it's past the pruning cutoff.
+ delete task;
+ } else {
+ MakeSubsetUnique(&(task->subset)); // remove duplicate Elements with the same state.
+ queue_.push(task); // Push the task onto the queue. The queue keeps it
+ // in prioritized order, so we always process the one with the "best"
+ // weight (highest in the semiring).
+
+ { // this is a check.
+ double best_cost = backward_costs_[ifst_->Start()],
+ tolerance = 0.01 + 1.0e-04 * std::abs(best_cost);
+ if (task->priority_cost < best_cost - tolerance) {
+ KALDI_WARN << "Cost below best cost was encountered:"
+ << task->priority_cost << " < " << best_cost;
+ }
+ }
+ }
+ }
+ all_elems.clear(); // as it's a reference to a class variable; we want it to stay
+ // empty.
+ }
+
+
+ bool IsIsymbolOrFinal(InputStateId state) { // returns true if this state
+ // of the input FST either is final or has an osymbol on an arc out of it.
+ // Uses the vector isymbol_or_final_ as a cache for this info.
+ KALDI_ASSERT(state >= 0);
+ if (isymbol_or_final_.size() <= state)
+ isymbol_or_final_.resize(state+1, static_cast<char>(OSF_UNKNOWN));
+ if (isymbol_or_final_[state] == static_cast<char>(OSF_NO))
+ return false;
+ else if (isymbol_or_final_[state] == static_cast<char>(OSF_YES))
+ return true;
+ // else work it out...
+ isymbol_or_final_[state] = static_cast<char>(OSF_NO);
+ if (ifst_->Final(state) != Weight::Zero())
+ isymbol_or_final_[state] = static_cast<char>(OSF_YES);
+ for (ArcIterator<ExpandedFst<Arc> > aiter(*ifst_, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ if (arc.ilabel != 0 && arc.weight != Weight::Zero()) {
+ isymbol_or_final_[state] = static_cast<char>(OSF_YES);
+ return true;
+ }
+ }
+ return IsIsymbolOrFinal(state); // will only recurse once.
+ }
+
+ void ComputeBackwardWeight() {
+ // Sets up the backward_costs_ array, and the cutoff_ variable.
+ KALDI_ASSERT(beam_ > 0);
+
+ // Only handle the toplogically sorted case.
+ backward_costs_.resize(ifst_->NumStates());
+ for (StateId s = ifst_->NumStates() - 1; s >= 0; s--) {
+ double &cost = backward_costs_[s];
+ cost = ConvertToCost(ifst_->Final(s));
+ for (ArcIterator<ExpandedFst<Arc> > aiter(*ifst_, s);
+ !aiter.Done(); aiter.Next()) {
+ const Arc &arc = aiter.Value();
+ cost = std::min(cost,
+ ConvertToCost(arc.weight) + backward_costs_[arc.nextstate]);
+ }
+ }
+
+ if (ifst_->Start() == kNoStateId) return; // we'll be returning
+ // an empty FST.
+
+ double best_cost = backward_costs_[ifst_->Start()];
+ if (best_cost == std::numeric_limits<double>::infinity())
+ KALDI_WARN << "Total weight of input lattice is zero.";
+ cutoff_ = best_cost + beam_;
+ }
+
+ void InitializeDeterminization() {
+ // We insist that the input lattice be topologically sorted. This is not a
+ // fundamental limitation of the algorithm (which in principle should be
+ // applicable to even cyclic FSTs), but it helps us more efficiently
+ // compute the backward_costs_ array. There may be some other reason we
+ // require this, that escapes me at the moment.
+ KALDI_ASSERT(ifst_->Properties(kTopSorted, true) != 0);
+ ComputeBackwardWeight();
+#if !(__GNUC__ == 4 && __GNUC_MINOR__ == 0)
+ if(ifst_->Properties(kExpanded, false) != 0) { // if we know the number of
+ // states in ifst_, it might be a bit more efficient
+ // to pre-size the hashes so we're not constantly rebuilding them.
+ StateId num_states =
+ down_cast<const ExpandedFst<Arc>*, const Fst<Arc> >(ifst_)->NumStates();
+ minimal_hash_.rehash(num_states/2 + 3);
+ initial_hash_.rehash(num_states/2 + 3);
+ }
+#endif
+ InputStateId start_id = ifst_->Start();
+ if (start_id != kNoStateId) {
+ /* Create determinized-state corresponding to the start state....
+ Unlike all the other states, we don't "normalize" the representation
+ of this determinized-state before we put it into minimal_hash_. This is actually
+ what we want, as otherwise we'd have problems dealing with any extra weight
+ and string and might have to create a "super-initial" state which would make
+ the output nondeterministic. Normalization is only needed to make the
+ determinized output more minimal anyway, it's not needed for correctness.
+ Note, we don't put anything in the initial_hash_. The initial_hash_ is only
+ a lookaside buffer anyway, so this isn't a problem-- it will get populated
+ later if it needs to be.
+ */
+ vector<Element> subset(1);
+ subset[0].state = start_id;
+ subset[0].weight = Weight::One();
+ subset[0].string = repository_.EmptyString(); // Id of empty sequence.
+ EpsilonClosure(&subset); // follow through epsilon-input links
+ ConvertToMinimal(&subset); // remove all but final states and
+ // states with input-labels on arcs out of them.
+ // Weight::One() is the "forward-weight" of this determinized state...
+ // i.e. the minimal cost from the start of the determinized FST to this
+ // state [One() because it's the start state].
+ OutputState *initial_state = new OutputState(subset, 0);
+ KALDI_ASSERT(output_states_.empty());
+ output_states_.push_back(initial_state);
+ num_elems_ += subset.size();
+ OutputStateId initial_state_id = 0;
+ minimal_hash_[&(initial_state->minimal_subset)] = initial_state_id;
+ ProcessFinal(initial_state_id);
+ ProcessTransitions(initial_state_id); // this will add tasks to
+ // the queue, which we'll start processing in Determinize().
+ }
+ }
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(LatticeDeterminizerPruned);
+
+ struct OutputState {
+ vector<Element> minimal_subset;
+ vector<TempArc> arcs; // arcs out of the state-- those that have been processed.
+ // Note: the final-weight is included here with kNoStateId as the state id. We
+ // always process the final-weight regardless of the beam; when producing the
+ // output we may have to ignore some of these.
+ double forward_cost; // Represents minimal cost from start-state
+ // to this state. Used in prioritization of tasks, and pruning.
+ // Note: we know this minimal cost from when we first create the OutputState;
+ // this is because of the priority-queue we use, that ensures that the
+ // "best" path into the state will be expanded first.
+ OutputState(const vector<Element> &minimal_subset,
+ double forward_cost): minimal_subset(minimal_subset),
+ forward_cost(forward_cost) { }
+ };
+
+ vector<OutputState*> output_states_; // All the info about the output states.
+
+ int num_arcs_; // keep track of memory usage: number of arcs in output_states_[ ]->arcs
+ int num_elems_; // keep track of memory usage: number of elems in output_states_ and
+ // the keys of initial_hash_
+
+ const ExpandedFst<Arc> *ifst_;
+ std::vector<double> backward_costs_; // This vector stores, for every state in ifst_,
+ // the minimal cost to the end-state (i.e. the sum of weights; they are guaranteed to
+ // have "take-the-minimum" semantics). We get the double from the ConvertToCost()
+ // function on the lattice weights.
+
+ double beam_;
+ double cutoff_; // beam plus total-weight of input (and note, the weight is
+ // guaranteed to be "tropical-like" so the sum does represent a min-cost.
+
+ DeterminizeLatticePrunedOptions opts_;
+ SubsetKey hasher_; // object that computes keys-- has no data members.
+ SubsetEqual equal_; // object that compares subsets-- only data member is delta_.
+ bool determinized_; // set to true when user called Determinize(); used to make
+ // sure this object is used correctly.
+ MinimalSubsetHash minimal_hash_; // hash from Subset to OutputStateId. Subset is "minimal
+ // representation" (only include final and states and states with
+ // nonzero ilabel on arc out of them. Owns the pointers
+ // in its keys.
+ InitialSubsetHash initial_hash_; // hash from Subset to Element, which
+ // represents the OutputStateId together
+ // with an extra weight and string. Subset
+ // is "initial representation". The extra
+ // weight and string is needed because after
+ // we convert to minimal representation and
+ // normalize, there may be an extra weight
+ // and string. Owns the pointers
+ // in its keys.
+
+ struct Task {
+ OutputStateId state; // State from which we're processing the transition.
+ Label label; // Label on the transition we're processing out of this state.
+ vector<Element> subset; // Weighted subset of states (with strings)-- not normalized.
+ double priority_cost; // Cost used in deciding priority of tasks. Note:
+ // we assume there is a ConvertToCost() function that converts the semiring to double.
+ };
+
+ struct TaskCompare {
+ inline int operator() (const Task *t1, const Task *t2) {
+ // view this like operator <, which is the default template parameter
+ // to std::priority_queue.
+ // returns true if t1 is worse than t2.
+ return (t1->priority_cost > t2->priority_cost);
+ }
+ };
+
+ // This priority queue contains "Task"s to be processed; these correspond
+ // to transitions out of determinized states. We process these in priority
+ // order according to the best weight of any path passing through these
+ // determinized states... it's possible to work this out.
+ std::priority_queue<Task*, vector<Task*>, TaskCompare> queue_;
+
+ vector<pair<Label, Element> > all_elems_tmp_; // temporary vector used in ProcessTransitions.
+
+ enum IsymbolOrFinal { OSF_UNKNOWN = 0, OSF_NO = 1, OSF_YES = 2 };
+
+ vector<char> isymbol_or_final_; // A kind of cache; it says whether
+ // each state is (emitting or final) where emitting means it has at least one
+ // non-epsilon output arc. Only accessed by IsIsymbolOrFinal()
+
+ LatticeStringRepository<IntType> repository_; // defines a compact and fast way of
+ // storing sequences of labels.
+
+ void AddStrings(const vector<Element> &vec,
+ vector<StringId> *needed_strings) {
+ for (typename std::vector<Element>::const_iterator iter = vec.begin();
+ iter != vec.end(); ++iter)
+ needed_strings->push_back(iter->string);
+ }
+};
+
+
+// normally Weight would be LatticeWeight<float> (which has two floats),
+// or possibly TropicalWeightTpl<float>, and IntType would be int32.
+// Caution: there are two versions of the function DeterminizeLatticePruned,
+// with identical code but different output FST types.
+template<class Weight, class IntType>
+bool DeterminizeLatticePruned(
+ const ExpandedFst<ArcTpl<Weight> >&ifst,
+ double beam,
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > >*ofst,
+ DeterminizeLatticePrunedOptions opts) {
+ ofst->SetInputSymbols(ifst.InputSymbols());
+ ofst->SetOutputSymbols(ifst.OutputSymbols());
+ if (ifst.NumStates() == 0) {
+ ofst->DeleteStates();
+ return true;
+ }
+ KALDI_ASSERT(opts.retry_cutoff >= 0.0 && opts.retry_cutoff < 1.0);
+ int32 max_num_iters = 10; // avoid the potential for infinite loops if
+ // retrying.
+ VectorFst<ArcTpl<Weight> > temp_fst;
+
+ for (int32 iter = 0; iter < max_num_iters; iter++) {
+ LatticeDeterminizerPruned<Weight, IntType> det(iter == 0 ? ifst : temp_fst,
+ beam, opts);
+ double effective_beam;
+ bool ans = det.Determinize(&effective_beam);
+ // if it returns false it will typically still produce reasonable output,
+ // just with a narrower beam than "beam". If the user specifies an infinite
+ // beam we don't do this beam-narrowing.
+ if (effective_beam >= beam * opts.retry_cutoff ||
+ beam == std::numeric_limits<double>::infinity() ||
+ iter + 1 == max_num_iters) {
+ det.Output(ofst);
+ return ans;
+ } else {
+ // The code below to set "beam" is a heuristic.
+ // If effective_beam is very small, we want to reduce by a lot.
+ // But never change the beam by more than a factor of two.
+ if (effective_beam < 0.0) effective_beam = 0.0;
+ double new_beam = beam * sqrt(effective_beam / beam);
+ if (new_beam < 0.5 * beam) new_beam = 0.5 * beam;
+ beam = new_beam;
+ if (iter == 0) temp_fst = ifst;
+ kaldi::PruneLattice(beam, &temp_fst);
+ KALDI_LOG << "Pruned state-level lattice with beam " << beam
+ << " and retrying determinization with that beam.";
+ }
+ }
+ return false; // Suppress compiler warning; this code is unreachable.
+}
+
+
+// normally Weight would be LatticeWeight<float> (which has two floats),
+// or possibly TropicalWeightTpl<float>, and IntType would be int32.
+// Caution: there are two versions of the function DeterminizeLatticePruned,
+// with identical code but different output FST types.
+template<class Weight>
+bool DeterminizeLatticePruned(const ExpandedFst<ArcTpl<Weight> > &ifst,
+ double beam,
+ MutableFst<ArcTpl<Weight> > *ofst,
+ DeterminizeLatticePrunedOptions opts) {
+ typedef int32 IntType;
+ ofst->SetInputSymbols(ifst.InputSymbols());
+ ofst->SetOutputSymbols(ifst.OutputSymbols());
+ KALDI_ASSERT(opts.retry_cutoff >= 0.0 && opts.retry_cutoff < 1.0);
+ if (ifst.NumStates() == 0) {
+ ofst->DeleteStates();
+ return true;
+ }
+ int32 max_num_iters = 10; // avoid the potential for infinite loops if
+ // retrying.
+ VectorFst<ArcTpl<Weight> > temp_fst;
+
+ for (int32 iter = 0; iter < max_num_iters; iter++) {
+ LatticeDeterminizerPruned<Weight, IntType> det(iter == 0 ? ifst : temp_fst,
+ beam, opts);
+ double effective_beam;
+ bool ans = det.Determinize(&effective_beam);
+ // if it returns false it will typically still
+ // produce reasonable output, just with a
+ // narrower beam than "beam".
+ if (effective_beam >= beam * opts.retry_cutoff ||
+ iter + 1 == max_num_iters) {
+ det.Output(ofst);
+ return ans;
+ } else {
+ // The code below to set "beam" is a heuristic.
+ // If effective_beam is very small, we want to reduce by a lot.
+ // But never change the beam by more than a factor of two.
+ if (effective_beam < 0)
+ effective_beam = 0;
+ double new_beam = beam * sqrt(effective_beam / beam);
+ if (new_beam < 0.5 * beam) new_beam = 0.5 * beam;
+ KALDI_WARN << "Effective beam " << effective_beam << " was less than beam "
+ << beam << " * cutoff " << opts.retry_cutoff << ", pruning raw "
+ << "lattice with new beam " << new_beam << " and retrying.";
+ beam = new_beam;
+ if (iter == 0) temp_fst = ifst;
+ kaldi::PruneLattice(beam, &temp_fst);
+ }
+ }
+ return false; // Suppress compiler warning; this code is unreachable.
+}
+
+//template<class Weight>
+//typename ArcTpl<Weight>::Label DeterminizeLatticeInsertPhones(
+// const kaldi::TransitionInformation &trans_model,
+// MutableFst<ArcTpl<Weight> > *fst) {
+// // Define some types.
+// typedef ArcTpl<Weight> Arc;
+// typedef typename Arc::StateId StateId;
+// typedef typename Arc::Label Label;
+//
+// // Work out the first phone symbol. This is more related to the phone
+// // insertion function, so we put it here and make it the returning value of
+// // DeterminizeLatticeInsertPhones().
+// Label first_phone_label = HighestNumberedInputSymbol(*fst) + 1;
+//
+// // Insert phones here.
+// for (StateIterator<MutableFst<Arc> > siter(*fst);
+// !siter.Done(); siter.Next()) {
+// StateId state = siter.Value();
+// if (state == fst->Start())
+// continue;
+// for (MutableArcIterator<MutableFst<Arc> > aiter(fst, state);
+// !aiter.Done(); aiter.Next()) {
+// Arc arc = aiter.Value();
+//
+// // Note: the words are on the input symbol side and transition-id's are on
+// // the output symbol side.
+// if ((arc.olabel != 0)
+// && (trans_model.TransitionIdIsStartOfPhone(arc.olabel))
+// && (!trans_model.IsSelfLoop(arc.olabel))) {
+// Label phone =
+// static_cast<Label>(trans_model.TransitionIdToPhone(arc.olabel));
+//
+// // Skips <eps>.
+// KALDI_ASSERT(phone != 0);
+//
+// if (arc.ilabel == 0) {
+// // If there is no word on the arc, insert the phone directly.
+// arc.ilabel = first_phone_label + phone;
+// } else {
+// // Otherwise, add an additional arc.
+// StateId additional_state = fst->AddState();
+// StateId next_state = arc.nextstate;
+// arc.nextstate = additional_state;
+// fst->AddArc(additional_state,
+// Arc(first_phone_label + phone, 0,
+// Weight::One(), next_state));
+// }
+// }
+//
+// aiter.SetValue(arc);
+// }
+// }
+//
+// return first_phone_label;
+//}
+//
+//template<class Weight>
+//void DeterminizeLatticeDeletePhones(
+// typename ArcTpl<Weight>::Label first_phone_label,
+// MutableFst<ArcTpl<Weight> > *fst) {
+// // Define some types.
+// typedef ArcTpl<Weight> Arc;
+// typedef typename Arc::StateId StateId;
+// typedef typename Arc::Label Label;
+//
+// // Delete phones here.
+// for (StateIterator<MutableFst<Arc> > siter(*fst);
+// !siter.Done(); siter.Next()) {
+// StateId state = siter.Value();
+// for (MutableArcIterator<MutableFst<Arc> > aiter(fst, state);
+// !aiter.Done(); aiter.Next()) {
+// Arc arc = aiter.Value();
+//
+// if (arc.ilabel >= first_phone_label)
+// arc.ilabel = 0;
+//
+// aiter.SetValue(arc);
+// }
+// }
+//}
+//// instantiate for type LatticeWeight
+//template
+//void DeterminizeLatticeDeletePhones(
+// ArcTpl<kaldi::LatticeWeight>::Label first_phone_label,
+// MutableFst<ArcTpl<kaldi::LatticeWeight> > *fst);
+//
+///** This function does a first pass determinization with phone symbols inserted
+// at phone boundary. It uses a transition model to work out the transition-id
+// to phone map. First, phones will be inserted into the word level lattice.
+// Second, determinization will be applied on top of the phone + word lattice.
+// Finally, the inserted phones will be removed, converting the lattice back to
+// a word level lattice. The output lattice of this pass is not deterministic,
+// since we remove the phone symbols as a last step. It is supposed to be
+// followed by another pass of determinization at the word level. It could also
+// be useful for some other applications such as fMLLR estimation, confidence
+// estimation, discriminative training, etc.
+//*/
+//template<class Weight, class IntType>
+//bool DeterminizeLatticePhonePrunedFirstPass(
+// const kaldi::TransitionInformation &trans_model,
+// double beam,
+// MutableFst<ArcTpl<Weight> > *fst,
+// const DeterminizeLatticePrunedOptions &opts) {
+// // First, insert the phones.
+// typename ArcTpl<Weight>::Label first_phone_label =
+// DeterminizeLatticeInsertPhones(trans_model, fst);
+// TopSort(fst);
+//
+// // Second, do determinization with phone inserted.
+// bool ans = DeterminizeLatticePruned<Weight>(*fst, beam, fst, opts);
+//
+// // Finally, remove the inserted phones.
+// DeterminizeLatticeDeletePhones(first_phone_label, fst);
+// TopSort(fst);
+//
+// return ans;
+//}
+//
+//// "Destructive" version of DeterminizeLatticePhonePruned() where the input
+//// lattice might be modified.
+//template<class Weight, class IntType>
+//bool DeterminizeLatticePhonePruned(
+// const kaldi::TransitionInformation &trans_model,
+// MutableFst<ArcTpl<Weight> > *ifst,
+// double beam,
+// MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > > *ofst,
+// DeterminizeLatticePhonePrunedOptions opts) {
+// // Returning status.
+// bool ans = true;
+//
+// // Make sure at least one of opts.phone_determinize and opts.word_determinize
+// // is not false, otherwise calling this function doesn't make any sense.
+// if ((opts.phone_determinize || opts.word_determinize) == false) {
+// KALDI_WARN << "Both --phone-determinize and --word-determinize are set to "
+// << "false, copying lattice without determinization.";
+// // We are expecting the words on the input side.
+// ConvertLattice<Weight, IntType>(*ifst, ofst, false);
+// return ans;
+// }
+//
+// // Determinization options.
+// DeterminizeLatticePrunedOptions det_opts;
+// det_opts.delta = opts.delta;
+// det_opts.max_mem = opts.max_mem;
+//
+// // If --phone-determinize is true, do the determinization on phone + word
+// // lattices.
+// if (opts.phone_determinize) {
+// KALDI_VLOG(3) << "Doing first pass of determinization on phone + word "
+// << "lattices.";
+// ans = DeterminizeLatticePhonePrunedFirstPass<Weight, IntType>(
+// trans_model, beam, ifst, det_opts) && ans;
+//
+// // If --word-determinize is false, we've finished the job and return here.
+// if (!opts.word_determinize) {
+// // We are expecting the words on the input side.
+// ConvertLattice<Weight, IntType>(*ifst, ofst, false);
+// return ans;
+// }
+// }
+//
+// // If --word-determinize is true, do the determinization on word lattices.
+// if (opts.word_determinize) {
+// KALDI_VLOG(3) << "Doing second pass of determinization on word lattices.";
+// ans = DeterminizeLatticePruned<Weight, IntType>(
+// *ifst, beam, ofst, det_opts) && ans;
+// }
+//
+// // If --minimize is true, push and minimize after determinization.
+// if (opts.minimize) {
+// KALDI_VLOG(3) << "Pushing and minimizing on word lattices.";
+// ans = PushCompactLatticeStrings<Weight, IntType>(ofst) && ans;
+// ans = PushCompactLatticeWeights<Weight, IntType>(ofst) && ans;
+// ans = MinimizeCompactLattice<Weight, IntType>(ofst) && ans;
+// }
+//
+// return ans;
+//}
+//
+//// Normal verson of DeterminizeLatticePhonePruned(), where the input lattice
+//// will be kept as unchanged.
+//template<class Weight, class IntType>
+//bool DeterminizeLatticePhonePruned(
+// const kaldi::TransitionInformation &trans_model,
+// const ExpandedFst<ArcTpl<Weight> > &ifst,
+// double beam,
+// MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > > *ofst,
+// DeterminizeLatticePhonePrunedOptions opts) {
+// VectorFst<ArcTpl<Weight> > temp_fst(ifst);
+// return DeterminizeLatticePhonePruned(trans_model, &temp_fst,
+// beam, ofst, opts);
+//}
+//
+//bool DeterminizeLatticePhonePrunedWrapper(
+// const kaldi::TransitionInformation &trans_model,
+// MutableFst<kaldi::LatticeArc> *ifst,
+// double beam,
+// MutableFst<kaldi::CompactLatticeArc> *ofst,
+// DeterminizeLatticePhonePrunedOptions opts) {
+// bool ans = true;
+// Invert(ifst);
+// if (ifst->Properties(fst::kTopSorted, true) == 0) {
+// if (!TopSort(ifst)) {
+// // Cannot topologically sort the lattice -- determinization will fail.
+// KALDI_ERR << "Topological sorting of state-level lattice failed (probably"
+// << " your lexicon has empty words or your LM has epsilon cycles"
+// << ").";
+// }
+// }
+// ILabelCompare<kaldi::LatticeArc> ilabel_comp;
+// ArcSort(ifst, ilabel_comp);
+// ans = DeterminizeLatticePhonePruned<kaldi::LatticeWeight, kaldi::int32>(
+// trans_model, ifst, beam, ofst, opts);
+// Connect(ofst);
+// return ans;
+//}
+
+// Instantiate the templates for the types we might need.
+// Note: there are actually four templates, each of which
+// we instantiate for a single type.
+template
+bool DeterminizeLatticePruned<kaldi::LatticeWeight>(
+ const ExpandedFst<kaldi::LatticeArc> &ifst,
+ double prune,
+ MutableFst<kaldi::CompactLatticeArc> *ofst,
+ DeterminizeLatticePrunedOptions opts);
+
+template
+bool DeterminizeLatticePruned<kaldi::LatticeWeight>(
+ const ExpandedFst<kaldi::LatticeArc> &ifst,
+ double prune,
+ MutableFst<kaldi::LatticeArc> *ofst,
+ DeterminizeLatticePrunedOptions opts);
+
+//template
+//bool DeterminizeLatticePhonePruned<kaldi::LatticeWeight, kaldi::int32>(
+// const kaldi::TransitionInformation &trans_model,
+// const ExpandedFst<kaldi::LatticeArc> &ifst,
+// double prune,
+// MutableFst<kaldi::CompactLatticeArc> *ofst,
+// DeterminizeLatticePhonePrunedOptions opts);
+//
+//template
+//bool DeterminizeLatticePhonePruned<kaldi::LatticeWeight, kaldi::int32>(
+// const kaldi::TransitionInformation &trans_model,
+// MutableFst<kaldi::LatticeArc> *ifst,
+// double prune,
+// MutableFst<kaldi::CompactLatticeArc> *ofst,
+// DeterminizeLatticePhonePrunedOptions opts);
+
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/determinize-lattice-pruned.h b/runtime/onnxruntime/third_party/kaldi/lat/determinize-lattice-pruned.h
new file mode 100644
index 000000000..c268f1299
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/determinize-lattice-pruned.h
@@ -0,0 +1,296 @@
+// lat/determinize-lattice-pruned.h
+
+// Copyright 2009-2012 Microsoft Corporation
+// 2012-2013 Johns Hopkins University (Author: Daniel Povey)
+// 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_LAT_DETERMINIZE_LATTICE_PRUNED_H_
+#define KALDI_LAT_DETERMINIZE_LATTICE_PRUNED_H_
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+#include <algorithm>
+#include <map>
+#include <set>
+#include <vector>
+#include "fstext/lattice-weight.h"
+#include "itf/transition-information.h"
+#include "itf/options-itf.h"
+#include "lat/kaldi-lattice.h"
+
+namespace fst {
+
+/// \addtogroup fst_extensions
+/// @{
+
+
+// For example of usage, see test-determinize-lattice-pruned.cc
+
+/*
+ DeterminizeLatticePruned implements a special form of determinization with
+ epsilon removal, optimized for a phase of lattice generation. This algorithm
+ also does pruning at the same time-- the combination is more efficient as it
+ somtimes prevents us from creating a lot of states that would later be pruned
+ away. This allows us to increase the lattice-beam and not have the algorithm
+ blow up. Also, because our algorithm processes states in order from those
+ that appear on high-scoring paths down to those that appear on low-scoring
+ paths, we can easily terminate the algorithm after a certain specified number
+ of states or arcs.
+
+ The input is an FST with weight-type BaseWeightType (usually a pair of floats,
+ with a lexicographical type of order, such as LatticeWeightTpl<float>).
+ Typically this would be a state-level lattice, with input symbols equal to
+ words, and output-symbols equal to p.d.f's (so like the inverse of HCLG). Imagine representing this as an
+ acceptor of type CompactLatticeWeightTpl<float>, in which the input/output
+ symbols are words, and the weights contain the original weights together with
+ strings (with zero or one symbol in them) containing the original output labels
+ (the p.d.f.'s). We determinize this using acceptor determinization with
+ epsilon removal. Remember (from lattice-weight.h) that
+ CompactLatticeWeightTpl has a special kind of semiring where we always take
+ the string corresponding to the best cost (of type BaseWeightType), and
+ discard the other. This corresponds to taking the best output-label sequence
+ (of p.d.f.'s) for each input-label sequence (of words). We couldn't use the
+ Gallic weight for this, or it would die as soon as it detected that the input
+ FST was non-functional. In our case, any acyclic FST (and many cyclic ones)
+ can be determinized.
+ We assume that there is a function
+ Compare(const BaseWeightType &a, const BaseWeightType &b)
+ that returns (-1, 0, 1) according to whether (a < b, a == b, a > b) in the
+ total order on the BaseWeightType... this information should be the
+ same as NaturalLess would give, but it's more efficient to do it this way.
+ You can define this for things like TropicalWeight if you need to instantiate
+ this class for that weight type.
+
+ We implement this determinization in a special way to make it efficient for
+ the types of FSTs that we will apply it to. One issue is that if we
+ explicitly represent the strings (in CompactLatticeWeightTpl) as vectors of
+ type vector<IntType>, the algorithm takes time quadratic in the length of
+ words (in states), because propagating each arc involves copying a whole
+ vector (of integers representing p.d.f.'s). Instead we use a hash structure
+ where each string is a pointer (Entry*), and uses a hash from (Entry*,
+ IntType), to the successor string (and a way to get the latest IntType and the
+ ancestor Entry*). [this is the class LatticeStringRepository].
+
+ Another issue is that rather than representing a determinized-state as a
+ collection of (state, weight), we represent it in a couple of reduced forms.
+ Suppose a determinized-state is a collection of (state, weight) pairs; call
+ this the "canonical representation". Note: these collections are always
+ normalized to remove any common weight and string part. Define end-states as
+ the subset of states that have an arc out of them with a label on, or are
+ final. If we represent a determinized-state a the set of just its (end-state,
+ weight) pairs, this will be a valid and more compact representation, and will
+ lead to a smaller set of determinized states (like early minimization). Call
+ this collection of (end-state, weight) pairs the "minimal representation". As
+ a mechanism to reduce compute, we can also consider another representation.
+ In the determinization algorithm, we start off with a set of (begin-state,
+ weight) pairs (where the "begin-states" are initial or have a label on the
+ transition into them), and the "canonical representation" consists of the
+ epsilon-closure of this set (i.e. follow epsilons). Call this set of
+ (begin-state, weight) pairs, appropriately normalized, the "initial
+ representation". If two initial representations are the same, the "canonical
+ representation" and hence the "minimal representation" will be the same. We
+ can use this to reduce compute. Note that if two initial representations are
+ different, this does not preclude the other representations from being the same.
+
+*/
+
+
+struct DeterminizeLatticePrunedOptions {
+ float delta; // A small offset used to measure equality of weights.
+ int max_mem; // If >0, determinization will fail and return false
+ // when the algorithm's (approximate) memory consumption crosses this threshold.
+ int max_loop; // If >0, can be used to detect non-determinizable input
+ // (a case that wouldn't be caught by max_mem).
+ int max_states;
+ int max_arcs;
+ float retry_cutoff;
+ DeterminizeLatticePrunedOptions(): delta(kDelta),
+ max_mem(-1),
+ max_loop(-1),
+ max_states(-1),
+ max_arcs(-1),
+ retry_cutoff(0.5) { }
+ void Register (kaldi::OptionsItf *opts) {
+ opts->Register("delta", &delta, "Tolerance used in determinization");
+ opts->Register("max-mem", &max_mem, "Maximum approximate memory usage in "
+ "determinization (real usage might be many times this)");
+ opts->Register("max-arcs", &max_arcs, "Maximum number of arcs in "
+ "output FST (total, not per state");
+ opts->Register("max-states", &max_states, "Maximum number of arcs in output "
+ "FST (total, not per state");
+ opts->Register("max-loop", &max_loop, "Option used to detect a particular "
+ "type of determinization failure, typically due to invalid input "
+ "(e.g., negative-cost loops)");
+ opts->Register("retry-cutoff", &retry_cutoff, "Controls pruning un-determinized "
+ "lattice and retrying determinization: if effective-beam < "
+ "retry-cutoff * beam, we prune the raw lattice and retry. Avoids "
+ "ever getting empty output for long segments.");
+ }
+};
+
+struct DeterminizeLatticePhonePrunedOptions {
+ // delta: a small offset used to measure equality of weights.
+ float delta;
+ // max_mem: if > 0, determinization will fail and return false when the
+ // algorithm's (approximate) memory consumption crosses this threshold.
+ int max_mem;
+ // phone_determinize: if true, do a first pass determinization on both phones
+ // and words.
+ bool phone_determinize;
+ // word_determinize: if true, do a second pass determinization on words only.
+ bool word_determinize;
+ // minimize: if true, push and minimize after determinization.
+ bool minimize;
+ DeterminizeLatticePhonePrunedOptions(): delta(kDelta),
+ max_mem(50000000),
+ phone_determinize(true),
+ word_determinize(true),
+ minimize(false) {}
+ void Register (kaldi::OptionsItf *opts) {
+ opts->Register("delta", &delta, "Tolerance used in determinization");
+ opts->Register("max-mem", &max_mem, "Maximum approximate memory usage in "
+ "determinization (real usage might be many times this).");
+ opts->Register("phone-determinize", &phone_determinize, "If true, do an "
+ "initial pass of determinization on both phones and words (see"
+ " also --word-determinize)");
+ opts->Register("word-determinize", &word_determinize, "If true, do a second "
+ "pass of determinization on words only (see also "
+ "--phone-determinize)");
+ opts->Register("minimize", &minimize, "If true, push and minimize after "
+ "determinization.");
+ }
+};
+
+/**
+ This function implements the normal version of DeterminizeLattice, in which the
+ output strings are represented using sequences of arcs, where all but the
+ first one has an epsilon on the input side. It also prunes using the beam
+ in the "prune" parameter. The input FST must be topologically sorted in order
+ for the algorithm to work. For efficiency it is recommended to sort ilabel as well.
+ Returns true on success, and false if it had to terminate the determinization
+ earlier than specified by the "prune" beam-- that is, if it terminated because
+ of the max_mem, max_loop or max_arcs constraints in the options.
+ CAUTION: you may want to use the version below which outputs to CompactLattice.
+*/
+template<class Weight>
+bool DeterminizeLatticePruned(
+ const ExpandedFst<ArcTpl<Weight> > &ifst,
+ double prune,
+ MutableFst<ArcTpl<Weight> > *ofst,
+ DeterminizeLatticePrunedOptions opts = DeterminizeLatticePrunedOptions());
+
+
+/* This is a version of DeterminizeLattice with a slightly more "natural" output format,
+ where the output sequences are encoded using the CompactLatticeArcTpl template
+ (i.e. the sequences of output symbols are represented directly as strings The input
+ FST must be topologically sorted in order for the algorithm to work. For efficiency
+ it is recommended to sort the ilabel for the input FST as well.
+ Returns true on normal success, and false if it had to terminate the determinization
+ earlier than specified by the "prune" beam-- that is, if it terminated because
+ of the max_mem, max_loop or max_arcs constraints in the options.
+ CAUTION: if Lattice is the input, you need to Invert() before calling this,
+ so words are on the input side.
+*/
+template<class Weight, class IntType>
+bool DeterminizeLatticePruned(
+ const ExpandedFst<ArcTpl<Weight> >&ifst,
+ double prune,
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > > *ofst,
+ DeterminizeLatticePrunedOptions opts = DeterminizeLatticePrunedOptions());
+
+/** This function takes in lattices and inserts phones at phone boundaries. It
+ uses the transition model to work out the transition_id to phone map. The
+ returning value is the starting index of the phone label. Typically we pick
+ (maximum_output_label_index + 1) as this value. The inserted phones are then
+ mapped to (returning_value + original_phone_label) in the new lattice. The
+ returning value will be used by DeterminizeLatticeDeletePhones() where it
+ works out the phones according to this value.
+*/
+template<class Weight>
+typename ArcTpl<Weight>::Label DeterminizeLatticeInsertPhones(
+ const kaldi::TransitionInformation &trans_model,
+ MutableFst<ArcTpl<Weight> > *fst);
+
+/** This function takes in lattices and deletes "phones" from them. The "phones"
+ here are actually any label that is larger than first_phone_label because
+ when we insert phones into the lattice, we map the original phone label to
+ (first_phone_label + original_phone_label). It is supposed to be used
+ together with DeterminizeLatticeInsertPhones()
+*/
+template<class Weight>
+void DeterminizeLatticeDeletePhones(
+ typename ArcTpl<Weight>::Label first_phone_label,
+ MutableFst<ArcTpl<Weight> > *fst);
+
+/** This function is a wrapper of DeterminizeLatticePhonePrunedFirstPass() and
+ DeterminizeLatticePruned(). If --phone-determinize is set to true, it first
+ calls DeterminizeLatticePhonePrunedFirstPass() to do the initial pass of
+ determinization on the phone + word lattices. If --word-determinize is set
+ true, it then does a second pass of determinization on the word lattices by
+ calling DeterminizeLatticePruned(). If both are set to false, then it gives
+ a warning and copying the lattices without determinization.
+
+ Note: the point of doing first a phone-level determinization pass and then
+ a word-level determinization pass is that it allows us to determinize
+ deeper lattices without "failing early" and returning a too-small lattice
+ due to the max-mem constraint. The result should be the same as word-level
+ determinization in general, but for deeper lattices it is a bit faster,
+ despite the fact that we now have two passes of determinization by default.
+*/
+template<class Weight, class IntType>
+bool DeterminizeLatticePhonePruned(
+ const kaldi::TransitionInformation &trans_model,
+ const ExpandedFst<ArcTpl<Weight> > &ifst,
+ double prune,
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > > *ofst,
+ DeterminizeLatticePhonePrunedOptions opts
+ = DeterminizeLatticePhonePrunedOptions());
+
+/** "Destructive" version of DeterminizeLatticePhonePruned() where the input
+ lattice might be changed.
+*/
+template<class Weight, class IntType>
+bool DeterminizeLatticePhonePruned(
+ const kaldi::TransitionInformation &trans_model,
+ MutableFst<ArcTpl<Weight> > *ifst,
+ double prune,
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > > *ofst,
+ DeterminizeLatticePhonePrunedOptions opts
+ = DeterminizeLatticePhonePrunedOptions());
+
+/** This function is a wrapper of DeterminizeLatticePhonePruned() that works for
+ Lattice type FSTs. It simplifies the calling process by calling
+ TopSort() Invert() and ArcSort() for you.
+ Unlike other determinization routines, the function
+ requires "ifst" to have transition-id's on the input side and words on the
+ output side.
+ This function can be used as the top-level interface to all the determinization
+ code.
+*/
+bool DeterminizeLatticePhonePrunedWrapper(
+ const kaldi::TransitionInformation &trans_model,
+ MutableFst<kaldi::LatticeArc> *ifst,
+ double prune,
+ MutableFst<kaldi::CompactLatticeArc> *ofst,
+ DeterminizeLatticePhonePrunedOptions opts
+ = DeterminizeLatticePhonePrunedOptions());
+
+/// @} end "addtogroup fst_extensions"
+
+} // end namespace fst
+
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/kaldi-lattice-test.cc b/runtime/onnxruntime/third_party/kaldi/lat/kaldi-lattice-test.cc
new file mode 100644
index 000000000..8dd454de2
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/kaldi-lattice-test.cc
@@ -0,0 +1,173 @@
+// lat/kaldi-lattice-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "lat/kaldi-lattice.h"
+#include "fstext/rand-fst.h"
+
+
+namespace kaldi {
+
+
+CompactLattice *RandCompactLattice() {
+ Lattice *fst = fst::RandPairFst<LatticeArc>();
+ CompactLattice *cfst = new CompactLattice;
+ ConvertLattice(*fst, cfst);
+ delete fst;
+ return cfst;
+}
+
+Lattice *RandLattice() {
+ Lattice *fst = fst::RandPairFst<LatticeArc>();
+ return fst;
+}
+
+void TestCompactLatticeTable(bool binary) {
+ CompactLatticeWriter writer(binary ? "ark:tmpf" : "ark,t:tmpf");
+ int N = 10;
+ std::vector<CompactLattice*> lat_vec(N);
+ for (int i = 0; i < N; i++) {
+ char buf[2];
+ buf[0] = '0' + i;
+ buf[1] = '\0';
+ std::string key = "key" + std::string(buf);
+ CompactLattice *fst = RandCompactLattice();
+ lat_vec[i] = fst;
+ writer.Write(key, *fst);
+ }
+ writer.Close();
+
+ RandomAccessCompactLatticeReader reader("ark:tmpf");
+ for (int i = 0; i < N; i++) {
+ char buf[2];
+ buf[0] = '0' + i;
+ buf[1] = '\0';
+ std::string key = "key" + std::string(buf);
+ const CompactLattice &fst = reader.Value(key);
+ KALDI_ASSERT(fst::Equal(fst, *(lat_vec[i])));
+ delete lat_vec[i];
+ }
+}
+
+// Write as CompactLattice, read as Lattice.
+void TestCompactLatticeTableCross(bool binary) {
+ CompactLatticeWriter writer(binary ? "ark:tmpf" : "ark,t:tmpf");
+ int N = 10;
+ std::vector<CompactLattice*> lat_vec(N);
+ for (int i = 0; i < N; i++) {
+ char buf[2];
+ buf[0] = '0' + i;
+ buf[1] = '\0';
+ std::string key = "key" + std::string(buf);
+ CompactLattice *fst = RandCompactLattice();
+ lat_vec[i] = fst;
+ writer.Write(key, *fst);
+ }
+ writer.Close();
+
+ RandomAccessLatticeReader reader("ark:tmpf");
+ for (int i = 0; i < N; i++) {
+ char buf[2];
+ buf[0] = '0' + i;
+ buf[1] = '\0';
+ std::string key = "key" + std::string(buf);
+ const Lattice &fst = reader.Value(key);
+ CompactLattice fst2;
+ ConvertLattice(fst, &fst2);
+ KALDI_ASSERT(fst::Equal(fst2, *(lat_vec[i])));
+ delete lat_vec[i];
+ }
+}
+
+// Lattice, binary.
+void TestLatticeTable(bool binary) {
+ LatticeWriter writer(binary ? "ark:tmpf" : "ark,t:tmpf");
+ int N = 10;
+ std::vector<Lattice*> lat_vec(N);
+ for (int i = 0; i < N; i++) {
+ char buf[2];
+ buf[0] = '0' + i;
+ buf[1] = '\0';
+ std::string key = "key" + std::string(buf);
+ Lattice *fst = RandLattice();
+ lat_vec[i] = fst;
+ writer.Write(key, *fst);
+ }
+ writer.Close();
+
+ RandomAccessLatticeReader reader("ark:tmpf");
+ for (int i = 0; i < N; i++) {
+ char buf[2];
+ buf[0] = '0' + i;
+ buf[1] = '\0';
+ std::string key = "key" + std::string(buf);
+ const Lattice &fst = reader.Value(key);
+ KALDI_ASSERT(fst::Equal(fst, *(lat_vec[i])));
+ delete lat_vec[i];
+ }
+}
+
+
+// Write as Lattice, read as CompactLattice.
+void TestLatticeTableCross(bool binary) {
+ LatticeWriter writer(binary ? "ark:tmpf" : "ark,t:tmpf");
+ int N = 10;
+ std::vector<Lattice*> lat_vec(N);
+ for (int i = 0; i < N; i++) {
+ char buf[2];
+ buf[0] = '0' + i;
+ buf[1] = '\0';
+ std::string key = "key" + std::string(buf);
+ Lattice *fst = RandLattice();
+ lat_vec[i] = fst;
+ writer.Write(key, *fst);
+ }
+ writer.Close();
+
+ RandomAccessCompactLatticeReader reader("ark:tmpf");
+ for (int i = 0; i < N; i++) {
+ char buf[2];
+ buf[0] = '0' + i;
+ buf[1] = '\0';
+ std::string key = "key" + std::string(buf);
+ const CompactLattice &fst = reader.Value(key);
+ Lattice fst2;
+ ConvertLattice(fst, &fst2);
+ KALDI_ASSERT(fst::RandEquivalent(fst2, *(lat_vec[i]), 5, 0.01, Rand(), 10));
+ delete lat_vec[i];
+ }
+}
+
+
+
+} // end namespace kaldi
+
+int main() {
+ using namespace kaldi;
+ for (int i = 0; i < 2; i++) {
+ bool binary = (i%2 == 0);
+ TestCompactLatticeTable(binary);
+ TestCompactLatticeTableCross(binary);
+ TestLatticeTable(binary);
+ TestLatticeTableCross(binary);
+ }
+ std::cout << "Test OK\n";
+
+ unlink("tmpf");
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/kaldi-lattice.cc b/runtime/onnxruntime/third_party/kaldi/lat/kaldi-lattice.cc
new file mode 100644
index 000000000..744cc5384
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/kaldi-lattice.cc
@@ -0,0 +1,506 @@
+// lat/kaldi-lattice.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "lat/kaldi-lattice.h"
+#include "fst/script/print-impl.h"
+
+namespace kaldi {
+
+/// Converts lattice types if necessary, deleting its input.
+template<class OrigWeightType>
+CompactLattice* ConvertToCompactLattice(fst::VectorFst<OrigWeightType> *ifst) {
+ if (!ifst) return NULL;
+ CompactLattice *ofst = new CompactLattice();
+ ConvertLattice(*ifst, ofst);
+ delete ifst;
+ return ofst;
+}
+
+// This overrides the template if there is no type conversion going on
+// (for efficiency).
+template<>
+CompactLattice* ConvertToCompactLattice(CompactLattice *ifst) {
+ return ifst;
+}
+
+/// Converts lattice types if necessary, deleting its input.
+template<class OrigWeightType>
+Lattice* ConvertToLattice(fst::VectorFst<OrigWeightType> *ifst) {
+ if (!ifst) return NULL;
+ Lattice *ofst = new Lattice();
+ ConvertLattice(*ifst, ofst);
+ delete ifst;
+ return ofst;
+}
+
+// This overrides the template if there is no type conversion going on
+// (for efficiency).
+template<>
+Lattice* ConvertToLattice(Lattice *ifst) {
+ return ifst;
+}
+
+
+bool WriteCompactLattice(std::ostream &os, bool binary,
+ const CompactLattice &t) {
+ if (binary) {
+ fst::FstWriteOptions opts;
+ // Leave all the options default. Normally these lattices wouldn't have any
+ // osymbols/isymbols so no point directing it not to write them (who knows what
+ // we'd want to if we had them).
+ return t.Write(os, opts);
+ } else {
+ // Text-mode output. Note: we expect that t.InputSymbols() and
+ // t.OutputSymbols() would always return NULL. The corresponding input
+ // routine would not work if the FST actually had symbols attached.
+ // Write a newline after the key, so the first line of the FST appears
+ // on its own line.
+ os << '\n';
+ bool acceptor = true, write_one = false;
+ fst::FstPrinter<CompactLatticeArc> printer(t, t.InputSymbols(),
+ t.OutputSymbols(),
+ NULL, acceptor, write_one, "\t");
+ printer.Print(&os, "<unknown>");
+ if (os.fail())
+ KALDI_WARN << "Stream failure detected.";
+ // Write another newline as a terminating character. The read routine will
+ // detect this [this is a Kaldi mechanism, not somethig in the original
+ // OpenFst code].
+ os << '\n';
+ return os.good();
+ }
+}
+
+/// LatticeReader provides (static) functions for reading both Lattice
+/// and CompactLattice, in text form.
+class LatticeReader {
+ typedef LatticeArc Arc;
+ typedef LatticeWeight Weight;
+ typedef CompactLatticeArc CArc;
+ typedef CompactLatticeWeight CWeight;
+ typedef Arc::Label Label;
+ typedef Arc::StateId StateId;
+ public:
+ // everything is static in this class.
+
+ /** This function reads from the FST text format; it does not know in advance
+ whether it's a Lattice or CompactLattice in the stream so it tries to
+ read both formats until it becomes clear which is the correct one.
+ */
+ static std::pair<Lattice*, CompactLattice*> ReadText(
+ std::istream &is) {
+ typedef std::pair<Lattice*, CompactLattice*> PairT;
+ using std::string;
+ using std::vector;
+ Lattice *fst = new Lattice();
+ CompactLattice *cfst = new CompactLattice();
+ string line;
+ size_t nline = 0;
+ string separator = FLAGS_fst_field_separator + "\r\n";
+ while (std::getline(is, line)) {
+ nline++;
+ vector<string> col;
+ // on Windows we'll write in text and read in binary mode.
+ SplitStringToVector(line, separator.c_str(), true, &col);
+ if (col.size() == 0) break; // Empty line is a signal to stop, in our
+ // archive format.
+ if (col.size() > 5) {
+ KALDI_WARN << "Reading lattice: bad line in FST: " << line;
+ delete fst;
+ delete cfst;
+ return PairT(static_cast<Lattice*>(NULL),
+ static_cast<CompactLattice*>(NULL));
+ }
+ StateId s;
+ if (!ConvertStringToInteger(col[0], &s)) {
+ KALDI_WARN << "FstCompiler: bad line in FST: " << line;
+ delete fst;
+ delete cfst;
+ return PairT(static_cast<Lattice*>(NULL),
+ static_cast<CompactLattice*>(NULL));
+ }
+ if (fst)
+ while (s >= fst->NumStates())
+ fst->AddState();
+ if (cfst)
+ while (s >= cfst->NumStates())
+ cfst->AddState();
+ if (nline == 1) {
+ if (fst) fst->SetStart(s);
+ if (cfst) cfst->SetStart(s);
+ }
+
+ if (fst) { // we still have fst; try to read that arc.
+ bool ok = true;
+ Arc arc;
+ Weight w;
+ StateId d = s;
+ switch (col.size()) {
+ case 1 :
+ fst->SetFinal(s, Weight::One());
+ break;
+ case 2:
+ if (!StrToWeight(col[1], true, &w)) ok = false;
+ else fst->SetFinal(s, w);
+ break;
+ case 3: // 3 columns not ok for Lattice format; it's not an acceptor.
+ ok = false;
+ break;
+ case 4:
+ ok = ConvertStringToInteger(col[1], &arc.nextstate) &&
+ ConvertStringToInteger(col[2], &arc.ilabel) &&
+ ConvertStringToInteger(col[3], &arc.olabel);
+ if (ok) {
+ d = arc.nextstate;
+ arc.weight = Weight::One();
+ fst->AddArc(s, arc);
+ }
+ break;
+ case 5:
+ ok = ConvertStringToInteger(col[1], &arc.nextstate) &&
+ ConvertStringToInteger(col[2], &arc.ilabel) &&
+ ConvertStringToInteger(col[3], &arc.olabel) &&
+ StrToWeight(col[4], false, &arc.weight);
+ if (ok) {
+ d = arc.nextstate;
+ fst->AddArc(s, arc);
+ }
+ break;
+ default:
+ ok = false;
+ }
+ while (d >= fst->NumStates())
+ fst->AddState();
+ if (!ok) {
+ delete fst;
+ fst = NULL;
+ }
+ }
+ if (cfst) {
+ bool ok = true;
+ CArc arc;
+ CWeight w;
+ StateId d = s;
+ switch (col.size()) {
+ case 1 :
+ cfst->SetFinal(s, CWeight::One());
+ break;
+ case 2:
+ if (!StrToCWeight(col[1], true, &w)) ok = false;
+ else cfst->SetFinal(s, w);
+ break;
+ case 3: // compact-lattice is acceptor format: state, next-state, label.
+ ok = ConvertStringToInteger(col[1], &arc.nextstate) &&
+ ConvertStringToInteger(col[2], &arc.ilabel);
+ if (ok) {
+ d = arc.nextstate;
+ arc.olabel = arc.ilabel;
+ arc.weight = CWeight::One();
+ cfst->AddArc(s, arc);
+ }
+ break;
+ case 4:
+ ok = ConvertStringToInteger(col[1], &arc.nextstate) &&
+ ConvertStringToInteger(col[2], &arc.ilabel) &&
+ StrToCWeight(col[3], false, &arc.weight);
+ if (ok) {
+ d = arc.nextstate;
+ arc.olabel = arc.ilabel;
+ cfst->AddArc(s, arc);
+ }
+ break;
+ case 5: default:
+ ok = false;
+ }
+ while (d >= cfst->NumStates())
+ cfst->AddState();
+ if (!ok) {
+ delete cfst;
+ cfst = NULL;
+ }
+ }
+ if (!fst && !cfst) {
+ KALDI_WARN << "Bad line in lattice text format: " << line;
+ // read until we get an empty line, so at least we
+ // have a chance to read the next one (although this might
+ // be a bit futile since the calling code will get unhappy
+ // about failing to read this one.
+ while (std::getline(is, line)) {
+ SplitStringToVector(line, separator.c_str(), true, &col);
+ if (col.empty()) break;
+ }
+ return PairT(static_cast<Lattice*>(NULL),
+ static_cast<CompactLattice*>(NULL));
+ }
+ }
+ return PairT(fst, cfst);
+ }
+
+ static bool StrToWeight(const std::string &s, bool allow_zero, Weight *w) {
+ std::istringstream strm(s);
+ strm >> *w;
+ if (!strm || (!allow_zero && *w == Weight::Zero())) {
+ return false;
+ }
+ return true;
+ }
+
+ static bool StrToCWeight(const std::string &s, bool allow_zero, CWeight *w) {
+ std::istringstream strm(s);
+ strm >> *w;
+ if (!strm || (!allow_zero && *w == CWeight::Zero())) {
+ return false;
+ }
+ return true;
+ }
+};
+
+
+CompactLattice *ReadCompactLatticeText(std::istream &is) {
+ std::pair<Lattice*, CompactLattice*> lat_pair = LatticeReader::ReadText(is);
+ if (lat_pair.second != NULL) {
+ delete lat_pair.first;
+ return lat_pair.second;
+ } else if (lat_pair.first != NULL) {
+ // note: ConvertToCompactLattice frees its input.
+ return ConvertToCompactLattice(lat_pair.first);
+ } else {
+ return NULL;
+ }
+}
+
+
+Lattice *ReadLatticeText(std::istream &is) {
+ std::pair<Lattice*, CompactLattice*> lat_pair = LatticeReader::ReadText(is);
+ if (lat_pair.first != NULL) {
+ delete lat_pair.second;
+ return lat_pair.first;
+ } else if (lat_pair.second != NULL) {
+ // note: ConvertToLattice frees its input.
+ return ConvertToLattice(lat_pair.second);
+ } else {
+ return NULL;
+ }
+}
+
+bool ReadCompactLattice(std::istream &is, bool binary,
+ CompactLattice **clat) {
+ KALDI_ASSERT(*clat == NULL);
+ if (binary) {
+ fst::FstHeader hdr;
+ if (!hdr.Read(is, "<unknown>")) {
+ KALDI_WARN << "Reading compact lattice: error reading FST header.";
+ return false;
+ }
+ if (hdr.FstType() != "vector") {
+ KALDI_WARN << "Reading compact lattice: unsupported FST type: "
+ << hdr.FstType();
+ return false;
+ }
+ fst::FstReadOptions ropts("<unspecified>",
+ &hdr);
+
+ typedef fst::CompactLatticeWeightTpl<fst::LatticeWeightTpl<float>, int32> T1;
+ typedef fst::CompactLatticeWeightTpl<fst::LatticeWeightTpl<double>, int32> T2;
+ typedef fst::LatticeWeightTpl<float> T3;
+ typedef fst::LatticeWeightTpl<double> T4;
+ typedef fst::VectorFst<fst::ArcTpl<T1> > F1;
+ typedef fst::VectorFst<fst::ArcTpl<T2> > F2;
+ typedef fst::VectorFst<fst::ArcTpl<T3> > F3;
+ typedef fst::VectorFst<fst::ArcTpl<T4> > F4;
+
+ CompactLattice *ans = NULL;
+ if (hdr.ArcType() == T1::Type()) {
+ ans = ConvertToCompactLattice(F1::Read(is, ropts));
+ } else if (hdr.ArcType() == T2::Type()) {
+ ans = ConvertToCompactLattice(F2::Read(is, ropts));
+ } else if (hdr.ArcType() == T3::Type()) {
+ ans = ConvertToCompactLattice(F3::Read(is, ropts));
+ } else if (hdr.ArcType() == T4::Type()) {
+ ans = ConvertToCompactLattice(F4::Read(is, ropts));
+ } else {
+ KALDI_WARN << "FST with arc type " << hdr.ArcType()
+ << " cannot be converted to CompactLattice.\n";
+ return false;
+ }
+ if (ans == NULL) {
+ KALDI_WARN << "Error reading compact lattice (after reading header).";
+ return false;
+ }
+ *clat = ans;
+ return true;
+ } else {
+ // The next line would normally consume the \r on Windows, plus any
+ // extra spaces that might have got in there somehow.
+ while (std::isspace(is.peek()) && is.peek() != '\n') is.get();
+ if (is.peek() == '\n') is.get(); // consume the newline.
+ else { // saw spaces but no newline.. this is not expected.
+ KALDI_WARN << "Reading compact lattice: unexpected sequence of spaces "
+ << " at file position " << is.tellg();
+ return false;
+ }
+ *clat = ReadCompactLatticeText(is); // that routine will warn on error.
+ return (*clat != NULL);
+ }
+}
+
+
+bool CompactLatticeHolder::Read(std::istream &is) {
+ Clear(); // in case anything currently stored.
+ int c = is.peek();
+ if (c == -1) {
+ KALDI_WARN << "End of stream detected reading CompactLattice.";
+ return false;
+ } else if (isspace(c)) { // The text form of the lattice begins
+ // with space (normally, '\n'), so this means it's text (the binary form
+ // cannot begin with space because it starts with the FST Type() which is not
+ // space).
+ return ReadCompactLattice(is, false, &t_);
+ } else if (c != 214) { // 214 is first char of FST magic number,
+ // on little-endian machines which is all we support (\326 octal)
+ KALDI_WARN << "Reading compact lattice: does not appear to be an FST "
+ << " [non-space but no magic number detected], file pos is "
+ << is.tellg();
+ return false;
+ } else {
+ return ReadCompactLattice(is, true, &t_);
+ }
+}
+
+bool WriteLattice(std::ostream &os, bool binary, const Lattice &t) {
+ if (binary) {
+ fst::FstWriteOptions opts;
+ // Leave all the options default. Normally these lattices wouldn't have any
+ // osymbols/isymbols so no point directing it not to write them (who knows what
+ // we'd want to do if we had them).
+ return t.Write(os, opts);
+ } else {
+ // Text-mode output. Note: we expect that t.InputSymbols() and
+ // t.OutputSymbols() would always return NULL. The corresponding input
+ // routine would not work if the FST actually had symbols attached.
+ // Write a newline after the key, so the first line of the FST appears
+ // on its own line.
+ os << '\n';
+ bool acceptor = false, write_one = false;
+ fst::FstPrinter<LatticeArc> printer(t, t.InputSymbols(),
+ t.OutputSymbols(),
+ NULL, acceptor, write_one, "\t");
+ printer.Print(&os, "<unknown>");
+ if (os.fail())
+ KALDI_WARN << "Stream failure detected.";
+ // Write another newline as a terminating character. The read routine will
+ // detect this [this is a Kaldi mechanism, not somethig in the original
+ // OpenFst code].
+ os << '\n';
+ return os.good();
+ }
+}
+
+bool ReadLattice(std::istream &is, bool binary,
+ Lattice **lat) {
+ KALDI_ASSERT(*lat == NULL);
+ if (binary) {
+ fst::FstHeader hdr;
+ if (!hdr.Read(is, "<unknown>")) {
+ KALDI_WARN << "Reading lattice: error reading FST header.";
+ return false;
+ }
+ if (hdr.FstType() != "vector") {
+ KALDI_WARN << "Reading lattice: unsupported FST type: "
+ << hdr.FstType();
+ return false;
+ }
+ fst::FstReadOptions ropts("<unspecified>",
+ &hdr);
+
+ typedef fst::CompactLatticeWeightTpl<fst::LatticeWeightTpl<float>, int32> T1;
+ typedef fst::CompactLatticeWeightTpl<fst::LatticeWeightTpl<double>, int32> T2;
+ typedef fst::LatticeWeightTpl<float> T3;
+ typedef fst::LatticeWeightTpl<double> T4;
+ typedef fst::VectorFst<fst::ArcTpl<T1> > F1;
+ typedef fst::VectorFst<fst::ArcTpl<T2> > F2;
+ typedef fst::VectorFst<fst::ArcTpl<T3> > F3;
+ typedef fst::VectorFst<fst::ArcTpl<T4> > F4;
+
+ Lattice *ans = NULL;
+ if (hdr.ArcType() == T1::Type()) {
+ ans = ConvertToLattice(F1::Read(is, ropts));
+ } else if (hdr.ArcType() == T2::Type()) {
+ ans = ConvertToLattice(F2::Read(is, ropts));
+ } else if (hdr.ArcType() == T3::Type()) {
+ ans = ConvertToLattice(F3::Read(is, ropts));
+ } else if (hdr.ArcType() == T4::Type()) {
+ ans = ConvertToLattice(F4::Read(is, ropts));
+ } else {
+ KALDI_WARN << "FST with arc type " << hdr.ArcType()
+ << " cannot be converted to Lattice.\n";
+ return false;
+ }
+ if (ans == NULL) {
+ KALDI_WARN << "Error reading lattice (after reading header).";
+ return false;
+ }
+ *lat = ans;
+ return true;
+ } else {
+ // The next line would normally consume the \r on Windows, plus any
+ // extra spaces that might have got in there somehow.
+ while (std::isspace(is.peek()) && is.peek() != '\n') is.get();
+ if (is.peek() == '\n') is.get(); // consume the newline.
+ else { // saw spaces but no newline.. this is not expected.
+ KALDI_WARN << "Reading compact lattice: unexpected sequence of spaces "
+ << " at file position " << is.tellg();
+ return false;
+ }
+ *lat = ReadLatticeText(is); // that routine will warn on error.
+ return (*lat != NULL);
+ }
+}
+
+
+/* Since we don't write the binary headers for this type of holder,
+ we use a different method to work out whether we're in binary mode.
+ */
+bool LatticeHolder::Read(std::istream &is) {
+ Clear(); // in case anything currently stored.
+ int c = is.peek();
+ if (c == -1) {
+ KALDI_WARN << "End of stream detected reading Lattice.";
+ return false;
+ } else if (isspace(c)) { // The text form of the lattice begins
+ // with space (normally, '\n'), so this means it's text (the binary form
+ // cannot begin with space because it starts with the FST Type() which is not
+ // space).
+ return ReadLattice(is, false, &t_);
+ } else if (c != 214) { // 214 is first char of FST magic number,
+ // on little-endian machines which is all we support (\326 octal)
+ KALDI_WARN << "Reading compact lattice: does not appear to be an FST "
+ << " [non-space but no magic number detected], file pos is "
+ << is.tellg();
+ return false;
+ } else {
+ return ReadLattice(is, true, &t_);
+ }
+}
+
+
+
+} // end namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/kaldi-lattice.h b/runtime/onnxruntime/third_party/kaldi/lat/kaldi-lattice.h
new file mode 100644
index 000000000..91efb3258
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/kaldi-lattice.h
@@ -0,0 +1,156 @@
+// lat/kaldi-lattice.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_LAT_KALDI_LATTICE_H_
+#define KALDI_LAT_KALDI_LATTICE_H_
+
+#include "fstext/fstext-lib.h"
+#include "base/kaldi-common.h"
+//#include "util/common-utils.h"
+
+
+namespace kaldi {
+// will import some things above...
+
+typedef fst::LatticeWeightTpl<BaseFloat> LatticeWeight;
+
+// careful: kaldi::int32 is not always the same C type as fst::int32
+typedef fst::CompactLatticeWeightTpl<LatticeWeight, int32> CompactLatticeWeight;
+
+typedef fst::CompactLatticeWeightCommonDivisorTpl<LatticeWeight, int32>
+ CompactLatticeWeightCommonDivisor;
+
+typedef fst::ArcTpl<LatticeWeight> LatticeArc;
+
+typedef fst::ArcTpl<CompactLatticeWeight> CompactLatticeArc;
+
+typedef fst::VectorFst<LatticeArc> Lattice;
+
+typedef fst::VectorFst<CompactLatticeArc> CompactLattice;
+
+// The following functions for writing and reading lattices in binary or text
+// form are provided here in case you need to include lattices in larger,
+// Kaldi-type objects with their own Read and Write functions. Caution: these
+// functions return false on stream failure rather than throwing an exception as
+// most similar Kaldi functions would do.
+
+bool WriteCompactLattice(std::ostream &os, bool binary,
+ const CompactLattice &clat);
+bool WriteLattice(std::ostream &os, bool binary,
+ const Lattice &lat);
+
+// the following function requires that *clat be
+// NULL when called.
+bool ReadCompactLattice(std::istream &is, bool binary,
+ CompactLattice **clat);
+// the following function requires that *lat be
+// NULL when called.
+bool ReadLattice(std::istream &is, bool binary,
+ Lattice **lat);
+
+
+class CompactLatticeHolder {
+ public:
+ typedef CompactLattice T;
+
+ CompactLatticeHolder() { t_ = NULL; }
+
+ static bool Write(std::ostream &os, bool binary, const T &t) {
+ // Note: we don't include the binary-mode header when writing
+ // this object to disk; this ensures that if we write to single
+ // files, the result can be read by OpenFst.
+ return WriteCompactLattice(os, binary, t);
+ }
+
+ bool Read(std::istream &is);
+
+ static bool IsReadInBinary() { return true; }
+
+ T &Value() {
+ KALDI_ASSERT(t_ != NULL && "Called Value() on empty CompactLatticeHolder");
+ return *t_;
+ }
+
+ void Clear() { delete t_; t_ = NULL; }
+
+ void Swap(CompactLatticeHolder *other) {
+ std::swap(t_, other->t_);
+ }
+
+ bool ExtractRange(const CompactLatticeHolder &other, const std::string &range) {
+ KALDI_ERR << "ExtractRange is not defined for this type of holder.";
+ return false;
+ }
+
+ ~CompactLatticeHolder() { Clear(); }
+ private:
+ T *t_;
+};
+
+class LatticeHolder {
+ public:
+ typedef Lattice T;
+
+ LatticeHolder() { t_ = NULL; }
+
+ static bool Write(std::ostream &os, bool binary, const T &t) {
+ // Note: we don't include the binary-mode header when writing
+ // this object to disk; this ensures that if we write to single
+ // files, the result can be read by OpenFst.
+ return WriteLattice(os, binary, t);
+ }
+
+ bool Read(std::istream &is);
+
+ static bool IsReadInBinary() { return true; }
+
+ T &Value() {
+ KALDI_ASSERT(t_ != NULL && "Called Value() on empty LatticeHolder");
+ return *t_;
+ }
+
+ void Clear() { delete t_; t_ = NULL; }
+
+ void Swap(LatticeHolder *other) {
+ std::swap(t_, other->t_);
+ }
+
+ bool ExtractRange(const LatticeHolder &other, const std::string &range) {
+ KALDI_ERR << "ExtractRange is not defined for this type of holder.";
+ return false;
+ }
+
+ ~LatticeHolder() { Clear(); }
+ private:
+ T *t_;
+};
+
+//typedef TableWriter<LatticeHolder> LatticeWriter;
+//typedef SequentialTableReader<LatticeHolder> SequentialLatticeReader;
+//typedef RandomAccessTableReader<LatticeHolder> RandomAccessLatticeReader;
+//
+//typedef TableWriter<CompactLatticeHolder> CompactLatticeWriter;
+//typedef SequentialTableReader<CompactLatticeHolder> SequentialCompactLatticeReader;
+//typedef RandomAccessTableReader<CompactLatticeHolder> RandomAccessCompactLatticeReader;
+
+
+} // namespace kaldi
+
+#endif // KALDI_LAT_KALDI_LATTICE_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions-transition-model.cc b/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions-transition-model.cc
new file mode 100644
index 000000000..6172610dc
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions-transition-model.cc
@@ -0,0 +1,262 @@
+// lat/lattice-functions-transition-model.cc
+
+// Copyright 2009-2011 Saarland University (Author: Arnab Ghoshal)
+// 2012-2013 Johns Hopkins University (Author: Daniel Povey); Chao Weng;
+// Bagher BabaAli
+// 2013 Cisco Systems (author: Neha Agrawal) [code modified
+// from original code in ../gmmbin/gmm-rescore-lattice.cc]
+// 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "lat/lattice-functions-transition-model.h"
+
+#include "hmm/hmm-utils.h"
+#include "hmm/transition-model.h"
+#include "lat/lattice-functions.h"
+
+namespace kaldi {
+
+BaseFloat LatticeForwardBackwardMmi(
+ const TransitionModel &tmodel,
+ const Lattice &lat,
+ const std::vector<int32> &num_ali,
+ bool drop_frames,
+ bool convert_to_pdf_ids,
+ bool cancel,
+ Posterior *post) {
+ // First compute the MMI posteriors.
+
+ Posterior den_post;
+ BaseFloat ans = LatticeForwardBackward(lat,
+ &den_post,
+ NULL);
+
+ Posterior num_post;
+ AlignmentToPosterior(num_ali, &num_post);
+
+ // Now negate the MMI posteriors and add the numerator
+ // posteriors.
+ ScalePosterior(-1.0, &den_post);
+
+ if (convert_to_pdf_ids) {
+ Posterior num_tmp;
+ ConvertPosteriorToPdfs(tmodel, num_post, &num_tmp);
+ num_tmp.swap(num_post);
+ Posterior den_tmp;
+ ConvertPosteriorToPdfs(tmodel, den_post, &den_tmp);
+ den_tmp.swap(den_post);
+ }
+
+ MergePosteriors(num_post, den_post,
+ cancel, drop_frames, post);
+
+ return ans;
+}
+
+
+bool CompactLatticeToWordProns(
+ const TransitionModel &tmodel,
+ const CompactLattice &clat,
+ std::vector<int32> *words,
+ std::vector<int32> *begin_times,
+ std::vector<int32> *lengths,
+ std::vector<std::vector<int32> > *prons,
+ std::vector<std::vector<int32> > *phone_lengths) {
+ words->clear();
+ begin_times->clear();
+ lengths->clear();
+ prons->clear();
+ phone_lengths->clear();
+ typedef CompactLattice::Arc Arc;
+ typedef Arc::Label Label;
+ typedef CompactLattice::StateId StateId;
+ typedef CompactLattice::Weight Weight;
+ using namespace fst;
+ StateId state = clat.Start();
+ int32 cur_time = 0;
+ if (state == kNoStateId) {
+ KALDI_WARN << "Empty lattice.";
+ return false;
+ }
+ while (1) {
+ Weight final = clat.Final(state);
+ size_t num_arcs = clat.NumArcs(state);
+ if (final != Weight::Zero()) {
+ if (num_arcs != 0) {
+ KALDI_WARN << "Lattice is not linear.";
+ return false;
+ }
+ if (! final.String().empty()) {
+ KALDI_WARN << "Lattice has alignments on final-weight: probably "
+ "was not word-aligned (alignments will be approximate)";
+ }
+ return true;
+ } else {
+ if (num_arcs != 1) {
+ KALDI_WARN << "Lattice is not linear: num-arcs = " << num_arcs;
+ return false;
+ }
+ fst::ArcIterator<CompactLattice> aiter(clat, state);
+ const Arc &arc = aiter.Value();
+ Label word_id = arc.ilabel; // Note: ilabel==olabel, since acceptor.
+ // Also note: word_id may be zero; we output it anyway.
+ int32 length = arc.weight.String().size();
+ words->push_back(word_id);
+ begin_times->push_back(cur_time);
+ lengths->push_back(length);
+ const std::vector<int32> &arc_alignment = arc.weight.String();
+ std::vector<std::vector<int32> > split_alignment;
+ SplitToPhones(tmodel, arc_alignment, &split_alignment);
+ std::vector<int32> phones(split_alignment.size());
+ std::vector<int32> plengths(split_alignment.size());
+ for (size_t i = 0; i < split_alignment.size(); i++) {
+ KALDI_ASSERT(!split_alignment[i].empty());
+ phones[i] = tmodel.TransitionIdToPhone(split_alignment[i][0]);
+ plengths[i] = split_alignment[i].size();
+ }
+ prons->push_back(phones);
+ phone_lengths->push_back(plengths);
+
+ cur_time += length;
+ state = arc.nextstate;
+ }
+ }
+}
+
+// Returns true if this vector of transition-ids could be a valid
+// word. Note: for testing, we assume that the lexicon always
+// has the same input-word and output-word. The other case is complex
+// to test.
+static bool IsPlausibleWord(const WordAlignLatticeLexiconInfo &lexicon_info,
+ const TransitionModel &tmodel,
+ int32 word_id,
+ const std::vector<int32> &transition_ids) {
+
+ std::vector<std::vector<int32> > split_alignment; // Split into phones.
+ if (!SplitToPhones(tmodel, transition_ids, &split_alignment)) {
+ KALDI_WARN << "Could not split word into phones correctly (forced-out?)";
+ }
+ std::vector<int32> phones(split_alignment.size());
+ for (size_t i = 0; i < split_alignment.size(); i++) {
+ KALDI_ASSERT(!split_alignment[i].empty());
+ phones[i] = tmodel.TransitionIdToPhone(split_alignment[i][0]);
+ }
+ std::vector<int32> lexicon_entry;
+ lexicon_entry.push_back(word_id);
+ lexicon_entry.insert(lexicon_entry.end(), phones.begin(), phones.end());
+
+ if (!lexicon_info.IsValidEntry(lexicon_entry)) {
+ std::ostringstream ostr;
+ for (size_t i = 0; i < lexicon_entry.size(); i++)
+ ostr << lexicon_entry[i] << ' ';
+ KALDI_WARN << "Invalid arc in aligned lattice (code error?) lexicon-entry is " << ostr.str();
+ return false;
+ } else {
+ return true;
+ }
+}
+
+/// Testing code; map word symbols in the lattice "lat" using the equivalence-classes
+/// obtained from the lexicon, using the function EquivalenceClassOf in the lexicon_info
+/// object.
+static void MapSymbols(const WordAlignLatticeLexiconInfo &lexicon_info,
+ CompactLattice *lat) {
+ typedef CompactLattice::StateId StateId;
+ for (StateId s = 0; s < lat->NumStates(); s++) {
+ for (fst::MutableArcIterator<CompactLattice> aiter(lat, s);
+ !aiter.Done(); aiter.Next()) {
+ CompactLatticeArc arc (aiter.Value());
+ KALDI_ASSERT(arc.ilabel == arc.olabel);
+ arc.ilabel = lexicon_info.EquivalenceClassOf(arc.ilabel);
+ arc.olabel = arc.ilabel;
+ aiter.SetValue(arc);
+ }
+ }
+}
+
+bool TestWordAlignedLattice(const WordAlignLatticeLexiconInfo &lexicon_info,
+ const TransitionModel &tmodel,
+ CompactLattice clat,
+ CompactLattice aligned_clat,
+ bool allow_duplicate_paths) {
+ int32 max_err = 5, num_err = 0;
+ { // We test whether the forward-backward likelihoods differ; this is intended
+ // to detect when we have duplicate paths in the aligned lattice, for some path
+ // in the input lattice (e.g. due to epsilon-sequencing problems).
+ Posterior post;
+ Lattice lat, aligned_lat;
+ ConvertLattice(clat, &lat);
+ ConvertLattice(aligned_clat, &aligned_lat);
+ TopSort(&lat);
+ TopSort(&aligned_lat);
+ BaseFloat like_before = LatticeForwardBackward(lat, &post),
+ like_after = LatticeForwardBackward(aligned_lat, &post);
+ if (fabs(like_before - like_after) >
+ 1.0e-04 * (fabs(like_before) + fabs(like_after))) {
+ KALDI_WARN << "Forward-backward likelihoods differ in word-aligned lattice "
+ << "testing, " << like_before << " != " << like_after;
+ if (!allow_duplicate_paths)
+ num_err++;
+ }
+ }
+
+ // Do a check on the arcs of the aligned lattice, that each arc corresponds
+ // to an entry in the lexicon.
+ for (CompactLattice::StateId s = 0; s < aligned_clat.NumStates(); s++) {
+ for (fst::ArcIterator<CompactLattice> aiter(aligned_clat, s);
+ !aiter.Done(); aiter.Next()) {
+ const CompactLatticeArc &arc (aiter.Value());
+ KALDI_ASSERT(arc.ilabel == arc.olabel);
+ int32 word_id = arc.ilabel;
+ const std::vector<int32> &tids = arc.weight.String();
+ if (word_id == 0 && tids.empty()) continue; // We allow epsilon arcs.
+
+ if (num_err < max_err)
+ if (!IsPlausibleWord(lexicon_info, tmodel, word_id, tids))
+ num_err++;
+ // Note: IsPlausibleWord will warn if there is an error.
+ }
+ if (!aligned_clat.Final(s).String().empty()) {
+ KALDI_WARN << "Aligned lattice has nonempty string on its final-prob.";
+ return false;
+ }
+ }
+
+ // Next we'll do an equivalence test.
+ // First map symbols into equivalence classes, so that we don't wrongly fail
+ // due to the capability of the framework to map words to other words.
+ // (e.g. mapping <eps> on silence arcs to SIL).
+
+ MapSymbols(lexicon_info, &clat);
+ MapSymbols(lexicon_info, &aligned_clat);
+
+ /// Check equivalence.
+ int32 num_paths = 5, seed = Rand(), max_path_length = -1;
+ BaseFloat delta = 0.2; // some lattices have large costs -> use large delta.
+
+ FLAGS_v = GetVerboseLevel(); // set the OpenFst verbose level to the Kaldi
+ // verbose level.
+ if (!RandEquivalent(clat, aligned_clat, num_paths, delta, seed, max_path_length)) {
+ KALDI_WARN << "Equivalence test failed during lattice alignment.";
+ return false;
+ }
+ FLAGS_v = 0;
+
+ return (num_err == 0);
+}
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions-transition-model.h b/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions-transition-model.h
new file mode 100644
index 000000000..96033c4e3
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions-transition-model.h
@@ -0,0 +1,104 @@
+// lat/lattice-functions-transition-model.h
+
+// Copyright 2009-2012 Saarland University (author: Arnab Ghoshal)
+// 2012-2013 Johns Hopkins University (Author: Daniel Povey);
+// Bagher BabaAli
+// 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_LAT_LATTICE_FUNCTIONS_TRANSITION_MODEL_H_
+#define KALDI_LAT_LATTICE_FUNCTIONS_TRANSITION_MODEL_H_
+
+#include <map>
+#include <vector>
+
+#include "base/kaldi-common.h"
+#include "fstext/fstext-lib.h"
+#include "hmm/transition-model.h"
+#include "hmm/hmm-utils.h"
+#include "hmm/posterior.h"
+#include "itf/decodable-itf.h"
+#include "lat/kaldi-lattice.h"
+#include "lat/word-align-lattice-lexicon.h"
+
+namespace kaldi {
+
+/**
+ This function can be used to compute posteriors for MMI, with a positive contribution
+ for the numerator and a negative one for the denominator. This function is not actually
+ used in our normal MMI training recipes, where it's instead done using various command
+ line programs that each do a part of the job. This function was written for use in
+ neural-net MMI training.
+
+ @param [in] trans The transition model. Used to map the
+ transition-ids to phones or pdfs.
+ @param [in] lat The denominator lattice
+ @param [in] num_ali The numerator alignment
+ @param [in] drop_frames If "drop_frames" is true, it will not compute any
+ posteriors on frames where the num and den have disjoint
+ pdf-ids.
+ @param [in] convert_to_pdf_ids If "convert_to_pdfs_ids" is true, it will
+ convert the output to be at the level of pdf-ids, not
+ transition-ids.
+ @param [in] cancel If "cancel" is true, it will cancel out any positive and
+ negative parts from the same transition-id (or pdf-id,
+ if convert_to_pdf_ids == true).
+ @param [out] arc_post The output MMI posteriors of transition-ids (or
+ pdf-ids if convert_to_pdf_ids == true) at each frame
+ i.e. the difference between the numerator
+ and denominator posteriors.
+
+ It returns the forward-backward likelihood of the lattice. */
+BaseFloat LatticeForwardBackwardMmi(
+ const TransitionModel &trans,
+ const Lattice &lat,
+ const std::vector<int32> &num_ali,
+ bool drop_frames,
+ bool convert_to_pdf_ids,
+ bool cancel,
+ Posterior *arc_post);
+
+/// This function takes a CompactLattice that should only contain a single
+/// linear sequence (e.g. derived from lattice-1best), and that should have been
+/// processed so that the arcs in the CompactLattice align correctly with the
+/// word boundaries (e.g. by lattice-align-words). It outputs 4 vectors of the
+/// same size, which give, for each word in the lattice (in sequence), the word
+/// label, the begin time and length in frames, and the pronunciation (sequence
+/// of phones). This is done even for zero words, corresponding to optional
+/// silences -- if you don't want them, just ignore them in the output.
+/// This function will print a warning and return false, if the lattice
+/// did not have the correct format (e.g. if it is empty or it is not
+/// linear).
+bool CompactLatticeToWordProns(
+ const TransitionModel &tmodel,
+ const CompactLattice &clat,
+ std::vector<int32> *words,
+ std::vector<int32> *begin_times,
+ std::vector<int32> *lengths,
+ std::vector<std::vector<int32> > *prons,
+ std::vector<std::vector<int32> > *phone_lengths);
+
+
+bool TestWordAlignedLattice(const WordAlignLatticeLexiconInfo &lexicon_info,
+ const TransitionModel &tmodel,
+ CompactLattice clat,
+ CompactLattice aligned_clat,
+ bool allow_duplicate_paths);
+
+} // namespace kaldi
+
+#endif // KALDI_LAT_LATTICE_FUNCTIONS_TRANSITION_MODEL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions.cc b/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions.cc
new file mode 100644
index 000000000..90a46a17e
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions.cc
@@ -0,0 +1,1880 @@
+// lat/lattice-functions.cc
+
+// Copyright 2009-2011 Saarland University (Author: Arnab Ghoshal)
+// 2012-2013 Johns Hopkins University (Author: Daniel Povey); Chao Weng;
+// Bagher BabaAli
+// 2013 Cisco Systems (author: Neha Agrawal) [code modified
+// from original code in ../gmmbin/gmm-rescore-lattice.cc]
+// 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-math.h"
+#include "lat/lattice-functions.h"
+
+namespace kaldi {
+using std::map;
+using std::vector;
+
+//void GetPerFrameAcousticCosts(const Lattice &nbest,
+// Vector<BaseFloat> *per_frame_loglikes) {
+// using namespace fst;
+// typedef Lattice::Arc::Weight Weight;
+// vector<BaseFloat> loglikes;
+//
+// int32 cur_state = nbest.Start();
+// int32 prev_frame = -1;
+// BaseFloat eps_acwt = 0.0;
+// while(1) {
+// Weight w = nbest.Final(cur_state);
+// if (w != Weight::Zero()) {
+// KALDI_ASSERT(nbest.NumArcs(cur_state) == 0);
+// if (per_frame_loglikes != NULL) {
+// SubVector<BaseFloat> subvec(&(loglikes[0]), loglikes.size());
+// Vector<BaseFloat> vec(subvec);
+// *per_frame_loglikes = vec;
+// }
+// break;
+// } else {
+// KALDI_ASSERT(nbest.NumArcs(cur_state) == 1);
+// fst::ArcIterator<Lattice> iter(nbest, cur_state);
+// const Lattice::Arc &arc = iter.Value();
+// BaseFloat acwt = arc.weight.Value2();
+// if (arc.ilabel != 0) {
+// if (eps_acwt > 0) {
+// acwt += eps_acwt;
+// eps_acwt = 0.0;
+// }
+// loglikes.push_back(acwt);
+// prev_frame++;
+// } else if (acwt == acwt){
+// if (prev_frame > -1) {
+// loglikes[prev_frame] += acwt;
+// } else {
+// eps_acwt += acwt;
+// }
+// }
+// cur_state = arc.nextstate;
+// }
+// }
+//}
+//
+//int32 LatticeStateTimes(const Lattice &lat, vector<int32> *times) {
+// if (!lat.Properties(fst::kTopSorted, true))
+// KALDI_ERR << "Input lattice must be topologically sorted.";
+// KALDI_ASSERT(lat.Start() == 0);
+// int32 num_states = lat.NumStates();
+// times->clear();
+// times->resize(num_states, -1);
+// (*times)[0] = 0;
+// for (int32 state = 0; state < num_states; state++) {
+// int32 cur_time = (*times)[state];
+// for (fst::ArcIterator<Lattice> aiter(lat, state); !aiter.Done();
+// aiter.Next()) {
+// const LatticeArc &arc = aiter.Value();
+//
+// if (arc.ilabel != 0) { // Non-epsilon input label on arc
+// // next time instance
+// if ((*times)[arc.nextstate] == -1) {
+// (*times)[arc.nextstate] = cur_time + 1;
+// } else {
+// KALDI_ASSERT((*times)[arc.nextstate] == cur_time + 1);
+// }
+// } else { // epsilon input label on arc
+// // Same time instance
+// if ((*times)[arc.nextstate] == -1)
+// (*times)[arc.nextstate] = cur_time;
+// else
+// KALDI_ASSERT((*times)[arc.nextstate] == cur_time);
+// }
+// }
+// }
+// return (*std::max_element(times->begin(), times->end()));
+//}
+//
+//int32 CompactLatticeStateTimes(const CompactLattice &lat,
+// vector<int32> *times) {
+// if (!lat.Properties(fst::kTopSorted, true))
+// KALDI_ERR << "Input lattice must be topologically sorted.";
+// KALDI_ASSERT(lat.Start() == 0);
+// int32 num_states = lat.NumStates();
+// times->clear();
+// times->resize(num_states, -1);
+// (*times)[0] = 0;
+// int32 utt_len = -1;
+// for (int32 state = 0; state < num_states; state++) {
+// int32 cur_time = (*times)[state];
+// for (fst::ArcIterator<CompactLattice> aiter(lat, state); !aiter.Done();
+// aiter.Next()) {
+// const CompactLatticeArc &arc = aiter.Value();
+// int32 arc_len = static_cast<int32>(arc.weight.String().size());
+// if ((*times)[arc.nextstate] == -1)
+// (*times)[arc.nextstate] = cur_time + arc_len;
+// else
+// KALDI_ASSERT((*times)[arc.nextstate] == cur_time + arc_len);
+// }
+// if (lat.Final(state) != CompactLatticeWeight::Zero()) {
+// int32 this_utt_len = (*times)[state] + lat.Final(state).String().size();
+// if (utt_len == -1) utt_len = this_utt_len;
+// else {
+// if (this_utt_len != utt_len) {
+// KALDI_WARN << "Utterance does not "
+// "seem to have a consistent length.";
+// utt_len = std::max(utt_len, this_utt_len);
+// }
+// }
+// }
+// }
+// if (utt_len == -1) {
+// KALDI_WARN << "Utterance does not have a final-state.";
+// return 0;
+// }
+// return utt_len;
+//}
+//
+//bool ComputeCompactLatticeAlphas(const CompactLattice &clat,
+// vector<double> *alpha) {
+// using namespace fst;
+//
+// // typedef the arc, weight types
+// typedef CompactLattice::Arc Arc;
+// typedef Arc::Weight Weight;
+// typedef Arc::StateId StateId;
+//
+// //Make sure the lattice is topologically sorted.
+// if (clat.Properties(fst::kTopSorted, true) == 0) {
+// KALDI_WARN << "Input lattice must be topologically sorted.";
+// return false;
+// }
+// if (clat.Start() != 0) {
+// KALDI_WARN << "Input lattice must start from state 0.";
+// return false;
+// }
+//
+// int32 num_states = clat.NumStates();
+// (*alpha).resize(0);
+// (*alpha).resize(num_states, kLogZeroDouble);
+//
+// // Now propagate alphas forward. Note that we don't acount the weight of the
+// // final state to alpha[final_state] -- we acount it to beta[final_state];
+// (*alpha)[0] = 0.0;
+// for (StateId s = 0; s < num_states; s++) {
+// double this_alpha = (*alpha)[s];
+// for (ArcIterator<CompactLattice> aiter(clat, s);
+// !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double arc_like = -(arc.weight.Weight().Value1() +
+// arc.weight.Weight().Value2());
+// (*alpha)[arc.nextstate] = LogAdd((*alpha)[arc.nextstate],
+// this_alpha + arc_like);
+// }
+// }
+//
+// return true;
+//}
+//
+//bool ComputeCompactLatticeBetas(const CompactLattice &clat,
+// vector<double> *beta) {
+// using namespace fst;
+//
+// // typedef the arc, weight types
+// typedef CompactLattice::Arc Arc;
+// typedef Arc::Weight Weight;
+// typedef Arc::StateId StateId;
+//
+// // Make sure the lattice is topologically sorted.
+// if (clat.Properties(fst::kTopSorted, true) == 0) {
+// KALDI_WARN << "Input lattice must be topologically sorted.";
+// return false;
+// }
+// if (clat.Start() != 0) {
+// KALDI_WARN << "Input lattice must start from state 0.";
+// return false;
+// }
+//
+// int32 num_states = clat.NumStates();
+// (*beta).resize(0);
+// (*beta).resize(num_states, kLogZeroDouble);
+//
+// // Now propagate betas backward. Note that beta[final_state] contains the
+// // weight of the final state in the lattice -- compare that with alpha.
+// for (StateId s = num_states-1; s >= 0; s--) {
+// Weight f = clat.Final(s);
+// double this_beta = -(f.Weight().Value1()+f.Weight().Value2());
+// for (ArcIterator<CompactLattice> aiter(clat, s);
+// !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double arc_like = -(arc.weight.Weight().Value1() +
+// arc.weight.Weight().Value2());
+// double arc_beta = (*beta)[arc.nextstate] + arc_like;
+// this_beta = LogAdd(this_beta, arc_beta);
+// }
+// (*beta)[s] = this_beta;
+// }
+//
+// return true;
+//}
+
+template<class LatType> // could be Lattice or CompactLattice
+bool PruneLattice(BaseFloat beam, LatType *lat) {
+ typedef typename LatType::Arc Arc;
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId StateId;
+
+ KALDI_ASSERT(beam > 0.0);
+ if (!lat->Properties(fst::kTopSorted, true)) {
+ if (fst::TopSort(lat) == false) {
+ KALDI_WARN << "Cycles detected in lattice";
+ return false;
+ }
+ }
+ // We assume states before "start" are not reachable, since
+ // the lattice is topologically sorted.
+ int32 start = lat->Start();
+ int32 num_states = lat->NumStates();
+ if (num_states == 0) return false;
+ std::vector<double> forward_cost(num_states,
+ std::numeric_limits<double>::infinity()); // viterbi forward.
+ forward_cost[start] = 0.0; // lattice can't have cycles so couldn't be
+ // less than this.
+ double best_final_cost = std::numeric_limits<double>::infinity();
+ // Update the forward probs.
+ // Thanks to Jing Zheng for finding a bug here.
+ for (int32 state = 0; state < num_states; state++) {
+ double this_forward_cost = forward_cost[state];
+ for (fst::ArcIterator<LatType> aiter(*lat, state);
+ !aiter.Done();
+ aiter.Next()) {
+ const Arc &arc(aiter.Value());
+ StateId nextstate = arc.nextstate;
+ KALDI_ASSERT(nextstate > state && nextstate < num_states);
+ double next_forward_cost = this_forward_cost +
+ ConvertToCost(arc.weight);
+ if (forward_cost[nextstate] > next_forward_cost)
+ forward_cost[nextstate] = next_forward_cost;
+ }
+ Weight final_weight = lat->Final(state);
+ double this_final_cost = this_forward_cost +
+ ConvertToCost(final_weight);
+ if (this_final_cost < best_final_cost)
+ best_final_cost = this_final_cost;
+ }
+ int32 bad_state = lat->AddState(); // this state is not final.
+ double cutoff = best_final_cost + beam;
+
+ // Go backwards updating the backward probs (which share memory with the
+ // forward probs), and pruning arcs and deleting final-probs. We prune arcs
+ // by making them point to the non-final state "bad_state". We'll then use
+ // Trim() to remove unnecessary arcs and states. [this is just easier than
+ // doing it ourselves.]
+ std::vector<double> &backward_cost(forward_cost);
+ for (int32 state = num_states - 1; state >= 0; state--) {
+ double this_forward_cost = forward_cost[state];
+ double this_backward_cost = ConvertToCost(lat->Final(state));
+ if (this_backward_cost + this_forward_cost > cutoff
+ && this_backward_cost != std::numeric_limits<double>::infinity())
+ lat->SetFinal(state, Weight::Zero());
+ for (fst::MutableArcIterator<LatType> aiter(lat, state);
+ !aiter.Done();
+ aiter.Next()) {
+ Arc arc(aiter.Value());
+ StateId nextstate = arc.nextstate;
+ KALDI_ASSERT(nextstate > state && nextstate < num_states);
+ double arc_cost = ConvertToCost(arc.weight),
+ arc_backward_cost = arc_cost + backward_cost[nextstate],
+ this_fb_cost = this_forward_cost + arc_backward_cost;
+ if (arc_backward_cost < this_backward_cost)
+ this_backward_cost = arc_backward_cost;
+ if (this_fb_cost > cutoff) { // Prune the arc.
+ arc.nextstate = bad_state;
+ aiter.SetValue(arc);
+ }
+ }
+ backward_cost[state] = this_backward_cost;
+ }
+ fst::Connect(lat);
+ return (lat->NumStates() > 0);
+}
+
+// instantiate the template for lattice and CompactLattice.
+template bool PruneLattice(BaseFloat beam, Lattice *lat);
+template bool PruneLattice(BaseFloat beam, CompactLattice *lat);
+
+
+//BaseFloat LatticeForwardBackward(const Lattice &lat, Posterior *post,
+// double *acoustic_like_sum) {
+// // Note, Posterior is defined as follows: Indexed [frame], then a list
+// // of (transition-id, posterior-probability) pairs.
+// // typedef std::vector<std::vector<std::pair<int32, BaseFloat> > > Posterior;
+// using namespace fst;
+// typedef Lattice::Arc Arc;
+// typedef Arc::Weight Weight;
+// typedef Arc::StateId StateId;
+//
+// if (acoustic_like_sum) *acoustic_like_sum = 0.0;
+//
+// // Make sure the lattice is topologically sorted.
+// if (lat.Properties(fst::kTopSorted, true) == 0)
+// KALDI_ERR << "Input lattice must be topologically sorted.";
+// KALDI_ASSERT(lat.Start() == 0);
+//
+// int32 num_states = lat.NumStates();
+// vector<int32> state_times;
+// int32 max_time = LatticeStateTimes(lat, &state_times);
+// std::vector<double> alpha(num_states, kLogZeroDouble);
+// std::vector<double> &beta(alpha); // we re-use the same memory for
+// // this, but it's semantically distinct so we name it differently.
+// double tot_forward_prob = kLogZeroDouble;
+//
+// post->clear();
+// post->resize(max_time);
+//
+// alpha[0] = 0.0;
+// // Propagate alphas forward.
+// for (StateId s = 0; s < num_states; s++) {
+// double this_alpha = alpha[s];
+// for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double arc_like = -ConvertToCost(arc.weight);
+// alpha[arc.nextstate] = LogAdd(alpha[arc.nextstate], this_alpha + arc_like);
+// }
+// Weight f = lat.Final(s);
+// if (f != Weight::Zero()) {
+// double final_like = this_alpha - (f.Value1() + f.Value2());
+// tot_forward_prob = LogAdd(tot_forward_prob, final_like);
+// KALDI_ASSERT(state_times[s] == max_time &&
+// "Lattice is inconsistent (final-prob not at max_time)");
+// }
+// }
+// for (StateId s = num_states-1; s >= 0; s--) {
+// Weight f = lat.Final(s);
+// double this_beta = -(f.Value1() + f.Value2());
+// for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double arc_like = -ConvertToCost(arc.weight),
+// arc_beta = beta[arc.nextstate] + arc_like;
+// this_beta = LogAdd(this_beta, arc_beta);
+// int32 transition_id = arc.ilabel;
+//
+// // The following "if" is an optimization to avoid un-needed exp().
+// if (transition_id != 0 || acoustic_like_sum != NULL) {
+// double posterior = Exp(alpha[s] + arc_beta - tot_forward_prob);
+//
+// if (transition_id != 0) // Arc has a transition-id on it [not epsilon]
+// (*post)[state_times[s]].push_back(std::make_pair(transition_id,
+// static_cast<kaldi::BaseFloat>(posterior)));
+// if (acoustic_like_sum != NULL)
+// *acoustic_like_sum -= posterior * arc.weight.Value2();
+// }
+// }
+// if (acoustic_like_sum != NULL && f != Weight::Zero()) {
+// double final_logprob = - ConvertToCost(f),
+// posterior = Exp(alpha[s] + final_logprob - tot_forward_prob);
+// *acoustic_like_sum -= posterior * f.Value2();
+// }
+// beta[s] = this_beta;
+// }
+// double tot_backward_prob = beta[0];
+// if (!ApproxEqual(tot_forward_prob, tot_backward_prob, 1e-8)) {
+// KALDI_WARN << "Total forward probability over lattice = " << tot_forward_prob
+// << ", while total backward probability = " << tot_backward_prob;
+// }
+// // Now combine any posteriors with the same transition-id.
+// for (int32 t = 0; t < max_time; t++)
+// MergePairVectorSumming(&((*post)[t]));
+// return tot_backward_prob;
+//}
+//
+//
+//void LatticeActivePhones(const Lattice &lat, const TransitionInformation &trans,
+// const vector<int32> &silence_phones,
+// vector< std::set<int32> > *active_phones) {
+// KALDI_ASSERT(IsSortedAndUniq(silence_phones));
+// vector<int32> state_times;
+// int32 num_states = lat.NumStates();
+// int32 max_time = LatticeStateTimes(lat, &state_times);
+// active_phones->clear();
+// active_phones->resize(max_time);
+// for (int32 state = 0; state < num_states; state++) {
+// int32 cur_time = state_times[state];
+// for (fst::ArcIterator<Lattice> aiter(lat, state); !aiter.Done();
+// aiter.Next()) {
+// const LatticeArc &arc = aiter.Value();
+// if (arc.ilabel != 0) { // Non-epsilon arc
+// int32 phone = trans.TransitionIdToPhone(arc.ilabel);
+// if (!std::binary_search(silence_phones.begin(),
+// silence_phones.end(), phone))
+// (*active_phones)[cur_time].insert(phone);
+// }
+// } // end looping over arcs
+// } // end looping over states
+//}
+//
+//void ConvertLatticeToPhones(const TransitionInformation &trans,
+// Lattice *lat) {
+// typedef LatticeArc Arc;
+// int32 num_states = lat->NumStates();
+// for (int32 state = 0; state < num_states; state++) {
+// for (fst::MutableArcIterator<Lattice> aiter(lat, state); !aiter.Done();
+// aiter.Next()) {
+// Arc arc(aiter.Value());
+// arc.olabel = 0; // remove any word.
+// if ((arc.ilabel != 0) // has a transition-id on input..
+// && (trans.TransitionIdIsStartOfPhone(arc.ilabel))
+// && (!trans.IsSelfLoop(arc.ilabel))) {
+// // && trans.IsFinal(arc.ilabel)) // there is one of these per phone...
+// arc.olabel = trans.TransitionIdToPhone(arc.ilabel);
+// }
+// aiter.SetValue(arc);
+// } // end looping over arcs
+// } // end looping over states
+//}
+//
+//
+//static inline double LogAddOrMax(bool viterbi, double a, double b) {
+// if (viterbi)
+// return std::max(a, b);
+// else
+// return LogAdd(a, b);
+//}
+//
+//template<typename LatticeType>
+//double ComputeLatticeAlphasAndBetas(const LatticeType &lat,
+// bool viterbi,
+// vector<double> *alpha,
+// vector<double> *beta) {
+// typedef typename LatticeType::Arc Arc;
+// typedef typename Arc::Weight Weight;
+// typedef typename Arc::StateId StateId;
+//
+// StateId num_states = lat.NumStates();
+// KALDI_ASSERT(lat.Properties(fst::kTopSorted, true) == fst::kTopSorted);
+// KALDI_ASSERT(lat.Start() == 0);
+// alpha->clear();
+// beta->clear();
+// alpha->resize(num_states, kLogZeroDouble);
+// beta->resize(num_states, kLogZeroDouble);
+//
+// double tot_forward_prob = kLogZeroDouble;
+// (*alpha)[0] = 0.0;
+// // Propagate alphas forward.
+// for (StateId s = 0; s < num_states; s++) {
+// double this_alpha = (*alpha)[s];
+// for (fst::ArcIterator<LatticeType> aiter(lat, s); !aiter.Done();
+// aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double arc_like = -ConvertToCost(arc.weight);
+// (*alpha)[arc.nextstate] = LogAddOrMax(viterbi, (*alpha)[arc.nextstate],
+// this_alpha + arc_like);
+// }
+// Weight f = lat.Final(s);
+// if (f != Weight::Zero()) {
+// double final_like = this_alpha - ConvertToCost(f);
+// tot_forward_prob = LogAddOrMax(viterbi, tot_forward_prob, final_like);
+// }
+// }
+// for (StateId s = num_states-1; s >= 0; s--) { // it's guaranteed signed.
+// double this_beta = -ConvertToCost(lat.Final(s));
+// for (fst::ArcIterator<LatticeType> aiter(lat, s); !aiter.Done();
+// aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double arc_like = -ConvertToCost(arc.weight),
+// arc_beta = (*beta)[arc.nextstate] + arc_like;
+// this_beta = LogAddOrMax(viterbi, this_beta, arc_beta);
+// }
+// (*beta)[s] = this_beta;
+// }
+// double tot_backward_prob = (*beta)[lat.Start()];
+// if (!ApproxEqual(tot_forward_prob, tot_backward_prob, 1e-8)) {
+// KALDI_WARN << "Total forward probability over lattice = " << tot_forward_prob
+// << ", while total backward probability = " << tot_backward_prob;
+// }
+// // Split the difference when returning... they should be the same.
+// return 0.5 * (tot_backward_prob + tot_forward_prob);
+//}
+//
+//// instantiate the template for Lattice and CompactLattice
+//template
+//double ComputeLatticeAlphasAndBetas(const Lattice &lat,
+// bool viterbi,
+// vector<double> *alpha,
+// vector<double> *beta);
+//
+//template
+//double ComputeLatticeAlphasAndBetas(const CompactLattice &lat,
+// bool viterbi,
+// vector<double> *alpha,
+// vector<double> *beta);
+//
+//
+//
+///// This is used in CompactLatticeLimitDepth.
+//struct LatticeArcRecord {
+// BaseFloat logprob; // logprob <= 0 is the best Viterbi logprob of this arc,
+// // minus the overall best-cost of the lattice.
+// CompactLatticeArc::StateId state; // state in the lattice.
+// size_t arc; // arc index within the state.
+// bool operator < (const LatticeArcRecord &other) const {
+// return logprob < other.logprob;
+// }
+//};
+//
+//void CompactLatticeLimitDepth(int32 max_depth_per_frame,
+// CompactLattice *clat) {
+// typedef CompactLatticeArc Arc;
+// typedef Arc::Weight Weight;
+// typedef Arc::StateId StateId;
+//
+// if (clat->Start() == fst::kNoStateId) {
+// KALDI_WARN << "Limiting depth of empty lattice.";
+// return;
+// }
+// if (clat->Properties(fst::kTopSorted, true) == 0) {
+// if (!TopSort(clat))
+// KALDI_ERR << "Topological sorting of lattice failed.";
+// }
+//
+// vector<int32> state_times;
+// int32 T = CompactLatticeStateTimes(*clat, &state_times);
+//
+// // The alpha and beta quantities here are "viterbi" alphas and beta.
+// std::vector<double> alpha;
+// std::vector<double> beta;
+// bool viterbi = true;
+// double best_prob = ComputeLatticeAlphasAndBetas(*clat, viterbi,
+// &alpha, &beta);
+//
+// std::vector<std::vector<LatticeArcRecord> > arc_records(T);
+//
+// StateId num_states = clat->NumStates();
+// for (StateId s = 0; s < num_states; s++) {
+// for (fst::ArcIterator<CompactLattice> aiter(*clat, s); !aiter.Done();
+// aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// LatticeArcRecord arc_record;
+// arc_record.state = s;
+// arc_record.arc = aiter.Position();
+// arc_record.logprob =
+// (alpha[s] + beta[arc.nextstate] - ConvertToCost(arc.weight))
+// - best_prob;
+// KALDI_ASSERT(arc_record.logprob < 0.1); // Should be zero or negative.
+// int32 num_frames = arc.weight.String().size(), start_t = state_times[s];
+// for (int32 t = start_t; t < start_t + num_frames; t++) {
+// KALDI_ASSERT(t < T);
+// arc_records[t].push_back(arc_record);
+// }
+// }
+// }
+// StateId dead_state = clat->AddState(); // A non-coaccesible state which we use
+// // to remove arcs (make them end
+// // there).
+// size_t max_depth = max_depth_per_frame;
+// for (int32 t = 0; t < T; t++) {
+// size_t size = arc_records[t].size();
+// if (size > max_depth) {
+// // we sort from worst to best, so we keep the later-numbered ones,
+// // and delete the lower-numbered ones.
+// size_t cutoff = size - max_depth;
+// std::nth_element(arc_records[t].begin(),
+// arc_records[t].begin() + cutoff,
+// arc_records[t].end());
+// for (size_t index = 0; index < cutoff; index++) {
+// LatticeArcRecord record(arc_records[t][index]);
+// fst::MutableArcIterator<CompactLattice> aiter(clat, record.state);
+// aiter.Seek(record.arc);
+// Arc arc = aiter.Value();
+// if (arc.nextstate != dead_state) { // not already killed.
+// arc.nextstate = dead_state;
+// aiter.SetValue(arc);
+// }
+// }
+// }
+// }
+// Connect(clat);
+// TopSortCompactLatticeIfNeeded(clat);
+//}
+//
+//
+//void TopSortCompactLatticeIfNeeded(CompactLattice *clat) {
+// if (clat->Properties(fst::kTopSorted, true) == 0) {
+// if (fst::TopSort(clat) == false) {
+// KALDI_ERR << "Topological sorting failed";
+// }
+// }
+//}
+//
+//void TopSortLatticeIfNeeded(Lattice *lat) {
+// if (lat->Properties(fst::kTopSorted, true) == 0) {
+// if (fst::TopSort(lat) == false) {
+// KALDI_ERR << "Topological sorting failed";
+// }
+// }
+//}
+//
+//
+///// Returns the depth of the lattice, defined as the average number of
+///// arcs crossing any given frame. Returns 1 for empty lattices.
+///// Requires that input is topologically sorted.
+//BaseFloat CompactLatticeDepth(const CompactLattice &clat,
+// int32 *num_frames) {
+// typedef CompactLattice::Arc::StateId StateId;
+// if (clat.Properties(fst::kTopSorted, true) == 0) {
+// KALDI_ERR << "Lattice input to CompactLatticeDepth was not topologically "
+// << "sorted.";
+// }
+// if (clat.Start() == fst::kNoStateId) {
+// *num_frames = 0;
+// return 1.0;
+// }
+// size_t num_arc_frames = 0;
+// int32 t;
+// {
+// vector<int32> state_times;
+// t = CompactLatticeStateTimes(clat, &state_times);
+// }
+// if (num_frames != NULL)
+// *num_frames = t;
+// for (StateId s = 0; s < clat.NumStates(); s++) {
+// for (fst::ArcIterator<CompactLattice> aiter(clat, s); !aiter.Done();
+// aiter.Next()) {
+// const CompactLatticeArc &arc = aiter.Value();
+// num_arc_frames += arc.weight.String().size();
+// }
+// num_arc_frames += clat.Final(s).String().size();
+// }
+// return num_arc_frames / static_cast<BaseFloat>(t);
+//}
+//
+//
+//void CompactLatticeDepthPerFrame(const CompactLattice &clat,
+// std::vector<int32> *depth_per_frame) {
+// typedef CompactLattice::Arc::StateId StateId;
+// if (clat.Properties(fst::kTopSorted, true) == 0) {
+// KALDI_ERR << "Lattice input to CompactLatticeDepthPerFrame was not "
+// << "topologically sorted.";
+// }
+// if (clat.Start() == fst::kNoStateId) {
+// depth_per_frame->clear();
+// return;
+// }
+// vector<int32> state_times;
+// int32 T = CompactLatticeStateTimes(clat, &state_times);
+//
+// depth_per_frame->clear();
+// if (T <= 0) {
+// return;
+// } else {
+// depth_per_frame->resize(T, 0);
+// for (StateId s = 0; s < clat.NumStates(); s++) {
+// int32 start_time = state_times[s];
+// for (fst::ArcIterator<CompactLattice> aiter(clat, s); !aiter.Done();
+// aiter.Next()) {
+// const CompactLatticeArc &arc = aiter.Value();
+// int32 len = arc.weight.String().size();
+// for (int32 t = start_time; t < start_time + len; t++) {
+// KALDI_ASSERT(t < T);
+// (*depth_per_frame)[t]++;
+// }
+// }
+// int32 final_len = clat.Final(s).String().size();
+// for (int32 t = start_time; t < start_time + final_len; t++) {
+// KALDI_ASSERT(t < T);
+// (*depth_per_frame)[t]++;
+// }
+// }
+// }
+//}
+//
+//
+//
+//void ConvertCompactLatticeToPhones(const TransitionInformation &trans,
+// CompactLattice *clat) {
+// typedef CompactLatticeArc Arc;
+// typedef Arc::Weight Weight;
+// int32 num_states = clat->NumStates();
+// for (int32 state = 0; state < num_states; state++) {
+// for (fst::MutableArcIterator<CompactLattice> aiter(clat, state);
+// !aiter.Done();
+// aiter.Next()) {
+// Arc arc(aiter.Value());
+// std::vector<int32> phone_seq;
+// const std::vector<int32> &tid_seq = arc.weight.String();
+// for (std::vector<int32>::const_iterator iter = tid_seq.begin();
+// iter != tid_seq.end(); ++iter) {
+// if (trans.IsFinal(*iter))// note: there is one of these per phone...
+// phone_seq.push_back(trans.TransitionIdToPhone(*iter));
+// }
+// arc.weight.SetString(phone_seq);
+// aiter.SetValue(arc);
+// } // end looping over arcs
+// Weight f = clat->Final(state);
+// if (f != Weight::Zero()) {
+// std::vector<int32> phone_seq;
+// const std::vector<int32> &tid_seq = f.String();
+// for (std::vector<int32>::const_iterator iter = tid_seq.begin();
+// iter != tid_seq.end(); ++iter) {
+// if (trans.IsFinal(*iter))// note: there is one of these per phone...
+// phone_seq.push_back(trans.TransitionIdToPhone(*iter));
+// }
+// f.SetString(phone_seq);
+// clat->SetFinal(state, f);
+// }
+// } // end looping over states
+//}
+//
+//bool LatticeBoost(const TransitionInformation &trans,
+// const std::vector<int32> &alignment,
+// const std::vector<int32> &silence_phones,
+// BaseFloat b,
+// BaseFloat max_silence_error,
+// Lattice *lat) {
+// TopSortLatticeIfNeeded(lat);
+//
+// // get all stored properties (test==false means don't test if not known).
+// uint64 props = lat->Properties(fst::kFstProperties,
+// false);
+//
+// KALDI_ASSERT(IsSortedAndUniq(silence_phones));
+// KALDI_ASSERT(max_silence_error >= 0.0 && max_silence_error <= 1.0);
+// vector<int32> state_times;
+// int32 num_states = lat->NumStates();
+// int32 num_frames = LatticeStateTimes(*lat, &state_times);
+// KALDI_ASSERT(num_frames == static_cast<int32>(alignment.size()));
+// for (int32 state = 0; state < num_states; state++) {
+// int32 cur_time = state_times[state];
+// for (fst::MutableArcIterator<Lattice> aiter(lat, state); !aiter.Done();
+// aiter.Next()) {
+// LatticeArc arc = aiter.Value();
+// if (arc.ilabel != 0) { // Non-epsilon arc
+// if (arc.ilabel < 0 || arc.ilabel > trans.NumTransitionIds()) {
+// KALDI_WARN << "Lattice has out-of-range transition-ids: "
+// << "lattice/model mismatch?";
+// return false;
+// }
+// int32 phone = trans.TransitionIdToPhone(arc.ilabel),
+// ref_phone = trans.TransitionIdToPhone(alignment[cur_time]);
+// BaseFloat frame_error;
+// if (phone == ref_phone) {
+// frame_error = 0.0;
+// } else { // an error...
+// if (std::binary_search(silence_phones.begin(), silence_phones.end(), phone))
+// frame_error = max_silence_error;
+// else
+// frame_error = 1.0;
+// }
+// BaseFloat delta_cost = -b * frame_error; // negative cost if
+// // frame is wrong, to boost likelihood of arcs with errors on them.
+// // Add this cost to the graph part.
+// arc.weight.SetValue1(arc.weight.Value1() + delta_cost);
+// aiter.SetValue(arc);
+// }
+// }
+// }
+// // All we changed is the weights, so any properties that were
+// // known before, are still known, except for whether or not the
+// // lattice was weighted.
+// lat->SetProperties(props,
+// ~(fst::kWeighted|fst::kUnweighted));
+//
+// return true;
+//}
+//
+//
+//
+//BaseFloat LatticeForwardBackwardMpeVariants(
+// const TransitionInformation &trans,
+// const std::vector<int32> &silence_phones,
+// const Lattice &lat,
+// const std::vector<int32> &num_ali,
+// std::string criterion,
+// bool one_silence_class,
+// Posterior *post) {
+// using namespace fst;
+// typedef Lattice::Arc Arc;
+// typedef Arc::Weight Weight;
+// typedef Arc::StateId StateId;
+//
+// KALDI_ASSERT(criterion == "mpfe" || criterion == "smbr");
+// bool is_mpfe = (criterion == "mpfe");
+//
+// if (lat.Properties(fst::kTopSorted, true) == 0)
+// KALDI_ERR << "Input lattice must be topologically sorted.";
+// KALDI_ASSERT(lat.Start() == 0);
+//
+// int32 num_states = lat.NumStates();
+// vector<int32> state_times;
+// int32 max_time = LatticeStateTimes(lat, &state_times);
+// KALDI_ASSERT(max_time == static_cast<int32>(num_ali.size()));
+// std::vector<double> alpha(num_states, kLogZeroDouble),
+// alpha_smbr(num_states, 0), //forward variable for sMBR
+// beta(num_states, kLogZeroDouble),
+// beta_smbr(num_states, 0); //backward variable for sMBR
+//
+// double tot_forward_prob = kLogZeroDouble;
+// double tot_forward_score = 0;
+//
+// post->clear();
+// post->resize(max_time);
+//
+// alpha[0] = 0.0;
+// // First Pass Forward,
+// for (StateId s = 0; s < num_states; s++) {
+// double this_alpha = alpha[s];
+// for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double arc_like = -ConvertToCost(arc.weight);
+// alpha[arc.nextstate] = LogAdd(alpha[arc.nextstate], this_alpha + arc_like);
+// }
+// Weight f = lat.Final(s);
+// if (f != Weight::Zero()) {
+// double final_like = this_alpha - (f.Value1() + f.Value2());
+// tot_forward_prob = LogAdd(tot_forward_prob, final_like);
+// KALDI_ASSERT(state_times[s] == max_time &&
+// "Lattice is inconsistent (final-prob not at max_time)");
+// }
+// }
+// // First Pass Backward,
+// for (StateId s = num_states-1; s >= 0; s--) {
+// Weight f = lat.Final(s);
+// double this_beta = -(f.Value1() + f.Value2());
+// for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double arc_like = -ConvertToCost(arc.weight),
+// arc_beta = beta[arc.nextstate] + arc_like;
+// this_beta = LogAdd(this_beta, arc_beta);
+// }
+// beta[s] = this_beta;
+// }
+// // First Pass Forward-Backward Check
+// double tot_backward_prob = beta[0];
+// // may loose the condition somehow here 1e-6 (was 1e-8)
+// if (!ApproxEqual(tot_forward_prob, tot_backward_prob, 1e-6)) {
+// KALDI_ERR << "Total forward probability over lattice = " << tot_forward_prob
+// << ", while total backward probability = " << tot_backward_prob;
+// }
+//
+// alpha_smbr[0] = 0.0;
+// // Second Pass Forward, calculate forward for MPFE/SMBR
+// for (StateId s = 0; s < num_states; s++) {
+// double this_alpha = alpha[s];
+// for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double arc_like = -ConvertToCost(arc.weight);
+// double frame_acc = 0.0;
+// if (arc.ilabel != 0) {
+// int32 cur_time = state_times[s];
+// int32 phone = trans.TransitionIdToPhone(arc.ilabel),
+// ref_phone = trans.TransitionIdToPhone(num_ali[cur_time]);
+// bool phone_is_sil = std::binary_search(silence_phones.begin(),
+// silence_phones.end(),
+// phone),
+// ref_phone_is_sil = std::binary_search(silence_phones.begin(),
+// silence_phones.end(),
+// ref_phone),
+// both_sil = phone_is_sil && ref_phone_is_sil;
+// if (!is_mpfe) { // smbr.
+// int32 pdf = trans.TransitionIdToPdf(arc.ilabel),
+// ref_pdf = trans.TransitionIdToPdf(num_ali[cur_time]);
+// if (!one_silence_class) // old behavior
+// frame_acc = (pdf == ref_pdf && !phone_is_sil) ? 1.0 : 0.0;
+// else
+// frame_acc = (pdf == ref_pdf || both_sil) ? 1.0 : 0.0;
+// } else {
+// if (!one_silence_class) // old behavior
+// frame_acc = (phone == ref_phone && !phone_is_sil) ? 1.0 : 0.0;
+// else
+// frame_acc = (phone == ref_phone || both_sil) ? 1.0 : 0.0;
+// }
+// }
+// double arc_scale = Exp(alpha[s] + arc_like - alpha[arc.nextstate]);
+// alpha_smbr[arc.nextstate] += arc_scale * (alpha_smbr[s] + frame_acc);
+// }
+// Weight f = lat.Final(s);
+// if (f != Weight::Zero()) {
+// double final_like = this_alpha - (f.Value1() + f.Value2());
+// double arc_scale = Exp(final_like - tot_forward_prob);
+// tot_forward_score += arc_scale * alpha_smbr[s];
+// KALDI_ASSERT(state_times[s] == max_time &&
+// "Lattice is inconsistent (final-prob not at max_time)");
+// }
+// }
+// // Second Pass Backward, collect Mpe style posteriors
+// for (StateId s = num_states-1; s >= 0; s--) {
+// for (ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double arc_like = -ConvertToCost(arc.weight),
+// arc_beta = beta[arc.nextstate] + arc_like;
+// double frame_acc = 0.0;
+// int32 transition_id = arc.ilabel;
+// if (arc.ilabel != 0) {
+// int32 cur_time = state_times[s];
+// int32 phone = trans.TransitionIdToPhone(arc.ilabel),
+// ref_phone = trans.TransitionIdToPhone(num_ali[cur_time]);
+// bool phone_is_sil = std::binary_search(silence_phones.begin(),
+// silence_phones.end(), phone),
+// ref_phone_is_sil = std::binary_search(silence_phones.begin(),
+// silence_phones.end(),
+// ref_phone),
+// both_sil = phone_is_sil && ref_phone_is_sil;
+// if (!is_mpfe) { // smbr.
+// int32 pdf = trans.TransitionIdToPdf(arc.ilabel),
+// ref_pdf = trans.TransitionIdToPdf(num_ali[cur_time]);
+// if (!one_silence_class) // old behavior
+// frame_acc = (pdf == ref_pdf && !phone_is_sil) ? 1.0 : 0.0;
+// else
+// frame_acc = (pdf == ref_pdf || both_sil) ? 1.0 : 0.0;
+// } else {
+// if (!one_silence_class) // old behavior
+// frame_acc = (phone == ref_phone && !phone_is_sil) ? 1.0 : 0.0;
+// else
+// frame_acc = (phone == ref_phone || both_sil) ? 1.0 : 0.0;
+// }
+// }
+// double arc_scale = Exp(beta[arc.nextstate] + arc_like - beta[s]);
+// // check arc_scale NAN,
+// // this is to prevent partial paths in Lattices
+// // i.e., paths don't survive to the final state
+// if (KALDI_ISNAN(arc_scale)) arc_scale = 0;
+// beta_smbr[s] += arc_scale * (beta_smbr[arc.nextstate] + frame_acc);
+//
+// if (transition_id != 0) { // Arc has a transition-id on it [not epsilon]
+// double posterior = Exp(alpha[s] + arc_beta - tot_forward_prob);
+// double acc_diff = alpha_smbr[s] + frame_acc + beta_smbr[arc.nextstate]
+// - tot_forward_score;
+// double posterior_smbr = posterior * acc_diff;
+// (*post)[state_times[s]].push_back(std::make_pair(transition_id,
+// static_cast<BaseFloat>(posterior_smbr)));
+// }
+// }
+// }
+//
+// //Second Pass Forward Backward check
+// double tot_backward_score = beta_smbr[0]; // Initial state id == 0
+// // may loose the condition somehow here 1e-5/1e-4
+// if (!ApproxEqual(tot_forward_score, tot_backward_score, 1e-4)) {
+// KALDI_ERR << "Total forward score over lattice = " << tot_forward_score
+// << ", while total backward score = " << tot_backward_score;
+// }
+//
+// // Output the computed posteriors
+// for (int32 t = 0; t < max_time; t++)
+// MergePairVectorSumming(&((*post)[t]));
+// return tot_forward_score;
+//}
+//
+//bool CompactLatticeToWordAlignment(const CompactLattice &clat,
+// std::vector<int32> *words,
+// std::vector<int32> *begin_times,
+// std::vector<int32> *lengths) {
+// words->clear();
+// begin_times->clear();
+// lengths->clear();
+// typedef CompactLattice::Arc Arc;
+// typedef Arc::Label Label;
+// typedef CompactLattice::StateId StateId;
+// typedef CompactLattice::Weight Weight;
+// using namespace fst;
+// StateId state = clat.Start();
+// int32 cur_time = 0;
+// if (state == kNoStateId) {
+// KALDI_WARN << "Empty lattice.";
+// return false;
+// }
+// while (1) {
+// Weight final = clat.Final(state);
+// size_t num_arcs = clat.NumArcs(state);
+// if (final != Weight::Zero()) {
+// if (num_arcs != 0) {
+// KALDI_WARN << "Lattice is not linear.";
+// return false;
+// }
+// if (! final.String().empty()) {
+// KALDI_WARN << "Lattice has alignments on final-weight: probably "
+// "was not word-aligned (alignments will be approximate)";
+// }
+// return true;
+// } else {
+// if (num_arcs != 1) {
+// KALDI_WARN << "Lattice is not linear: num-arcs = " << num_arcs;
+// return false;
+// }
+// fst::ArcIterator<CompactLattice> aiter(clat, state);
+// const Arc &arc = aiter.Value();
+// Label word_id = arc.ilabel; // Note: ilabel==olabel, since acceptor.
+// // Also note: word_id may be zero; we output it anyway.
+// int32 length = arc.weight.String().size();
+// words->push_back(word_id);
+// begin_times->push_back(cur_time);
+// lengths->push_back(length);
+// cur_time += length;
+// state = arc.nextstate;
+// }
+// }
+//}
+//
+//
+//void CompactLatticeShortestPath(const CompactLattice &clat,
+// CompactLattice *shortest_path) {
+// using namespace fst;
+// if (clat.Properties(fst::kTopSorted, true) == 0) {
+// CompactLattice clat_copy(clat);
+// if (!TopSort(&clat_copy))
+// KALDI_ERR << "Was not able to topologically sort lattice (cycles found?)";
+// CompactLatticeShortestPath(clat_copy, shortest_path);
+// return;
+// }
+// // Now we can assume it's topologically sorted.
+// shortest_path->DeleteStates();
+// if (clat.Start() == kNoStateId) return;
+// typedef CompactLatticeArc Arc;
+// typedef Arc::StateId StateId;
+// typedef CompactLatticeWeight Weight;
+// vector<std::pair<double, StateId> > best_cost_and_pred(clat.NumStates() + 1);
+// StateId superfinal = clat.NumStates();
+// for (StateId s = 0; s <= clat.NumStates(); s++) {
+// best_cost_and_pred[s].first = std::numeric_limits<double>::infinity();
+// best_cost_and_pred[s].second = fst::kNoStateId;
+// }
+// best_cost_and_pred[clat.Start()].first = 0;
+// for (StateId s = 0; s < clat.NumStates(); s++) {
+// double my_cost = best_cost_and_pred[s].first;
+// for (ArcIterator<CompactLattice> aiter(clat, s);
+// !aiter.Done();
+// aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double arc_cost = ConvertToCost(arc.weight),
+// next_cost = my_cost + arc_cost;
+// if (next_cost < best_cost_and_pred[arc.nextstate].first) {
+// best_cost_and_pred[arc.nextstate].first = next_cost;
+// best_cost_and_pred[arc.nextstate].second = s;
+// }
+// }
+// double final_cost = ConvertToCost(clat.Final(s)),
+// tot_final = my_cost + final_cost;
+// if (tot_final < best_cost_and_pred[superfinal].first) {
+// best_cost_and_pred[superfinal].first = tot_final;
+// best_cost_and_pred[superfinal].second = s;
+// }
+// }
+// std::vector<StateId> states; // states on best path.
+// StateId cur_state = superfinal, start_state = clat.Start();
+// while (cur_state != start_state) {
+// StateId prev_state = best_cost_and_pred[cur_state].second;
+// if (prev_state == kNoStateId) {
+// KALDI_WARN << "Failure in best-path algorithm for lattice (infinite costs?)";
+// return; // return empty best-path.
+// }
+// states.push_back(prev_state);
+// KALDI_ASSERT(cur_state != prev_state && "Lattice with cycles");
+// cur_state = prev_state;
+// }
+// std::reverse(states.begin(), states.end());
+// for (size_t i = 0; i < states.size(); i++)
+// shortest_path->AddState();
+// for (StateId s = 0; static_cast<size_t>(s) < states.size(); s++) {
+// if (s == 0) shortest_path->SetStart(s);
+// if (static_cast<size_t>(s + 1) < states.size()) { // transition to next state.
+// bool have_arc = false;
+// Arc cur_arc;
+// for (ArcIterator<CompactLattice> aiter(clat, states[s]);
+// !aiter.Done();
+// aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// if (arc.nextstate == states[s+1]) {
+// if (!have_arc ||
+// ConvertToCost(arc.weight) < ConvertToCost(cur_arc.weight)) {
+// cur_arc = arc;
+// have_arc = true;
+// }
+// }
+// }
+// KALDI_ASSERT(have_arc && "Code error.");
+// shortest_path->AddArc(s, Arc(cur_arc.ilabel, cur_arc.olabel,
+// cur_arc.weight, s+1));
+// } else { // final-prob.
+// shortest_path->SetFinal(s, clat.Final(states[s]));
+// }
+// }
+//}
+//
+//
+//void ExpandCompactLattice(const CompactLattice &clat,
+// double epsilon,
+// CompactLattice *expand_clat) {
+// using namespace fst;
+// typedef CompactLattice::Arc Arc;
+// typedef Arc::Weight Weight;
+// typedef Arc::StateId StateId;
+// typedef std::pair<StateId, StateId> StatePair;
+// typedef unordered_map<StatePair, StateId, PairHasher<StateId> > MapType;
+// typedef MapType::iterator IterType;
+//
+// if (clat.Start() == kNoStateId) return;
+// // Make sure the input lattice is topologically sorted.
+// if (clat.Properties(kTopSorted, true) == 0) {
+// CompactLattice clat_copy(clat);
+// KALDI_LOG << "Topsort this lattice.";
+// if (!TopSort(&clat_copy))
+// KALDI_ERR << "Was not able to topologically sort lattice (cycles found?)";
+// ExpandCompactLattice(clat_copy, epsilon, expand_clat);
+// return;
+// }
+//
+// // Compute backward logprobs betas for the expanded lattice.
+// // Note: the backward logprobs in the original lattice <clat> and the
+// // expanded lattice <expand_clat> are the same.
+// int32 num_states = clat.NumStates();
+// std::vector<double> beta(num_states, kLogZeroDouble);
+// ComputeCompactLatticeBetas(clat, &beta);
+// double tot_backward_logprob = beta[0];
+// std::vector<double> alpha;
+// alpha.push_back(0.0);
+// expand_clat->DeleteStates();
+// MapType state_map; // Map from state pair (orig_state, copy_state) to
+// // copy_state, where orig_state is a state in the original lattice, and
+// // copy_state is its corresponding one in the expanded lattice.
+// unordered_map<StateId, StateId> states; // Map from orig_state to its
+// // copy_state for states with incoming arcs' posteriors <= epsilon.
+// std::queue<StatePair> state_queue;
+//
+// // Set start state in the expanded lattice.
+// StateId start_state = expand_clat->AddState();
+// expand_clat->SetStart(start_state);
+// StatePair start_pair(clat.Start(), start_state);
+// state_queue.push(start_pair);
+// std::pair<IterType, bool> result =
+// state_map.insert(std::make_pair(start_pair, start_state));
+// KALDI_ASSERT(result.second == true);
+//
+// // Expand <clat> and update forward logprobs alphas in <expand_clat>.
+// while (!state_queue.empty()) {
+// StatePair s = state_queue.front();
+// StateId s1 = s.first,
+// s2 = s.second;
+// state_queue.pop();
+//
+// Weight f = clat.Final(s1);
+// if (f != Weight::Zero()) {
+// KALDI_ASSERT(state_map.find(s) != state_map.end());
+// expand_clat->SetFinal(state_map[s], f);
+// }
+//
+// for (ArcIterator<CompactLattice> aiter(clat, s1);
+// !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// StateId orig_state = arc.nextstate;
+// double arc_like = -ConvertToCost(arc.weight),
+// this_alpha = alpha[s2] + arc_like,
+// arc_post = Exp(this_alpha + beta[orig_state] -
+// tot_backward_logprob);
+// // Generate the expanded lattice.
+// StateId copy_state;
+// if (arc_post > epsilon) {
+// copy_state = expand_clat->AddState();
+// StatePair next_pair(orig_state, copy_state);
+// std::pair<IterType, bool> result =
+// state_map.insert(std::make_pair(next_pair, copy_state));
+// KALDI_ASSERT(result.second == true);
+// state_queue.push(next_pair);
+// } else {
+// unordered_map<StateId, StateId>::iterator iter = states.find(orig_state);
+// if (iter == states.end() ) { // The counterpart state of orig_state
+// // has not been created in <expand_clat> yet.
+// copy_state = expand_clat->AddState();
+// StatePair next_pair(orig_state, copy_state);
+// std::pair<IterType, bool> result =
+// state_map.insert(std::make_pair(next_pair, copy_state));
+// KALDI_ASSERT(result.second == true);
+// state_queue.push(next_pair);
+// states[orig_state] = copy_state;
+// } else {
+// copy_state = iter->second;
+// }
+// }
+// // Create an arc from state_map[s] to copy_state in the expanded lattice.
+// expand_clat->AddArc(state_map[s], Arc(arc.ilabel, arc.olabel, arc.weight,
+// copy_state));
+// // Compute forward logprobs alpha for the expanded lattice.
+// if ((alpha.size() - 1) < copy_state) { // The first time to compute alpha
+// // for copy_state in <expand_clat>.
+// alpha.push_back(this_alpha);
+// } else { // Accumulate alpha.
+// alpha[copy_state] = LogAdd(alpha[copy_state], this_alpha);
+// }
+// }
+// } // end while
+//}
+//
+//
+//void CompactLatticeBestCostsAndTracebacks(
+// const CompactLattice &clat,
+// CostTraceType *forward_best_cost_and_pred,
+// CostTraceType *backward_best_cost_and_pred) {
+//
+// // typedef the arc, weight types
+// typedef CompactLatticeArc Arc;
+// typedef Arc::Weight Weight;
+// typedef Arc::StateId StateId;
+//
+// forward_best_cost_and_pred->clear();
+// backward_best_cost_and_pred->clear();
+// forward_best_cost_and_pred->resize(clat.NumStates());
+// backward_best_cost_and_pred->resize(clat.NumStates());
+// // Initialize the cost and predecessor state for each state.
+// for (StateId s = 0; s < clat.NumStates(); s++) {
+// (*forward_best_cost_and_pred)[s].first =
+// std::numeric_limits<double>::infinity();
+// (*backward_best_cost_and_pred)[s].first =
+// std::numeric_limits<double>::infinity();
+// (*forward_best_cost_and_pred)[s].second = fst::kNoStateId;
+// (*backward_best_cost_and_pred)[s].second = fst::kNoStateId;
+// }
+//
+// StateId start_state = clat.Start();
+// (*forward_best_cost_and_pred)[start_state].first = 0;
+// // Transverse the lattice forwardly to compute the best cost from the start
+// // state to each state and the best predecessor state of each state.
+// for (StateId s = 0; s < clat.NumStates(); s++) {
+// double cur_cost = (*forward_best_cost_and_pred)[s].first;
+// for (fst::ArcIterator<CompactLattice> aiter(clat, s);
+// !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double next_cost = cur_cost + ConvertToCost(arc.weight);
+// if (next_cost < (*forward_best_cost_and_pred)[arc.nextstate].first) {
+// (*forward_best_cost_and_pred)[arc.nextstate].first = next_cost;
+// (*forward_best_cost_and_pred)[arc.nextstate].second = s;
+// }
+// }
+// }
+// // Transverse the lattice backwardly to compute the best cost from a final
+// // state to each state and the best predecessor state of each state.
+// for (StateId s = clat.NumStates() - 1; s >= 0; s--) {
+// double this_cost = ConvertToCost(clat.Final(s));
+// for (fst::ArcIterator<CompactLattice> aiter(clat, s);
+// !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// double next_cost = (*backward_best_cost_and_pred)[arc.nextstate].first +
+// ConvertToCost(arc.weight);
+// if (next_cost < this_cost) {
+// this_cost = next_cost;
+// (*backward_best_cost_and_pred)[s].second = arc.nextstate;
+// }
+// }
+// (*backward_best_cost_and_pred)[s].first = this_cost;
+// }
+//}
+//
+//
+//void AddNnlmScoreToCompactLattice(const MapT &nnlm_scores,
+// CompactLattice *clat) {
+// if (clat->Start() == fst::kNoStateId) return;
+// // Make sure the input lattice is topologically sorted.
+// if (clat->Properties(fst::kTopSorted, true) == 0) {
+// KALDI_LOG << "Topsort this lattice.";
+// if (!TopSort(clat))
+// KALDI_ERR << "Was not able to topologically sort lattice (cycles found?)";
+// AddNnlmScoreToCompactLattice(nnlm_scores, clat);
+// return;
+// }
+//
+// // typedef the arc, weight types
+// typedef CompactLatticeArc Arc;
+// typedef Arc::Weight Weight;
+// typedef Arc::StateId StateId;
+// typedef std::pair<int32, int32> StatePair;
+//
+// int32 num_states = clat->NumStates();
+// unordered_map<StatePair, bool, PairHasher<int32> > final_state_check;
+// for (StateId s = 0; s < num_states; s++) {
+// for (fst::MutableArcIterator<CompactLattice> aiter(clat, s);
+// !aiter.Done(); aiter.Next()) {
+// Arc arc(aiter.Value());
+// StatePair arc_index = std::make_pair(static_cast<int32>(s),
+// static_cast<int32>(arc.nextstate));
+// MapT::const_iterator it = nnlm_scores.find(arc_index);
+// double nnlm_score;
+// if (it != nnlm_scores.end())
+// nnlm_score = it->second;
+// else
+// KALDI_ERR << "Some arc does not have neural language model score.";
+// if (arc.ilabel != 0) { // if there is a word on this arc
+// LatticeWeight weight = arc.weight.Weight();
+// // Add associated neural LM score to each arc.
+// weight.SetValue1(weight.Value1() + nnlm_score);
+// arc.weight.SetWeight(weight);
+// aiter.SetValue(arc);
+// }
+// Weight clat_final = clat->Final(arc.nextstate);
+// StatePair final_pair = std::make_pair(arc.nextstate, arc.nextstate);
+// // Add neural LM scores to each final state only once.
+// if (clat_final != CompactLatticeWeight::Zero() &&
+// final_state_check.find(final_pair) == final_state_check.end()) {
+// MapT::const_iterator final_it = nnlm_scores.find(final_pair);
+// double final_nnlm_score = 0.0;
+// if (final_it != nnlm_scores.end())
+// final_nnlm_score = final_it->second;
+// // Add neural LM scores to the final weight.
+// Weight final_weight(LatticeWeight(clat_final.Weight().Value1() +
+// final_nnlm_score,
+// clat_final.Weight().Value2()),
+// clat_final.String());
+// clat->SetFinal(arc.nextstate, final_weight);
+// final_state_check[final_pair] = true;
+// }
+// } // end looping over arcs
+// } // end looping over states
+//}
+//
+//void AddWordInsPenToCompactLattice(BaseFloat word_ins_penalty,
+// CompactLattice *clat) {
+// typedef CompactLatticeArc Arc;
+// int32 num_states = clat->NumStates();
+//
+// //scan the lattice
+// for (int32 state = 0; state < num_states; state++) {
+// for (fst::MutableArcIterator<CompactLattice> aiter(clat, state);
+// !aiter.Done(); aiter.Next()) {
+//
+// Arc arc(aiter.Value());
+//
+// if (arc.ilabel != 0) { // if there is a word on this arc
+// LatticeWeight weight = arc.weight.Weight();
+// // add word insertion penalty to lattice
+// weight.SetValue1( weight.Value1() + word_ins_penalty);
+// arc.weight.SetWeight(weight);
+// aiter.SetValue(arc);
+// }
+// } // end looping over arcs
+// } // end looping over states
+//}
+//
+//struct ClatRescoreTuple {
+// ClatRescoreTuple(int32 state, int32 arc, int32 tid):
+// state_id(state), arc_id(arc), tid(tid) { }
+// int32 state_id;
+// int32 arc_id;
+// int32 tid;
+//};
+//
+///** RescoreCompactLatticeInternal is the internal code for both
+// RescoreCompactLattice and RescoreCompatLatticeSpeedup. For
+// RescoreCompactLattice, "tmodel" will be NULL and speedup_factor will be 1.0.
+// */
+//bool RescoreCompactLatticeInternal(
+// const TransitionInformation *tmodel,
+// BaseFloat speedup_factor,
+// DecodableInterface *decodable,
+// CompactLattice *clat) {
+// KALDI_ASSERT(speedup_factor >= 1.0);
+// if (clat->NumStates() == 0) {
+// KALDI_WARN << "Rescoring empty lattice";
+// return false;
+// }
+// if (!clat->Properties(fst::kTopSorted, true)) {
+// if (fst::TopSort(clat) == false) {
+// KALDI_WARN << "Cycles detected in lattice.";
+// return false;
+// }
+// }
+// std::vector<int32> state_times;
+// int32 utt_len = kaldi::CompactLatticeStateTimes(*clat, &state_times);
+//
+// std::vector<std::vector<ClatRescoreTuple> > time_to_state(utt_len);
+//
+// int32 num_states = clat->NumStates();
+// KALDI_ASSERT(num_states == state_times.size());
+// for (size_t state = 0; state < num_states; state++) {
+// KALDI_ASSERT(state_times[state] >= 0);
+// int32 t = state_times[state];
+// int32 arc_id = 0;
+// for (fst::MutableArcIterator<CompactLattice> aiter(clat, state);
+// !aiter.Done(); aiter.Next(), arc_id++) {
+// CompactLatticeArc arc = aiter.Value();
+// std::vector<int32> arc_string = arc.weight.String();
+//
+// for (size_t offset = 0; offset < arc_string.size(); offset++) {
+// if (t < utt_len) { // end state may be past this..
+// int32 tid = arc_string[offset];
+// time_to_state[t+offset].push_back(ClatRescoreTuple(state, arc_id, tid));
+// } else {
+// if (t != utt_len) {
+// KALDI_WARN << "There appears to be lattice/feature mismatch, "
+// << "aborting.";
+// return false;
+// }
+// }
+// }
+// }
+// if (clat->Final(state) != CompactLatticeWeight::Zero()) {
+// arc_id = -1;
+// std::vector<int32> arc_string = clat->Final(state).String();
+// for (size_t offset = 0; offset < arc_string.size(); offset++) {
+// KALDI_ASSERT(t + offset < utt_len); // already checked in
+// // CompactLatticeStateTimes, so would be code error.
+// time_to_state[t+offset].push_back(
+// ClatRescoreTuple(state, arc_id, arc_string[offset]));
+// }
+// }
+// }
+//
+// for (int32 t = 0; t < utt_len; t++) {
+// if ((t < utt_len - 1) && decodable->IsLastFrame(t)) {
+// KALDI_WARN << "Features are too short for lattice: utt-len is "
+// << utt_len << ", " << t << " is last frame";
+// return false;
+// }
+// // frame_scale is the scale we put on the computed acoustic probs for this
+// // frame. It will always be 1.0 if tmodel == NULL (i.e. if we are not doing
+// // the "speedup" code). For frames with multiple pdf-ids it will be one.
+// // For frames with only one pdf-id, it will equal speedup_factor (>=1.0)
+// // with probability 1.0 / speedup_factor, and zero otherwise. If it is zero,
+// // we can avoid computing the probabilities.
+// BaseFloat frame_scale = 1.0;
+// KALDI_ASSERT(!time_to_state[t].empty());
+// if (tmodel != NULL) {
+// int32 pdf_id = tmodel->TransitionIdToPdf(time_to_state[t][0].tid);
+// bool frame_has_multiple_pdfs = false;
+// for (size_t i = 1; i < time_to_state[t].size(); i++) {
+// if (tmodel->TransitionIdToPdf(time_to_state[t][i].tid) != pdf_id) {
+// frame_has_multiple_pdfs = true;
+// break;
+// }
+// }
+// if (frame_has_multiple_pdfs) {
+// frame_scale = 1.0;
+// } else {
+// if (WithProb(1.0 / speedup_factor)) {
+// frame_scale = speedup_factor;
+// } else {
+// frame_scale = 0.0;
+// }
+// }
+// if (frame_scale == 0.0)
+// continue; // the code below would be pointless.
+// }
+//
+// for (size_t i = 0; i < time_to_state[t].size(); i++) {
+// int32 state = time_to_state[t][i].state_id;
+// int32 arc_id = time_to_state[t][i].arc_id;
+// int32 tid = time_to_state[t][i].tid;
+//
+// if (arc_id == -1) { // Final state
+// // Access the trans_id
+// CompactLatticeWeight curr_clat_weight = clat->Final(state);
+//
+// // Calculate likelihood
+// BaseFloat log_like = decodable->LogLikelihood(t, tid) * frame_scale;
+// // update weight
+// CompactLatticeWeight new_clat_weight = curr_clat_weight;
+// LatticeWeight new_lat_weight = new_clat_weight.Weight();
+// new_lat_weight.SetValue2(-log_like + curr_clat_weight.Weight().Value2());
+// new_clat_weight.SetWeight(new_lat_weight);
+// clat->SetFinal(state, new_clat_weight);
+// } else {
+// fst::MutableArcIterator<CompactLattice> aiter(clat, state);
+//
+// aiter.Seek(arc_id);
+// CompactLatticeArc arc = aiter.Value();
+//
+// // Calculate likelihood
+// BaseFloat log_like = decodable->LogLikelihood(t, tid) * frame_scale;
+// // update weight
+// LatticeWeight new_weight = arc.weight.Weight();
+// new_weight.SetValue2(-log_like + arc.weight.Weight().Value2());
+// arc.weight.SetWeight(new_weight);
+// aiter.SetValue(arc);
+// }
+// }
+// }
+// return true;
+//}
+//
+//
+//bool RescoreCompactLatticeSpeedup(
+// const TransitionInformation &tmodel,
+// BaseFloat speedup_factor,
+// DecodableInterface *decodable,
+// CompactLattice *clat) {
+// return RescoreCompactLatticeInternal(&tmodel, speedup_factor, decodable, clat);
+//}
+//
+//bool RescoreCompactLattice(DecodableInterface *decodable,
+// CompactLattice *clat) {
+// return RescoreCompactLatticeInternal(NULL, 1.0, decodable, clat);
+//}
+//
+//
+//bool RescoreLattice(DecodableInterface *decodable,
+// Lattice *lat) {
+// if (lat->NumStates() == 0) {
+// KALDI_WARN << "Rescoring empty lattice";
+// return false;
+// }
+// if (!lat->Properties(fst::kTopSorted, true)) {
+// if (fst::TopSort(lat) == false) {
+// KALDI_WARN << "Cycles detected in lattice.";
+// return false;
+// }
+// }
+// std::vector<int32> state_times;
+// int32 utt_len = kaldi::LatticeStateTimes(*lat, &state_times);
+//
+// std::vector<std::vector<int32> > time_to_state(utt_len );
+//
+// int32 num_states = lat->NumStates();
+// KALDI_ASSERT(num_states == state_times.size());
+// for (size_t state = 0; state < num_states; state++) {
+// int32 t = state_times[state];
+// // Don't check t >= 0 because non-accessible states could have t = -1.
+// KALDI_ASSERT(t <= utt_len);
+// if (t >= 0 && t < utt_len)
+// time_to_state[t].push_back(state);
+// }
+//
+// for (int32 t = 0; t < utt_len; t++) {
+// if ((t < utt_len - 1) && decodable->IsLastFrame(t)) {
+// KALDI_WARN << "Features are too short for lattice: utt-len is "
+// << utt_len << ", " << t << " is last frame";
+// return false;
+// }
+// for (size_t i = 0; i < time_to_state[t].size(); i++) {
+// int32 state = time_to_state[t][i];
+// for (fst::MutableArcIterator<Lattice> aiter(lat, state);
+// !aiter.Done(); aiter.Next()) {
+// LatticeArc arc = aiter.Value();
+// if (arc.ilabel != 0) {
+// int32 trans_id = arc.ilabel; // Note: it doesn't necessarily
+// // have to be a transition-id, just whatever the Decodable
+// // object is expecting, but it's normally a transition-id.
+//
+// BaseFloat log_like = decodable->LogLikelihood(t, trans_id);
+// arc.weight.SetValue2(-log_like + arc.weight.Value2());
+// aiter.SetValue(arc);
+// }
+// }
+// }
+// }
+// return true;
+//}
+//
+//
+//int32 LongestSentenceLength(const Lattice &lat) {
+// typedef Lattice::Arc Arc;
+// typedef Arc::Label Label;
+// typedef Arc::StateId StateId;
+//
+// if (lat.Properties(fst::kTopSorted, true) == 0) {
+// Lattice lat_copy(lat);
+// if (!TopSort(&lat_copy))
+// KALDI_ERR << "Was not able to topologically sort lattice (cycles found?)";
+// return LongestSentenceLength(lat_copy);
+// }
+// std::vector<int32> max_length(lat.NumStates(), 0);
+// int32 lattice_max_length = 0;
+// for (StateId s = 0; s < lat.NumStates(); s++) {
+// int32 this_max_length = max_length[s];
+// for (fst::ArcIterator<Lattice> aiter(lat, s); !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// bool arc_has_word = (arc.olabel != 0);
+// StateId nextstate = arc.nextstate;
+// KALDI_ASSERT(static_cast<size_t>(nextstate) < max_length.size());
+// if (arc_has_word) {
+// // A lattice should ideally not have cycles anyway; a cycle with a word
+// // on is something very bad.
+// KALDI_ASSERT(nextstate > s && "Lattice has cycles with words on.");
+// max_length[nextstate] = std::max(max_length[nextstate],
+// this_max_length + 1);
+// } else {
+// max_length[nextstate] = std::max(max_length[nextstate],
+// this_max_length);
+// }
+// }
+// if (lat.Final(s) != LatticeWeight::Zero())
+// lattice_max_length = std::max(lattice_max_length, max_length[s]);
+// }
+// return lattice_max_length;
+//}
+//
+//int32 LongestSentenceLength(const CompactLattice &clat) {
+// typedef CompactLattice::Arc Arc;
+// typedef Arc::Label Label;
+// typedef Arc::StateId StateId;
+//
+// if (clat.Properties(fst::kTopSorted, true) == 0) {
+// CompactLattice clat_copy(clat);
+// if (!TopSort(&clat_copy))
+// KALDI_ERR << "Was not able to topologically sort lattice (cycles found?)";
+// return LongestSentenceLength(clat_copy);
+// }
+// std::vector<int32> max_length(clat.NumStates(), 0);
+// int32 lattice_max_length = 0;
+// for (StateId s = 0; s < clat.NumStates(); s++) {
+// int32 this_max_length = max_length[s];
+// for (fst::ArcIterator<CompactLattice> aiter(clat, s);
+// !aiter.Done(); aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// bool arc_has_word = (arc.ilabel != 0); // note: olabel == ilabel.
+// // also note: for normal CompactLattice, e.g. as produced by
+// // determinization, all arcs will have nonzero labels, but the user might
+// // decide to remplace some of the labels with zero for some reason, and we
+// // want to support this.
+// StateId nextstate = arc.nextstate;
+// KALDI_ASSERT(static_cast<size_t>(nextstate) < max_length.size());
+// KALDI_ASSERT(nextstate > s && "CompactLattice has cycles");
+// if (arc_has_word)
+// max_length[nextstate] = std::max(max_length[nextstate],
+// this_max_length + 1);
+// else
+// max_length[nextstate] = std::max(max_length[nextstate],
+// this_max_length);
+// }
+// if (clat.Final(s) != CompactLatticeWeight::Zero())
+// lattice_max_length = std::max(lattice_max_length, max_length[s]);
+// }
+// return lattice_max_length;
+//}
+//
+//void ComposeCompactLatticeDeterministic(
+// const CompactLattice& clat,
+// fst::DeterministicOnDemandFst<fst::StdArc>* det_fst,
+// CompactLattice* composed_clat) {
+// // StdFst::Arc and CompactLatticeArc has the same StateId type.
+// typedef fst::StdArc::StateId StateId;
+// typedef fst::StdArc::Weight Weight1;
+// typedef CompactLatticeArc::Weight Weight2;
+// typedef std::pair<StateId, StateId> StatePair;
+// typedef unordered_map<StatePair, StateId, PairHasher<StateId> > MapType;
+// typedef MapType::iterator IterType;
+//
+// // Empties the output FST.
+// KALDI_ASSERT(composed_clat != NULL);
+// composed_clat->DeleteStates();
+//
+// MapType state_map;
+// std::queue<StatePair> state_queue;
+//
+// // Sets start state in <composed_clat>.
+// StateId start_state = composed_clat->AddState();
+// StatePair start_pair(clat.Start(), det_fst->Start());
+// composed_clat->SetStart(start_state);
+// state_queue.push(start_pair);
+// std::pair<IterType, bool> result =
+// state_map.insert(std::make_pair(start_pair, start_state));
+// KALDI_ASSERT(result.second == true);
+//
+// // Starts composition here.
+// while (!state_queue.empty()) {
+// // Gets the first state in the queue.
+// StatePair s = state_queue.front();
+// StateId s1 = s.first;
+// StateId s2 = s.second;
+// state_queue.pop();
+//
+//
+// Weight2 clat_final = clat.Final(s1);
+// if (clat_final.Weight().Value1() !=
+// std::numeric_limits<BaseFloat>::infinity()) {
+// // Test for whether the final-prob of state s1 was zero.
+// Weight1 det_fst_final = det_fst->Final(s2);
+// if (det_fst_final.Value() !=
+// std::numeric_limits<BaseFloat>::infinity()) {
+// // Test for whether the final-prob of state s2 was zero. If neither
+// // source-state final prob was zero, then we should create final state
+// // in fst_composed. We compute the product manually since this is more
+// // efficient.
+// Weight2 final_weight(LatticeWeight(clat_final.Weight().Value1() +
+// det_fst_final.Value(),
+// clat_final.Weight().Value2()),
+// clat_final.String());
+// // we can assume final_weight is not Zero(), since neither of
+// // the sources was zero.
+// KALDI_ASSERT(state_map.find(s) != state_map.end());
+// composed_clat->SetFinal(state_map[s], final_weight);
+// }
+// }
+//
+// // Loops over pair of edges at s1 and s2.
+// for (fst::ArcIterator<CompactLattice> aiter(clat, s1);
+// !aiter.Done(); aiter.Next()) {
+// const CompactLatticeArc& arc1 = aiter.Value();
+// fst::StdArc arc2;
+// StateId next_state1 = arc1.nextstate, next_state2;
+// bool matched = false;
+//
+// if (arc1.olabel == 0) {
+// // If the symbol on <arc1> is <epsilon>, we transit to the next state
+// // for <clat>, but keep <det_fst> at the current state.
+// matched = true;
+// next_state2 = s2;
+// } else {
+// // Otherwise try to find the matched arc in <det_fst>.
+// matched = det_fst->GetArc(s2, arc1.olabel, &arc2);
+// if (matched) {
+// next_state2 = arc2.nextstate;
+// }
+// }
+//
+// // If matched arc is found in <det_fst>, then we have to add new arcs to
+// // <composed_clat>.
+// if (matched) {
+// StatePair next_state_pair(next_state1, next_state2);
+// IterType siter = state_map.find(next_state_pair);
+// StateId next_state;
+//
+// // Adds composed state to <state_map>.
+// if (siter == state_map.end()) {
+// // If the composed state has not been created yet, create it.
+// next_state = composed_clat->AddState();
+// std::pair<const StatePair, StateId> next_state_map(next_state_pair,
+// next_state);
+// std::pair<IterType, bool> result = state_map.insert(next_state_map);
+// KALDI_ASSERT(result.second);
+// state_queue.push(next_state_pair);
+// } else {
+// // If the composed state is already in <state_map>, we can directly
+// // use that.
+// next_state = siter->second;
+// }
+//
+// // Adds arc to <composed_clat>.
+// if (arc1.olabel == 0) {
+// composed_clat->AddArc(state_map[s],
+// CompactLatticeArc(arc1.ilabel, 0,
+// arc1.weight, next_state));
+// } else {
+// Weight2 composed_weight(
+// LatticeWeight(arc1.weight.Weight().Value1() +
+// arc2.weight.Value(),
+// arc1.weight.Weight().Value2()),
+// arc1.weight.String());
+// composed_clat->AddArc(state_map[s],
+// CompactLatticeArc(arc1.ilabel, arc2.olabel,
+// composed_weight, next_state));
+// }
+// }
+// }
+// }
+// fst::Connect(composed_clat);
+//}
+//
+//
+//void ComputeAcousticScoresMap(
+// const Lattice &lat,
+// unordered_map<std::pair<int32, int32>, std::pair<BaseFloat, int32>,
+// PairHasher<int32> > *acoustic_scores) {
+// // typedef the arc, weight types
+// typedef Lattice::Arc Arc;
+// typedef Arc::Weight LatticeWeight;
+// typedef Arc::StateId StateId;
+//
+// acoustic_scores->clear();
+//
+// std::vector<int32> state_times;
+// LatticeStateTimes(lat, &state_times); // Assumes the input is top sorted
+//
+// KALDI_ASSERT(lat.Start() == 0);
+//
+// for (StateId s = 0; s < lat.NumStates(); s++) {
+// int32 t = state_times[s];
+// for (fst::ArcIterator<Lattice> aiter(lat, s); !aiter.Done();
+// aiter.Next()) {
+// const Arc &arc = aiter.Value();
+// const LatticeWeight &weight = arc.weight;
+//
+// int32 tid = arc.ilabel;
+//
+// if (tid != 0) {
+// unordered_map<std::pair<int32, int32>, std::pair<BaseFloat, int32>,
+// PairHasher<int32> >::iterator it = acoustic_scores->find(std::make_pair(t, tid));
+// if (it == acoustic_scores->end()) {
+// acoustic_scores->insert(std::make_pair(std::make_pair(t, tid),
+// std::make_pair(weight.Value2(), 1)));
+// } else {
+// if (it->second.second == 2
+// && it->second.first / it->second.second != weight.Value2()) {
+// KALDI_VLOG(2) << "Transitions on the same frame have different "
+// << "acoustic costs for tid " << tid << "; "
+// << it->second.first / it->second.second
+// << " vs " << weight.Value2();
+// }
+// it->second.first += weight.Value2();
+// it->second.second++;
+// }
+// } else {
+// // Arcs with epsilon input label (tid) must have 0 acoustic cost
+// KALDI_ASSERT(weight.Value2() == 0);
+// }
+// }
+//
+// LatticeWeight f = lat.Final(s);
+// if (f != LatticeWeight::Zero()) {
+// // Final acoustic cost must be 0 as we are reading from
+// // non-determinized, non-compact lattice
+// KALDI_ASSERT(f.Value2() == 0.0);
+// }
+// }
+//}
+//
+//void ReplaceAcousticScoresFromMap(
+// const unordered_map<std::pair<int32, int32>, std::pair<BaseFloat, int32>,
+// PairHasher<int32> > &acoustic_scores,
+// Lattice *lat) {
+// // typedef the arc, weight types
+// typedef Lattice::Arc Arc;
+// typedef Arc::Weight LatticeWeight;
+// typedef Arc::StateId StateId;
+//
+// TopSortLatticeIfNeeded(lat);
+//
+// std::vector<int32> state_times;
+// LatticeStateTimes(*lat, &state_times);
+//
+// KALDI_ASSERT(lat->Start() == 0);
+//
+// for (StateId s = 0; s < lat->NumStates(); s++) {
+// int32 t = state_times[s];
+// for (fst::MutableArcIterator<Lattice> aiter(lat, s);
+// !aiter.Done(); aiter.Next()) {
+// Arc arc(aiter.Value());
+//
+// int32 tid = arc.ilabel;
+// if (tid != 0) {
+// unordered_map<std::pair<int32, int32>, std::pair<BaseFloat, int32>,
+// PairHasher<int32> >::const_iterator it = acoustic_scores.find(std::make_pair(t, tid));
+// if (it == acoustic_scores.end()) {
+// KALDI_ERR << "Could not find tid " << tid << " at time " << t
+// << " in the acoustic scores map.";
+// } else {
+// arc.weight.SetValue2(it->second.first / it->second.second);
+// }
+// } else {
+// // For epsilon arcs, set acoustic cost to 0.0
+// arc.weight.SetValue2(0.0);
+// }
+// aiter.SetValue(arc);
+// }
+//
+// LatticeWeight f = lat->Final(s);
+// if (f != LatticeWeight::Zero()) {
+// // Set final acoustic cost to 0.0
+// f.SetValue2(0.0);
+// lat->SetFinal(s, f);
+// }
+// }
+//}
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions.h b/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions.h
new file mode 100644
index 000000000..6b1b6656c
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/lattice-functions.h
@@ -0,0 +1,455 @@
+// lat/lattice-functions.h
+
+// Copyright 2009-2012 Saarland University (author: Arnab Ghoshal)
+// 2012-2013 Johns Hopkins University (Author: Daniel Povey);
+// Bagher BabaAli
+// 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_LAT_LATTICE_FUNCTIONS_H_
+#define KALDI_LAT_LATTICE_FUNCTIONS_H_
+
+#include <vector>
+#include <map>
+
+#include "base/kaldi-common.h"
+// #include "hmm/posterior.h"
+#include "fstext/fstext-lib.h"
+// #include "hmm/transition-model.h"
+#include "lat/kaldi-lattice.h"
+// #include "itf/decodable-itf.h"
+
+namespace kaldi {
+
+// /**
+// This function extracts the per-frame log likelihoods from a linear
+// lattice (which we refer to as an 'nbest' lattice elsewhere in Kaldi code).
+// The dimension of *per_frame_loglikes will be set to the
+// number of input symbols in 'nbest'. The elements of
+// '*per_frame_loglikes' will be set to the .Value2() elements of the lattice
+// weights, which represent the acoustic costs; you may want to scale this
+// vector afterward by -1/acoustic_scale to get the original loglikes.
+// If there are acoustic costs on input-epsilon arcs or the final-prob in 'nbest'
+// (and this should not normally be the case in situations where it makes
+// sense to call this function), they will be included to the cost of the
+// preceding input symbol, or the following input symbol for input-epsilons
+// encountered prior to any input symbol. If 'nbest' has no input symbols,
+// 'per_frame_loglikes' will be set to the empty vector.
+// **/
+// void GetPerFrameAcousticCosts(const Lattice &nbest,
+// Vector<BaseFloat> *per_frame_loglikes);
+//
+// /// This function iterates over the states of a topologically sorted lattice and
+// /// counts the time instance corresponding to each state. The times are returned
+// /// in a vector of integers 'times' which is resized to have a size equal to the
+// /// number of states in the lattice. The function also returns the maximum time
+// /// in the lattice (this will equal the number of frames in the file).
+// int32 LatticeStateTimes(const Lattice &lat, std::vector<int32> *times);
+//
+// /// As LatticeStateTimes, but in the CompactLattice format. Note: must
+// /// be topologically sorted. Returns length of the utterance in frames, which
+// /// might not be the same as the maximum time in the lattice, due to frames
+// /// in the final-prob.
+// int32 CompactLatticeStateTimes(const CompactLattice &clat,
+// std::vector<int32> *times);
+//
+// /// This function does the forward-backward over lattices and computes the
+// /// posterior probabilities of the arcs. It returns the total log-probability
+// /// of the lattice. The Posterior quantities contain pairs of (transition-id, weight)
+// /// on each frame.
+// /// If the pointer "acoustic_like_sum" is provided, this value is set to
+// /// the sum over the arcs, of the posterior of the arc times the
+// /// acoustic likelihood [i.e. negated acoustic score] on that link.
+// /// This is used in combination with other quantities to work out
+// /// the objective function in MMI discriminative training.
+// BaseFloat LatticeForwardBackward(const Lattice &lat,
+// Posterior *arc_post,
+// double *acoustic_like_sum = NULL);
+//
+// // This function is something similar to LatticeForwardBackward(), but it is on
+// // the CompactLattice lattice format. Also we only need the alpha in the forward
+// // path, not the posteriors.
+// bool ComputeCompactLatticeAlphas(const CompactLattice &lat,
+// std::vector<double> *alpha);
+//
+// // A sibling of the function CompactLatticeAlphas()... We compute the beta from
+// // the backward path here.
+// bool ComputeCompactLatticeBetas(const CompactLattice &lat,
+// std::vector<double> *beta);
+//
+//
+// // Computes (normal or Viterbi) alphas and betas; returns (total-prob, or
+// // best-path negated cost) Note: in either case, the alphas and betas are
+// // negated costs. Requires that lat be topologically sorted. This code
+// // will work for either CompactLattice or Latice.
+// template<typename LatticeType>
+// double ComputeLatticeAlphasAndBetas(const LatticeType &lat,
+// bool viterbi,
+// std::vector<double> *alpha,
+// std::vector<double> *beta);
+//
+//
+// /// Topologically sort the compact lattice if not already topologically sorted.
+// /// Will crash if the lattice cannot be topologically sorted.
+// void TopSortCompactLatticeIfNeeded(CompactLattice *clat);
+//
+//
+// /// Topologically sort the lattice if not already topologically sorted.
+// /// Will crash if lattice cannot be topologically sorted.
+// void TopSortLatticeIfNeeded(Lattice *clat);
+//
+// /// Returns the depth of the lattice, defined as the average number of arcs (or
+// /// final-prob strings) crossing any given frame. Returns 1 for empty lattices.
+// /// Requires that clat is topologically sorted!
+// BaseFloat CompactLatticeDepth(const CompactLattice &clat,
+// int32 *num_frames = NULL);
+//
+// /// This function returns, for each frame, the number of arcs crossing that
+// /// frame.
+// void CompactLatticeDepthPerFrame(const CompactLattice &clat,
+// std::vector<int32> *depth_per_frame);
+//
+//
+// /// This function limits the depth of the lattice, per frame: that means, it
+// /// does not allow more than a specified number of arcs active on any given
+// /// frame. This can be used to reduce the size of the "very deep" portions of
+// /// the lattice.
+// void CompactLatticeLimitDepth(int32 max_arcs_per_frame,
+// CompactLattice *clat);
+//
+//
+// /// Given a lattice, and a transition model to map pdf-ids to phones,
+// /// outputs for each frame the set of phones active on that frame. If
+// /// sil_phones (which must be sorted and uniq) is nonempty, it excludes
+// /// phones in this list.
+// void LatticeActivePhones(const Lattice &lat, const TransitionModel &trans,
+// const std::vector<int32> &sil_phones,
+// std::vector<std::set<int32> > *active_phones);
+//
+// /// Given a lattice, and a transition model to map pdf-ids to phones,
+// /// replace the output symbols (presumably words), with phones; we
+// /// use the TransitionModel to work out the phone sequence. Note
+// /// that the phone labels are not exactly aligned with the phone
+// /// boundaries. We put a phone label to coincide with any transition
+// /// to the final, nonemitting state of a phone (this state always exists,
+// /// we ensure this in HmmTopology::Check()). This would be the last
+// /// transition-id in the phone if reordering is not done (but typically
+// /// we do reorder).
+// /// Also see PhoneAlignLattice, in phone-align-lattice.h.
+// void ConvertLatticeToPhones(const TransitionModel &trans_model,
+// Lattice *lat);
+
+/// Prunes a lattice or compact lattice. Returns true on success, false if
+/// there was some kind of failure.
+template<class LatticeType>
+bool PruneLattice(BaseFloat beam, LatticeType *lat);
+
+//
+// /// Given a lattice, and a transition model to map pdf-ids to phones,
+// /// replace the sequences of transition-ids with sequences of phones.
+// /// Note that this is different from ConvertLatticeToPhones, in that
+// /// we replace the transition-ids not the words.
+// void ConvertCompactLatticeToPhones(const TransitionModel &trans_model,
+// CompactLattice *clat);
+//
+// /// Boosts LM probabilities by b * [number of frame errors]; equivalently, adds
+// /// -b*[number of frame errors] to the graph-component of the cost of each arc/path.
+// /// There is a frame error if a particular transition-id on a particular frame
+// /// corresponds to a phone not matching transcription's alignment for that frame.
+// /// This is used in "margin-inspired" discriminative training, esp. Boosted MMI.
+// /// The TransitionModel is used to map transition-ids in the lattice
+// /// input-side to phones; the phones appearing in
+// /// "silence_phones" are treated specially in that we replace the frame error f
+// /// (either zero or 1) for a frame, with the minimum of f or max_silence_error.
+// /// For the normal recipe, max_silence_error would be zero.
+// /// Returns true on success, false if there was some kind of mismatch.
+// /// At input, silence_phones must be sorted and unique.
+// bool LatticeBoost(const TransitionModel &trans,
+// const std::vector<int32> &alignment,
+// const std::vector<int32> &silence_phones,
+// BaseFloat b,
+// BaseFloat max_silence_error,
+// Lattice *lat);
+//
+//
+// /**
+// This function implements either the MPFE (minimum phone frame error) or SMBR
+// (state-level minimum bayes risk) forward-backward, depending on whether
+// "criterion" is "mpfe" or "smbr". It returns the MPFE
+// criterion of SMBR criterion for this utterance, and outputs the posteriors (which
+// may be positive or negative) into "post".
+//
+// @param [in] trans The transition model. Used to map the
+// transition-ids to phones or pdfs.
+// @param [in] silence_phones A list of integer ids of silence phones. The
+// silence frames i.e. the frames where num_ali
+// corresponds to a silence phones are treated specially.
+// The behavior is determined by 'one_silence_class'
+// being false (traditional behavior) or true.
+// Usually in our setup, several phones including
+// the silence, vocalized noise, non-spoken noise
+// and unk are treated as "silence phones"
+// @param [in] lat The denominator lattice
+// @param [in] num_ali The numerator alignment
+// @param [in] criterion The objective function. Must be "mpfe" or "smbr"
+// for MPFE (minimum phone frame error) or sMBR
+// (state minimum bayes risk) training.
+// @param [in] one_silence_class Determines how the silence frames are treated.
+// Setting this to false gives the old traditional behavior,
+// where the silence frames (according to num_ali) are
+// treated as incorrect. However, this means that the
+// insertions are not penalized by the objective.
+// Setting this to true gives the new behaviour, where we
+// treat silence as any other phone, except that all pdfs
+// of silence phones are collapsed into a single class for
+// the frame-error computation. This can possible reduce
+// the insertions in the trained model. This is closer to
+// the WER metric that we actually care about, since WER is
+// generally computed after filtering out noises, but
+// does penalize insertions.
+// @param [out] post The "MBR posteriors" i.e. derivatives w.r.t to the
+// pseudo log-likelihoods of states at each frame.
+// */
+// BaseFloat LatticeForwardBackwardMpeVariants(
+// const TransitionModel &trans,
+// const std::vector<int32> &silence_phones,
+// const Lattice &lat,
+// const std::vector<int32> &num_ali,
+// std::string criterion,
+// bool one_silence_class,
+// Posterior *post);
+//
+// /**
+// This function can be used to compute posteriors for MMI, with a positive contribution
+// for the numerator and a negative one for the denominator. This function is not actually
+// used in our normal MMI training recipes, where it's instead done using various command
+// line programs that each do a part of the job. This function was written for use in
+// neural-net MMI training.
+//
+// @param [in] trans The transition model. Used to map the
+// transition-ids to phones or pdfs.
+// @param [in] lat The denominator lattice
+// @param [in] num_ali The numerator alignment
+// @param [in] drop_frames If "drop_frames" is true, it will not compute any
+// posteriors on frames where the num and den have disjoint
+// pdf-ids.
+// @param [in] convert_to_pdf_ids If "convert_to_pdfs_ids" is true, it will
+// convert the output to be at the level of pdf-ids, not
+// transition-ids.
+// @param [in] cancel If "cancel" is true, it will cancel out any positive and
+// negative parts from the same transition-id (or pdf-id,
+// if convert_to_pdf_ids == true).
+// @param [out] arc_post The output MMI posteriors of transition-ids (or
+// pdf-ids if convert_to_pdf_ids == true) at each frame
+// i.e. the difference between the numerator
+// and denominator posteriors.
+//
+// It returns the forward-backward likelihood of the lattice. */
+// BaseFloat LatticeForwardBackwardMmi(
+// const TransitionModel &trans,
+// const Lattice &lat,
+// const std::vector<int32> &num_ali,
+// bool drop_frames,
+// bool convert_to_pdf_ids,
+// bool cancel,
+// Posterior *arc_post);
+//
+//
+// /// This function takes a CompactLattice that should only contain a single
+// /// linear sequence (e.g. derived from lattice-1best), and that should have been
+// /// processed so that the arcs in the CompactLattice align correctly with the
+// /// word boundaries (e.g. by lattice-align-words). It outputs 3 vectors of the
+// /// same size, which give, for each word in the lattice (in sequence), the word
+// /// label and the begin time and length in frames. This is done even for zero
+// /// (epsilon) words, generally corresponding to optional silence-- if you don't
+// /// want them, just ignore them in the output.
+// /// This function will print a warning and return false, if the lattice
+// /// did not have the correct format (e.g. if it is empty or it is not
+// /// linear).
+// bool CompactLatticeToWordAlignment(const CompactLattice &clat,
+// std::vector<int32> *words,
+// std::vector<int32> *begin_times,
+// std::vector<int32> *lengths);
+//
+// /// This function takes a CompactLattice that should only contain a single
+// /// linear sequence (e.g. derived from lattice-1best), and that should have been
+// /// processed so that the arcs in the CompactLattice align correctly with the
+// /// word boundaries (e.g. by lattice-align-words). It outputs 4 vectors of the
+// /// same size, which give, for each word in the lattice (in sequence), the word
+// /// label, the begin time and length in frames, and the pronunciation (sequence
+// /// of phones). This is done even for zero words, corresponding to optional
+// /// silences -- if you don't want them, just ignore them in the output.
+// /// This function will print a warning and return false, if the lattice
+// /// did not have the correct format (e.g. if it is empty or it is not
+// /// linear).
+// bool CompactLatticeToWordProns(
+// const TransitionModel &tmodel,
+// const CompactLattice &clat,
+// std::vector<int32> *words,
+// std::vector<int32> *begin_times,
+// std::vector<int32> *lengths,
+// std::vector<std::vector<int32> > *prons,
+// std::vector<std::vector<int32> > *phone_lengths);
+//
+//
+// /// A form of the shortest-path/best-path algorithm that's specially coded for
+// /// CompactLattice. Requires that clat be acyclic.
+// void CompactLatticeShortestPath(const CompactLattice &clat,
+// CompactLattice *shortest_path);
+//
+// /// This function expands a CompactLattice to ensure high-probability paths
+// /// have unique histories. Arcs with posteriors larger than epsilon get splitted.
+// void ExpandCompactLattice(const CompactLattice &clat,
+// double epsilon,
+// CompactLattice *expand_clat);
+//
+// /// For each state, compute forward and backward best (viterbi) costs and its
+// /// traceback states (for generating best paths later). The forward best cost
+// /// for a state is the cost of the best path from the start state to the state.
+// /// The traceback state of this state is its predecessor state in the best path.
+// /// The backward best cost for a state is the cost of the best path from the
+// /// state to a final one. Its traceback state is the successor state in the best
+// /// path in the forward direction.
+// /// Note: final weights of states are in backward_best_cost_and_pred.
+// /// Requires the input CompactLattice clat be acyclic.
+// typedef std::vector<std::pair<double,
+// CompactLatticeArc::StateId> > CostTraceType;
+// void CompactLatticeBestCostsAndTracebacks(
+// const CompactLattice &clat,
+// CostTraceType *forward_best_cost_and_pred,
+// CostTraceType *backward_best_cost_and_pred);
+//
+// /// This function adds estimated neural language model scores of words in a
+// /// minimal list of hypotheses that covers a lattice, to the graph scores on the
+// /// arcs. The list of hypotheses are generated by latbin/lattice-path-cover.
+// typedef unordered_map<std::pair<int32, int32>, double, PairHasher<int32> > MapT;
+// void AddNnlmScoreToCompactLattice(const MapT &nnlm_scores,
+// CompactLattice *clat);
+//
+// /// This function add the word insertion penalty to graph score of each word
+// /// in the compact lattice
+// void AddWordInsPenToCompactLattice(BaseFloat word_ins_penalty,
+// CompactLattice *clat);
+//
+// /// This function *adds* the negated scores obtained from the Decodable object,
+// /// to the acoustic scores on the arcs. If you want to replace them, you should
+// /// use ScaleCompactLattice to first set the acoustic scores to zero. Returns
+// /// true on success, false on error (typically some kind of mismatched inputs).
+// bool RescoreCompactLattice(DecodableInterface *decodable,
+// CompactLattice *clat);
+//
+//
+// /// This function returns the number of words in the longest sentence in a
+// /// CompactLattice (i.e. the the maximum of any path, of the count of
+// /// olabels on that path).
+// int32 LongestSentenceLength(const Lattice &lat);
+//
+// /// This function returns the number of words in the longest sentence in a
+// /// CompactLattice, i.e. the the maximum of any path, of the count of
+// /// labels on that path... note, in CompactLattice, the ilabels and olabels
+// /// are identical because it is an acceptor.
+// int32 LongestSentenceLength(const CompactLattice &lat);
+//
+//
+// /// This function is like RescoreCompactLattice, but it is modified to avoid
+// /// computing probabilities on most frames where all the pdf-ids are the same.
+// /// (it needs the transition-model to work out whether two transition-ids map to
+// /// the same pdf-id, and it assumes that the lattice has transition-ids on it).
+// /// The naive thing would be to just set all probabilities to zero on frames
+// /// where all the pdf-ids are the same (because this value won't affect the
+// /// lattice posterior). But this would become confusing when we compute
+// /// corpus-level diagnostics such as the MMI objective function. Instead,
+// /// imagine speedup_factor = 100 (it must be >= 1.0)... with probability (1.0 /
+// /// speedup_factor) we compute those likelihoods and multiply them by
+// /// speedup_factor; otherwise we set them to zero. This gives the right
+// /// expected probability so our corpus-level diagnostics will be about right.
+// bool RescoreCompactLatticeSpeedup(
+// const TransitionModel &tmodel,
+// BaseFloat speedup_factor,
+// DecodableInterface *decodable,
+// CompactLattice *clat);
+//
+//
+// /// This function *adds* the negated scores obtained from the Decodable object,
+// /// to the acoustic scores on the arcs. If you want to replace them, you should
+// /// use ScaleCompactLattice to first set the acoustic scores to zero. Returns
+// /// true on success, false on error (e.g. some kind of mismatched inputs).
+// /// The input labels, if nonzero, are interpreted as transition-ids or whatever
+// /// other index the Decodable object expects.
+// bool RescoreLattice(DecodableInterface *decodable,
+// Lattice *lat);
+//
+// /// This function Composes a CompactLattice format lattice with a
+// /// DeterministicOnDemandFst<fst::StdFst> format fst, and outputs another
+// /// CompactLattice format lattice. The first element (the one that corresponds
+// /// to LM weight) in CompactLatticeWeight is used for composition.
+// ///
+// /// Note that the DeterministicOnDemandFst interface is not "const", therefore
+// /// we cannot use "const" for <det_fst>.
+// void ComposeCompactLatticeDeterministic(
+// const CompactLattice& clat,
+// fst::DeterministicOnDemandFst<fst::StdArc>* det_fst,
+// CompactLattice* composed_clat);
+//
+// /// This function computes the mapping from the pair
+// /// (frame-index, transition-id) to the pair
+// /// (sum-of-acoustic-scores, num-of-occurences) over all occurences of the
+// /// transition-id in that frame.
+// /// frame-index in the lattice.
+// /// This function is useful for retaining the acoustic scores in a
+// /// non-compact lattice after a process like determinization where the
+// /// frame-level acoustic scores are typically lost.
+// /// The function ReplaceAcousticScoresFromMap is used to restore the
+// /// acoustic scores computed by this function.
+// ///
+// /// @param [in] lat Input lattice. Expected to be top-sorted. Otherwise the
+// /// function will crash.
+// /// @param [out] acoustic_scores
+// /// Pointer to a map from the pair (frame-index,
+// /// transition-id) to a pair (sum-of-acoustic-scores,
+// /// num-of-occurences).
+// /// Usually the acoustic scores for a pdf-id (and hence
+// /// transition-id) on a frame will be the same for all the
+// /// occurences of the pdf-id in that frame.
+// /// But if not, we will take the average of the acoustic
+// /// scores. Hence, we store both the sum-of-acoustic-scores
+// /// and the num-of-occurences of the transition-id in that
+// /// frame.
+// void ComputeAcousticScoresMap(
+// const Lattice &lat,
+// unordered_map<std::pair<int32, int32>, std::pair<BaseFloat, int32>,
+// PairHasher<int32> > *acoustic_scores);
+//
+// /// This function restores acoustic scores computed using the function
+// /// ComputeAcousticScoresMap into the lattice.
+// ///
+// /// @param [in] acoustic_scores
+// /// A map from the pair (frame-index, transition-id) to a
+// /// pair (sum-of-acoustic-scores, num-of-occurences) of
+// /// the occurences of the transition-id in that frame.
+// /// See the comments for ComputeAcousticScoresMap for
+// /// details.
+// /// @param [out] lat Pointer to the output lattice.
+// void ReplaceAcousticScoresFromMap(
+// const unordered_map<std::pair<int32, int32>, std::pair<BaseFloat, int32>,
+// PairHasher<int32> > &acoustic_scores,
+// Lattice *lat);
+
+} // namespace kaldi
+
+#endif // KALDI_LAT_LATTICE_FUNCTIONS_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/phone-align-lattice.cc b/runtime/onnxruntime/third_party/kaldi/lat/phone-align-lattice.cc
new file mode 100644
index 000000000..626d72a82
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/phone-align-lattice.cc
@@ -0,0 +1,421 @@
+// lat/phone-align-lattice.cc
+
+// Copyright 2012-2013 Microsoft Corporation
+// Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "lat/phone-align-lattice.h"
+#include "util/stl-utils.h"
+
+namespace kaldi {
+
+class LatticePhoneAligner {
+ public:
+ typedef CompactLatticeArc::StateId StateId;
+ typedef CompactLatticeArc::Label Label;
+
+ class ComputationState { /// The state of the computation in which,
+ /// along a single path in the lattice, we work out the phone
+ /// boundaries and output phone-aligned arcs. [These may or may not have
+ /// words on them; the word symbols are not aligned with anything.
+ public:
+
+ /// Advance the computation state by adding the symbols and weights
+ /// from this arc. Gets rid of the weight and puts it in "weight" which
+ /// will be put on the output arc; this keeps the state-space small.
+ void Advance(const CompactLatticeArc &arc, const PhoneAlignLatticeOptions &opts,
+ LatticeWeight *weight) {
+ const std::vector<int32> &string = arc.weight.String();
+ transition_ids_.insert(transition_ids_.end(),
+ string.begin(), string.end());
+ if (arc.ilabel != 0 && !opts.replace_output_symbols) // note: arc.ilabel==arc.olabel (acceptor)
+ word_labels_.push_back(arc.ilabel);
+ *weight = Times(weight_, arc.weight.Weight());
+ weight_ = LatticeWeight::One();
+ }
+
+ /// If it can output a whole phone, it will do so, will put it in arc_out,
+ /// and return true; else it will return false. If it detects an error
+ /// condition and *error = false, it will set *error to true and print
+ /// a warning. In this case it will still output phone arcs, they will
+ /// just be inaccurate. Of course once *error is set, something has gone
+ /// wrong so don't trust the output too fully.
+ /// Note: the "next_state" of the arc will not be set, you have to do that
+ /// yourself.
+ bool OutputPhoneArc(const TransitionInformation &tmodel,
+ const PhoneAlignLatticeOptions &opts,
+ CompactLatticeArc *arc_out,
+ bool *error);
+
+ /// This will succeed (and output the arc) if we have >1 word in words_;
+ /// the arc won't have any transition-ids on it. This is intended to fix
+ /// a particular pathology where too many words were pending and we had
+ /// blowup.
+ bool OutputWordArc(const TransitionInformation &tmodel,
+ const PhoneAlignLatticeOptions &opts,
+ CompactLatticeArc *arc_out,
+ bool *error);
+
+ bool IsEmpty() { return (transition_ids_.empty() && word_labels_.empty()); }
+
+ /// FinalWeight() will return "weight" if both transition_ids
+ /// and word_labels are empty, otherwise it will return
+ /// Weight::Zero().
+ LatticeWeight FinalWeight() { return (IsEmpty() ? weight_ : LatticeWeight::Zero()); }
+
+ /// This function may be called when you reach the end of
+ /// the lattice and this structure hasn't voluntarily
+ /// output words using "OutputArc". If IsEmpty() == false,
+ /// then you can call this function and it will output
+ /// an arc. The only
+ /// non-error state in which this happens, is when a word
+ /// (or silence) has ended, but we don't know that it's
+ /// ended because we haven't seen the first transition-id
+ /// from the next word. Otherwise (error state), the output
+ /// will consist of partial words, and this will only
+ /// happen for lattices that were somehow broken, i.e.
+ /// had not reached the final state.
+ void OutputArcForce(const TransitionInformation &tmodel,
+ const PhoneAlignLatticeOptions &opts,
+ CompactLatticeArc *arc_out,
+ bool *error);
+
+ size_t Hash() const {
+ VectorHasher<int32> vh;
+ return vh(transition_ids_) + 90647 * vh(word_labels_);
+ // 90647 is an arbitrary largish prime number.
+ // We don't bother including the weight in the hash--
+ // we don't really expect duplicates with the same vectors
+ // but different weights, and anyway, this is only an
+ // efficiency issue.
+ }
+
+ // Just need an arbitrary complete order.
+ bool operator == (const ComputationState &other) const {
+ return (transition_ids_ == other.transition_ids_
+ && word_labels_ == other.word_labels_
+ && weight_ == other.weight_);
+ }
+
+ ComputationState(): weight_(LatticeWeight::One()) { } // initial state.
+ ComputationState(const ComputationState &other):
+ transition_ids_(other.transition_ids_), word_labels_(other.word_labels_),
+ weight_(other.weight_) { }
+ private:
+ std::vector<int32> transition_ids_;
+ std::vector<int32> word_labels_;
+ LatticeWeight weight_; // contains two floats.
+ };
+
+
+ struct Tuple {
+ Tuple(StateId input_state, ComputationState comp_state):
+ input_state(input_state), comp_state(comp_state) {}
+ StateId input_state;
+ ComputationState comp_state;
+ };
+
+ struct TupleHash {
+ size_t operator() (const Tuple &state) const {
+ return state.input_state + 102763 * state.comp_state.Hash();
+ // 102763 is just an arbitrary prime number
+ }
+ };
+ struct TupleEqual {
+ bool operator () (const Tuple &state1, const Tuple &state2) const {
+ // treat this like operator ==
+ return (state1.input_state == state2.input_state
+ && state1.comp_state == state2.comp_state);
+ }
+ };
+
+ typedef unordered_map<Tuple, StateId, TupleHash, TupleEqual> MapType;
+
+ StateId GetStateForTuple(const Tuple &tuple, bool add_to_queue) {
+ MapType::iterator iter = map_.find(tuple);
+ if (iter == map_.end()) { // not in map.
+ StateId output_state = lat_out_->AddState();
+ map_[tuple] = output_state;
+ if (add_to_queue)
+ queue_.push_back(std::make_pair(tuple, output_state));
+ return output_state;
+ } else {
+ return iter->second;
+ }
+ }
+
+ void ProcessFinal(Tuple tuple, StateId output_state) {
+ // ProcessFinal is only called if the input_state has
+ // final-prob of One(). [else it should be zero. This
+ // is because we called CreateSuperFinal().]
+
+ if (tuple.comp_state.IsEmpty()) { // computation state doesn't have
+ // anything pending.
+ std::vector<int32> empty_vec;
+ CompactLatticeWeight cw(tuple.comp_state.FinalWeight(), empty_vec);
+ lat_out_->SetFinal(output_state, Plus(lat_out_->Final(output_state), cw));
+ } else {
+ // computation state has something pending, i.e. input or
+ // output symbols that need to be flushed out. Note: OutputArc() would
+ // have returned false or we wouldn't have been called, so we have to
+ // force it out.
+ CompactLatticeArc lat_arc;
+ // Note: the next call will change the computation-state of the tuple,
+ // so it becomes a different tuple.
+ tuple.comp_state.OutputArcForce(tmodel_, opts_, &lat_arc, &error_);
+ lat_arc.nextstate = GetStateForTuple(tuple, true); // true == add to queue.
+ // The final-prob stuff will get called again from ProcessQueueElement().
+ // Note: because we did CreateSuperFinal(), this final-state on the input
+ // lattice will have no output arcs (and unit final-prob), so there will be
+ // no complications with processing the arcs from this state (there won't
+ // be any).
+ KALDI_ASSERT(output_state != lat_arc.nextstate);
+ lat_out_->AddArc(output_state, lat_arc);
+ }
+ }
+
+
+ void ProcessQueueElement() {
+ KALDI_ASSERT(!queue_.empty());
+ Tuple tuple = queue_.back().first;
+ StateId output_state = queue_.back().second;
+ queue_.pop_back();
+
+ // First thing is-- we see whether the computation-state has something
+ // pending that it wants to output. In this case we don't do
+ // anything further. This is a chosen behavior similar to the
+ // epsilon-sequencing rules encoded by the filters in
+ // composition.
+ CompactLatticeArc lat_arc;
+ if (tuple.comp_state.OutputPhoneArc(tmodel_, opts_, &lat_arc, &error_) ||
+ tuple.comp_state.OutputWordArc(tmodel_, opts_, &lat_arc, &error_)) {
+ // note: the functions OutputPhoneArc() and OutputWordArc() change the
+ // tuple (when they return true).
+ lat_arc.nextstate = GetStateForTuple(tuple, true); // true == add to
+ // queue, if not
+ // already present.
+ KALDI_ASSERT(output_state != lat_arc.nextstate);
+ lat_out_->AddArc(output_state, lat_arc);
+ } else {
+ // when there's nothing to output, we'll process arcs from the input-state.
+ // note: it would in a sense be valid to do both (i.e. process the stuff
+ // above, and also these), but this is a bit like the epsilon-sequencing
+ // stuff in composition: we avoid duplicate arcs by doing it this way.
+
+ if (lat_.Final(tuple.input_state) != CompactLatticeWeight::Zero()) {
+ KALDI_ASSERT(lat_.Final(tuple.input_state) == CompactLatticeWeight::One());
+ // ... since we did CreateSuperFinal.
+ ProcessFinal(tuple, output_state);
+ }
+ // Now process the arcs. Note: final-states shouldn't have any arcs.
+ for(fst::ArcIterator<CompactLattice> aiter(lat_, tuple.input_state);
+ !aiter.Done(); aiter.Next()) {
+ const CompactLatticeArc &arc = aiter.Value();
+ Tuple next_tuple(tuple);
+ LatticeWeight weight;
+ next_tuple.comp_state.Advance(arc, opts_, &weight);
+ next_tuple.input_state = arc.nextstate;
+ StateId next_output_state = GetStateForTuple(next_tuple, true); // true == add to queue,
+ // if not already present.
+ // We add an epsilon arc here (as the input and output happens
+ // separately)... the epsilons will get removed later.
+ KALDI_ASSERT(next_output_state != output_state);
+ lat_out_->AddArc(output_state,
+ CompactLatticeArc(0, 0,
+ CompactLatticeWeight(weight, std::vector<int32>()),
+ next_output_state));
+ }
+ }
+ }
+
+ LatticePhoneAligner(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const PhoneAlignLatticeOptions &opts,
+ CompactLattice *lat_out):
+ lat_(lat), tmodel_(tmodel), opts_(opts), lat_out_(lat_out),
+ error_(false) {
+ fst::CreateSuperFinal(&lat_); // Creates a super-final state, so the
+ // only final-probs are One().
+ }
+
+ // Removes epsilons; also removes unreachable states...
+ // not sure if these would exist if original was connected.
+ // This also replaces the temporary symbols for the silence
+ // and partial-words, with epsilons, if we wanted epsilons.
+ void RemoveEpsilonsFromLattice() {
+ RmEpsilon(lat_out_, true); // true = connect.
+ }
+
+ bool AlignLattice() {
+ lat_out_->DeleteStates();
+ if (lat_.Start() == fst::kNoStateId) {
+ KALDI_WARN << "Trying to word-align empty lattice.";
+ return false;
+ }
+ ComputationState initial_comp_state;
+ Tuple initial_tuple(lat_.Start(), initial_comp_state);
+ StateId start_state = GetStateForTuple(initial_tuple, true); // True = add this to queue.
+ lat_out_->SetStart(start_state);
+
+ while (!queue_.empty())
+ ProcessQueueElement();
+
+ if (opts_.remove_epsilon)
+ RemoveEpsilonsFromLattice();
+
+ return !error_;
+ }
+
+ CompactLattice lat_;
+ const TransitionInformation &tmodel_;
+ const PhoneAlignLatticeOptions &opts_;
+ CompactLattice *lat_out_;
+
+ std::vector<std::pair<Tuple, StateId> > queue_;
+ MapType map_; // map from tuples to StateId.
+ bool error_;
+};
+
+bool LatticePhoneAligner::ComputationState::OutputPhoneArc(
+ const TransitionInformation &tmodel,
+ const PhoneAlignLatticeOptions &opts,
+ CompactLatticeArc *arc_out,
+ bool *error) {
+ if (transition_ids_.empty()) return false;
+ int32 phone = tmodel.TransitionIdToPhone(transition_ids_[0]);
+ // we assume the start of transition_ids_ is the start of the phone;
+ // this is a precondition.
+ size_t len = transition_ids_.size(), i;
+ // Keep going till we reach a "final" transition-id; note, if
+ // reorder==true, we have to go a bit further after this.
+ for (i = 0; i < len; i++) {
+ int32 tid = transition_ids_[i];
+ int32 this_phone = tmodel.TransitionIdToPhone(tid);
+ if (this_phone != phone && ! *error) { // error condition: should have
+ // reached final transition-id first.
+ *error = true;
+ KALDI_WARN << phone << " -> " << this_phone;
+ KALDI_WARN << "Phone changed before final transition-id found "
+ "[broken lattice or mismatched model or wrong --reorder option?]";
+ }
+ if (tmodel.IsFinal(tid))
+ break;
+ }
+ if (i == len) return false; // fell off loop.
+ i++; // go past the one for which IsFinal returned true.
+ if (opts.reorder) // we have to consume the following self-loop transition-ids.
+ while (i < len && tmodel.IsSelfLoop(transition_ids_[i])) i++;
+ if (i == len) return false; // we don't know if it ends here... so can't output arc.
+
+ // interpret i as the number of transition-ids to consume.
+ std::vector<int32> tids_out(transition_ids_.begin(),
+ transition_ids_.begin()+i);
+
+ Label output_label = 0;
+ if (!word_labels_.empty()) {
+ output_label = word_labels_[0];
+ word_labels_.erase(word_labels_.begin(), word_labels_.begin()+1);
+ }
+ if (opts.replace_output_symbols)
+ output_label = phone;
+ *arc_out = CompactLatticeArc(output_label, output_label,
+ CompactLatticeWeight(weight_, tids_out),
+ fst::kNoStateId);
+ transition_ids_.erase(transition_ids_.begin(), transition_ids_.begin()+i);
+ weight_ = LatticeWeight::One(); // we just output the weight.
+ return true;
+}
+
+bool LatticePhoneAligner::ComputationState::OutputWordArc(
+ const TransitionInformation &tmodel,
+ const PhoneAlignLatticeOptions &opts,
+ CompactLatticeArc *arc_out,
+ bool *error) {
+ // output a word but no phones.
+ if (word_labels_.size() < 2) return false;
+
+ int32 output_label = word_labels_[0];
+ word_labels_.erase(word_labels_.begin(), word_labels_.begin()+1);
+
+ *arc_out = CompactLatticeArc(output_label, output_label,
+ CompactLatticeWeight(weight_, std::vector<int32>()),
+ fst::kNoStateId);
+ weight_ = LatticeWeight::One(); // we just output the weight, so set it to one.
+ return true;
+}
+
+
+void LatticePhoneAligner::ComputationState::OutputArcForce(
+ const TransitionInformation &tmodel,
+ const PhoneAlignLatticeOptions &opts,
+ CompactLatticeArc *arc_out,
+ bool *error) {
+ KALDI_ASSERT(!IsEmpty());
+
+ int32 phone = -1; // This value -1 will never be used,
+ // although it might not be obvious from superficially checking
+ // the code. IsEmpty() would be true if we had transition_ids_.empty()
+ // and opts.replace_output_symbols, so we would already die by assertion;
+ // in fact, this function would never be called.
+
+ if (!transition_ids_.empty()) { // Do some checking here.
+ int32 tid = transition_ids_[0];
+ phone = tmodel.TransitionIdToPhone(tid);
+ int32 num_final = 0;
+ for (int32 i = 0; i < transition_ids_.size(); i++) { // A check.
+ int32 this_tid = transition_ids_[i];
+ int32 this_phone = tmodel.TransitionIdToPhone(this_tid);
+ bool is_final = tmodel.IsFinal(this_tid); // should be exactly one.
+ if (is_final) num_final++;
+ if (this_phone != phone && ! *error) {
+ KALDI_WARN << "Mismatch in phone: error in lattice or mismatched transition model?";
+ *error = true;
+ }
+ }
+ if (num_final != 1 && ! *error) {
+ KALDI_WARN << "Problem phone-aligning lattice: saw " << num_final
+ << " final-states in last phone in lattice (forced out?) "
+ << "Producing partial lattice.";
+ *error = true;
+ }
+ }
+
+ Label output_label = 0;
+ if (!word_labels_.empty()) {
+ output_label = word_labels_[0];
+ word_labels_.erase(word_labels_.begin(), word_labels_.begin()+1);
+ }
+ if (opts.replace_output_symbols)
+ output_label = phone;
+ *arc_out = CompactLatticeArc(output_label, output_label,
+ CompactLatticeWeight(weight_, transition_ids_),
+ fst::kNoStateId);
+ transition_ids_.clear();
+ weight_ = LatticeWeight::One(); // we just output the weight.
+}
+
+bool PhoneAlignLattice(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const PhoneAlignLatticeOptions &opts,
+ CompactLattice *lat_out) {
+ LatticePhoneAligner aligner(lat, tmodel, opts, lat_out);
+ return aligner.AlignLattice();
+}
+
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/phone-align-lattice.h b/runtime/onnxruntime/third_party/kaldi/lat/phone-align-lattice.h
new file mode 100644
index 000000000..e4529f9ac
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/phone-align-lattice.h
@@ -0,0 +1,68 @@
+// lat/phone-align-lattice.h
+
+// Copyright 2009-2012 Microsoft Corporation Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_LAT_PHONE_ALIGN_LATTICE_H_
+#define KALDI_LAT_PHONE_ALIGN_LATTICE_H_
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fstext/fstext-lib.h"
+#include "itf/transition-information.h"
+#include "lat/kaldi-lattice.h"
+
+namespace kaldi {
+
+
+struct PhoneAlignLatticeOptions {
+ bool reorder;
+ bool remove_epsilon;
+ bool replace_output_symbols;
+ PhoneAlignLatticeOptions(): reorder(true),
+ remove_epsilon(true),
+ replace_output_symbols(false) { }
+ void Register(OptionsItf *opts) {
+ opts->Register("reorder", &reorder, "True if lattice was created from HCLG with "
+ "--reorder=true option.");
+ opts->Register("remove-epsilon", &remove_epsilon, "If true, removes epsilons from "
+ "the phone lattice; if replace-output-symbols==false, this will "
+ "mean that an arc can have multiple phones on it.");
+ opts->Register("replace-output-symbols", &replace_output_symbols, "If true, "
+ "the output symbols (typically words) will be replaced with "
+ "phones.");
+ }
+};
+
+/// Outputs a lattice in which the arcs correspond exactly to sequences of
+/// phones, so the boundaries between the arcs correspond to the boundaries
+/// between phones If remove-epsilon == false and replace-output-symbols ==
+/// false, but an arc may have >1 phone on it, but the boundaries will still
+/// correspond with the boundaries between phones. Note: it's possible
+/// to have arcs with words on them but no transition-ids at all. Returns true if
+/// everything was OK, false if some kind of error was detected (e.g. the
+/// "reorder" option was incorrectly specified.)
+bool PhoneAlignLattice(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const PhoneAlignLatticeOptions &opts,
+ CompactLattice *lat_out);
+
+
+} // end namespace kaldi
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/push-lattice-test.cc b/runtime/onnxruntime/third_party/kaldi/lat/push-lattice-test.cc
new file mode 100644
index 000000000..c2643292f
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/push-lattice-test.cc
@@ -0,0 +1,120 @@
+// lat/push-lattice-test.cc
+
+// Copyright 2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "lat/kaldi-lattice.h"
+#include "lat/push-lattice.h"
+#include "fstext/rand-fst.h"
+
+
+namespace kaldi {
+using namespace fst;
+
+CompactLattice *RandCompactLattice() {
+ RandFstOptions opts;
+ opts.acyclic = true;
+ Lattice *fst = fst::RandPairFst<LatticeArc>(opts);
+ CompactLattice *cfst = new CompactLattice;
+ ConvertLattice(*fst, cfst);
+ delete fst;
+ return cfst;
+}
+
+void TestPushCompactLatticeStrings() {
+ CompactLattice *clat = RandCompactLattice();
+ CompactLattice clat2(*clat);
+ PushCompactLatticeStrings(&clat2);
+ KALDI_ASSERT(fst::RandEquivalent(*clat, clat2, 5, 0.001, Rand(), 10));
+ for (CompactLatticeArc::StateId s = 0; s < clat2.NumStates(); s++) {
+ if (s == 0)
+ continue; // We don't check state zero, as the "leftover string" stays
+ // there.
+ int32 first_label = -1;
+ bool ok = false;
+ bool first_label_set = false;
+ for (ArcIterator<CompactLattice> aiter(clat2, s); !aiter.Done();
+ aiter.Next()) {
+ if (aiter.Value().weight.String().size() == 0) {
+ ok = true;
+ } else {
+ int32 this_label = aiter.Value().weight.String().front();
+ if (first_label_set) {
+ if (this_label != first_label) ok = true;
+ } else {
+ first_label = this_label;
+ first_label_set = true;
+ }
+ }
+ }
+ if (clat2.Final(s) != CompactLatticeWeight::Zero()) {
+ if (clat2.Final(s).String().size() == 0) ok = true;
+ else {
+ int32 this_label = clat2.Final(s).String().front();
+ if (first_label_set && this_label != first_label) ok = true;
+ }
+ }
+ KALDI_ASSERT(ok);
+ }
+ delete clat;
+}
+
+void TestPushCompactLatticeWeights() {
+ CompactLattice *clat = RandCompactLattice();
+ CompactLattice clat2(*clat);
+ PushCompactLatticeWeights(&clat2);
+ KALDI_ASSERT(fst::RandEquivalent(*clat, clat2, 5, 0.001, Rand(), 10));
+ for (CompactLatticeArc::StateId s = 0; s < clat2.NumStates(); s++) {
+ if (s == 0)
+ continue; // We don't check state zero, as the "leftover string" stays
+ // there.
+ LatticeWeight sum = clat2.Final(s).Weight();
+ for (ArcIterator<CompactLattice> aiter(clat2, s); !aiter.Done();
+ aiter.Next()) {
+ sum = Plus(sum, aiter.Value().weight.Weight());
+ }
+ if (!ApproxEqual(sum, LatticeWeight::One())) {
+ {
+ fst::FstPrinter<CompactLatticeArc> printer(clat2, NULL, NULL,
+ NULL, true, true, "\t");
+ printer.Print(&std::cerr, "<unknown>");
+ }
+ {
+ fst::FstPrinter<CompactLatticeArc> printer(*clat, NULL, NULL,
+ NULL, true, true, "\t");
+ printer.Print(&std::cerr, "<unknown>");
+ }
+ KALDI_ERR << "Bad lattice being pushed.";
+ }
+ }
+ delete clat;
+}
+
+
+
+} // end namespace kaldi
+
+int main() {
+ using namespace kaldi;
+ using kaldi::int32;
+ for (int32 i = 0; i < 15; i++) {
+ TestPushCompactLatticeStrings();
+ TestPushCompactLatticeWeights();
+ }
+ KALDI_LOG << "Success.";
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/push-lattice.cc b/runtime/onnxruntime/third_party/kaldi/lat/push-lattice.cc
new file mode 100644
index 000000000..f4eb322d0
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/push-lattice.cc
@@ -0,0 +1,290 @@
+// lat/push-lattice.cc
+
+// Copyright 2009-2011 Saarland University (Author: Arnab Ghoshal)
+// 2012-2013 Johns Hopkins University (Author: Daniel Povey); Chao Weng;
+// Bagher BabaAli
+// 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "lat/push-lattice.h"
+#include "util/stl-utils.h"
+
+namespace fst {
+
+
+template<class Weight, class IntType> class CompactLatticePusher {
+ public:
+ typedef CompactLatticeWeightTpl<Weight, IntType> CompactWeight;
+ typedef ArcTpl<CompactWeight> CompactArc;
+ typedef typename CompactArc::StateId StateId;
+
+ CompactLatticePusher(MutableFst<CompactArc> *clat): clat_(clat) { }
+ bool Push() {
+ if (clat_->Properties(kTopSorted, true) == 0) {
+ if (!TopSort(clat_)) {
+ KALDI_WARN << "Topological sorting of state-level lattice failed "
+ "(probably your lexicon has empty words or your LM has epsilon cycles; this "
+ " is a bad idea.)";
+ return false;
+ }
+ }
+ ComputeShifts();
+ ApplyShifts();
+ return true;
+ }
+
+ // Gets the string of length [end - begin], starting at this
+ // state and taking arc "arc_idx" (and thereafter an arbitrary sequence).
+ // Note: here, arc_idx == -1 means take an arbitrary path.
+ static void GetString(const ExpandedFst<CompactArc> &clat,
+ StateId state,
+ size_t arc_idx,
+ typename std::vector<IntType>::iterator begin,
+ typename std::vector<IntType>::iterator end) {
+ CompactWeight final = clat.Final(state);
+ size_t len = end - begin;
+ KALDI_ASSERT(len >= 0);
+ if (len == 0) return;
+ if (arc_idx == -1 && final != CompactWeight::Zero()) {
+ const std::vector<IntType> &string = final.String();
+ KALDI_ASSERT(string.size() >= len &&
+ "Either code error, or paths in lattice have inconsistent lengths");
+ std::copy(string.begin(), string.begin() + len, begin);
+ return;
+ }
+
+ ArcIterator<ExpandedFst<CompactArc> > aiter(clat, state);
+ if (arc_idx != -1)
+ aiter.Seek(arc_idx);
+ KALDI_ASSERT(!aiter.Done() &&
+ "Either code error, or paths in lattice are inconsistent in length.");
+
+ const CompactArc &arc = aiter.Value();
+ size_t arc_len = arc.weight.String().size();
+ if (arc_len >= len) {
+ std::copy(arc.weight.String().begin(), arc.weight.String().begin() + len, begin);
+ } else {
+ std::copy(arc.weight.String().begin(), arc.weight.String().end(), begin);
+ // Recurse.
+ GetString(clat, arc.nextstate, -1, begin + arc_len, end);
+ }
+ }
+
+ void CheckForConflict(const CompactWeight &final,
+ StateId state,
+ int32 *shift) {
+ if (shift == NULL) return;
+ // At input, "shift" has the maximum value that we could shift back assuming
+ // there is no conflict between the values of the strings. We need to check
+ // if there is conflict, and if so, reduce the "shift".
+ bool is_final = (final != CompactWeight::Zero());
+ size_t num_arcs = clat_->NumArcs(state);
+ if (num_arcs + (is_final ? 1 : 0) > 1 && *shift > 0) {
+ // There is potential for conflict between string values, because >1
+ // [arc or final-prob]. Find the longest shift up to and including the
+ // current shift, that gives no conflict.
+
+ std::vector<IntType> string(*shift), compare_string(*shift);
+ size_t arc;
+ if (is_final) {
+ KALDI_ASSERT(final.String().size() >= *shift);
+ std::copy(final.String().begin(), final.String().begin() + *shift,
+ string.begin());
+ arc = 0;
+ } else {
+ // set "string" to string if we take 1st arc.
+ GetString(*clat_, state, 0, string.begin(), string.end());
+ arc = 1;
+ }
+ for (; arc < num_arcs; arc++) { // for the other arcs..
+ GetString(*clat_, state, arc,
+ compare_string.begin(), compare_string.end());
+ std::pair<typename std::vector<IntType>::iterator,
+ typename std::vector<IntType>::iterator> pr =
+ std::mismatch(string.begin(), string.end(),
+ compare_string.begin());
+ if (pr.first != string.end()) { // There was a mismatch. Reduce the shift
+ // to a value where they will match.
+ *shift = pr.first - string.begin();
+ string.resize(*shift);
+ compare_string.resize(*shift);
+ }
+ }
+ }
+ }
+
+ void ComputeShifts() {
+ StateId num_states = clat_->NumStates();
+ shift_vec_.resize(num_states, 0);
+
+ // The for loop will only work if StateId is signed, so assert this.
+ KALDI_COMPILE_TIME_ASSERT(static_cast<StateId>(-1) < static_cast<StateId>(0));
+ // We rely on the topological sorting, so clat_->Start() should be zero or
+ // at least any preceding states should be non-accessible. We leave the
+ // shift at zero for the start state because we can't shift to before that.
+ for (StateId state = num_states - 1; state > clat_->Start(); state--) {
+ size_t num_arcs = clat_->NumArcs(state);
+ CompactWeight final = clat_->Final(state);
+ if (num_arcs == 0) {
+ // we can shift back by the number of transition-ids on the
+ // final-prob, if any.
+ shift_vec_[state] = final.String().size();
+ } else { // We have arcs ...
+ int32 shift = std::numeric_limits<int32>::max();
+ size_t num_arcs = 0;
+ bool is_final = (final != CompactWeight::Zero());
+ if (is_final)
+ shift = std::min(shift, static_cast<int32>(final.String().size()));
+ for (ArcIterator<MutableFst<CompactArc> > aiter(*clat_, state);
+ !aiter.Done(); aiter.Next(), num_arcs++) {
+ const CompactArc &arc (aiter.Value());
+ shift = std::min(shift, shift_vec_[arc.nextstate] +
+ static_cast<int32>(arc.weight.String().size()));
+ }
+ CheckForConflict(final, state, &shift);
+ shift_vec_[state] = shift;
+ }
+ }
+ }
+
+ void ApplyShifts() {
+ StateId num_states = clat_->NumStates();
+ for (StateId state = 0; state < num_states; state++) {
+ int32 shift = shift_vec_[state];
+ std::vector<IntType> string;
+ for (MutableArcIterator<MutableFst<CompactArc> > aiter(clat_, state);
+ !aiter.Done(); aiter.Next()) {
+ CompactArc arc(aiter.Value());
+ KALDI_ASSERT(arc.nextstate > state && "Cyclic lattice");
+
+ string = arc.weight.String();
+ size_t orig_len = string.size(), next_shift = shift_vec_[arc.nextstate];
+ // extend "string" by next_shift.
+ string.resize(string.size() + next_shift);
+ // The next command sets the last "next_shift" elements of 'string' to
+ // the string starting from arc.nextstate (taking an arbitrary path).
+ GetString(*clat_, arc.nextstate, -1,
+ string.begin() + orig_len, string.end());
+ // Remove the first "shift" elements of this string and set the
+ // arc-weight string to this.
+ arc.weight.SetString(std::vector<IntType>(string.begin() + shift,
+ string.end()));
+ aiter.SetValue(arc);
+ }
+
+ CompactWeight final = clat_->Final(state);
+ if (final != CompactWeight::Zero()) {
+ // Erase first "shift" elements of final-prob.
+ final.SetString(std::vector<IntType>(final.String().begin() + shift,
+ final.String().end()));
+ clat_->SetFinal(state, final);
+ }
+ }
+ }
+
+ private:
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > > *clat_;
+
+ // For each state s, shift_vec_[s] >= 0 is how much we will shift the
+ // transition-ids back at this state.
+ std::vector<int32> shift_vec_;
+};
+
+template<class Weight, class IntType>
+bool PushCompactLatticeStrings(
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > > *clat) {
+ CompactLatticePusher<Weight, IntType> pusher(clat);
+ return pusher.Push();
+}
+
+template<class Weight, class IntType>
+bool PushCompactLatticeWeights(
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > > *clat) {
+ if (clat->Properties(kTopSorted, true) == 0) {
+ if (!TopSort(clat)) {
+ KALDI_WARN << "Topological sorting of state-level lattice failed "
+ "(probably your lexicon has empty words or your LM has epsilon cycles; this "
+ " is a bad idea.)";
+ return false;
+ }
+ }
+ typedef CompactLatticeWeightTpl<Weight, IntType> CompactWeight;
+ typedef ArcTpl<CompactWeight> CompactArc;
+ typedef typename CompactArc::StateId StateId;
+
+ StateId num_states = clat->NumStates();
+ if (num_states == 0) {
+ KALDI_WARN << "Pushing weights of empty compact lattice";
+ return true; // this is technically success because an empty
+ // lattice is already pushed.
+ }
+ std::vector<Weight> weight_to_end(num_states); // Note: LatticeWeight
+ // contains two floats.
+ for (StateId s = num_states - 1; s >= 0; s--) {
+ Weight this_weight_to_end = clat->Final(s).Weight();
+ for (ArcIterator<MutableFst<CompactArc> > aiter(*clat, s);
+ !aiter.Done(); aiter.Next()) {
+ const CompactArc &arc = aiter.Value();
+ KALDI_ASSERT(arc.nextstate > s && "Cyclic lattices not allowed.");
+ this_weight_to_end = Plus(this_weight_to_end,
+ Times(aiter.Value().weight.Weight(),
+ weight_to_end[arc.nextstate]));
+ }
+ if (this_weight_to_end == Weight::Zero()) {
+ KALDI_WARN << "Lattice has non-coaccessible states.";
+ }
+ weight_to_end[s] = this_weight_to_end;
+ }
+ weight_to_end[0] = Weight::One(); // We leave the "leftover weight" on
+ // the start state, which won't
+ // necessarily end up summing to one.
+ for (StateId s = 0; s < num_states; s++) {
+ Weight this_weight_to_end = weight_to_end[s];
+ if (this_weight_to_end == Weight::Zero())
+ continue;
+ for (MutableArcIterator<MutableFst<CompactArc> > aiter(clat, s);
+ !aiter.Done(); aiter.Next()) {
+ CompactArc arc = aiter.Value();
+ Weight next_weight_to_end = weight_to_end[arc.nextstate];
+ if (next_weight_to_end != Weight::Zero()) {
+ arc.weight.SetWeight(Times(arc.weight.Weight(),
+ Divide(next_weight_to_end,
+ this_weight_to_end)));
+ aiter.SetValue(arc);
+ }
+ }
+ CompactWeight final_weight = clat->Final(s);
+ if (final_weight != CompactWeight::Zero()) {
+ final_weight.SetWeight(Divide(final_weight.Weight(), this_weight_to_end));
+ clat->SetFinal(s, final_weight);
+ }
+ }
+
+ return true;
+}
+
+// Instantiate for CompactLattice.
+template
+bool PushCompactLatticeStrings<kaldi::LatticeWeight, kaldi::int32>(
+ MutableFst<kaldi::CompactLatticeArc> *clat);
+
+template
+bool PushCompactLatticeWeights<kaldi::LatticeWeight, kaldi::int32>(
+ MutableFst<kaldi::CompactLatticeArc> *clat);
+
+} // namespace fst
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/push-lattice.h b/runtime/onnxruntime/third_party/kaldi/lat/push-lattice.h
new file mode 100644
index 000000000..080bb6376
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/push-lattice.h
@@ -0,0 +1,61 @@
+// lat/push-lattice.h
+
+// Copyright 2013 Johns Hopkins University (Author: Daniel Povey)
+// 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_LAT_PUSH_LATTICE_H_
+#define KALDI_LAT_PUSH_LATTICE_H_
+
+#include <vector>
+#include <map>
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fstext/fstext-lib.h"
+#include "lat/kaldi-lattice.h"
+
+namespace fst {
+
+
+/// This function pushes the transition-ids as far towards the start as they
+/// will go. It can be useful prior to lattice-align-words (for non-linear
+/// lattices). We can't use the generic OpenFst "push" function because
+/// it uses the sum as the divisor, which is not appropriate in this case
+/// (a+b generally won't divide a or b in this semiring).
+/// It returns true on success, false if it failed due to TopSort failing,
+/// which should never happen, but we handle it gracefully by just leaving the
+/// lattice the same.
+/// This function used to be called just PushCompactLattice.
+template<class Weight, class IntType>
+bool PushCompactLatticeStrings(
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > > *clat);
+
+/// This function pushes the weights in the CompactLattice so that all states
+/// except possibly the start state, have Weight components (of type
+/// LatticeWeight) that "sum to one" in the LatticeWeight (i.e. interpreting the
+/// weights as negated log-probs). It returns true on success, false if it
+/// failed due to TopSort failing, which should never happen, but we handle it
+/// gracefully by just leaving the lattice the same.
+template<class Weight, class IntType>
+bool PushCompactLatticeWeights(
+ MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > > *clat);
+
+} // namespace fst
+
+#endif // KALDI_LAT_PUSH_LATTICE_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/sausages.cc b/runtime/onnxruntime/third_party/kaldi/lat/sausages.cc
new file mode 100644
index 000000000..b851bc360
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/sausages.cc
@@ -0,0 +1,432 @@
+// lat/sausages.cc
+
+// Copyright 2012 Johns Hopkins University (Author: Daniel Povey)
+// 2015 Guoguo Chen
+// 2019 Dogan Can
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "lat/sausages.h"
+#include "lat/lattice-functions.h"
+
+namespace kaldi {
+
+// this is Figure 6 in the paper.
+void MinimumBayesRisk::MbrDecode() {
+
+ for (size_t counter = 0; ; counter++) {
+ NormalizeEps(&R_);
+ AccStats(); // writes to gamma_
+ double delta_Q = 0.0; // change in objective function.
+
+ one_best_times_.clear();
+ one_best_confidences_.clear();
+
+ // Caution: q in the line below is (q-1) in the algorithm
+ // in the paper; both R_ and gamma_ are indexed by q-1.
+ for (size_t q = 0; q < R_.size(); q++) {
+ if (opts_.decode_mbr) { // This loop updates R_ [indexed same as gamma_].
+ // gamma_[i] is sorted in reverse order so most likely one is first.
+ const std::vector<std::pair<int32, BaseFloat> > &this_gamma = gamma_[q];
+ double old_gamma = 0, new_gamma = this_gamma[0].second;
+ int32 rq = R_[q], rhat = this_gamma[0].first; // rq: old word, rhat: new.
+ for (size_t j = 0; j < this_gamma.size(); j++)
+ if (this_gamma[j].first == rq) old_gamma = this_gamma[j].second;
+ delta_Q += (old_gamma - new_gamma); // will be 0 or negative; a bound on
+ // change in error.
+ if (rq != rhat)
+ KALDI_VLOG(2) << "Changing word " << rq << " to " << rhat;
+ R_[q] = rhat;
+ }
+ // build the outputs (time, confidences),
+ if (R_[q] != 0 || opts_.print_silence) {
+ // see which 'item' from the sausage-bin should we select,
+ // (not necessarily the 1st one when MBR decoding disabled)
+ int32 s = 0;
+ for (int32 j=0; j<gamma_[q].size(); j++) {
+ if (gamma_[q][j].first == R_[q]) {
+ s = j;
+ break;
+ }
+ }
+ one_best_times_.push_back(times_[q][s]);
+ // post-process the times,
+ size_t i = one_best_times_.size();
+ if (i > 1 && one_best_times_[i-2].second > one_best_times_[i-1].first) {
+ // It's quite possible for this to happen, but it seems like it would
+ // have a bad effect on the downstream processing, so we fix it here.
+ // We resolve overlaps by redistributing the available time interval.
+ BaseFloat prev_right = i > 2 ? one_best_times_[i-3].second : 0.0;
+ BaseFloat left = std::max(prev_right,
+ std::min(one_best_times_[i-2].first,
+ one_best_times_[i-1].first));
+ BaseFloat right = std::max(one_best_times_[i-2].second,
+ one_best_times_[i-1].second);
+ BaseFloat first_dur =
+ one_best_times_[i-2].second - one_best_times_[i-2].first;
+ BaseFloat second_dur =
+ one_best_times_[i-1].second - one_best_times_[i-1].first;
+ BaseFloat mid = first_dur > 0 ? left + (right - left) * first_dur /
+ (first_dur + second_dur) : left;
+ one_best_times_[i-2].first = left;
+ one_best_times_[i-2].second = one_best_times_[i-1].first = mid;
+ one_best_times_[i-1].second = right;
+ }
+ BaseFloat confidence = 0.0;
+ for (int32 j = 0; j < gamma_[q].size(); j++) {
+ if (gamma_[q][j].first == R_[q]) {
+ confidence = gamma_[q][j].second;
+ break;
+ }
+ }
+ one_best_confidences_.push_back(confidence);
+ }
+ }
+ KALDI_VLOG(2) << "Iter = " << counter << ", delta-Q = " << delta_Q;
+ if (delta_Q == 0) break;
+ if (counter > 100) {
+ KALDI_WARN << "Iterating too many times in MbrDecode; stopping.";
+ break;
+ }
+ }
+ if (!opts_.print_silence) RemoveEps(&R_);
+}
+
+struct Int32IsZero {
+ bool operator() (int32 i) { return (i == 0); }
+};
+// static
+void MinimumBayesRisk::RemoveEps(std::vector<int32> *vec) {
+ Int32IsZero pred;
+ vec->erase(std::remove_if (vec->begin(), vec->end(), pred),
+ vec->end());
+}
+
+// static
+void MinimumBayesRisk::NormalizeEps(std::vector<int32> *vec) {
+ RemoveEps(vec);
+ vec->resize(1 + vec->size() * 2);
+ int32 s = vec->size();
+ for (int32 i = s/2 - 1; i >= 0; i--) {
+ (*vec)[i*2 + 1] = (*vec)[i];
+ (*vec)[i*2 + 2] = 0;
+ }
+ (*vec)[0] = 0;
+}
+
+double MinimumBayesRisk::EditDistance(int32 N, int32 Q,
+ Vector<double> &alpha,
+ Matrix<double> &alpha_dash,
+ Vector<double> &alpha_dash_arc) {
+ alpha(1) = 0.0; // = log(1). Line 5.
+ alpha_dash(1, 0) = 0.0; // Line 5.
+ for (int32 q = 1; q <= Q; q++)
+ alpha_dash(1, q) = alpha_dash(1, q-1) + l(0, r(q)); // Line 7.
+ for (int32 n = 2; n <= N; n++) {
+ double alpha_n = kLogZeroDouble;
+ for (size_t i = 0; i < pre_[n].size(); i++) {
+ const Arc &arc = arcs_[pre_[n][i]];
+ alpha_n = LogAdd(alpha_n, alpha(arc.start_node) + arc.loglike);
+ }
+ alpha(n) = alpha_n; // Line 10.
+ // Line 11 omitted: matrix was initialized to zero.
+ for (size_t i = 0; i < pre_[n].size(); i++) {
+ const Arc &arc = arcs_[pre_[n][i]];
+ int32 s_a = arc.start_node, w_a = arc.word;
+ BaseFloat p_a = arc.loglike;
+ for (int32 q = 0; q <= Q; q++) {
+ if (q == 0) {
+ alpha_dash_arc(q) = // line 15.
+ alpha_dash(s_a, q) + l(w_a, 0, true);
+ } else { // a1,a2,a3 are the 3 parts of min expression of line 17.
+ int32 r_q = r(q);
+ double a1 = alpha_dash(s_a, q-1) + l(w_a, r_q),
+ a2 = alpha_dash(s_a, q) + l(w_a, 0, true),
+ a3 = alpha_dash_arc(q-1) + l(0, r_q);
+ alpha_dash_arc(q) = std::min(a1, std::min(a2, a3));
+ }
+ // line 19:
+ alpha_dash(n, q) += Exp(alpha(s_a) + p_a - alpha(n)) * alpha_dash_arc(q);
+ }
+ }
+ }
+ return alpha_dash(N, Q); // line 23.
+}
+
+// Figure 5 in the paper.
+void MinimumBayesRisk::AccStats() {
+ using std::map;
+
+ int32 N = static_cast<int32>(pre_.size()) - 1,
+ Q = static_cast<int32>(R_.size());
+
+ Vector<double> alpha(N+1); // index (1...N)
+ Matrix<double> alpha_dash(N+1, Q+1); // index (1...N, 0...Q)
+ Vector<double> alpha_dash_arc(Q+1); // index 0...Q
+ Matrix<double> beta_dash(N+1, Q+1); // index (1...N, 0...Q)
+ Vector<double> beta_dash_arc(Q+1); // index 0...Q
+ std::vector<char> b_arc(Q+1); // integer in {1,2,3}; index 1...Q
+ std::vector<map<int32, double> > gamma(Q+1); // temp. form of gamma.
+ // index 1...Q [word] -> occ.
+
+ // The tau maps below are the sums over arcs with the same word label
+ // of the tau_b and tau_e timing quantities mentioned in Appendix C of
+ // the paper... we are using these to get averaged times for both the
+ // the sausage bins and the 1-best output.
+ std::vector<map<int32, double> > tau_b(Q+1), tau_e(Q+1);
+
+ double Ltmp = EditDistance(N, Q, alpha, alpha_dash, alpha_dash_arc);
+ if (L_ != 0 && Ltmp > L_) { // L_ != 0 is to rule out 1st iter.
+ KALDI_WARN << "Edit distance increased: " << Ltmp << " > "
+ << L_;
+ }
+ L_ = Ltmp;
+ KALDI_VLOG(2) << "L = " << L_;
+ // omit line 10: zero when initialized.
+ beta_dash(N, Q) = 1.0; // Line 11.
+ for (int32 n = N; n >= 2; n--) {
+ for (size_t i = 0; i < pre_[n].size(); i++) {
+ const Arc &arc = arcs_[pre_[n][i]];
+ int32 s_a = arc.start_node, w_a = arc.word;
+ BaseFloat p_a = arc.loglike;
+ alpha_dash_arc(0) = alpha_dash(s_a, 0) + l(w_a, 0, true); // line 14.
+ for (int32 q = 1; q <= Q; q++) { // this loop == lines 15-18.
+ int32 r_q = r(q);
+ double a1 = alpha_dash(s_a, q-1) + l(w_a, r_q),
+ a2 = alpha_dash(s_a, q) + l(w_a, 0, true),
+ a3 = alpha_dash_arc(q-1) + l(0, r_q);
+ if (a1 <= a2) {
+ if (a1 <= a3) { b_arc[q] = 1; alpha_dash_arc(q) = a1; }
+ else { b_arc[q] = 3; alpha_dash_arc(q) = a3; }
+ } else {
+ if (a2 <= a3) { b_arc[q] = 2; alpha_dash_arc(q) = a2; }
+ else { b_arc[q] = 3; alpha_dash_arc(q) = a3; }
+ }
+ }
+ beta_dash_arc.SetZero(); // line 19.
+ for (int32 q = Q; q >= 1; q--) {
+ // line 21:
+ beta_dash_arc(q) += Exp(alpha(s_a) + p_a - alpha(n)) * beta_dash(n, q);
+ switch (static_cast<int>(b_arc[q])) { // lines 22 and 23:
+ case 1:
+ beta_dash(s_a, q-1) += beta_dash_arc(q);
+ // next: gamma(q, w(a)) += beta_dash_arc(q)
+ AddToMap(w_a, beta_dash_arc(q), &(gamma[q]));
+ // next: accumulating times, see decl for tau_b,tau_e
+ AddToMap(w_a, state_times_[s_a] * beta_dash_arc(q), &(tau_b[q]));
+ AddToMap(w_a, state_times_[n] * beta_dash_arc(q), &(tau_e[q]));
+ break;
+ case 2:
+ beta_dash(s_a, q) += beta_dash_arc(q);
+ break;
+ case 3:
+ beta_dash_arc(q-1) += beta_dash_arc(q);
+ // next: gamma(q, epsilon) += beta_dash_arc(q)
+ AddToMap(0, beta_dash_arc(q), &(gamma[q]));
+ // next: accumulating times, see decl for tau_b,tau_e
+ // WARNING: there was an error in Appendix C. If we followed
+ // the instructions there the next line would say state_times_[sa], but
+ // it would be wrong. I will try to publish an erratum.
+ AddToMap(0, state_times_[n] * beta_dash_arc(q), &(tau_b[q]));
+ AddToMap(0, state_times_[n] * beta_dash_arc(q), &(tau_e[q]));
+ break;
+ default:
+ KALDI_ERR << "Invalid b_arc value"; // error in code.
+ }
+ }
+ beta_dash_arc(0) += Exp(alpha(s_a) + p_a - alpha(n)) * beta_dash(n, 0);
+ beta_dash(s_a, 0) += beta_dash_arc(0); // line 26.
+ }
+ }
+ beta_dash_arc.SetZero(); // line 29.
+ for (int32 q = Q; q >= 1; q--) {
+ beta_dash_arc(q) += beta_dash(1, q);
+ beta_dash_arc(q-1) += beta_dash_arc(q);
+ AddToMap(0, beta_dash_arc(q), &(gamma[q]));
+ // the statements below are actually redundant because
+ // state_times_[1] is zero.
+ AddToMap(0, state_times_[1] * beta_dash_arc(q), &(tau_b[q]));
+ AddToMap(0, state_times_[1] * beta_dash_arc(q), &(tau_e[q]));
+ }
+ for (int32 q = 1; q <= Q; q++) { // a check (line 35)
+ double sum = 0.0;
+ for (map<int32, double>::iterator iter = gamma[q].begin();
+ iter != gamma[q].end(); ++iter) sum += iter->second;
+ if (fabs(sum - 1.0) > 0.1)
+ KALDI_WARN << "sum of gamma[" << q << ",s] is " << sum;
+ }
+ // The next part is where we take gamma, and convert
+ // to the class member gamma_, which is using a different
+ // data structure and indexed from zero, not one.
+ gamma_.clear();
+ gamma_.resize(Q);
+ for (int32 q = 1; q <= Q; q++) {
+ for (map<int32, double>::iterator iter = gamma[q].begin();
+ iter != gamma[q].end(); ++iter)
+ gamma_[q-1].push_back(
+ std::make_pair(iter->first, static_cast<BaseFloat>(iter->second)));
+ // sort gamma_[q-1] from largest to smallest posterior.
+ GammaCompare comp;
+ std::sort(gamma_[q-1].begin(), gamma_[q-1].end(), comp);
+ }
+ // We do the same conversion for the state times tau_b and tau_e:
+ // they get turned into the times_ data member, which has zero-based
+ // indexing.
+ times_.clear();
+ times_.resize(Q);
+ sausage_times_.clear();
+ sausage_times_.resize(Q);
+ for (int32 q = 1; q <= Q; q++) {
+ double t_b = 0.0, t_e = 0.0;
+ for (std::vector<std::pair<int32, BaseFloat>>::iterator iter = gamma_[q-1].begin();
+ iter != gamma_[q-1].end(); ++iter) {
+ double w_b = tau_b[q][iter->first], w_e = tau_e[q][iter->first];
+ if (w_b > w_e)
+ KALDI_WARN << "Times out of order"; // this is quite bad.
+ times_[q-1].push_back(
+ std::make_pair(static_cast<BaseFloat>(w_b / iter->second),
+ static_cast<BaseFloat>(w_e / iter->second)));
+ t_b += w_b;
+ t_e += w_e;
+ }
+ sausage_times_[q-1].first = t_b;
+ sausage_times_[q-1].second = t_e;
+ if (sausage_times_[q-1].first > sausage_times_[q-1].second)
+ KALDI_WARN << "Times out of order"; // this is quite bad.
+ if (q > 1 && sausage_times_[q-2].second > sausage_times_[q-1].first) {
+ // We previously had a warning here, but now we'll just set both
+ // those values to their average. It's quite possible for this
+ // condition to happen, but it seems like it would have a bad effect
+ // on the downstream processing, so we fix it.
+ sausage_times_[q-2].second = sausage_times_[q-1].first =
+ 0.5 * (sausage_times_[q-2].second + sausage_times_[q-1].first);
+ }
+ }
+}
+
+void MinimumBayesRisk::PrepareLatticeAndInitStats(CompactLattice *clat) {
+ KALDI_ASSERT(clat != NULL);
+
+ CreateSuperFinal(clat); // Add super-final state to clat... this is
+ // one of the requirements of the MBR algorithm, as mentioned in the
+ // paper (i.e. just one final state).
+
+ // Topologically sort the lattice, if not already sorted.
+ kaldi::uint64 props = clat->Properties(fst::kFstProperties, false);
+ if (!(props & fst::kTopSorted)) {
+ if (fst::TopSort(clat) == false)
+ KALDI_ERR << "Cycles detected in lattice.";
+ }
+ CompactLatticeStateTimes(*clat, &state_times_); // work out times of
+ // the states in clat
+ state_times_.push_back(0); // we'll convert to 1-based numbering.
+ for (size_t i = state_times_.size()-1; i > 0; i--)
+ state_times_[i] = state_times_[i-1];
+
+ // Now we convert the information in "clat" into a special internal
+ // format (pre_, post_ and arcs_) which allows us to access the
+ // arcs preceding any given state.
+ // Note: in our internal format the states will be numbered from 1,
+ // which involves adding 1 to the OpenFst states.
+ int32 N = clat->NumStates();
+ pre_.resize(N+1);
+
+ // Careful: "Arc" is a class-member struct, not an OpenFst type of arc as one
+ // would normally assume.
+ for (int32 n = 1; n <= N; n++) {
+ for (fst::ArcIterator<CompactLattice> aiter(*clat, n-1);
+ !aiter.Done();
+ aiter.Next()) {
+ const CompactLatticeArc &carc = aiter.Value();
+ Arc arc; // in our local format.
+ arc.word = carc.ilabel; // == carc.olabel
+ arc.start_node = n;
+ arc.end_node = carc.nextstate + 1; // convert to 1-based.
+ arc.loglike = - (carc.weight.Weight().Value1() +
+ carc.weight.Weight().Value2());
+ // loglike: sum graph/LM and acoustic cost, and negate to
+ // convert to loglikes. We assume acoustic scaling is already done.
+
+ pre_[arc.end_node].push_back(arcs_.size()); // record index of this arc.
+ arcs_.push_back(arc);
+ }
+ }
+}
+
+MinimumBayesRisk::MinimumBayesRisk(const CompactLattice &clat_in,
+ MinimumBayesRiskOptions opts) : opts_(opts) {
+ CompactLattice clat(clat_in); // copy.
+
+ PrepareLatticeAndInitStats(&clat);
+
+ // We don't need to look at clat.Start() or clat.Final(state):
+ // we know clat.Start() == 0 since it's topologically sorted,
+ // and clat.Final(state) is Zero() except for One() at the last-
+ // numbered state, thanks to CreateSuperFinal and the topological
+ // sorting.
+
+ { // Now set R_ to one best in the FST.
+ RemoveAlignmentsFromCompactLattice(&clat); // will be more efficient
+ // in best-path if we do this.
+ Lattice lat;
+ ConvertLattice(clat, &lat); // convert from CompactLattice to Lattice.
+ fst::VectorFst<fst::StdArc> fst;
+ ConvertLattice(lat, &fst); // convert from lattice to normal FST.
+ fst::VectorFst<fst::StdArc> fst_shortest_path;
+ fst::ShortestPath(fst, &fst_shortest_path); // take shortest path of FST.
+ std::vector<int32> alignment, words;
+ fst::TropicalWeight weight;
+ GetLinearSymbolSequence(fst_shortest_path, &alignment, &words, &weight);
+ KALDI_ASSERT(alignment.empty()); // we removed the alignment.
+ R_ = words;
+ L_ = 0.0; // Set current edit-distance to 0 [just so we know
+ // when we're on the 1st iter.]
+ }
+
+ MbrDecode();
+
+}
+
+MinimumBayesRisk::MinimumBayesRisk(const CompactLattice &clat_in,
+ const std::vector<int32> &words,
+ MinimumBayesRiskOptions opts) : opts_(opts) {
+ CompactLattice clat(clat_in); // copy.
+
+ PrepareLatticeAndInitStats(&clat);
+
+ R_ = words;
+ L_ = 0.0;
+
+ MbrDecode();
+}
+
+MinimumBayesRisk::MinimumBayesRisk(const CompactLattice &clat_in,
+ const std::vector<int32> &words,
+ const std::vector<std::pair<BaseFloat,BaseFloat> > &times,
+ MinimumBayesRiskOptions opts) : opts_(opts) {
+ CompactLattice clat(clat_in); // copy.
+
+ PrepareLatticeAndInitStats(&clat);
+
+ R_ = words;
+ sausage_times_ = times;
+ L_ = 0.0;
+
+ MbrDecode();
+}
+
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/sausages.h b/runtime/onnxruntime/third_party/kaldi/lat/sausages.h
new file mode 100644
index 000000000..13f359c60
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/sausages.h
@@ -0,0 +1,270 @@
+// lat/sausages.h
+
+// Copyright 2012 Johns Hopkins University (Author: Daniel Povey)
+// 2015 Guoguo Chen
+// 2019 Dogan Can
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_LAT_SAUSAGES_H_
+#define KALDI_LAT_SAUSAGES_H_
+
+#include <vector>
+#include <map>
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fstext/fstext-lib.h"
+#include "lat/kaldi-lattice.h"
+
+namespace kaldi {
+
+/// The implementation of the Minimum Bayes Risk decoding method described in
+/// "Minimum Bayes Risk decoding and system combination based on a recursion for
+/// edit distance", Haihua Xu, Daniel Povey, Lidia Mangu and Jie Zhu, Computer
+/// Speech and Language, 2011
+/// This is a slightly more principled way to do Minimum Bayes Risk (MBR) decoding
+/// than the standard "Confusion Network" method. Note: MBR decoding aims to
+/// minimize the expected word error rate, assuming the lattice encodes the
+/// true uncertainty about what was spoken; standard Viterbi decoding gives the
+/// most likely utterance, which corresponds to minimizing the expected sentence
+/// error rate.
+///
+/// In addition to giving the MBR output, we also provide a way to get a
+/// "Confusion Network" or informally "sausage"-like structure. This is a
+/// linear sequence of bins, and in each bin, there is a distribution over
+/// words (or epsilon, meaning no word). This is useful for estimating
+/// confidence. Note: due to the way these sausages are made, typically there
+/// will be, between each bin representing a high-confidence word, a bin
+/// in which epsilon (no word) is the most likely word. Inside these bins
+/// is where we put possible insertions.
+
+struct MinimumBayesRiskOptions {
+ /// Boolean configuration parameter: if true, we actually update the hypothesis
+ /// to do MBR decoding (if false, our output is the MAP decoded output, but we
+ /// output the stats too (i.e. the confidences)).
+ bool decode_mbr;
+ /// Boolean configuration parameter: if true, the 1-best path will 'keep' the <eps> bins,
+ bool print_silence;
+
+ MinimumBayesRiskOptions() : decode_mbr(true), print_silence(false)
+ { }
+ void Register(OptionsItf *opts) {
+ opts->Register("decode-mbr", &decode_mbr, "If true, do Minimum Bayes Risk "
+ "decoding (else, Maximum a Posteriori)");
+ opts->Register("print-silence", &print_silence, "Keep the inter-word '<eps>' "
+ "bins in the 1-best output (ctm, <eps> can be a 'silence' or a 'deleted' word)");
+ }
+};
+
+/// This class does the word-level Minimum Bayes Risk computation, and gives you
+/// either the 1-best MBR output together with the expected Bayes Risk,
+/// or a sausage-like structure.
+class MinimumBayesRisk {
+ public:
+ /// Initialize with compact lattice-- any acoustic scaling etc., is assumed
+ /// to have been done already.
+ /// This does the whole computation. You get the output with
+ /// GetOneBest(), GetBayesRisk(), and GetSausageStats().
+ MinimumBayesRisk(const CompactLattice &clat,
+ MinimumBayesRiskOptions opts = MinimumBayesRiskOptions());
+
+ // Uses the provided <words> as <R_> instead of using the lattice best path.
+ // Note that the default value of opts.decode_mbr is true. If you provide 1-best
+ // hypothesis from MAP decoding, the output ctm from MBR decoding may be
+ // mismatched with the provided <words> (<words> would be used as the starting
+ // point of optimization).
+ MinimumBayesRisk(const CompactLattice &clat,
+ const std::vector<int32> &words,
+ MinimumBayesRiskOptions opts = MinimumBayesRiskOptions());
+ // Uses the provided <words> as <R_> and <times> of bins instead of using the lattice best path.
+ // Note that the default value of opts.decode_mbr is true. If you provide 1-best
+ // hypothesis from MAP decoding, the output ctm from MBR decoding may be
+ // mismatched with the provided <words> (<words> would be used as the starting
+ // point of optimization).
+ MinimumBayesRisk(const CompactLattice &clat,
+ const std::vector<int32> &words,
+ const std::vector<std::pair<BaseFloat,BaseFloat> > &times,
+ MinimumBayesRiskOptions opts = MinimumBayesRiskOptions());
+
+ const std::vector<int32> &GetOneBest() const { // gets one-best (with no epsilons)
+ return R_;
+ }
+
+ const std::vector<std::vector<std::pair<BaseFloat, BaseFloat> > > GetTimes() const {
+ return times_; // returns average (start,end) times for each word in each
+ // bin. These are raw averages without any processing, i.e. time intervals
+ // from different bins can overlap.
+ }
+
+ const std::vector<std::pair<BaseFloat, BaseFloat> > GetSausageTimes() const {
+ return sausage_times_; // returns average (start,end) times for each bin.
+ // This is typically the weighted average of the times in GetTimes() but can
+ // be slightly different if the times for the bins overlap, in which case
+ // the times returned by this method do not overlap unlike the times
+ // returned by GetTimes().
+ }
+
+ const std::vector<std::pair<BaseFloat, BaseFloat> > &GetOneBestTimes() const {
+ return one_best_times_; // returns average (start,end) times for each word
+ // corresponding to an entry in the one-best output. This is typically the
+ // appropriate subset of the times in GetTimes() but can be slightly
+ // different if the times for the one-best words overlap, in which case
+ // the times returned by this method do not overlap unlike the times
+ // returned by GetTimes().
+ }
+
+ /// Outputs the confidences for the one-best transcript.
+ const std::vector<BaseFloat> &GetOneBestConfidences() const {
+ return one_best_confidences_;
+ }
+
+ /// Returns the expected WER over this sentence (assuming model correctness).
+ BaseFloat GetBayesRisk() const { return L_; }
+
+ const std::vector<std::vector<std::pair<int32, BaseFloat> > > &GetSausageStats() const {
+ return gamma_;
+ }
+
+ private:
+ void PrepareLatticeAndInitStats(CompactLattice *clat);
+
+ /// Minimum-Bayes-Risk Decode. Top-level algorithm. Figure 6 of the paper.
+ void MbrDecode();
+
+ /// Without the 'penalize' argument this gives us the basic edit-distance
+ /// function l(a,b), as in the paper.
+ /// With the 'penalize' argument it can be interpreted as the edit distance
+ /// plus the 'delta' from the paper, except that we make a kind of conceptual
+ /// bug-fix and only apply the delta if the edit-distance was not already
+ /// zero. This bug-fix was necessary in order to force all the stats to show
+ /// up, that should show up, and applying the bug-fix makes the sausage stats
+ /// significantly less sparse.
+ inline double l(int32 a, int32 b, bool penalize = false) {
+ if (a == b) return 0.0;
+ else return (penalize ? 1.0 + delta() : 1.0);
+ }
+
+ /// returns r_q, in one-based indexing, as in the paper.
+ inline int32 r(int32 q) { return R_[q-1]; }
+
+
+ /// Figure 4 of the paper; called from AccStats (Fig. 5)
+ double EditDistance(int32 N, int32 Q,
+ Vector<double> &alpha,
+ Matrix<double> &alpha_dash,
+ Vector<double> &alpha_dash_arc);
+
+ /// Figure 5 of the paper. Outputs to gamma_ and L_.
+ void AccStats();
+
+ /// Removes epsilons (symbol 0) from a vector
+ static void RemoveEps(std::vector<int32> *vec);
+
+ // Ensures that between each word in "vec" and at the beginning and end, is
+ // epsilon (0). (But if no words in vec, just one epsilon)
+ static void NormalizeEps(std::vector<int32> *vec);
+
+ // delta() is a constant used in the algorithm, which penalizes
+ // the use of certain epsilon transitions in the edit-distance which would cause
+ // words not to show up in the accumulated edit-distance statistics.
+ // There has been a conceptual bug-fix versus the way it was presented in
+ // the paper: we now add delta only if the edit-distance was not already
+ // zero.
+ static inline BaseFloat delta() { return 1.0e-05; }
+
+
+ /// Function used to increment map.
+ static inline void AddToMap(int32 i, double d, std::map<int32, double> *gamma) {
+ if (d == 0) return;
+ std::pair<const int32, double> pr(i, d);
+ std::pair<std::map<int32, double>::iterator, bool> ret = gamma->insert(pr);
+ if (!ret.second) // not inserted, so add to contents.
+ ret.first->second += d;
+ }
+
+ struct Arc {
+ int32 word;
+ int32 start_node;
+ int32 end_node;
+ BaseFloat loglike;
+ };
+
+ MinimumBayesRiskOptions opts_;
+
+
+ /// Arcs in the topologically sorted acceptor form of the word-level lattice,
+ /// with one final-state. Contains (word-symbol, log-likelihood on arc ==
+ /// negated cost). Indexed from zero.
+ std::vector<Arc> arcs_;
+
+ /// For each node in the lattice, a list of arcs entering that node. Indexed
+ /// from 1 (first node == 1).
+ std::vector<std::vector<int32> > pre_;
+
+ std::vector<int32> state_times_; // time of each state in the word lattice,
+ // indexed from 1 (same index as into pre_)
+
+ std::vector<int32> R_; // current 1-best word sequence, normalized to have
+ // epsilons between each word and at the beginning and end. R in paper...
+ // caution: indexed from zero, not from 1 as in paper.
+
+ double L_; // current averaged edit-distance between lattice and R_.
+ // \hat{L} in paper.
+
+ std::vector<std::vector<std::pair<int32, BaseFloat> > > gamma_;
+ // The stats we accumulate; these are pairs of (posterior, word-id), and note
+ // that word-id may be epsilon. Caution: indexed from zero, not from 1 as in
+ // paper. We sort in reverse order on the second member (posterior), so more
+ // likely word is first.
+
+ std::vector<std::vector<std::pair<BaseFloat, BaseFloat> > > times_;
+ // The average start and end times for words in each confusion-network bin.
+ // This is like an average over arcs, of the tau_b and tau_e quantities in
+ // Appendix C of the paper. Indexed from zero, like gamma_ and R_.
+
+ std::vector<std::pair<BaseFloat, BaseFloat> > sausage_times_;
+ // The average start and end times for each confusion-network bin. This
+ // is like an average over words, of the tau_b and tau_e quantities in
+ // Appendix C of the paper. Indexed from zero, like gamma_ and R_.
+
+ std::vector<std::pair<BaseFloat, BaseFloat> > one_best_times_;
+ // The average start and end times for words in the one best output. This
+ // is like an average over the arcs, of the tau_b and tau_e quantities in
+ // Appendix C of the paper. Indexed from zero, like gamma_ and R_.
+
+ std::vector<BaseFloat> one_best_confidences_;
+ // vector of confidences for the 1-best output (which could be
+ // the MAP output if opts_.decode_mbr == false, or the MBR output otherwise).
+ // Indexed by the same index as one_best_times_.
+
+ struct GammaCompare{
+ // should be like operator <. But we want reverse order
+ // on the 2nd element (posterior), so it'll be like operator
+ // > that looks first at the posterior.
+ bool operator () (const std::pair<int32, BaseFloat> &a,
+ const std::pair<int32, BaseFloat> &b) const {
+ if (a.second > b.second) return true;
+ else if (a.second < b.second) return false;
+ else return a.first > b.first;
+ }
+ };
+};
+
+} // namespace kaldi
+
+#endif // KALDI_LAT_SAUSAGES_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice-lexicon-test.cc b/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice-lexicon-test.cc
new file mode 100644
index 000000000..cfd5574b6
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice-lexicon-test.cc
@@ -0,0 +1,250 @@
+// lat/word-align-lattice-lexicon-test.cc
+
+// Copyright 2015 Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "lat/determinize-lattice-pruned.h"
+#include "fstext/lattice-utils.h"
+#include "fstext/fst-test-utils.h"
+#include "lat/kaldi-lattice.h"
+#include "lat/lattice-functions.h"
+#include "lat/lattice-functions-transition-model.h"
+#include "hmm/hmm-test-utils.h"
+#include "lat/word-align-lattice-lexicon.h"
+
+#include <random>
+
+namespace kaldi {
+
+// This function generates a lexicon in the same format that
+// WordAlignLatticeLexicon uses: (original-word-id), (new-word-id), (phone-seq).
+void GenerateLexicon(const std::vector<int32> &phones,
+ bool allow_zero_words,
+ bool allow_empty_word,
+ bool allow_multiple_prons,
+ std::vector<std::vector<int32> > *lexicon) {
+ KALDI_ASSERT(!phones.empty());
+ lexicon->clear();
+ int32 num_words = RandInt(1, 20);
+ for (int32 word = 1; word <= num_words; word++) {
+ int32 num_prons = RandInt(1, (allow_multiple_prons ? 2 : 1));
+ bool is_zero_word = allow_zero_words && (RandInt(1, 5) == 1);
+
+ for (int32 j = 0; j < num_prons; j++) {
+ // don't allow empty pron if this word isn't labeled in the lattice (zero word,
+ // like optional silence). This doesn't make sense.
+ int32 pron_length = RandInt(((allow_empty_word && !is_zero_word) ? 0 : 1),
+ 4);
+ std::vector<int32> this_entry;
+ this_entry.push_back(is_zero_word ? 0 : word);
+ this_entry.push_back(word);
+ for (int32 p = 0; p < pron_length; p++)
+ this_entry.push_back(phones[RandInt(0, phones.size() - 1)]);
+ lexicon->push_back(this_entry);
+ }
+ }
+ SortAndUniq(lexicon);
+
+ // randomize the order.
+ std::random_device rd;
+ std::mt19937 g(rd());
+ std::shuffle(lexicon->begin(), lexicon->end(), g);
+
+
+ for (size_t i = 0; i < lexicon->size(); i++) {
+ if ((*lexicon)[i].size() > 2) {
+ // ok, this lexicon has at least one nonempty word: potentially OK. Do
+ // further check that the info object doesn't complain.
+ try {
+ WordAlignLatticeLexiconInfo info(*lexicon);
+ return; // OK, we're satisfied with this lexicon.
+ } catch (...) {
+ break; // will re-try, see below.
+ }
+ }
+ }
+ // there were no nonempty words in the lexicon -> try again.
+ // recursing is the easiest way.
+ GenerateLexicon(phones, allow_zero_words, allow_empty_word, allow_multiple_prons,
+ lexicon);
+
+
+}
+
+
+static void PrintLexicon(const std::vector<std::vector<int32> > &lexicon) {
+ KALDI_LOG << "Lexicon is: ";
+ for (size_t i = 0; i < lexicon.size(); i++) {
+ KALDI_ASSERT(lexicon[i].size() >= 2);
+ const std::vector<int32> &entry = lexicon[i];
+ std::cerr << entry[0] << "\t" << entry[1] << "\t";
+ for (size_t j = 2; j < entry.size(); j++)
+ std::cerr << entry[j] << " ";
+ std::cerr << "\n";
+ }
+}
+
+static void PrintWordsAndPhones(const std::vector<int32> &words,
+ const std::vector<int32> &phones) {
+ std::ostringstream word_str, phone_str;
+ for (size_t i = 0; i < words.size(); i++)
+ word_str << words[i] << " ";
+ for (size_t i = 0; i < phones.size(); i++)
+ phone_str << phones[i] << " ";
+ KALDI_LOG << "Word-sequence is: " << word_str.str();
+ KALDI_LOG << "Phone-sequence is: " << phone_str.str();
+}
+
+
+// generates a phone and word sequence together from the lexicon. Not
+// guaranteed nonempty.
+void GenerateWordAndPhoneSequence(std::vector<std::vector<int32> > &lexicon,
+ std::vector<int32> *phone_seq,
+ std::vector<int32> *word_seq) {
+ int32 num_words = RandInt(0, 5);
+ phone_seq->clear();
+ word_seq->clear();
+ for (int32 i = 0; i < num_words; i++) {
+ const std::vector<int32> &lexicon_entry =
+ lexicon[RandInt(0, lexicon.size() - 1)];
+ // the zeroth element of 'lexicon_entry' is how it appears in
+ // the lattice prior to word alignment.
+ int32 word = lexicon_entry[0];
+ if (word != 0) word_seq->push_back(word);
+ // add everything from position 2 in the lexicon entry, to the
+ // phone sequence.
+ phone_seq->insert(phone_seq->end(),
+ lexicon_entry.begin() + 2,
+ lexicon_entry.end());
+ }
+}
+
+
+
+void GenerateCompactLatticeRandomly(const std::vector<int32> &alignment,
+ const std::vector<int32> &words,
+ CompactLattice *clat) {
+ clat->DeleteStates();
+ clat->AddState();
+ clat->SetStart(0);
+ int32 cur_state = 0;
+ size_t word_start = 0, alignment_start = 0,
+ num_words = words.size(), num_transition_ids = alignment.size();
+ for (; word_start < num_words; word_start++) {
+ int32 word = words[word_start];
+ int32 ali_length = RandInt(0, num_transition_ids - alignment_start);
+ std::vector<int32> this_ali(ali_length);
+ for (int32 i = 0; i < ali_length; i++)
+ this_ali[i] = alignment[alignment_start + i];
+ alignment_start += ali_length;
+ CompactLatticeWeight weight(LatticeWeight::One(), this_ali);
+ int32 ilabel = word;
+ int32 next_state = clat->AddState();
+ CompactLatticeArc arc(ilabel, ilabel, weight, next_state);
+ clat->AddArc(cur_state, arc);
+ cur_state = next_state;
+ }
+ if (alignment_start < alignment.size()) {
+ int32 ali_length = num_transition_ids - alignment_start;
+ std::vector<int32> this_ali(ali_length);
+ for (int32 i = 0; i < ali_length; i++)
+ this_ali[i] = alignment[alignment_start + i];
+ alignment_start += ali_length;
+ CompactLatticeWeight weight(LatticeWeight::One(), this_ali);
+ int32 ilabel = 0;
+ int32 next_state = clat->AddState();
+ CompactLatticeArc arc(ilabel, ilabel, weight, next_state);
+ clat->AddArc(cur_state, arc);
+ cur_state = next_state;
+ }
+ clat->SetFinal(cur_state, CompactLatticeWeight::One());
+}
+
+
+
+void TestWordAlignLatticeLexicon() {
+ ContextDependency *ctx_dep;
+ TransitionModel *trans_model = GenRandTransitionModel(&ctx_dep);
+ bool allow_zero_words = true;
+ bool allow_empty_word = true;
+ bool allow_multiple_prons = true;
+
+ const std::vector<int32> &phones = trans_model->GetPhones();
+ std::vector<std::vector<int32> > lexicon;
+ GenerateLexicon(phones, allow_zero_words, allow_empty_word,
+ allow_multiple_prons, &lexicon);
+
+ std::vector<int32> phone_seq;
+ std::vector<int32> word_seq;
+ while (phone_seq.empty())
+ GenerateWordAndPhoneSequence(lexicon, &phone_seq, &word_seq);
+
+ PrintLexicon(lexicon);
+ PrintWordsAndPhones(word_seq, phone_seq);
+
+ std::vector<int32> alignment;
+ bool reorder = (RandInt(0, 1) == 0);
+ GenerateRandomAlignment(*ctx_dep, *trans_model, reorder,
+ phone_seq, &alignment);
+
+ CompactLattice clat;
+ GenerateCompactLatticeRandomly(alignment, word_seq, &clat);
+
+ KALDI_LOG << "clat is ";
+ WriteCompactLattice(std::cerr, false, clat);
+
+ WordAlignLatticeLexiconOpts opts;
+ WordAlignLatticeLexiconInfo lexicon_info(lexicon);
+ opts.reorder = reorder;
+ CompactLattice aligned_clat;
+ bool allow_duplicate_paths = true;
+ bool ans = WordAlignLatticeLexicon(clat, *trans_model, lexicon_info, opts,
+ &aligned_clat);
+ if (ans) { // We only test if it succeeded.
+ if (!TestWordAlignedLattice(lexicon_info, *trans_model, clat, aligned_clat,
+ allow_duplicate_paths)) {
+ KALDI_WARN << "Lattice failed test (activated because --test=true). "
+ << "Probable code error, please contact Kaldi maintainers.";
+ ans = false;
+ }
+ }
+
+ KALDI_LOG << "Aligned clat is ";
+ WriteCompactLattice(std::cerr, false, aligned_clat);
+ KALDI_ASSERT(ans);
+
+ Lattice lat;
+ ConvertLattice(clat, &lat);
+ int32 n = 1000; // a maximum.
+ Lattice nbest_lat;
+ std::vector<Lattice> nbest_lats;
+ fst::ShortestPath(lat, &nbest_lat, n);
+ fst::ConvertNbestToVector(nbest_lat, &nbest_lats);
+ KALDI_LOG << "Word-aligned lattice has " << nbest_lats.size() << " paths.";
+
+ delete ctx_dep;
+ delete trans_model;
+}
+
+} // end namespace kaldi
+
+int main() {
+ for (int32 i = 0; i < 3; i++)
+ kaldi::TestWordAlignLatticeLexicon();
+ std::cout << "Tests succeeded\n";
+}
+
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice-lexicon.cc b/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice-lexicon.cc
new file mode 100644
index 000000000..5cd75078c
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice-lexicon.cc
@@ -0,0 +1,935 @@
+// lat/word-align-lattice-lexicon.cc
+
+// Copyright 2013 Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "lat/phone-align-lattice.h"
+#include "lat/word-align-lattice-lexicon.h"
+#include "lat/lattice-functions.h"
+#include "hmm/transition-model.h"
+#include "hmm/hmm-utils.h"
+#include "util/stl-utils.h"
+
+namespace kaldi {
+
+const int kTemporaryEpsilon = -2;
+const int kNumStatesOffset = 1000; // relates to how we apply the
+// max-states to the lattices; relates to the --max-expand option which
+// stops this blowing up for pathological cases or in case of a mismatch.
+
+class LatticeLexiconWordAligner {
+ public:
+ typedef CompactLatticeArc::StateId StateId;
+ typedef CompactLatticeArc::Label Label;
+ typedef WordAlignLatticeLexiconInfo::ViabilityMap ViabilityMap;
+ typedef WordAlignLatticeLexiconInfo::LexiconMap LexiconMap;
+ typedef WordAlignLatticeLexiconInfo::NumPhonesMap NumPhonesMap;
+
+ /*
+ The Freshness enum is applied to phone and word-sequences in the computation
+ state; it is related to the epsilon sequencing problem. If a phone or word
+ is new (added by the latest transition), it is fresh. We are only concerned
+ with the freshness of the left-most word (i.e. word index 0) in words_, and
+ the freshness of that can take only two values, kNotFresh or kFresh. As
+ regards the phones_ variable, the difference between kFresh and kAllFresh
+ is: if we just appended a phone it's kFresh, but if we just shifted off a
+ phone or phones by outputting a nonempty word it's kAllFresh, meaning that
+ all sub-sequences of the phone sequence are new. Note: if a phone or
+ word-sequence is empty the freshness of that sequence does not matter or is
+ not defined; we'll let it default to kNotFresh.
+ */
+ typedef enum {
+ kNotFresh,
+ kFresh,
+ kAllFresh
+ } Freshness;
+
+ class ComputationState {
+ /// The state of the computation in which,
+ /// along a single path in the lattice, we work out the word
+ /// boundaries and output aligned arcs.
+ public:
+
+ /// Advance the computation state by adding the symbols and weights from
+ /// this arc. Outputs weight to "leftover_weight" and sets the weight to
+ /// 1.0 (this helps keep the state space small). Note: because we
+ /// previously did PhoneAlignLattice, we can assume this arc corresponds to
+ /// exactly one or zero phones.
+ void Advance(const CompactLatticeArc &arc,
+ const TransitionInformation &tmodel,
+ LatticeWeight *leftover_weight);
+
+ /// Returns true if, assuming we were to add one or more phones by calling
+ /// Advance one or more times on this, we might be able later to
+ /// successfully call TakeTransition. It's a kind of co-accessibility test
+ /// that avoids us creating an exponentially large number of states that
+ /// would contribute nothing to the final output.
+ bool ViableIfAdvanced(const ViabilityMap &viability_map) const;
+
+ int32 NumPhones() const { return phones_.size(); }
+ int32 NumWords() const { return words_.size(); }
+ int32 PendingWord() const { KALDI_ASSERT(!words_.empty()); return words_[0]; }
+ Freshness WordFreshness() const { return word_fresh_; }
+ Freshness PhoneFreshness() const { return phone_fresh_; }
+
+ /// This may be called at the end of a lattice, if it was forced
+ /// out. Note: we will only use "partial_word_label" if there are
+ /// phones without corresponding words; otherwise we'll use the
+ /// word label that was there.
+ void TakeForcedTransition(int32 partial_word_label,
+ ComputationState *next_state,
+ CompactLatticeArc *arc_out) const;
+
+ /// Take a transition, if possible; consume "num_phones" phones and (if
+ /// word_id != 0) the word "word_id" which must be the first word in words_.
+ /// Returns true if we could take the transition.
+ bool TakeTransition(const LexiconMap &lexicon_map,
+ int32 word_id,
+ int32 num_phones,
+ ComputationState *next_state,
+ CompactLatticeArc *arc_out) const;
+
+ bool IsEmpty() const { return (transition_ids_.empty() && words_.empty()); }
+
+ /// FinalWeight() will return "weight" if both transition_ids
+ /// and word_labels are empty, otherwise it will return
+ /// Weight::Zero().
+ LatticeWeight FinalWeight() const {
+ return (IsEmpty() ? weight_ : LatticeWeight::Zero());
+ }
+
+ size_t Hash() const {
+ VectorHasher<int32> vh;
+ const int32 p1 = 11117, p2 = 90647, p3 = 3967, p4 = 3557; // primes.
+ size_t ans = 0;
+ for (int32 i = 0; i < static_cast<int32>(transition_ids_.size()); i++) {
+ ans *= p1;
+ ans += vh(transition_ids_[i]);
+ }
+ ans += p2 * vh(words_)
+ + static_cast<int32>(word_fresh_) * p3
+ + static_cast<int32>(phone_fresh_) * p4;
+ // phones_ is determined by transition-id sequence so we don't
+ // need to include it in the hash.
+ return ans;
+ }
+
+ bool operator == (const ComputationState &other) const {
+ // phones_ is determined by transition-id sequence so don't
+ // need to compare it.
+ return (transition_ids_ == other.transition_ids_ &&
+ words_ == other.words_ &&
+ weight_ == other.weight_ &&
+ phone_fresh_ == other.phone_fresh_ &&
+ word_fresh_ == other.word_fresh_);
+ }
+
+ ComputationState(): phone_fresh_(kNotFresh), word_fresh_(kNotFresh),
+ weight_(LatticeWeight::One()) { } // initial state.
+
+ ComputationState(const ComputationState &other):
+ phones_(other.phones_), words_(other.words_),
+ phone_fresh_(other.phone_fresh_), word_fresh_(other.word_fresh_),
+ transition_ids_(other.transition_ids_), weight_(other.weight_) { }
+ private:
+ std::vector<int32> phones_; // sequence of pending phones
+ std::vector<int32> words_; // sequence of pending words.
+
+ // The following variables tell us whether the phones_ and/or words_
+ // variables were modified by the last operation on the computation state.
+ // This is used to make sure we don't have multiple ways of handling the
+ // same sequence, by taking transitions at multiple points (see code for
+ // more details). It's related to the epsilon sequencing problem.
+ // See the declaration above of the enum "Freshness".
+ Freshness phone_fresh_;
+ Freshness word_fresh_;
+
+ std::vector<std::vector<int32> > transition_ids_; // sequence of transition-ids for each phone..
+
+ LatticeWeight weight_; // contains two floats.
+ };
+
+
+ static void AppendVectors(
+ std::vector<std::vector<int32> >::const_iterator input_begin,
+ std::vector<std::vector<int32> >::const_iterator input_end,
+ std::vector<int32> *output);
+
+ struct Tuple {
+ Tuple(StateId input_state, ComputationState comp_state):
+ input_state(input_state), comp_state(comp_state) {}
+ Tuple() {}
+ StateId input_state;
+ ComputationState comp_state;
+ };
+
+ struct TupleHash {
+ size_t operator() (const Tuple &state) const {
+ return state.input_state + 102763 * state.comp_state.Hash();
+ // 102763 is just an arbitrary prime number
+ }
+ };
+ struct TupleEqual {
+ bool operator () (const Tuple &state1, const Tuple &state2) const {
+ // treat this like operator ==
+ return (state1.input_state == state2.input_state
+ && state1.comp_state == state2.comp_state);
+ }
+ };
+
+ typedef unordered_map<Tuple, StateId, TupleHash, TupleEqual> MapType;
+
+ // This function may alter queue_.
+ StateId GetStateForTuple(const Tuple &tuple) {
+ MapType::iterator iter = map_.find(tuple);
+ if (iter == map_.end()) { // not in map.
+ StateId output_state = lat_out_->AddState();
+ map_[tuple] = output_state;
+ queue_.push_back(std::make_pair(tuple, output_state));
+ return output_state;
+ } else {
+ return iter->second;
+ }
+ }
+
+ // This function may alter queue_, via GetStateForTuple.
+ void ProcessTransition(StateId prev_output_state, // state-id of from-state in output lattice
+ const Tuple &next_tuple,
+ CompactLatticeArc *arc) { // arc to add (must first modify it by adding "nextstate")
+ arc->nextstate = GetStateForTuple(next_tuple); // adds it to queue_ if new.
+ lat_out_->AddArc(prev_output_state, *arc);
+ }
+
+ // Process any epsilon transitions out of this state. This refers to
+ // filler-words, such as silence, which have epsilon as the symbol in the
+ // original lattice, or no symbol at all (typically the original lattice
+ // will be determinized with epsilon-removal so there is no separate arc,
+ // just one or more extra phones that don't match up with any word.
+ void ProcessEpsilonTransitions(const Tuple &tuple, StateId output_state);
+
+ // Process any non-epsilon transitions out of this state in the output lattice.
+ void ProcessWordTransitions(const Tuple &tuple, StateId output_state);
+
+ // Take any transitions that correspond to advancing along arcs arc in the
+ // original FST.
+ void PossiblyAdvanceArc(const Tuple &tuple, StateId output_state);
+
+ /// Process all final-probs (normal case, no forcing-out).
+ /// returns true if we had at least one final-prob.
+ bool ProcessFinal();
+
+ /// This function returns true if the state "output_state" in the output
+ /// lattice has arcs out that have either a non-epsilon symbol or transition-ids
+ /// in the string of the weight.
+ bool HasNonEpsArcsOut(StateId output_state);
+
+ /// Creates arcs from all the tuples that were final in the original lattice
+ /// but have no arcs out of them in the output lattice that consume words or
+ /// phones-- does so by "forcing out" any words and phones there are pending
+ /// in the computation states. This function is only called if no states were
+ /// "naturally" final; this will only happen for lattices that were forced out
+ /// during decoding.
+ void ProcessFinalForceOut();
+
+ // Process all final-probs -- a wrapper function that handles the forced-out case.
+ void ProcessFinalWrapper() {
+ if (final_queue_.empty()) {
+ KALDI_WARN << "No final-probs to process.";
+ error_ = true;
+ return;
+ }
+ if (ProcessFinal()) return;
+ error_ = true;
+ KALDI_WARN << "Word-aligning lattice: lattice was forced out, will have partial words at end.";
+
+ ProcessFinalForceOut();
+
+ if (ProcessFinal()) return;
+ KALDI_WARN << "Word-aligning lattice: had no final-states even after forcing out "
+ << "(result will be empty). This probably indicates wrong input.";
+ return;
+ }
+
+ void ProcessQueueElement() {
+ KALDI_ASSERT(!queue_.empty());
+ Tuple tuple = queue_.back().first;
+ StateId output_state = queue_.back().second;
+ queue_.pop_back();
+
+ ProcessEpsilonTransitions(tuple, output_state);
+ ProcessWordTransitions(tuple, output_state);
+ PossiblyAdvanceArc(tuple, output_state);
+
+ // Note: we'll do a bit more filtering in ProcessFinal(), meaning
+ // that we won't necessarily give a final-prob to all of the things
+ // that go onto final_queue_.
+ if (lat_in_.Final(tuple.input_state) != CompactLatticeWeight::Zero())
+ final_queue_.push_back(std::make_pair(tuple, output_state));
+ }
+
+ LatticeLexiconWordAligner(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const WordAlignLatticeLexiconInfo &lexicon_info,
+ int32 max_states,
+ int32 partial_word_label,
+ CompactLattice *lat_out):
+ lat_in_(lat), tmodel_(tmodel), lexicon_info_(lexicon_info),
+ max_states_(max_states),
+ lat_out_(lat_out),
+ partial_word_label_(partial_word_label == 0 ?
+ kTemporaryEpsilon : partial_word_label),
+ error_(false) {
+ // lat_in_ is after PhoneAlignLattice, it is not deterministic and contains epsilons
+
+ fst::CreateSuperFinal(&lat_in_); // Creates a super-final state, so the
+ // only final-probs are One(). Note: the member lat_in_ is not a reference.
+
+ }
+
+ // Removes epsilons; also removes unreachable states...
+ // not sure if these would exist if original was connected.
+ // This also replaces the temporary symbols for the silence
+ // and partial-words, with epsilons, if we wanted epsilons.
+ void RemoveEpsilonsFromLattice() {
+ Connect(lat_out_);
+ RmEpsilon(lat_out_, true); // true = connect.
+ std::vector<int32> syms_to_remove;
+ syms_to_remove.push_back(kTemporaryEpsilon);
+ RemoveSomeInputSymbols(syms_to_remove, lat_out_);
+ Project(lat_out_, fst::PROJECT_INPUT);
+ }
+
+ bool AlignLattice() {
+ lat_out_->DeleteStates();
+ if (lat_in_.Start() == fst::kNoStateId) {
+ KALDI_WARN << "Trying to word-align empty lattice.";
+ return false;
+ }
+ ComputationState initial_comp_state;
+ Tuple initial_tuple(lat_in_.Start(), initial_comp_state);
+ StateId start_state = GetStateForTuple(initial_tuple);
+ lat_out_->SetStart(start_state);
+
+ while (!queue_.empty()) {
+ if (max_states_ > 0 && lat_out_->NumStates() > max_states_) {
+ KALDI_WARN << "Number of states in lattice exceeded max-states of "
+ << max_states_ << ", original lattice had "
+ << lat_in_.NumStates() << " states. Returning empty lattice.";
+ lat_out_->DeleteStates();
+ return false;
+ }
+ ProcessQueueElement();
+ }
+ ProcessFinalWrapper();
+
+ RemoveEpsilonsFromLattice();
+
+ return !error_;
+ }
+
+ CompactLattice lat_in_;
+ const TransitionInformation &tmodel_;
+ const WordAlignLatticeLexiconInfo &lexicon_info_;
+ int32 max_states_;
+ CompactLattice *lat_out_;
+
+ std::vector<std::pair<Tuple, StateId> > queue_;
+
+ std::vector<std::pair<Tuple, StateId> > final_queue_; // as queue_, but
+ // just contains states that may have final-probs to process. We process these
+ // all at once, at the end.
+
+ MapType map_; // map from tuples to StateId.
+ int32 partial_word_label_;
+ bool error_;
+};
+
+// static
+void LatticeLexiconWordAligner::AppendVectors(
+ std::vector<std::vector<int32> >::const_iterator input_begin,
+ std::vector<std::vector<int32> >::const_iterator input_end,
+ std::vector<int32> *output) {
+ size_t size = 0;
+ for (std::vector<std::vector<int32> >::const_iterator iter = input_begin;
+ iter != input_end;
+ ++iter)
+ size += iter->size();
+ output->clear();
+ output->reserve(size);
+ for (std::vector<std::vector<int32> >::const_iterator iter = input_begin;
+ iter != input_end;
+ ++iter)
+ output->insert(output->end(), iter->begin(), iter->end());
+}
+
+void LatticeLexiconWordAligner::ProcessEpsilonTransitions(
+ const Tuple &tuple, StateId output_state) {
+ const ComputationState &comp_state = tuple.comp_state;
+ StateId input_state = tuple.input_state;
+ StateId zero_word = 0;
+ NumPhonesMap::const_iterator iter =
+ lexicon_info_.num_phones_map_.find(zero_word);
+ if (iter == lexicon_info_.num_phones_map_.end()) {
+ return; // No epsilons to match; this can only happen if the lexicon
+ // we were provided had no lines with 0 as the first entry, i.e. no
+ // optional silences or the like.
+ }
+ // Now decide what range of phone-lengths we must process. This is all
+ // about only getting a single opportunity to process any given sequence of
+ // phones.
+ int32 min_num_phones, max_num_phones;
+
+ if (comp_state.PhoneFreshness() == kAllFresh) {
+ // All sub-sequences of the phone sequence are fresh because we just
+ // shifted some phones off, so we do this for all lengths. We can limit
+ // ourselves to the range of possible lengths for the epsilon symbol,
+ // in the lexicon.
+ min_num_phones = iter->second.first;
+ max_num_phones = std::min(iter->second.second, comp_state.NumPhones());
+ } else if (comp_state.PhoneFreshness() == kFresh) {
+ // only last phone is "fresh", so only consider the sequence of all
+ // phones including the last one.
+ int32 num_phones = comp_state.NumPhones();
+ if (num_phones >= iter->second.first &&
+ num_phones <= iter->second.second) {
+ min_num_phones = num_phones;
+ max_num_phones = num_phones;
+ } else {
+ return;
+ }
+ } else { // kNotFresh
+ return;
+ }
+
+ if (min_num_phones == 0)
+ KALDI_ERR << "Lexicon error: epsilon transition that produces no output:";
+
+ for (int32 num_phones = min_num_phones;
+ num_phones <= max_num_phones;
+ num_phones++) {
+ Tuple next_tuple;
+ next_tuple.input_state = input_state; // We're not taking a transition in the
+ // input FST so this stays the same.
+ CompactLatticeArc arc;
+ if (comp_state.TakeTransition(lexicon_info_.lexicon_map_,
+ zero_word,
+ num_phones,
+ &next_tuple.comp_state,
+ &arc)) {
+ ProcessTransition(output_state, next_tuple, &arc);
+ }
+ }
+}
+
+void LatticeLexiconWordAligner::ProcessWordTransitions(
+ const Tuple &tuple, StateId output_state) {
+ const ComputationState &comp_state = tuple.comp_state;
+ StateId input_state = tuple.input_state;
+ if (comp_state.NumWords() > 0) {
+ int32 min_num_phones, max_num_phones;
+ int32 word_id = comp_state.PendingWord();
+
+ if (comp_state.WordFreshness() == kFresh ||
+ comp_state.PhoneFreshness() == kAllFresh) {
+ // Just saw word, or shifted phones,
+ // so 1st opportunity to process phone-sequences of all possible sizes,
+ // with this word.
+ NumPhonesMap::const_iterator iter =
+ lexicon_info_.num_phones_map_.find(word_id);
+ if (iter == lexicon_info_.num_phones_map_.end()) {
+ KALDI_ERR << "Word " << word_id << " is not present in the lexicon.";
+ }
+ min_num_phones = iter->second.first;
+ max_num_phones = std::min(iter->second.second,
+ comp_state.NumPhones());
+ } else if (comp_state.PhoneFreshness() == kFresh) {
+ // just the latest phone is new -> just try to process the
+ // phone-sequence of all the phones we have.
+ min_num_phones = comp_state.NumPhones();
+ max_num_phones = min_num_phones;
+ } else {
+ return; // Nothing to do, since neither the word nor the phones are fresh.
+ }
+
+ for (int32 num_phones = min_num_phones;
+ num_phones <= max_num_phones;
+ num_phones++) {
+ Tuple next_tuple;
+ next_tuple.input_state = input_state; // We're not taking a transition in the
+ // input FST so this stays the same.
+ CompactLatticeArc arc;
+ if (comp_state.TakeTransition(lexicon_info_.lexicon_map_,
+ word_id,
+ num_phones,
+ &next_tuple.comp_state,
+ &arc)) {
+ ProcessTransition(output_state, next_tuple, &arc);
+ }
+ }
+ }
+}
+
+
+void LatticeLexiconWordAligner::PossiblyAdvanceArc(
+ const Tuple &tuple, StateId output_state) {
+ if (tuple.comp_state.ViableIfAdvanced(lexicon_info_.viability_map_)) {
+ for(fst::ArcIterator<CompactLattice> aiter(lat_in_, tuple.input_state);
+ !aiter.Done(); aiter.Next()) {
+ const CompactLatticeArc &arc_in = aiter.Value();
+ Tuple next_tuple(arc_in.nextstate, tuple.comp_state);
+ LatticeWeight arc_weight;
+ next_tuple.comp_state.Advance(arc_in, tmodel_, &arc_weight);
+ // Note: GetStateForTuple will add the tuple to the queue,
+ // if necessary.
+
+ StateId next_output_state = GetStateForTuple(next_tuple);
+ CompactLatticeArc arc_out(0, 0,
+ CompactLatticeWeight(arc_weight,
+ std::vector<int32>()),
+ next_output_state);
+ lat_out_->AddArc(output_state,
+ arc_out);
+ }
+ }
+}
+
+bool LatticeLexiconWordAligner::ProcessFinal() {
+ bool saw_final = false;
+ // Find final-states...
+ for (size_t i = 0; i < final_queue_.size(); i++) {
+ const Tuple &tuple = final_queue_[i].first;
+ StateId output_state = final_queue_[i].second;
+ KALDI_ASSERT(lat_in_.Final(tuple.input_state) == CompactLatticeWeight::One());
+ LatticeWeight final_weight = tuple.comp_state.FinalWeight();
+ if (final_weight != LatticeWeight::Zero()) {
+ // note: final_weight is only nonzero if there are no
+ // pending transition-ids, so there is no string component.
+ std::vector<int32> empty_vec;
+ lat_out_->SetFinal(output_state,
+ CompactLatticeWeight(final_weight, empty_vec));
+ saw_final = true;
+ }
+ }
+ return saw_final;
+}
+
+bool LatticeLexiconWordAligner::HasNonEpsArcsOut(StateId output_state) {
+ for (fst::ArcIterator<CompactLattice> aiter(*lat_out_, output_state);
+ !aiter.Done(); aiter.Next()) {
+ const CompactLatticeArc &arc = aiter.Value();
+ if (arc.ilabel != 0 || arc.olabel != 0 || !arc.weight.String().empty())
+ return true;
+ }
+ return false;
+}
+
+void LatticeLexiconWordAligner::ProcessFinalForceOut() {
+ KALDI_ASSERT(queue_.empty());
+ std::vector<std::pair<Tuple, StateId> > new_final_queue_;
+ new_final_queue_.reserve(final_queue_.size());
+ for (size_t i = 0; i < final_queue_.size();i++) { // note: all the states will
+ // be final in the orig. lattice
+ const Tuple &tuple = final_queue_[i].first;
+ StateId output_state = final_queue_[i].second;
+
+ if (!HasNonEpsArcsOut(output_state)) { // This if-statement
+ // avoids forcing things out too early, when they had words
+ // that could naturally have been put out. [without it,
+ // we'd have multiple alternate paths at the end.]
+
+ CompactLatticeArc arc;
+ Tuple next_tuple;
+ next_tuple.input_state = tuple.input_state;
+ tuple.comp_state.TakeForcedTransition(partial_word_label_,
+ &next_tuple.comp_state,
+ &arc);
+ // Note: the following call may add to queue_, but we'll clear it,
+ // we don't want to process these states.
+ StateId new_state = GetStateForTuple(next_tuple);
+ arc.nextstate = new_state;
+ lat_out_->AddArc(output_state, arc);
+ new_final_queue_.push_back(std::make_pair(next_tuple, new_state));
+ }
+ }
+ queue_.clear();
+ std::swap(final_queue_, new_final_queue_);
+}
+
+void LatticeLexiconWordAligner::ComputationState::Advance(
+ const CompactLatticeArc &arc, const TransitionInformation &tmodel,
+ LatticeWeight *weight) {
+ const std::vector<int32> &tids = arc.weight.String();
+ int32 phone;
+ if (tids.empty()) phone = 0;
+ else {
+ phone = tmodel.TransitionIdToPhone(tids.front());
+ KALDI_ASSERT(phone == tmodel.TransitionIdToPhone(tids.back()) &&
+ "Error: lattice is not phone-aligned.");
+ }
+ if (arc.ilabel != 0) { // note: arc.ilabel==arc.olabel (acceptor)
+ words_.push_back(arc.ilabel);
+ // Note: the word freshness only applies to the word in position 0,
+ // so only if the word-sequence is now of size 1, is it fresh.
+ if (words_.size() == 1) word_fresh_ = kFresh;
+ else word_fresh_ = kNotFresh;
+ } else { // No word added -> word not fresh.
+ word_fresh_ = kNotFresh;
+ }
+ if (phone != 0) {
+ phones_.push_back(phone);
+ transition_ids_.push_back(tids);
+ phone_fresh_ = kFresh;
+ } else {
+ phone_fresh_ = kNotFresh;
+ }
+ *weight = Times(weight_, arc.weight.Weight()); // will go on arc in output lattice
+ weight_ = LatticeWeight::One();
+}
+
+
+bool LatticeLexiconWordAligner::ComputationState::ViableIfAdvanced(
+ const ViabilityMap &viability_map) const {
+ /* This will ideally to return true if and only if we can ever take
+ any kind of transition out of this state after "advancing" it by adding
+ words and/or phones. It's OK to return true in some cases where the
+ condition is false, though, if it's a pain to check, because the result
+ will just be doing extra work for nothing (those states won't be
+ co-accessible in the output).
+ */
+ if (phones_.empty()) return true;
+ if (words_.empty()) return true;
+ else {
+ // neither phones_ or words_ is empty. Return true if a longer sequence
+ // than this phone sequence can have either zero (<eps>/epsilon) or the
+ // first element of words_, as an entry in the lexicon with that phone
+ // sequence.
+ ViabilityMap::const_iterator iter = viability_map.find(phones_);
+ if (iter == viability_map.end()) return false;
+ else {
+ const std::vector<int32> &this_set = iter->second; // sorted vector.
+ // Return true if either 0 or words_[0] is in the set. If 0 is
+ // in the set, it will be the 1st element of the vector, because it's
+ // the lowest element.
+ return (this_set.front() == 0 ||
+ std::binary_search(this_set.begin(), this_set.end(), words_[0]));
+ }
+ }
+}
+
+
+void LatticeLexiconWordAligner::ComputationState::TakeForcedTransition(
+ int32 partial_word_label,
+ ComputationState *next_state,
+ CompactLatticeArc *arc_out) const {
+ KALDI_ASSERT(!IsEmpty());
+
+ next_state->phones_.clear();
+ next_state->words_.clear();
+ next_state->transition_ids_.clear();
+ // neither of the following variables should matter, actually,
+ // they will never be inspected. So just set them to kFresh for consistency,
+ // so they end up at the same place in the tuple-map_.
+ next_state->word_fresh_ = kFresh;
+ next_state->phone_fresh_ = kFresh;
+ next_state->weight_ = LatticeWeight::One();
+
+ int32 word_id;
+ if (words_.size() >= 1) {
+ word_id = words_[0];
+ if (words_.size() > 1)
+ KALDI_WARN << "Word-aligning lattice: discarding extra word at end of lattice"
+ << "(forced-out).";
+ } else {
+ word_id = partial_word_label;
+ }
+ KALDI_ASSERT(word_id != 0); // any zeros would have been replaced with
+ // 'temporary epsilon' = 2.
+ std::vector<int32> appended_transition_ids;
+ AppendVectors(transition_ids_.begin(),
+ transition_ids_.end(),
+ &appended_transition_ids);
+ arc_out->ilabel = word_id;
+ arc_out->olabel = word_id;
+ arc_out->weight = CompactLatticeWeight(weight_,
+ appended_transition_ids);
+ // arc_out->nextstate will be set by the calling code.
+}
+
+
+bool LatticeLexiconWordAligner::ComputationState::TakeTransition(
+ const LexiconMap &lexicon_map, int32 word_id, int32 num_phones,
+ ComputationState *next_state, CompactLatticeArc *arc_out) const {
+ KALDI_ASSERT(word_id == 0 || (!words_.empty() && word_id == words_[0]));
+ KALDI_ASSERT(num_phones <= static_cast<int32>(phones_.size()));
+
+ std::vector<int32> lexicon_key;
+ lexicon_key.reserve(1 + num_phones);
+ lexicon_key.push_back(word_id); // put 1st word in lexicon_key.
+ lexicon_key.insert(lexicon_key.end(),
+ phones_.begin(), phones_.begin() + num_phones);
+ LexiconMap::const_iterator iter = lexicon_map.find(lexicon_key);
+ if (iter == lexicon_map.end()) { // no such entry
+ return false;
+ } else { // Entry exists. We'll create an arc.
+ next_state->phones_.assign(phones_.begin() + num_phones, phones_.end());
+ next_state->words_.assign(words_.begin() + (word_id == 0 ? 0 : 1),
+ words_.end());
+ next_state->transition_ids_.assign(transition_ids_.begin() + num_phones,
+ transition_ids_.end());
+ next_state->word_fresh_ =
+ (word_id != 0 && !next_state->words_.empty()) ? kFresh : kNotFresh;
+ next_state->phone_fresh_ =
+ (next_state->phones_.empty() || num_phones == 0) ? kNotFresh : kAllFresh;
+
+ // this next thing is a bit hard to explain. If we just consumed a word with
+ // no phones, we treat the phones as fresh. The idea is that if we need to
+ // both consume a word with no phones and a phone with no words (e.g.
+ // an empty word and then silence), we need to have the phones marked
+ // as fresh in order for this to be possible.
+ if (num_phones == 0 && word_id != 0 && !next_state->phones_.empty())
+ next_state->phone_fresh_ = kAllFresh;
+
+ next_state->weight_ = LatticeWeight::One();
+
+ if (GetVerboseLevel() >= 5) {
+ std::ostringstream ostr;
+ for (size_t i = 0; i < num_phones; i++)
+ ostr << phones_[i] << " ";
+ KALDI_VLOG(5) << "Taking arc with word = " << word_id
+ << " and phones = " << ostr.str()
+ << ", output-word = " << iter->second
+ << ", dest-state has num-words = " << next_state->words_.size()
+ << " and num-phones = " << next_state->phones_.size();
+ }
+
+ // Set arc_out:
+ Label word_id = iter->second; // word_id will typically be
+ // the same as words_[0], i.e. the
+ // word we consumed.
+
+ KALDI_ASSERT(word_id != 0); // we replaced zeros with 'temporary epsilon' = -2.
+
+ std::vector<int32> appended_transition_ids;
+ AppendVectors(transition_ids_.begin(),
+ transition_ids_.begin() + num_phones,
+ &appended_transition_ids);
+ arc_out->ilabel = word_id;
+ arc_out->olabel = word_id;
+ arc_out->weight = CompactLatticeWeight(weight_,
+ appended_transition_ids);
+ // arc_out->nextstate will be set in the calling code.
+ return true;
+ }
+}
+
+void WordAlignLatticeLexiconInfo::UpdateViabilityMap(
+ const std::vector<int32> &lexicon_entry) {
+ int32 word = lexicon_entry[0]; // note: word may be zero.
+ int32 num_phones = static_cast<int32>(lexicon_entry.size()) - 2;
+ std::vector<int32> phones;
+ if (num_phones > 0)
+ phones.reserve(num_phones - 1);
+ // for each nonempty sequence of phones that is a strict prefix of the phones
+ // in the lexicon entry (i.e. lexicon_entry [2 ... ]), add the word to the set
+ // in viability_map_[phones].
+ for (int32 n = 0; n < num_phones - 1; n++) {
+ phones.push_back(lexicon_entry[n + 2]); // first phone is at position 2.
+ // n+1 is the length of the sequence of phones
+ viability_map_[phones].push_back(word);
+ }
+}
+
+void WordAlignLatticeLexiconInfo::FinalizeViabilityMap() {
+ for (ViabilityMap::iterator iter = viability_map_.begin();
+ iter != viability_map_.end();
+ ++iter) {
+ std::vector<int32> &words = iter->second;
+ SortAndUniq(&words);
+ KALDI_ASSERT(words[0] >= 0 && "Error: negative labels in lexicon.");
+ }
+}
+
+/// Update the map from a vector (orig-word-symbol phone1 phone2 ... ) to the
+/// new word-symbol. The new word-symbol must always be nonzero; we'll replace
+/// it with kTemporaryEpsilon = -2, if it was zero.
+void WordAlignLatticeLexiconInfo::UpdateLexiconMap(
+ const std::vector<int32> &lexicon_entry) {
+ KALDI_ASSERT(lexicon_entry.size() >= 2);
+ std::vector<int32> key;
+ key.reserve(lexicon_entry.size() - 1);
+ // add the original word:
+ key.push_back(lexicon_entry[0]);
+ // add the phones:
+ key.insert(key.end(), lexicon_entry.begin() + 2, lexicon_entry.end());
+ int32 new_word = lexicon_entry[1]; // This will typically be the same as
+ // the original word at lexicon_entry[0] but is allowed to differ.
+ if (new_word == 0) new_word = kTemporaryEpsilon; // replace 0's with -2;
+ // we'll revert the change at the end.
+ if (lexicon_map_.count(key) != 0) {
+ if (lexicon_map_[key] == new_word)
+ KALDI_WARN << "Duplicate entry in lexicon map for word " << lexicon_entry[0];
+ else
+ KALDI_ERR << "Duplicate entry in lexicon map for word " << lexicon_entry[0]
+ << " with inconsistent to-word.";
+ }
+ lexicon_map_[key] = new_word;
+
+ if (lexicon_entry[0] != lexicon_entry[1]) {
+ // Add reverse lexicon entry, this time with no 0 -> -2 mapping.
+ key[0] = lexicon_entry[1];
+ // Note: we ignore the situation where there are conflicting
+ // entries in reverse_lexicon_map_, as we never actually inspect
+ // the contents so it won't matter.
+ reverse_lexicon_map_[key] = lexicon_entry[0];
+ }
+}
+
+void WordAlignLatticeLexiconInfo::UpdateNumPhonesMap(
+ const std::vector<int32> &lexicon_entry) {
+ int32 num_phones = static_cast<int32>(lexicon_entry.size()) - 2;
+ int32 word = lexicon_entry[0];
+ if (num_phones_map_.count(word) == 0)
+ num_phones_map_[word] = std::make_pair(num_phones, num_phones);
+ else {
+ std::pair<int32, int32> &pr = num_phones_map_[word];
+ pr.first = std::min(pr.first, num_phones); // update min-num-phones
+ pr.second = std::max(pr.second, num_phones); // update max-num-phones
+ if (pr.first == 0 && word == 0)
+ KALDI_ERR << "Zero word with empty pronunciation is not allowed.";
+ }
+}
+
+/// Entry contains new-word-id phone1 phone2 ...
+/// equivalent to all but the 1st entry on a line of the input file.
+bool WordAlignLatticeLexiconInfo::IsValidEntry(const std::vector<int32> &entry) const {
+ KALDI_ASSERT(!entry.empty());
+ LexiconMap::const_iterator iter = lexicon_map_.find(entry);
+ if (iter != lexicon_map_.end()) {
+ int32 tgt_word = (iter->second == kTemporaryEpsilon ? 0 : iter->second);
+ if (tgt_word == entry[0]) return true; // symmetric entry.
+ // this means that that there would be an output-word with this
+ // value, and this sequence of phones.
+ }
+ // For entries that were not symmetric:
+ return (reverse_lexicon_map_.count(entry) != 0);
+}
+
+int32 WordAlignLatticeLexiconInfo::EquivalenceClassOf(int32 word) const {
+ unordered_map<int32, int32>::const_iterator iter =
+ equivalence_map_.find(word);
+ if (iter == equivalence_map_.end()) return word; // not in map.
+ else return iter->second;
+}
+
+void WordAlignLatticeLexiconInfo::UpdateEquivalenceMap(
+ const std::vector<std::vector<int32> > &lexicon) {
+ std::vector<std::pair<int32, int32> > equiv_pairs; // pairs of
+ // (lower,higher) words that are equivalent.
+ for (size_t i = 0; i < lexicon.size(); i++) {
+ KALDI_ASSERT(lexicon[i].size() >= 2);
+ int32 w1 = lexicon[i][0], w2 = lexicon[i][1];
+ if (w1 == w2) continue; // They are the same; this provides no information
+ // about equivalence, since any word is equivalent
+ // to itself.
+ if (w1 > w2) std::swap(w1, w2); // make sure w1 < w2.
+ equiv_pairs.push_back(std::make_pair(w1, w2));
+ }
+ SortAndUniq(&equiv_pairs);
+ equivalence_map_.clear();
+ for (size_t i = 0; i < equiv_pairs.size(); i++) {
+ int32 w1 = equiv_pairs[i].first, w2 = equiv_pairs[i].second,
+ w1dash = EquivalenceClassOf(w1);
+ equivalence_map_[w2] = w1dash;
+ }
+}
+
+
+WordAlignLatticeLexiconInfo::WordAlignLatticeLexiconInfo(
+ const std::vector<std::vector<int32> > &lexicon) {
+ for (size_t i = 0; i < lexicon.size(); i++) {
+ const std::vector<int32> &lexicon_entry = lexicon[i];
+ KALDI_ASSERT(lexicon_entry.size() >= 2);
+ UpdateViabilityMap(lexicon_entry);
+ UpdateLexiconMap(lexicon_entry);
+ UpdateNumPhonesMap(lexicon_entry);
+ }
+ FinalizeViabilityMap();
+ UpdateEquivalenceMap(lexicon);
+}
+
+// This is the wrapper function for users to call.
+bool WordAlignLatticeLexicon(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const WordAlignLatticeLexiconInfo &lexicon_info,
+ const WordAlignLatticeLexiconOpts &opts,
+ CompactLattice *lat_out) {
+ PhoneAlignLatticeOptions phone_align_opts;
+ phone_align_opts.reorder = opts.reorder;
+ phone_align_opts.replace_output_symbols = false;
+ phone_align_opts.remove_epsilon = false;
+
+ // Input Lattice should be deterministic and w/o epsilons.
+ bool test = true;
+ uint64 props = lat.Properties(fst::kIDeterministic|fst::kIEpsilons, test);
+ if (props != fst::kIDeterministic) {
+ KALDI_WARN << "[Lattice has input epsilons and/or is not input-deterministic "
+ << "(in Mohri sense)]-- i.e. lattice is not deterministic. "
+ << "Word-alignment may be slow and-or blow up in memory.";
+ }
+
+ CompactLattice phone_aligned_lat;
+ bool ans = PhoneAlignLattice(lat, tmodel, phone_align_opts,
+ &phone_aligned_lat);
+ // 'phone_aligned_lat' is no longer deterministic and contains epsilons.
+
+ int32 max_states;
+ if (opts.max_expand <= 0) {
+ max_states = -1;
+ } else {
+ // The 1000 is a fixed offset to give it more wiggle room for very
+ // small inputs.
+ max_states = kNumStatesOffset + opts.max_expand * phone_aligned_lat.NumStates();
+ }
+
+ // If ans == false, we hope this is due to a forced-out lattice, and we try to
+ // continue.
+ LatticeLexiconWordAligner aligner(phone_aligned_lat, tmodel, lexicon_info,
+ max_states, opts.partial_word_label, lat_out);
+ // We'll let the calling code warn if this is false; it will know the utterance-id.
+ ans = aligner.AlignLattice() && ans;
+ return ans;
+}
+
+bool ReadLexiconForWordAlign (std::istream &is,
+ std::vector<std::vector<int32> > *lexicon) {
+ lexicon->clear();
+ std::string line;
+ while (std::getline(is, line)) {
+ std::vector<int32> this_entry;
+ if (!SplitStringToIntegers(line, " \t\r", false, &this_entry) ||
+ this_entry.size() < 2) {
+ KALDI_WARN << "Lexicon line '" << line << "' is invalid";
+ return false;
+ }
+ lexicon->push_back(this_entry);
+ }
+ return (!lexicon->empty());
+}
+
+} // namespace kaldi
+
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice-lexicon.h b/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice-lexicon.h
new file mode 100644
index 000000000..5a4edcad7
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice-lexicon.h
@@ -0,0 +1,160 @@
+// lat/word-align-lattice-lexicon.h
+
+// Copyright 2013 Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_LAT_WORD_ALIGN_LATTICE_LEXICON_H_
+#define KALDI_LAT_WORD_ALIGN_LATTICE_LEXICON_H_
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fstext/fstext-lib.h"
+#include "hmm/transition-model.h"
+#include "lat/kaldi-lattice.h"
+
+namespace kaldi {
+
+/** Read the lexicon in the special format required for word alignment. Each line has
+ a series of integers on it (at least two on each line), representing:
+
+ <old-word-id> <new-word-id> [<phone-id-1> [<phone-id-2> ... ] ]
+
+ Here, <old-word-id> is the word-id that appears in the lattice before alignment, and
+ <new-word-id> is the word-is that should appear in the lattice after alignment. This
+ is mainly useful when the lattice may have no symbol for the optional-silence arcs
+ (so <old-word-id> would equal zero), but we want it to be output with a symbol on those
+ arcs (so <new-word-id> would be nonzero).
+ If the silence should not be added to the lattice, both <old-word-id> and <new-word-id>
+ may be zero.
+
+ This function is very simple: it just reads in a series of lines from a text file,
+ each with at least two integers on them.
+*/
+bool ReadLexiconForWordAlign (std::istream &is,
+ std::vector<std::vector<int32> > *lexicon);
+
+
+
+/// This class extracts some information from the lexicon and stores it
+/// in a suitable form for the word-alignment code to use.
+class WordAlignLatticeLexiconInfo {
+ public:
+ WordAlignLatticeLexiconInfo(const std::vector<std::vector<int32> > &lexicon);
+
+ /// Returns true if this lexicon-entry can appear, intepreted as
+ /// (output-word phone1 phone2 ...). This is just used in testing code.
+ bool IsValidEntry(const std::vector<int32> &entry) const;
+
+ /// Purely for the testing code, we map words into equivalence classes derived
+ /// from the mappings in the first two fields of each line in the lexicon. This
+ /// function maps from each word-id to the lowest member of its equivalence class.
+ int32 EquivalenceClassOf(int32 word) const;
+ protected:
+ friend class LatticeLexiconWordAligner;
+
+ void UpdateViabilityMap(const std::vector<int32> &lexicon_entry);
+ void UpdateLexiconMap(const std::vector<int32> &lexicon_entry);
+ void UpdateNumPhonesMap(const std::vector<int32> &lexicon_entry);
+ void UpdateEquivalenceMap(const std::vector<std::vector<int32> > &lexicon);
+
+ void FinalizeViabilityMap(); // sorts the vectors.
+
+ /// The type ViabilityMap maps from sequences of phones (excluding the empty
+ /// sequence), to the sets of all word-labels [on the input lattice] that
+ /// could correspond to phone sequences that start with s [but are longer than
+ /// s]. The sets of word-labels are represented as sorted vectors of int32
+ /// Note: the zero word-label is included here. This is used in a kind
+ /// of co-accessibility test, to see whether it is worth extending this state
+ /// by traversing arcs in the input lattice.
+ typedef unordered_map<std::vector<int32>,
+ std::vector<int32>,
+ VectorHasher<int32> > ViabilityMap;
+
+ /// This is a map from a vector (orig-word-symbol phone1 phone2 ... ) to
+ /// the new word-symbol. [todo: make sure the new word-symbol is always nonzero.]
+ typedef unordered_map<std::vector<int32>, int32,
+ VectorHasher<int32> > LexiconMap;
+
+ /// This is a map from the word-id (as present in the original lattice)
+ /// to the minimum and maximum #phones of lexicon entries for that word.
+ /// It helps improve efficiency.
+ typedef unordered_map<int32, std::pair<int32, int32> > NumPhonesMap;
+
+ /// This is used only in testing code; it defines a mapping from a word
+ /// to the primary member of that word's equivalence-class.
+ typedef unordered_map<int32, int32> EquivalenceMap;
+
+ // The following three variables represent various types of information
+ // gathered from the lexicon.
+ LexiconMap lexicon_map_;
+ NumPhonesMap num_phones_map_;
+ ViabilityMap viability_map_;
+
+ // As lexicon_map but in reverse sense w.r.t. words [we only
+ // do this for asymmetric entries.] Used only in testing code.
+ LexiconMap reverse_lexicon_map_;
+
+ // This is used only in testing code; it defines a mapping from a word
+ // to the primary member of that word's equivalence-class. If an index
+ // is not present in the map, it's assumed to map to itself.
+ EquivalenceMap equivalence_map_;
+};
+
+
+struct WordAlignLatticeLexiconOpts {
+ int32 partial_word_label;
+ bool reorder;
+ BaseFloat max_expand;
+
+ WordAlignLatticeLexiconOpts(): partial_word_label(0), reorder(true),
+ max_expand(-1.0) { }
+
+ void Register(OptionsItf *opts) {
+ opts->Register("partial-word-label", &partial_word_label, "Numeric id of "
+ "word symbol that is to be used for arcs in the word-aligned "
+ "lattice corresponding to partial words at the end of "
+ "\"forced-out\" utterances (zero is OK)");
+ opts->Register("reorder", &reorder, "True if the lattices were generated "
+ "from graphs that had the --reorder option true, relating to "
+ "reordering self-loops (typically true)");
+ opts->Register("max-expand", &max_expand, "If >0.0, the maximum ratio "
+ "by which we allow the lattice-alignment code to increase the #states "
+ "in a lattice (vs. the phone-aligned lattice) before we fail and "
+ "refuse to align the lattice. This is helpful in order to "
+ "prevent 'pathological' lattices from causing the program to "
+ "exhaust memory. Actual max-states is 1000 + max-expand * "
+ "orig-num-states.");
+ }
+};
+
+
+/// Align lattice so that each arc has the transition-ids on it
+/// that correspond to the word that is on that arc. [May also have
+/// epsilon arcs for optional silences.]
+/// Returns true if everything was OK, false if there was any kind of
+/// error including when the the lattice seems to have been "forced out"
+/// (did not reach end state, resulting in partial word at end).
+bool WordAlignLatticeLexicon(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const WordAlignLatticeLexiconInfo &lexicon_info,
+ const WordAlignLatticeLexiconOpts &opts,
+ CompactLattice *lat_out);
+
+} // namespace kaldi
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice.cc b/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice.cc
new file mode 100644
index 000000000..d644709cb
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice.cc
@@ -0,0 +1,927 @@
+// lat/word-align-lattice.cc
+
+// Copyright 2011-2012 Microsoft Corporation Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "lat/word-align-lattice.h"
+#include "util/stl-utils.h"
+
+namespace kaldi {
+
+class LatticeWordAligner {
+ public:
+ typedef CompactLatticeArc::StateId StateId;
+ typedef CompactLatticeArc::Label Label;
+
+ class ComputationState { /// The state of the computation in which,
+ /// along a single path in the lattice, we work out the word
+ /// boundaries and output aligned arcs.
+ public:
+
+ /// Advance the computation state by adding the symbols and weights
+ /// from this arc. We'll put the weight on the output arc; this helps
+ /// keep the state-space smaller.
+ void Advance(const CompactLatticeArc &arc, LatticeWeight *weight) {
+ const std::vector<int32> &string = arc.weight.String();
+ transition_ids_.insert(transition_ids_.end(),
+ string.begin(), string.end());
+ if (arc.ilabel != 0) // note: arc.ilabel==arc.olabel (acceptor)
+ word_labels_.push_back(arc.ilabel);
+ *weight = Times(weight_, arc.weight.Weight());
+ weight_ = LatticeWeight::One();
+ }
+
+ /// If it can output a whole word, it will do so, will put it in arc_out,
+ /// and return true; else it will return false. If it detects an error
+ /// condition and *error = false, it will set *error to true and print
+ /// a warning. In this case it may or may not [output an arc and return true],
+ /// depending on what we think is most likely the right thing to do. Of
+ /// course once *error is set, something has gone wrong so don't trust
+ /// the output too fully.
+ /// Note: the "next_state" of the arc will not be set, you have to do that
+ /// yourself.
+ bool OutputArc(const WordBoundaryInfo &info,
+ const TransitionInformation &tmodel,
+ CompactLatticeArc *arc_out,
+ bool *error) {
+ // order of this ||-expression doesn't matter for
+ // function behavior, only for efficiency, since the
+ // cases are disjoint.
+ return OutputNormalWordArc(info, tmodel, arc_out, error) ||
+ OutputSilenceArc(info, tmodel, arc_out, error) ||
+ OutputOnePhoneWordArc(info, tmodel, arc_out, error);
+ }
+
+ bool OutputSilenceArc(const WordBoundaryInfo &info,
+ const TransitionInformation &tmodel,
+ CompactLatticeArc *arc_out,
+ bool *error);
+ bool OutputOnePhoneWordArc(const WordBoundaryInfo &info,
+ const TransitionInformation &tmodel,
+ CompactLatticeArc *arc_out,
+ bool *error);
+ bool OutputNormalWordArc(const WordBoundaryInfo &info,
+ const TransitionInformation &tmodel,
+ CompactLatticeArc *arc_out,
+ bool *error);
+
+ bool IsEmpty() { return (transition_ids_.empty() && word_labels_.empty()); }
+
+ /// FinalWeight() will return "weight" if both transition_ids
+ /// and word_labels are empty, otherwise it will return
+ /// Weight::Zero().
+ LatticeWeight FinalWeight() { return (IsEmpty() ? weight_ : LatticeWeight::Zero()); }
+
+ /// This function may be called when you reach the end of
+ /// the lattice and this structure hasn't voluntarily
+ /// output words using "OutputArc". If IsEmpty() == false,
+ /// then you can call this function and it will output
+ /// an arc. The only
+ /// non-error state in which this happens, is when a word
+ /// (or silence) has ended, but we don't know that it's
+ /// ended because we haven't seen the first transition-id
+ /// from the next word. Otherwise (error state), the output
+ /// will consist of partial words, and this will only
+ /// happen for lattices that were somehow broken, i.e.
+ /// had not reached the final state.
+ void OutputArcForce(const WordBoundaryInfo &info,
+ const TransitionInformation &tmodel,
+ CompactLatticeArc *arc_out,
+ bool *error);
+
+ size_t Hash() const {
+ VectorHasher<int32> vh;
+ return vh(transition_ids_) + 90647 * vh(word_labels_);
+ // 90647 is an arbitrary largish prime number.
+ // We don't bother including the weight in the hash--
+ // we don't really expect duplicates with the same vectors
+ // but different weights, and anyway, this is only an
+ // efficiency issue.
+ }
+
+ // Just need an arbitrary complete order.
+ bool operator == (const ComputationState &other) const {
+ return (transition_ids_ == other.transition_ids_
+ && word_labels_ == other.word_labels_
+ && weight_ == other.weight_);
+ }
+
+ ComputationState(): weight_(LatticeWeight::One()) { } // initial state.
+ ComputationState(const ComputationState &other):
+ transition_ids_(other.transition_ids_), word_labels_(other.word_labels_),
+ weight_(other.weight_) { }
+ private:
+ std::vector<int32> transition_ids_;
+ std::vector<int32> word_labels_;
+ LatticeWeight weight_; // contains two floats.
+ };
+
+
+ struct Tuple {
+ Tuple(StateId input_state, ComputationState comp_state):
+ input_state(input_state), comp_state(comp_state) {}
+ StateId input_state;
+ ComputationState comp_state;
+ };
+
+ struct TupleHash {
+ size_t operator() (const Tuple &state) const {
+ return state.input_state + 102763 * state.comp_state.Hash();
+ // 102763 is just an arbitrary prime number
+ }
+ };
+ struct TupleEqual {
+ bool operator () (const Tuple &state1, const Tuple &state2) const {
+ // treat this like operator ==
+ return (state1.input_state == state2.input_state
+ && state1.comp_state == state2.comp_state);
+ }
+ };
+
+ typedef unordered_map<Tuple, StateId, TupleHash, TupleEqual> MapType;
+
+ StateId GetStateForTuple(const Tuple &tuple, bool add_to_queue) {
+ MapType::iterator iter = map_.find(tuple);
+ if (iter == map_.end()) { // not in map.
+ StateId output_state = lat_out_->AddState();
+ map_[tuple] = output_state;
+ if (add_to_queue)
+ queue_.push_back(std::make_pair(tuple, output_state));
+ return output_state;
+ } else {
+ return iter->second;
+ }
+ }
+
+ void ProcessFinal(Tuple tuple, StateId output_state) {
+ // ProcessFinal is only called if the input_state has
+ // final-prob of One(). [else it should be zero. This
+ // is because we called CreateSuperFinal().]
+
+ if (tuple.comp_state.IsEmpty()) { // computation state doesn't have
+ // anything pending.
+ std::vector<int32> empty_vec;
+ CompactLatticeWeight cw(tuple.comp_state.FinalWeight(), empty_vec);
+ lat_out_->SetFinal(output_state, Plus(lat_out_->Final(output_state), cw));
+ } else {
+ // computation state has something pending, i.e. input or
+ // output symbols that need to be flushed out. Note: OutputArc() would
+ // have returned false or we wouldn't have been called, so we have to
+ // force it out.
+ CompactLatticeArc lat_arc;
+ tuple.comp_state.OutputArcForce(info_, tmodel_, &lat_arc, &error_);
+ // True in the next line means add it to the queue.
+ lat_arc.nextstate = GetStateForTuple(tuple, true);
+ // The final-prob stuff will get called again from ProcessQueueElement().
+ // Note: because we did CreateSuperFinal(), this final-state on the input
+ // lattice will have no output arcs (and unit final-prob), so there will be
+ // no complications with processing the arcs from this state (there won't
+ // be any).
+ KALDI_ASSERT(output_state != lat_arc.nextstate);
+ lat_out_->AddArc(output_state, lat_arc);
+ }
+ }
+
+
+ void ProcessQueueElement() {
+ KALDI_ASSERT(!queue_.empty());
+ Tuple tuple = queue_.back().first;
+ StateId output_state = queue_.back().second;
+ queue_.pop_back();
+
+ // First thing is-- we see whether the computation-state has something
+ // pending that it wants to output. In this case we don't do
+ // anything further. This is a chosen behavior similar to the
+ // epsilon-sequencing rules encoded by the filters in
+ // composition.
+ CompactLatticeArc lat_arc;
+ if (tuple.comp_state.OutputArc(info_, tmodel_, &lat_arc, &error_)) {
+ // note: this function changes the tuple (when it returns true).
+ lat_arc.nextstate = GetStateForTuple(tuple, true); // true == add to queue,
+ // if not already present.
+ KALDI_ASSERT(output_state != lat_arc.nextstate);
+ lat_out_->AddArc(output_state, lat_arc);
+ } else {
+ // when there's nothing to output, we'll process arcs from the input-state.
+ // note: it would in a sense be valid to do both (i.e. process the stuff
+ // above, and also these), but this is a bit like the epsilon-sequencing
+ // stuff in composition: we avoid duplicate arcs by doing it this way.
+
+ if (lat_.Final(tuple.input_state) != CompactLatticeWeight::Zero()) {
+ KALDI_ASSERT(lat_.Final(tuple.input_state) == CompactLatticeWeight::One());
+ // ... since we did CreateSuperFinal.
+ ProcessFinal(tuple, output_state);
+ }
+ // Now process the arcs. Note: final-state shouldn't have any arcs.
+ for (fst::ArcIterator<CompactLattice> aiter(lat_, tuple.input_state);
+ !aiter.Done(); aiter.Next()) {
+ const CompactLatticeArc &arc = aiter.Value();
+ Tuple next_tuple(tuple);
+ LatticeWeight weight;
+ next_tuple.comp_state.Advance(arc, &weight);
+ next_tuple.input_state = arc.nextstate;
+ StateId next_output_state = GetStateForTuple(next_tuple, true); // true == add to queue,
+ // if not already present.
+ // We add an epsilon arc here (as the input and output happens
+ // separately)... the epsilons will get removed later.
+ KALDI_ASSERT(next_output_state != output_state);
+ lat_out_->AddArc(output_state,
+ CompactLatticeArc(0, 0,
+ CompactLatticeWeight(weight, std::vector<int32>()),
+ next_output_state));
+ }
+ }
+ }
+
+ LatticeWordAligner(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const WordBoundaryInfo &info,
+ int32 max_states,
+ CompactLattice *lat_out):
+ lat_(lat), tmodel_(tmodel), info_in_(info), info_(info),
+ max_states_(max_states), lat_out_(lat_out),
+ error_(false) {
+ bool test = true;
+ uint64 props = lat_.Properties(fst::kIDeterministic|fst::kIEpsilons, test);
+ if (props != fst::kIDeterministic) {
+ KALDI_WARN << "[Lattice has input epsilons and/or is not input-deterministic "
+ << "(in Mohri sense)]-- i.e. lattice is not deterministic. "
+ << "Word-alignment may be slow and-or blow up in memory.";
+ }
+ fst::CreateSuperFinal(&lat_); // Creates a super-final state, so the
+ // only final-probs are One().
+
+ // Inside this class, we don't want to use zero for the silence
+ // or partial-word labels, as this will interfere with the RmEpsilon
+ // stage, where we don't want the arcs corresponding to silence or
+ // partial words to be removed-- only the arcs with nothing at all
+ // on them.
+ if (info_.partial_word_label == 0 || info_.silence_label == 0) {
+ int32 unused_label = 1 + HighestNumberedOutputSymbol(lat);
+ if (info_.partial_word_label >= unused_label)
+ unused_label = info_.partial_word_label + 1;
+ if (info_.silence_label >= unused_label)
+ unused_label = info_.silence_label + 1;
+ KALDI_ASSERT(unused_label > 0);
+ if (info_.partial_word_label == 0)
+ info_.partial_word_label = unused_label++;
+ if (info_.silence_label == 0)
+ info_.silence_label = unused_label;
+ }
+ }
+
+ // Removes epsilons; also removes unreachable states...
+ // not sure if these would exist if original was connected.
+ // This also replaces the temporary symbols for the silence
+ // and partial-words, with epsilons, if we wanted epsilons.
+ void RemoveEpsilonsFromLattice() {
+ // Remove epsilon arcs from output lattice.
+ RmEpsilon(lat_out_, true); // true = connect.
+ std::vector<int32> syms_to_remove;
+ if (info_in_.partial_word_label == 0)
+ syms_to_remove.push_back(info_.partial_word_label);
+ if (info_in_.silence_label == 0)
+ syms_to_remove.push_back(info_.silence_label);
+ if (!syms_to_remove.empty()) {
+ RemoveSomeInputSymbols(syms_to_remove, lat_out_);
+ Project(lat_out_, fst::PROJECT_INPUT);
+ }
+ }
+
+ bool AlignLattice() {
+ lat_out_->DeleteStates();
+ if (lat_.Start() == fst::kNoStateId) {
+ KALDI_WARN << "Trying to word-align empty lattice.";
+ return false;
+ }
+ ComputationState initial_comp_state;
+ Tuple initial_tuple(lat_.Start(), initial_comp_state);
+ StateId start_state = GetStateForTuple(initial_tuple, true); // True = add this to queue.
+ lat_out_->SetStart(start_state);
+
+ while (!queue_.empty()) {
+ if (max_states_ > 0 && lat_out_->NumStates() > max_states_) {
+ KALDI_WARN << "Number of states in lattice exceeded max-states of "
+ << max_states_ << ", original lattice had "
+ << lat_.NumStates() << " states. Returning what we have.";
+ RemoveEpsilonsFromLattice();
+ return false;
+ }
+ ProcessQueueElement();
+ }
+
+ RemoveEpsilonsFromLattice();
+
+ return !error_;
+ }
+
+ CompactLattice lat_;
+ const TransitionInformation &tmodel_;
+ const WordBoundaryInfo &info_in_;
+ WordBoundaryInfo info_;
+ int32 max_states_;
+ CompactLattice *lat_out_;
+
+ std::vector<std::pair<Tuple, StateId> > queue_;
+
+
+
+ MapType map_; // map from tuples to StateId.
+ bool error_;
+
+};
+
+bool LatticeWordAligner::ComputationState::OutputSilenceArc(
+ const WordBoundaryInfo &info, const TransitionInformation &tmodel,
+ CompactLatticeArc *arc_out, bool *error) {
+ if (transition_ids_.empty()) return false;
+ int32 phone = tmodel.TransitionIdToPhone(transition_ids_[0]);
+ if (info.TypeOfPhone(phone) != WordBoundaryInfo::kNonWordPhone) return false;
+
+ // we assume the start of transition_ids_ is the start of the phone [silence];
+ // this is a precondition.
+ size_t len = transition_ids_.size(), i;
+ // Keep going till we reach a "final" transition-id; note, if
+ // reorder==true, we have to go a bit further after this.
+ for (i = 0; i < len; i++) {
+ int32 tid = transition_ids_[i];
+ int32 this_phone = tmodel.TransitionIdToPhone(tid);
+ if (this_phone != phone && ! *error) { // error condition: should have reached final transition-id first.
+ *error = true;
+ KALDI_WARN << "Phone changed before final transition-id found "
+ "[broken lattice or mismatched model or wrong --reorder option?]";
+ }
+ if (tmodel.IsFinal(tid))
+ break;
+ }
+ if (i == len) return false; // fell off loop.
+ i++; // go past the one for which IsFinal returned true.
+ if (info.reorder) // we have to consume the following self-loop transition-ids.
+ while (i < len && tmodel.IsSelfLoop(transition_ids_[i])) i++;
+ if (i == len) return false; // we don't know if it ends here... so can't output arc.
+
+ if (tmodel.TransitionIdToPhone(transition_ids_[i-1]) != phone
+ && ! *error) { // another check.
+ KALDI_WARN << "Phone changed unexpectedly in lattice "
+ "[broken lattice or mismatched model?]";
+ }
+ // interpret i as the number of transition-ids to consume.
+ std::vector<int32> tids_out(transition_ids_.begin(), transition_ids_.begin()+i);
+
+ // consumed transition ids from our internal state.
+ *arc_out = CompactLatticeArc(info.silence_label, info.silence_label,
+ CompactLatticeWeight(weight_, tids_out), fst::kNoStateId);
+ transition_ids_.erase(transition_ids_.begin(), transition_ids_.begin()+i); // delete these
+ weight_ = LatticeWeight::One(); // we just output the weight.
+ return true;
+}
+
+
+bool LatticeWordAligner::ComputationState::OutputOnePhoneWordArc(
+ const WordBoundaryInfo &info, const TransitionInformation &tmodel,
+ CompactLatticeArc *arc_out, bool *error) {
+ if (transition_ids_.empty()) return false;
+ if (word_labels_.empty()) return false;
+ int32 phone = tmodel.TransitionIdToPhone(transition_ids_[0]);
+ if (info.TypeOfPhone(phone) != WordBoundaryInfo::kWordBeginAndEndPhone)
+ return false;
+ // we assume the start of transition_ids_ is the start of the phone.
+ // this is a precondition.
+ size_t len = transition_ids_.size(), i;
+ for (i = 0; i < len; i++) {
+ int32 tid = transition_ids_[i];
+ int32 this_phone = tmodel.TransitionIdToPhone(tid);
+ if (this_phone != phone && ! *error) { // error condition: should have reached final transition-id first.
+ KALDI_WARN << "Phone changed before final transition-id found "
+ "[broken lattice or mismatched model or wrong --reorder option?]";
+ // just continue, ignoring this-- we'll probably output something...
+ }
+ if (tmodel.IsFinal(tid))
+ break;
+ }
+ if (i == len) return false; // fell off loop.
+ i++; // go past the one for which IsFinal returned true.
+ if (info.reorder) // we have to consume the following self-loop transition-ids.
+ while (i < len && tmodel.IsSelfLoop(transition_ids_[i])) i++;
+ if (i == len) return false; // we don't know if it ends here... so can't output arc.
+
+ if (tmodel.TransitionIdToPhone(transition_ids_[i-1]) != phone
+ && ! *error) { // another check.
+ KALDI_WARN << "Phone changed unexpectedly in lattice "
+ "[broken lattice or mismatched model?]";
+ *error = true;
+ }
+
+ // interpret i as the number of transition-ids to consume.
+ std::vector<int32> tids_out(transition_ids_.begin(),
+ transition_ids_.begin() + i);
+
+ // consumed transition ids from our internal state.
+ int32 word = word_labels_[0];
+ *arc_out = CompactLatticeArc(word, word,
+ CompactLatticeWeight(weight_, tids_out), fst::kNoStateId);
+ transition_ids_.erase(transition_ids_.begin(),
+ transition_ids_.begin() + i); // delete these
+ // Remove the word that we just output.
+ word_labels_.erase(word_labels_.begin(), word_labels_.begin() + 1);
+ weight_ = LatticeWeight::One(); // we just output the weight.
+ return true;
+}
+
+
+/// This function tries to see if it can output a normal word arc--
+/// one with at least two phones in it.
+bool LatticeWordAligner::ComputationState::OutputNormalWordArc(
+ const WordBoundaryInfo &info, const TransitionInformation &tmodel,
+ CompactLatticeArc *arc_out, bool *error) {
+ if (transition_ids_.empty()) return false;
+ if (word_labels_.empty()) return false;
+ int32 begin_phone = tmodel.TransitionIdToPhone(transition_ids_[0]);
+ if (info.TypeOfPhone(begin_phone) != WordBoundaryInfo::kWordBeginPhone)
+ return false;
+ // we assume the start of transition_ids_ is the start of the phone.
+ // this is a precondition.
+ size_t len = transition_ids_.size(), i;
+
+ // Eat up the transition-ids of this word-begin phone until we get to the
+ // "final" transition-id. [there may be self-loops following this though,
+ // if reorder==true]
+ for (i = 0; i < len && !tmodel.IsFinal(transition_ids_[i]); i++);
+ if (i == len) return false;
+ i++; // Skip over this final-transition.
+ if (info.reorder) // Skip over any reordered self-loops for this final-transition
+ for (; i < len && tmodel.IsSelfLoop(transition_ids_[i]); i++);
+ if (i == len) return false;
+ if (tmodel.TransitionIdToPhone(transition_ids_[i-1]) != begin_phone
+ && ! *error) { // another check.
+ KALDI_WARN << "Phone changed unexpectedly in lattice "
+ "[broken lattice or mismatched model?]";
+ *error = true;
+ }
+ // Now keep going till we hit a word-ending phone.
+ // Note: we don't expect anything except word-internal phones
+ // here, but we'll just print a warning if we get something
+ // else.
+ for (; i < len; i++) {
+ int32 this_phone = tmodel.TransitionIdToPhone(transition_ids_[i]);
+ if (info.TypeOfPhone(this_phone) == WordBoundaryInfo::kWordEndPhone)
+ break;
+ if (info.TypeOfPhone(this_phone) != WordBoundaryInfo::kWordInternalPhone
+ && !*error) {
+ KALDI_WARN << "Unexpected phone " << this_phone
+ << " found inside a word.";
+ *error = true;
+ }
+ }
+ if (i == len) return false;
+
+ // OK, we hit a word-ending phone. Continue till we get to
+ // a "final-transition".
+
+ // this variable just used for checks.
+ int32 final_phone = tmodel.TransitionIdToPhone(transition_ids_[i]);
+ for (; i < len; i++) {
+ int32 this_phone = tmodel.TransitionIdToPhone(transition_ids_[i]);
+ if (this_phone != final_phone && ! *error) {
+ *error = true;
+ KALDI_WARN << "Phone changed before final transition-id found "
+ "[broken lattice or mismatched model or wrong --reorder option?]";
+ }
+ if (tmodel.IsFinal(transition_ids_[i])) break;
+ }
+ if (i == len) return false;
+ i++;
+ // We got to the final-transition of the final phone;
+ // if reorder==true, continue eating up the self-loop.
+ if (info.reorder == true)
+ while (i < len && tmodel.IsSelfLoop(transition_ids_[i])) i++;
+ if (i == len) return false;
+ if (tmodel.TransitionIdToPhone(transition_ids_[i-1]) != final_phone
+ && ! *error) {
+ *error = true;
+ KALDI_WARN << "Phone changed while following final self-loop "
+ "[broken lattice or mismatched model or wrong --reorder option?]";
+ }
+
+ // OK, we're ready to output the word.
+ // Interpret i as the number of transition-ids to consume.
+ std::vector<int32> tids_out(transition_ids_.begin(),
+ transition_ids_.begin() + i);
+
+ // consumed transition ids from our internal state.
+ int32 word = word_labels_[0];
+ *arc_out = CompactLatticeArc(word, word,
+ CompactLatticeWeight(weight_, tids_out),
+ fst::kNoStateId);
+ transition_ids_.erase(transition_ids_.begin(),
+ transition_ids_.begin() + i); // delete these
+ // Remove the word that we just output.
+ word_labels_.erase(word_labels_.begin(),
+ word_labels_.begin() + 1);
+ weight_ = LatticeWeight::One(); // we just output the weight.
+ return true;
+}
+
+// Returns true if this vector of transition-ids could be a valid
+// word. Note: the checks are not 100% exhaustive.
+static bool IsPlausibleWord(const WordBoundaryInfo &info,
+ const TransitionInformation &tmodel,
+ const std::vector<int32> &transition_ids) {
+ if (transition_ids.empty()) return false;
+ int32 first_phone = tmodel.TransitionIdToPhone(transition_ids.front()),
+ last_phone = tmodel.TransitionIdToPhone(transition_ids.back());
+ if ( (info.TypeOfPhone(first_phone) == WordBoundaryInfo::kWordBeginAndEndPhone
+ && first_phone == last_phone)
+ ||
+ (info.TypeOfPhone(first_phone) == WordBoundaryInfo::kWordBeginPhone &&
+ info.TypeOfPhone(last_phone) == WordBoundaryInfo::kWordEndPhone) ) {
+ if (! info.reorder) {
+ return (tmodel.IsFinal(transition_ids.back()));
+ } else {
+ int32 i = transition_ids.size() - 1;
+ while (i > 0 && tmodel.IsSelfLoop(transition_ids[i])) i--;
+ return tmodel.IsFinal(transition_ids[i]);
+ }
+ } else return false;
+}
+
+
+void LatticeWordAligner::ComputationState::OutputArcForce(
+ const WordBoundaryInfo &info, const TransitionInformation &tmodel,
+ CompactLatticeArc *arc_out, bool *error) {
+
+ KALDI_ASSERT(!IsEmpty());
+ if (!word_labels_.empty()
+ && !transition_ids_.empty()) { // We have at least one word to
+ // output, and some transition-ids. We assume that the normal OutputArc was called
+ // and failed, so this means we didn't see the end of that
+ // word.
+ int32 word = word_labels_[0];
+ if (! *error && !IsPlausibleWord(info, tmodel, transition_ids_)) {
+ *error = true;
+ KALDI_WARN << "Invalid word at end of lattice [partial lattice, forced out?]";
+ }
+ CompactLatticeWeight cw(weight_, transition_ids_);
+ *arc_out = CompactLatticeArc(word, word, cw, fst::kNoStateId);
+ weight_ = LatticeWeight::One();
+ transition_ids_.clear();
+ word_labels_.erase(word_labels_.begin(), word_labels_.begin()+1);
+ } else if (!word_labels_.empty() && transition_ids_.empty()) {
+ // We won't create arcs with these word labels on, as most likely
+ // this will cause errors down the road. This is an error
+ // condition anyway, in some sense.
+ if (! *error) {
+ *error = true;
+ KALDI_WARN << "Discarding word-ids at the end of a sentence, "
+ "that don't have alignments.";
+ }
+ CompactLatticeWeight cw(weight_, transition_ids_);
+ // This creates an epsilon arc with a weight on it, but
+ // no transition-ids since the vector is empty.
+ // The word labels are discarded.
+ *arc_out = CompactLatticeArc(0, 0, cw, fst::kNoStateId);
+ weight_ = LatticeWeight::One();
+ word_labels_.clear();
+ } else if (!transition_ids_.empty() && word_labels_.empty()) {
+ // Transition-ids but no word label-- either silence or partial word.
+ int32 first_phone = tmodel.TransitionIdToPhone(transition_ids_[0]);
+ if (info.TypeOfPhone(first_phone) == WordBoundaryInfo::kNonWordPhone) {
+ // first phone is silence...
+ if (first_phone != tmodel.TransitionIdToPhone(transition_ids_.back())
+ && ! *error) {
+ *error = true;
+ // Phone changed-- this is a code error, because the regular OutputArc
+ // should have output an arc (a silence arc) if that phone finished.
+ // So we make it fatal.
+ KALDI_ERR << "Broken silence arc at end of utterance (the phone "
+ "changed); code error";
+ }
+ if (!*error) { // Check that it ends at the end state of silence; error otherwise.
+ int32 i = transition_ids_.size() - 1;
+ if (info.reorder)
+ while (tmodel.IsSelfLoop(transition_ids_[i]) && i > 0)
+ i--;
+ if (!tmodel.IsFinal(transition_ids_[i])) {
+ *error = true;
+ KALDI_WARN << "Broken silence arc at end of utterance (does not "
+ "reach end of silence)";
+ }
+ }
+ CompactLatticeWeight cw(weight_, transition_ids_);
+ *arc_out = CompactLatticeArc(info.silence_label, info.silence_label,
+ cw, fst::kNoStateId);
+ } else {
+ // Not silence phone -- treat as partial word (with no word label).
+ // This is in itself an error condition, i.e. the lattice was maybe
+ // forced out.
+ if (! *error) {
+ *error = true;
+ KALDI_WARN << "Partial word detected at end of utterance";
+ }
+ CompactLatticeWeight cw(weight_, transition_ids_);
+ *arc_out = CompactLatticeArc(info.partial_word_label, info.partial_word_label,
+ cw, fst::kNoStateId);
+ }
+ transition_ids_.clear();
+ weight_ = LatticeWeight::One();
+ } else {
+ KALDI_ERR << "Code error, word-aligning lattice"; // this shouldn't
+ // be able to happen; we don't call this function of they're both empty.
+ }
+}
+
+// This code will eventually be removed.
+void WordBoundaryInfo::SetOptions(const std::string int_list, PhoneType phone_type) {
+ KALDI_ASSERT(!int_list.empty() && phone_type != kNoPhone);
+ std::vector<int32> phone_list;
+ if (!kaldi::SplitStringToIntegers(int_list, ":",
+ false,
+ &phone_list)
+ || phone_list.empty())
+ KALDI_ERR << "Invalid argument to --*-phones option: " << int_list;
+ for (size_t i= 0; i < phone_list.size(); i++) {
+ if (phone_to_type.size() <= phone_list[i])
+ phone_to_type.resize(phone_list[i]+1, kNoPhone);
+ if (phone_to_type[phone_list[i]] != kNoPhone)
+ KALDI_ERR << "Phone " << phone_list[i] << "was given two incompatible "
+ "assignments.";
+ phone_to_type[phone_list[i]] = phone_type;
+ }
+}
+
+// This initializer will be deleted eventually.
+WordBoundaryInfo::WordBoundaryInfo(const WordBoundaryInfoOpts &opts) {
+ SetOptions(opts.wbegin_phones, kWordBeginPhone);
+ SetOptions(opts.wend_phones, kWordEndPhone);
+ SetOptions(opts.wbegin_and_end_phones, kWordBeginAndEndPhone);
+ SetOptions(opts.winternal_phones, kWordInternalPhone);
+ SetOptions(opts.silence_phones, (opts.silence_has_olabels ?
+ kWordBeginAndEndPhone : kNonWordPhone));
+ reorder = opts.reorder;
+ silence_label = opts.silence_label;
+ partial_word_label = opts.partial_word_label;
+}
+
+WordBoundaryInfo::WordBoundaryInfo(const WordBoundaryInfoNewOpts &opts) {
+ reorder = opts.reorder;
+ silence_label = opts.silence_label;
+ partial_word_label = opts.partial_word_label;
+}
+
+WordBoundaryInfo::WordBoundaryInfo(const WordBoundaryInfoNewOpts &opts,
+ std::string word_boundary_file) {
+ reorder = opts.reorder;
+ silence_label = opts.silence_label;
+ partial_word_label = opts.partial_word_label;
+ bool binary_in;
+ Input ki(word_boundary_file, &binary_in);
+ KALDI_ASSERT(!binary_in && "Not expecting binary word-boundary file.");
+ Init(ki.Stream());
+}
+
+void WordBoundaryInfo::Init(std::istream &stream) {
+ std::string line;
+ while (std::getline(stream, line)) {
+ std::vector<std::string> split_line;
+ SplitStringToVector(line, " \t\r", true, &split_line);// split the line by space or tab
+ int32 p = 0;
+ if (split_line.size() != 2 ||
+ !ConvertStringToInteger(split_line[0], &p))
+ KALDI_ERR << "Invalid line in word-boundary file: " << line;
+ KALDI_ASSERT(p > 0);
+ if (phone_to_type.size() <= static_cast<size_t>(p))
+ phone_to_type.resize(p+1, kNoPhone);
+ std::string t = split_line[1];
+ if (t == "nonword") phone_to_type[p] = kNonWordPhone;
+ else if (t == "begin") phone_to_type[p] = kWordBeginPhone;
+ else if (t == "singleton") phone_to_type[p] = kWordBeginAndEndPhone;
+ else if (t == "end") phone_to_type[p] = kWordEndPhone;
+ else if (t == "internal") phone_to_type[p] = kWordInternalPhone;
+ else
+ KALDI_ERR << "Invalid line in word-boundary file: " << line;
+ }
+ if (phone_to_type.empty())
+ KALDI_ERR << "Empty word-boundary file";
+}
+
+bool WordAlignLattice(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const WordBoundaryInfo &info,
+ int32 max_states,
+ CompactLattice *lat_out) {
+ LatticeWordAligner aligner(lat, tmodel, info, max_states, lat_out);
+ return aligner.AlignLattice();
+}
+
+
+
+class WordAlignedLatticeTester {
+ public:
+ WordAlignedLatticeTester(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const WordBoundaryInfo &info,
+ const CompactLattice &aligned_lat):
+ lat_(lat), tmodel_(tmodel), info_(info), aligned_lat_(aligned_lat) { }
+
+ void Test() {
+ // First test that each aligned arc is valid.
+ typedef CompactLattice::StateId StateId ;
+ for (StateId s = 0; s < aligned_lat_.NumStates(); s++) {
+ for (fst::ArcIterator<CompactLattice> iter(aligned_lat_, s);
+ !iter.Done();
+ iter.Next()) {
+ TestArc(iter.Value());
+ }
+ if (aligned_lat_.Final(s) != CompactLatticeWeight::Zero()) {
+ TestFinal(aligned_lat_.Final(s));
+ }
+ }
+ TestEquivalent();
+ }
+ private:
+ void TestArc(const CompactLatticeArc &arc) {
+ if (! (TestArcSilence(arc) || TestArcNormalWord(arc) || TestArcOnePhoneWord(arc)
+ || TestArcEmpty(arc)))
+ KALDI_ERR << "Invalid arc in aligned CompactLattice: "
+ << arc.ilabel << " " << arc.olabel << " " << arc.nextstate
+ << " " << arc.weight;
+ }
+ bool TestArcEmpty(const CompactLatticeArc &arc) {
+ if (arc.ilabel != 0) return false; // Check there is no label. Note, ilabel==olabel.
+ const std::vector<int32> &tids = arc.weight.String();
+ return tids.empty();
+ }
+ bool TestArcSilence(const CompactLatticeArc &arc) {
+ // This only applies when silence doesn't have word labels.
+ if (arc.ilabel != info_.silence_label) return false; // Check the label is
+ // the silence label. Note, ilabel==olabel.
+ const std::vector<int32> &tids = arc.weight.String();
+ if (tids.empty()) return false;
+ int32 first_phone = tmodel_.TransitionIdToPhone(tids.front());
+ if (info_.TypeOfPhone(first_phone) != WordBoundaryInfo::kNonWordPhone)
+ return false;
+ for (size_t i = 0; i < tids.size(); i++)
+ if (tmodel_.TransitionIdToPhone(tids[i]) != first_phone) return false;
+
+ if (!info_.reorder) return tmodel_.IsFinal(tids.back());
+ else {
+ for (size_t i = 0; i < tids.size(); i++) {
+ if (tmodel_.IsFinal(tids[i])) { // got the "final" transition, which is
+ // reordered to actually not be final. Make sure that all the
+ // rest of the transition ids are the self-loop of that same
+ // transition-state.
+ for (size_t j = i+1; j < tids.size(); j++) {
+ if (!tmodel_.TransitionIdsEquivalent(tids[j], tids[i])) return false;
+ }
+ return true;
+ }
+ }
+ return false; // fell off loop. No final-state present.
+ }
+ }
+
+ bool TestArcOnePhoneWord(const CompactLatticeArc &arc) {
+ if (arc.ilabel == 0) return false; // Check there's a label. Note, ilabel==olabel.
+ const std::vector<int32> &tids = arc.weight.String();
+ if (tids.empty()) return false;
+ int32 first_phone = tmodel_.TransitionIdToPhone(tids.front());
+ if (info_.TypeOfPhone(first_phone) !=
+ WordBoundaryInfo::kWordBeginAndEndPhone) return false;
+ for (size_t i = 0; i < tids.size(); i++)
+ if (tmodel_.TransitionIdToPhone(tids[i]) != first_phone) return false;
+
+ if (!info_.reorder) return tmodel_.IsFinal(tids.back());
+ else {
+ for (size_t i = 0; i < tids.size(); i++) {
+ if (tmodel_.IsFinal(tids[i])) { // got the "final" transition, which is
+ // reordered to actually not be final. Make sure that all the
+ // rest of the transition ids are the self-loop of that same
+ // transition-state.
+ for (size_t j = i+1; j < tids.size(); j++) {
+ if (!tmodel_.TransitionIdsEquivalent(tids[j], tids[i])) return false;
+ }
+ return true;
+ }
+ }
+ return false; // fell off loop. No final-state present.
+ }
+ }
+
+ bool TestArcNormalWord(const CompactLatticeArc &arc) {
+ if (arc.ilabel == 0) return false; // Check there's a label. Note, ilabel==olabel.
+ const std::vector<int32> &tids = arc.weight.String();
+ if (tids.empty()) return false;
+ int32 first_phone = tmodel_.TransitionIdToPhone(tids.front());
+ if (info_.TypeOfPhone(first_phone) != WordBoundaryInfo::kWordBeginPhone)
+ return false;
+ size_t i;
+ { // first phone.
+ int num_final = 0;
+ for (i = 0; i < tids.size(); i++) {
+ if (tmodel_.TransitionIdToPhone(tids[i]) != first_phone) break;
+ if (tmodel_.IsFinal(tids[i])) num_final++;
+ }
+ if (num_final != 1)
+ return false; // Something went wrong-- perhaps we
+ // got two beginning phones in a row.
+ }
+ { // middle phones. Skip over them.
+ while (i < tids.size() &&
+ info_.TypeOfPhone(tmodel_.TransitionIdToPhone(tids[i]))
+ == WordBoundaryInfo::kWordInternalPhone)
+ i++;
+ }
+ if (i == tids.size()) return false;
+ int32 final_phone = tmodel_.TransitionIdToPhone(tids[i]);
+ if (info_.TypeOfPhone(final_phone) != WordBoundaryInfo::kWordEndPhone)
+ return false; // not word-ending.
+ for (size_t j = i; j < tids.size(); j++) // make sure only this final phone till end.
+ if (tmodel_.TransitionIdToPhone(tids[j]) != final_phone)
+ return false; // Other phones after final phone.
+
+ for (size_t j = i; j < tids.size(); j++) {
+ if (tmodel_.IsFinal(tids[j])) { // Found "final transition".. Note:
+ // may be "reordered" with its self loops.
+ if (!info_.reorder) return (j+1 == tids.size());
+ else {
+ // Make sure the only thing that follows this is self-loops
+ // of the final transition-state.
+ for (size_t k = j + 1; k < tids.size(); k++)
+ if (!tmodel_.TransitionIdsEquivalent(tids[k], tids[j])
+ || !tmodel_.IsSelfLoop(tids[k]))
+ return false;
+ return true;
+ }
+ }
+ }
+ return false; // Found no final state.
+ }
+
+ bool TestArcPartialWord(const CompactLatticeArc &arc) {
+ if (arc.ilabel != info_.partial_word_label) return false; // label should
+ // be the partial-word label.
+ const std::vector<int32> &tids = arc.weight.String();
+ if (tids.empty()) return false;
+ return true; // We're pretty liberal when it comes to partial words here.
+ }
+
+ void TestFinal(const CompactLatticeWeight &w) {
+ if (!w.String().empty())
+ KALDI_ERR << "Expect to have no strings on final-weights of lattices.";
+ }
+ void TestEquivalent() {
+ CompactLattice aligned_lat(aligned_lat_);
+ if (info_.silence_label != 0) { // remove silence labels.
+ std::vector<int32> to_remove;
+ to_remove.push_back(info_.silence_label);
+ RemoveSomeInputSymbols(to_remove, &aligned_lat);
+ Project(&aligned_lat, fst::PROJECT_INPUT);
+ }
+
+ if (!RandEquivalent(lat_, aligned_lat, 5/*paths*/, 1.0e+10/*delta*/, Rand()/*seed*/,
+ 200/*path length (max?)*/))
+ KALDI_ERR << "Equivalence test failed (testing word-alignment of lattices.) "
+ << "Make sure your model and lattices match!";
+ }
+
+ const CompactLattice &lat_;
+ const TransitionInformation &tmodel_;
+ const WordBoundaryInfo &info_;
+ const CompactLattice &aligned_lat_;
+};
+
+
+
+
+/// You should only test a lattice if WordAlignLattice returned true (i.e. it
+/// succeeded and it wasn't a forced-out lattice); otherwise the test will most
+/// likely fail.
+void TestWordAlignedLattice(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const WordBoundaryInfo &info,
+ const CompactLattice &aligned_lat) {
+ WordAlignedLatticeTester t(lat, tmodel, info, aligned_lat);
+ t.Test();
+}
+
+
+
+
+
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice.h b/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice.h
new file mode 100644
index 000000000..e688e3e48
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lat/word-align-lattice.h
@@ -0,0 +1,211 @@
+// lat/word-align-lattice.h
+
+// Copyright 2009-2012 Microsoft Corporation Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_LAT_WORD_ALIGN_LATTICE_H_
+#define KALDI_LAT_WORD_ALIGN_LATTICE_H_
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+
+#include "base/kaldi-common.h"
+#include "util/common-utils.h"
+#include "fstext/fstext-lib.h"
+#include "itf/transition-information.h"
+#include "lat/kaldi-lattice.h"
+
+namespace kaldi {
+
+
+struct WordBoundaryInfoOpts {
+ // Note: use of this structure
+ // is deprecated, see WordBoundaryInfoNewOpts.
+
+ // Note: this structure (and the code in word-align-lattice.{h,cc}
+ // makes stronger assumptions than the rest of the Kaldi toolkit:
+ // that is, it assumes you have word-position-dependent phones,
+ // with disjoint subsets of phones for (word-begin, word-end,
+ // word-internal, word-begin-and-end), and of course silence,
+ // which is assumed not to be inside a word [it will just print
+ // a warning if it is, though, and should give the right output
+ // as long as it's not at the beginning or end of a word].
+
+ std::string wbegin_phones;
+ std::string wend_phones;
+ std::string wbegin_and_end_phones;
+ std::string winternal_phones;
+ std::string silence_phones;
+ int32 silence_label;
+ int32 partial_word_label;
+ bool reorder;
+ bool silence_may_be_word_internal;
+ bool silence_has_olabels;
+
+ WordBoundaryInfoOpts(): silence_label(0), partial_word_label(0),
+ reorder(true), silence_may_be_word_internal(false),
+ silence_has_olabels(false) { }
+
+ void Register(OptionsItf *opts) {
+ opts->Register("wbegin-phones", &wbegin_phones, "Colon-separated list of "
+ "numeric ids of phones that begin a word");
+ opts->Register("wend-phones", &wend_phones, "Colon-separated list of "
+ "numeric ids of phones that end a word");
+ opts->Register("winternal-phones", &winternal_phones, "Colon-separated list "
+ "of numeric ids of phones that are internal to a word");
+ opts->Register("wbegin-and-end-phones", &wbegin_and_end_phones, "Colon-separated "
+ "list of numeric ids of phones that are used for "
+ "single-phone words.");
+ opts->Register("silence-phones", &silence_phones, "Colon-separated list of "
+ "numeric ids of phones that are used for silence (and other "
+ "non-word events such as noise - anything that doesn't have "
+ "a corresponding symbol in the lexicon.");
+ opts->Register("silence-label", &silence_label, "Numeric id of word symbol "
+ "that is to be used for silence arcs in the word-aligned "
+ "lattice (zero is OK)");
+ opts->Register("partial-word-label", &partial_word_label, "Numeric id of "
+ "word symbol that is to be used for arcs in the word-aligned "
+ "lattice corresponding to partial words at the end of "
+ "\"forced-out\" utterances (zero is OK)");
+ opts->Register("reorder", &reorder, "True if the lattices were generated "
+ "from graphs that had the --reorder option true, relating to "
+ "reordering self-loops (typically true)");
+ opts->Register("silence-may-be-word-internal", &silence_may_be_word_internal,
+ "If true, silence may appear inside words' prons (but not at begin/end!)\n");
+ opts->Register("silence-has-olabels", &silence_has_olabels,
+ "If true, silence phones have output labels in the lattice, just\n"
+ "like regular words. [This means you can't have un-labeled silences]");
+ }
+};
+
+
+// This structure is to be used for newer code, from s5 scripts on.
+struct WordBoundaryInfoNewOpts {
+ int32 silence_label;
+ int32 partial_word_label;
+ bool reorder;
+
+ WordBoundaryInfoNewOpts(): silence_label(0), partial_word_label(0),
+ reorder(true) { }
+
+ void Register(OptionsItf *opts) {
+ opts->Register("silence-label", &silence_label, "Numeric id of word symbol "
+ "that is to be used for silence arcs in the word-aligned "
+ "lattice (zero is OK)");
+ opts->Register("partial-word-label", &partial_word_label, "Numeric id of "
+ "word symbol that is to be used for arcs in the word-aligned "
+ "lattice corresponding to partial words at the end of "
+ "\"forced-out\" utterances (zero is OK)");
+ opts->Register("reorder", &reorder, "True if the lattices were generated "
+ "from graphs that had the --reorder option true, relating to "
+ "reordering self-loops (typically true)");
+ }
+};
+
+
+struct WordBoundaryInfo {
+ // This initializer will be deleted eventually.
+ WordBoundaryInfo(const WordBoundaryInfoOpts &opts); // Initialize from
+ // options class. Note: this throws. Don't try to catch this error
+ // and continue; catching errors thrown from initializers is dangerous.
+ // Note: the following vectors are initialized from the corresponding
+ // options strings in the options class, but if silence_may_be_word_internal=true
+ // or silence_has_olabels=true, we modify them as needed to make
+ // silence phones behave in this way.
+
+ // This initializer is to be used in future.
+ WordBoundaryInfo(const WordBoundaryInfoNewOpts &opts);
+ WordBoundaryInfo(const WordBoundaryInfoNewOpts &opts,
+ std::string word_boundary_file);
+
+ void Init(std::istream &stream);
+
+ enum PhoneType {
+ kNoPhone = 0,
+ kWordBeginPhone,
+ kWordEndPhone,
+ kWordBeginAndEndPhone,
+ kWordInternalPhone,
+ kNonWordPhone // non-word phones are typically silence phones; but the point
+ // is that there is
+ // no word label associated with them in the lattice. If a silence phone
+ // had a word label with it, we'd have to call it kWordBeginAndEndPhone.
+ };
+ PhoneType TypeOfPhone(int32 p) const {
+ if ((p < 0 || p > phone_to_type.size()))
+ KALDI_ERR << "Phone " << p << " was not specified in "
+ "word-boundary file (or options)";
+ return phone_to_type[p];
+ }
+
+ std::vector<PhoneType> phone_to_type;
+
+ int32 silence_label; // The integer label we give to silence words.
+ // (May be zero).
+ int32 partial_word_label; // The label we give to partially
+ // formed words that we might get at the end of the utterance
+ // if the lattice was "forced out" (no end state was reached).
+
+ bool reorder; // True if the "reordering" of self-loops versus
+ // forward-transition was done during graph creation (will
+ // normally be true.
+
+ private:
+ // This is to be removed eventually, when we all move to s5 scripts.
+ void SetOptions(const std::string int_list, PhoneType phone_type);
+};
+
+/// Align lattice so that each arc has the transition-ids on it
+/// that correspond to the word that is on that arc. [May also have
+/// epsilon arcs for optional silences.]
+/// Returns true if everything was OK, false if some kind of
+/// error was detected (e.g. the words didn't have the kinds of
+/// sequences we would expect if the WordBoundaryInfo was
+/// correct). Note: we don't expect silence inside words,
+/// or empty words (words with no phones), and we expect
+/// the word to start with a wbegin_phone, to end with
+/// a wend_phone, and to possibly have winternal_phones
+/// inside (or to consist of just one wbegin_and_end_phone).
+/// Note: if it returns false, it doesn't mean the lattice
+/// that the output is necessarily bad: it might just be that
+/// the lattice was "forced out" as the end-state was not
+/// reached during decoding, and in this case the output might
+/// be usable.
+/// If max_states > 0, if this code detects that the #states
+/// of the output will be greater than max_states, it will
+/// abort the computation, return false and produce an empty
+/// lattice out.
+bool WordAlignLattice(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const WordBoundaryInfo &info,
+ int32 max_states,
+ CompactLattice *lat_out);
+
+
+
+/// This function is designed to crash if something went wrong with the
+/// word-alignment of the lattice. It verifies
+/// that arcs are of 4 types:
+/// properly-aligned word arcs, with a word label.
+/// partial-word arcs, with the partial-word label.
+/// silence arcs, with the silence label.
+void TestWordAlignedLattice(const CompactLattice &lat,
+ const TransitionInformation &tmodel,
+ const WordBoundaryInfo &info,
+ const CompactLattice &aligned_lat);
+
+} // end namespace kaldi
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/Makefile b/runtime/onnxruntime/third_party/kaldi/lm/Makefile
new file mode 100644
index 000000000..e3398e292
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/Makefile
@@ -0,0 +1,25 @@
+EXTRA_CXXFLAGS = -Wno-sign-compare
+
+all:
+
+include ../kaldi.mk
+
+TESTFILES = arpa-file-parser-test arpa-lm-compiler-test
+
+OBJFILES = arpa-file-parser.o arpa-lm-compiler.o const-arpa-lm.o \
+ kaldi-rnnlm.o mikolov-rnnlm-lib.o
+
+ifdef KENLM_ROOT
+TESTFILES += kenlm-test
+OBJFILES += kenlm.o
+EXTRA_CXXFLAGS += $(KENLM_CXXFLAGS)
+EXTRA_LDFLAGS += $(KENLM_LDFLAGS)
+EXTRA_LDLIBS += $(KENLM_LDLIBS)
+endif
+
+LIBNAME = kaldi-lm
+
+ADDLIBS = ../fstext/kaldi-fstext.a ../util/kaldi-util.a \
+ ../matrix/kaldi-matrix.a ../base/kaldi-base.a
+
+include ../makefiles/default_rules.mk
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/README b/runtime/onnxruntime/third_party/kaldi/lm/README
new file mode 100644
index 000000000..2ca0c9322
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/README
@@ -0,0 +1,108 @@
+#
+# README
+#
+# Language model & lexicon examples
+# using command-line executables in lm/
+
+# To print and display FSTs,
+# make sure you have OpenFst binaries in your PATH, for example:
+# export PATH=$PATH:~/Sources/UBM-ASR/branches/clean/openfst-1.2/bin
+
+# If you have X installed in your local machine, you can display
+# FSTs from merlin by ssh'ing with X forwarding, for example:
+# ssh -X qboulianne@merlin
+
+# The following commands and examples assume that your are
+# in working directory UBM-ASR/branches/clean/src/lm
+
+#-------------------------------------------
+# Language model FST (G)
+
+# The command-line utility for
+# creating a language model FST from an arpa file is
+# "arpa2fst".
+
+# A summary of options and usage can be displayed with:
+./arpa2fst --help
+
+# Read an arpa file to produce an FST with symbol tables:
+./arpa2fst < input.arpa > grammar.fst
+
+# Print it or display it:
+fstprint grammar.fst
+fstdraw grammar.fst | dotty -
+
+# Note that arpa2fst will create a word symbol table
+# from all the words are in the ARPA file.
+# You can save this symbol table in text format
+# for examination or later reuse.
+fstprint --save_isymbols=grammar.syms grammar.fst > /dev/null
+
+#----------------------------------------------
+# Lexicon (L)
+
+# The command-line utility for
+# creating a lexicon FST from a text file is
+# "lex2fst".
+
+# A summary of options and usage can be displayed with:
+./lex2fst --help
+
+# Read a lexicon file (containing pronunciation probabilities)
+# and produce an FST with symbol tables.
+# By default it will have disambiguation markers,
+# optional silence between words,
+# and FST weights will be -log(prob).
+./lex2fst < prob_input.lex > lexicon.fst
+
+# Print it or display it
+fstprint lexicon.fst
+fstdraw lexicon.fst | dotty -
+
+# To produce one without markers (and also smaller):
+./lex2fst --nodisamb < prob_input.lex > lexicon_nomarkers.fst
+
+#---------------------------------
+# Combining lexicon and grammar
+
+# lgrecipe.cc is an example recipe for building det(LoG)
+# in C++ using calls to functions in lm/kaldi-lm.a
+# Here we use a large lexicon and language model from last year's.
+# First get input files:
+export MDIR=/homes/eva/q/qgoel/englishModels
+cp $MDIR/lm_callhome_gigaword_switchboard_web.hd.dct largelexicon.dct
+gunzip -c $MDIR/lm_callhome_gigaword_switchboard_web.3gram.arpa.gz > largelm.arpa
+
+# Set memory limits (by default limited to 400 MB). Make it 4 GB.
+ulimit -m 4000000 -v 8000000
+./lgrecipe largelexicon.dct largelm.arpa detlg.fst
+
+# Check its size: should be close to 13 M arcs and 8 M nodes
+fstinfo detlg.fst | head -15
+
+#---------------------------------------
+# Expanding nested grammars
+
+# replace-example is a use-case example that creates
+# small grammars from text files. These grammars
+# refer to other grammars using non-terminal symbols.
+# The result is the fully expanded grammar FST,
+# where each non-terminal has been expanded entirely
+# to non-terminals.
+cd examples
+
+# Example 1 : create the expanded grammar
+../replace-example input3.txt CREATURE.txt > input3.fst
+
+# and generate a random sentence from the expanded grammar
+fstrandgen input3.fst | fstrmepsilon | fstprint | cut -f 4
+
+# Example 2 : create the expanded grammar
+../replace-example input4.txt DAYOFMONTH.txt MONTH.txt YEAR.txt YEARDATE.txt > input4.fst
+
+# and generate random sentence
+fstrandgen input4.fst | fstproject --project_output | fstrmepsilon | fstprint | cut -f 4
+
+#--------------------------------------------
+# TODO: Adapt README.testfiles as an example of how to create
+# an arpa language model and evaluate its score / perplexity.
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/arpa-file-parser-test.cc b/runtime/onnxruntime/third_party/kaldi/lm/arpa-file-parser-test.cc
new file mode 100644
index 000000000..5331f9a33
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/arpa-file-parser-test.cc
@@ -0,0 +1,373 @@
+// lm/arpa-file-parser-test.cc
+
+// Copyright 2016 Smart Action Company LLC (kkm)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+/**
+ * @file arpa-file-parser-test.cc
+ * @brief Unit tests for language model code.
+ */
+
+#include <iomanip>
+#include <iostream>
+#include <string>
+#include <sstream>
+#include <vector>
+
+#include "base/kaldi-common.h"
+#include "fst/fstlib.h"
+#include "lm/arpa-file-parser.h"
+
+namespace kaldi {
+namespace {
+
+const int kMaxOrder = 3;
+
+struct NGramTestData {
+ int32 line_number;
+ float logprob;
+ int32 words[kMaxOrder];
+ float backoff;
+};
+
+std::ostream& operator<<(std::ostream &os, const NGramTestData &data) {
+ std::ios::fmtflags saved_state(os.flags());
+ os << std::fixed << std::setprecision(6);
+
+ os << data.logprob << ' ';
+ for (int i = 0; i < kMaxOrder; ++i) os << data.words[i] << ' ';
+ os << data.backoff << " // Line " << data.line_number;
+
+ os.flags(saved_state);
+ return os;
+}
+
+// This does not own the array pointer, and uset to simplify passing expected
+// result to TestableArpaFileParser::Verify.
+template <class T>
+struct CountedArray {
+ template <size_t N>
+ CountedArray(T(&array)[N]) : array(array), count(N) { }
+ const T *array;
+ const size_t count;
+};
+
+template <class T, size_t N>
+inline CountedArray<T> MakeCountedArray(T(&array)[N]) {
+ return CountedArray<T>(array);
+}
+
+class TestableArpaFileParser : public ArpaFileParser {
+ public:
+ TestableArpaFileParser(const ArpaParseOptions &options,
+ fst::SymbolTable *symbols)
+ : ArpaFileParser(options, symbols),
+ header_available_(false),
+ read_complete_(false),
+ last_order_(0) { }
+ void Validate(CountedArray<int32> counts, CountedArray<NGramTestData> ngrams);
+
+ private:
+ // ArpaFileParser overrides.
+ virtual void HeaderAvailable();
+ virtual void ConsumeNGram(const NGram& ngram);
+ virtual void ReadComplete();
+
+ bool header_available_;
+ bool read_complete_;
+ int32 last_order_;
+ std::vector<NGramTestData> ngrams_;
+};
+
+void TestableArpaFileParser::HeaderAvailable() {
+ KALDI_ASSERT(!header_available_);
+ KALDI_ASSERT(!read_complete_);
+ header_available_ = true;
+ KALDI_ASSERT(NgramCounts().size() <= kMaxOrder);
+}
+
+void TestableArpaFileParser::ConsumeNGram(const NGram& ngram) {
+ KALDI_ASSERT(header_available_);
+ KALDI_ASSERT(!read_complete_);
+ KALDI_ASSERT(ngram.words.size() <= NgramCounts().size());
+ KALDI_ASSERT(ngram.words.size() >= last_order_);
+ last_order_ = ngram.words.size();
+
+ NGramTestData entry = { 0 };
+ entry.line_number = LineNumber();
+ entry.logprob = ngram.logprob;
+ entry.backoff = ngram.backoff;
+ std::copy(ngram.words.begin(), ngram.words.end(), entry.words);
+ ngrams_.push_back(entry);
+}
+
+void TestableArpaFileParser::ReadComplete() {
+ KALDI_ASSERT(header_available_);
+ KALDI_ASSERT(!read_complete_);
+ read_complete_ = true;
+}
+
+bool CompareNgrams(const NGramTestData &actual,
+ NGramTestData expected) {
+ expected.logprob *= Log(10.0);
+ expected.backoff *= Log(10.0);
+ if (actual.line_number != expected.line_number
+ || !std::equal(actual.words, actual.words + kMaxOrder,
+ expected.words)
+ || !ApproxEqual(actual.logprob, expected.logprob)
+ || !ApproxEqual(actual.backoff, expected.backoff)) {
+ KALDI_WARN << "Actual n-gram [" << actual
+ << "] differs from expected [" << expected << "]";
+ return false;
+ }
+ return true;
+}
+
+void TestableArpaFileParser::Validate(
+ CountedArray<int32> expect_counts,
+ CountedArray<NGramTestData> expect_ngrams) {
+ // This needs better disagnostics probably.
+ KALDI_ASSERT(NgramCounts().size() == expect_counts.count);
+ KALDI_ASSERT(std::equal(NgramCounts().begin(), NgramCounts().end(),
+ expect_counts.array));
+
+ KALDI_ASSERT(ngrams_.size() == expect_ngrams.count);
+ // auto mpos = std::mismatch(ngrams_.begin(), ngrams_.end(),
+ // expect_ngrams.array, CompareNgrams);
+ // if (mpos.first != ngrams_.end())
+ // KALDI_ERR << "Maismatch at index " << mpos.first - ngrams_.begin();
+ // TODO: auto above requres C++11, and I cannot spell out the type!!!
+ KALDI_ASSERT(std::equal(ngrams_.begin(), ngrams_.end(),
+ expect_ngrams.array, CompareNgrams));
+}
+
+// Read integer LM (no symbols) with log base conversion.
+void ReadIntegerLmLogconvExpectSuccess() {
+ KALDI_LOG << "ReadIntegerLmLogconvExpectSuccess()";
+
+ static std::string integer_lm = "\
+\\data\\\n\
+ngram 1=4\n\
+ngram 2=2\n\
+ngram 3=2\n\
+\n\
+\\1-grams:\n\
+-5.2\t4\t-3.3\n\
+-3.4\t5\n\
+0\t1\t-2.5\n\
+-4.3\t2\n\
+\n\
+\\2-grams:\n\
+-1.4\t4 5\t-3.2\n\
+-1.3\t1 4\t-4.2\n\
+\n\
+\\3-grams:\n\
+-0.3\t1 4 5\n\
+-0.2\t4 5 2\n\
+\n\
+\\end\\";
+
+ int32 expect_counts[] = { 4, 2, 2 };
+ NGramTestData expect_ngrams[] = {
+ { 7, -5.2, { 4, 0, 0 }, -3.3 },
+ { 8, -3.4, { 5, 0, 0 }, 0.0 },
+ { 9, 0.0, { 1, 0, 0 }, -2.5 },
+ { 10, -4.3, { 2, 0, 0 }, 0.0 },
+
+ { 13, -1.4, { 4, 5, 0 }, -3.2 },
+ { 14, -1.3, { 1, 4, 0 }, -4.2 },
+
+ { 17, -0.3, { 1, 4, 5 }, 0.0 },
+ { 18, -0.2, { 4, 5, 2 }, 0.0 } };
+
+ ArpaParseOptions options;
+ options.bos_symbol = 1;
+ options.eos_symbol = 2;
+
+ TestableArpaFileParser parser(options, NULL);
+ std::istringstream stm(integer_lm, std::ios_base::in);
+ parser.Read(stm);
+ parser.Validate(MakeCountedArray(expect_counts),
+ MakeCountedArray(expect_ngrams));
+}
+
+// \xCE\xB2 = UTF-8 for Greek beta, to churn some UTF-8 cranks.
+static std::string symbolic_lm = "\
+We also allow random text coming before the \\data\\\n\
+section marker. Even this is ok:\n\
+\n\
+\\1-grams:\n\
+\n\
+and should be ignored before the \\data\\ marker\n\
+is seen alone by itself on a line.\n\
+\n\
+\\data\\\n\
+ngram 1=4\n\
+ngram 2=2\n\
+ngram 3=2\n\
+\n\
+\\1-grams: \n\
+-5.2\ta\t-3.3\n\
+-3.4\t\xCE\xB2\n\
+0.0\t<s>\t-2.5\n\
+-4.3\t</s>\n\
+\n\
+\\2-grams:\t\n\
+-1.5\ta \xCE\xB2\t-3.2\n\
+-1.3\t<s> a\t-4.2\n\
+\n\
+\\3-grams:\n\
+-0.3\t<s> a \xCE\xB2\n\
+-0.2\t<s> a </s>\n\
+\\end\\";
+
+// Symbol table that is created with predefined test symbols, "a" but no "b".
+class TestSymbolTable : public fst::SymbolTable {
+ public:
+ TestSymbolTable() {
+ AddSymbol("<eps>", 0);
+ AddSymbol("<s>", 1);
+ AddSymbol("</s>", 2);
+ AddSymbol("<unk>", 3);
+ AddSymbol("a", 4);
+ }
+};
+
+// Full expected result shared between ReadSymbolicLmNoOovImpl and
+// ReadSymbolicLmWithOovAddToSymbols().
+NGramTestData expect_symbolic_full[] = {
+ { 15, -5.2, { 4, 0, 0 }, -3.3 },
+ { 16, -3.4, { 5, 0, 0 }, 0.0 },
+ { 17, 0.0, { 1, 0, 0 }, -2.5 },
+ { 18, -4.3, { 2, 0, 0 }, 0.0 },
+
+ { 21, -1.5, { 4, 5, 0 }, -3.2 },
+ { 22, -1.3, { 1, 4, 0 }, -4.2 },
+
+ { 25, -0.3, { 1, 4, 5 }, 0.0 },
+ { 26, -0.2, { 1, 4, 2 }, 0.0 } };
+
+// This is run with all possible oov setting and yields same result.
+void ReadSymbolicLmNoOovImpl(ArpaParseOptions::OovHandling oov) {
+ int32 expect_counts[] = { 4, 2, 2 };
+ TestSymbolTable symbols;
+ symbols.AddSymbol("\xCE\xB2", 5);
+
+ ArpaParseOptions options;
+ options.bos_symbol = 1;
+ options.eos_symbol = 2;
+ options.unk_symbol = 3;
+ options.oov_handling = oov;
+ TestableArpaFileParser parser(options, &symbols);
+ std::istringstream stm(symbolic_lm, std::ios_base::in);
+ parser.Read(stm);
+ parser.Validate(MakeCountedArray(expect_counts),
+ MakeCountedArray(expect_symbolic_full));
+ KALDI_ASSERT(symbols.NumSymbols() == 6);
+}
+
+void ReadSymbolicLmNoOovTests() {
+ KALDI_LOG << "ReadSymbolicLmNoOovImpl(kRaiseError)";
+ ReadSymbolicLmNoOovImpl(ArpaParseOptions::kRaiseError);
+ KALDI_LOG << "ReadSymbolicLmNoOovImpl(kAddToSymbols)";
+ ReadSymbolicLmNoOovImpl(ArpaParseOptions::kAddToSymbols);
+ KALDI_LOG << "ReadSymbolicLmNoOovImpl(kReplaceWithUnk)";
+ ReadSymbolicLmNoOovImpl(ArpaParseOptions::kReplaceWithUnk);
+ KALDI_LOG << "ReadSymbolicLmNoOovImpl(kSkipNGram)";
+ ReadSymbolicLmNoOovImpl(ArpaParseOptions::kSkipNGram);
+}
+
+// This is run with all possible oov setting and yields same result.
+void ReadSymbolicLmWithOovImpl(
+ ArpaParseOptions::OovHandling oov,
+ CountedArray<NGramTestData> expect_ngrams,
+ fst::SymbolTable* symbols) {
+ int32 expect_counts[] = { 4, 2, 2 };
+ ArpaParseOptions options;
+ options.bos_symbol = 1;
+ options.eos_symbol = 2;
+ options.unk_symbol = 3;
+ options.oov_handling = oov;
+ TestableArpaFileParser parser(options, symbols);
+ std::istringstream stm(symbolic_lm, std::ios_base::in);
+ parser.Read(stm);
+ parser.Validate(MakeCountedArray(expect_counts), expect_ngrams);
+}
+
+void ReadSymbolicLmWithOovAddToSymbols() {
+ TestSymbolTable symbols;
+ ReadSymbolicLmWithOovImpl(ArpaParseOptions::kAddToSymbols,
+ MakeCountedArray(expect_symbolic_full),
+ &symbols);
+ KALDI_ASSERT(symbols.NumSymbols() == 6);
+ KALDI_ASSERT(symbols.Find("\xCE\xB2") == 5);
+}
+
+void ReadSymbolicLmWithOovReplaceWithUnk() {
+ NGramTestData expect_symbolic_unk_b[] = {
+ { 15, -5.2, { 4, 0, 0 }, -3.3 },
+ { 16, -3.4, { 3, 0, 0 }, 0.0 },
+ { 17, 0.0, { 1, 0, 0 }, -2.5 },
+ { 18, -4.3, { 2, 0, 0 }, 0.0 },
+
+ { 21, -1.5, { 4, 3, 0 }, -3.2 },
+ { 22, -1.3, { 1, 4, 0 }, -4.2 },
+
+ { 25, -0.3, { 1, 4, 3 }, 0.0 },
+ { 26, -0.2, { 1, 4, 2 }, 0.0 } };
+
+ TestSymbolTable symbols;
+ ReadSymbolicLmWithOovImpl(ArpaParseOptions::kReplaceWithUnk,
+ MakeCountedArray(expect_symbolic_unk_b),
+ &symbols);
+ KALDI_ASSERT(symbols.NumSymbols() == 5);
+}
+
+void ReadSymbolicLmWithOovSkipNGram() {
+ NGramTestData expect_symbolic_no_b[] = {
+ { 15, -5.2, { 4, 0, 0 }, -3.3 },
+ { 17, 0.0, { 1, 0, 0 }, -2.5 },
+ { 18, -4.3, { 2, 0, 0 }, 0.0 },
+
+ { 22, -1.3, { 1, 4, 0 }, -4.2 },
+
+ { 26, -0.2, { 1, 4, 2 }, 0.0 } };
+
+ TestSymbolTable symbols;
+ ReadSymbolicLmWithOovImpl(ArpaParseOptions::kSkipNGram,
+ MakeCountedArray(expect_symbolic_no_b),
+ &symbols);
+ KALDI_ASSERT(symbols.NumSymbols() == 5);
+}
+
+void ReadSymbolicLmWithOovTests() {
+ KALDI_LOG << "ReadSymbolicLmWithOovAddToSymbols()";
+ ReadSymbolicLmWithOovAddToSymbols();
+ KALDI_LOG << "ReadSymbolicLmWithOovReplaceWithUnk()";
+ ReadSymbolicLmWithOovReplaceWithUnk();
+ KALDI_LOG << "ReadSymbolicLmWithOovSkipNGram()";
+ ReadSymbolicLmWithOovSkipNGram();
+}
+
+} // namespace
+} // namespace kaldi
+
+int main(int argc, char *argv[]) {
+ kaldi::ReadIntegerLmLogconvExpectSuccess();
+ kaldi::ReadSymbolicLmNoOovTests();
+ kaldi::ReadSymbolicLmWithOovTests();
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/arpa-file-parser.cc b/runtime/onnxruntime/third_party/kaldi/lm/arpa-file-parser.cc
new file mode 100644
index 000000000..81b63ed13
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/arpa-file-parser.cc
@@ -0,0 +1,281 @@
+// lm/arpa-file-parser.cc
+
+// Copyright 2014 Guoguo Chen
+// Copyright 2016 Smart Action Company LLC (kkm)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include <fst/fstlib.h>
+
+#include <sstream>
+
+#include "base/kaldi-error.h"
+#include "base/kaldi-math.h"
+#include "lm/arpa-file-parser.h"
+#include "util/text-utils.h"
+
+namespace kaldi {
+
+ArpaFileParser::ArpaFileParser(const ArpaParseOptions& options,
+ fst::SymbolTable* symbols)
+ : options_(options), symbols_(symbols),
+ line_number_(0), warning_count_(0) {
+}
+
+ArpaFileParser::~ArpaFileParser() {
+}
+
+void TrimTrailingWhitespace(std::string *str) {
+ str->erase(str->find_last_not_of(" \n\r\t") + 1);
+}
+
+void ArpaFileParser::Read(std::istream &is) {
+ // Argument sanity checks.
+ if (options_.bos_symbol <= 0 || options_.eos_symbol <= 0 ||
+ options_.bos_symbol == options_.eos_symbol)
+ KALDI_ERR << "BOS and EOS symbols are required, must not be epsilons, and "
+ << "differ from each other. Given:"
+ << " BOS=" << options_.bos_symbol
+ << " EOS=" << options_.eos_symbol;
+ if (symbols_ != NULL &&
+ options_.oov_handling == ArpaParseOptions::kReplaceWithUnk &&
+ (options_.unk_symbol <= 0 ||
+ options_.unk_symbol == options_.bos_symbol ||
+ options_.unk_symbol == options_.eos_symbol))
+ KALDI_ERR << "When symbol table is given and OOV mode is kReplaceWithUnk, "
+ << "UNK symbol is required, must not be epsilon, and "
+ << "differ from both BOS and EOS symbols. Given:"
+ << " UNK=" << options_.unk_symbol
+ << " BOS=" << options_.bos_symbol
+ << " EOS=" << options_.eos_symbol;
+ if (symbols_ != NULL && symbols_->Find(options_.bos_symbol).empty())
+ KALDI_ERR << "BOS symbol must exist in symbol table";
+ if (symbols_ != NULL && symbols_->Find(options_.eos_symbol).empty())
+ KALDI_ERR << "EOS symbol must exist in symbol table";
+ if (symbols_ != NULL && options_.unk_symbol > 0 &&
+ symbols_->Find(options_.unk_symbol).empty())
+ KALDI_ERR << "UNK symbol must exist in symbol table";
+
+ ngram_counts_.clear();
+ line_number_ = 0;
+ warning_count_ = 0;
+ current_line_.clear();
+
+#define PARSE_ERR KALDI_ERR << LineReference() << ": "
+
+ // Give derived class an opportunity to prepare its state.
+ ReadStarted();
+
+ // Processes "\data\" section.
+ bool keyword_found = false;
+ while (++line_number_, getline(is, current_line_) && !is.eof()) {
+ if (current_line_.find_first_not_of(" \t\n\r") == std::string::npos) {
+ continue;
+ }
+
+ TrimTrailingWhitespace(&current_line_);
+
+ // Continue skipping lines until the \data\ marker alone on a line is found.
+ if (!keyword_found) {
+ if (current_line_ == "\\data\\") {
+ KALDI_LOG << "Reading \\data\\ section.";
+ keyword_found = true;
+ }
+ continue;
+ }
+
+ if (current_line_[0] == '\\') break;
+
+ // Enters "\data\" section, and looks for patterns like "ngram 1=1000",
+ // which means there are 1000 unigrams.
+ std::size_t equal_symbol_pos = current_line_.find("=");
+ if (equal_symbol_pos != std::string::npos)
+ // Guaranteed spaces around the "=".
+ current_line_.replace(equal_symbol_pos, 1, " = ");
+ std::vector<std::string> col;
+ SplitStringToVector(current_line_, " \t", true, &col);
+ if (col.size() == 4 && col[0] == "ngram" && col[2] == "=") {
+ int32 order, ngram_count = 0;
+ if (!ConvertStringToInteger(col[1], &order) ||
+ !ConvertStringToInteger(col[3], &ngram_count)) {
+ PARSE_ERR << "cannot parse ngram count";
+ }
+ if (ngram_counts_.size() <= order) {
+ ngram_counts_.resize(order);
+ }
+ ngram_counts_[order - 1] = ngram_count;
+ } else {
+ KALDI_WARN << LineReference()
+ << ": uninterpretable line in \\data\\ section";
+ }
+ }
+
+ if (ngram_counts_.size() == 0)
+ PARSE_ERR << "\\data\\ section missing or empty.";
+
+ // Signal that grammar order and n-gram counts are known.
+ HeaderAvailable();
+
+ NGram ngram;
+ ngram.words.reserve(ngram_counts_.size());
+
+ // Processes "\N-grams:" section.
+ for (int32 cur_order = 1; cur_order <= ngram_counts_.size(); ++cur_order) {
+ // Skips n-grams with zero count.
+ if (ngram_counts_[cur_order - 1] == 0)
+ KALDI_WARN << "Zero ngram count in ngram order " << cur_order
+ << "(look for 'ngram " << cur_order << "=0' in the \\data\\ "
+ << " section). There is possibly a problem with the file.";
+
+ // Must be looking at a \k-grams: directive at this point.
+ std::ostringstream keyword;
+ keyword << "\\" << cur_order << "-grams:";
+ if (current_line_ != keyword.str()) {
+ PARSE_ERR << "invalid directive, expecting '" << keyword.str() << "'";
+ }
+ KALDI_LOG << "Reading " << current_line_ << " section.";
+
+ int32 ngram_count = 0;
+ while (++line_number_, getline(is, current_line_) && !is.eof()) {
+ if (current_line_.find_first_not_of(" \n\t\r") == std::string::npos) {
+ continue;
+ }
+ if (current_line_[0] == '\\') {
+ TrimTrailingWhitespace(&current_line_);
+ std::ostringstream next_keyword;
+ next_keyword << "\\" << cur_order + 1 << "-grams:";
+ if ((current_line_ != next_keyword.str()) &&
+ (current_line_ != "\\end\\")) {
+ if (ShouldWarn()) {
+ KALDI_WARN << "ignoring possible directive '" << current_line_
+ << "' expecting '" << next_keyword.str() << "'";
+
+ if (warning_count_ > 0 &&
+ warning_count_ > static_cast<uint32>(options_.max_warnings)) {
+ KALDI_WARN << "Of " << warning_count_ << " parse warnings, "
+ << options_.max_warnings << " were reported. "
+ << "Run program with --max-arpa-warnings=-1 "
+ << "to see all warnings";
+ }
+ }
+ } else {
+ break;
+ }
+ }
+
+ std::vector<std::string> col;
+ SplitStringToVector(current_line_, " \t", true, &col);
+
+ if (col.size() < 1 + cur_order ||
+ col.size() > 2 + cur_order ||
+ (cur_order == ngram_counts_.size() && col.size() != 1 + cur_order)) {
+ PARSE_ERR << "Invalid n-gram data line";
+ }
+ ++ngram_count;
+
+ // Parse out n-gram logprob and, if present, backoff weight.
+ if (!ConvertStringToReal(col[0], &ngram.logprob)) {
+ PARSE_ERR << "invalid n-gram logprob '" << col[0] << "'";
+ }
+ ngram.backoff = 0.0;
+ if (col.size() > cur_order + 1) {
+ if (!ConvertStringToReal(col[cur_order + 1], &ngram.backoff))
+ PARSE_ERR << "invalid backoff weight '" << col[cur_order + 1] << "'";
+ }
+ // Convert to natural log.
+ ngram.logprob *= M_LN10;
+ ngram.backoff *= M_LN10;
+
+ ngram.words.resize(cur_order);
+ bool skip_ngram = false;
+ for (int32 index = 0; !skip_ngram && index < cur_order; ++index) {
+ int32 word;
+ if (symbols_) {
+ // Symbol table provided, so symbol labels are expected.
+ if (options_.oov_handling == ArpaParseOptions::kAddToSymbols) {
+ word = symbols_->AddSymbol(col[1 + index]);
+ } else {
+ word = symbols_->Find(col[1 + index]);
+ if (word == -1) { // fst::kNoSymbol
+ switch (options_.oov_handling) {
+ case ArpaParseOptions::kReplaceWithUnk:
+ word = options_.unk_symbol;
+ break;
+ case ArpaParseOptions::kSkipNGram:
+ if (ShouldWarn())
+ KALDI_WARN << LineReference() << " skipped: word '"
+ << col[1 + index] << "' not in symbol table";
+ skip_ngram = true;
+ break;
+ default:
+ PARSE_ERR << "word '" << col[1 + index]
+ << "' not in symbol table";
+ }
+ }
+ }
+ } else {
+ // Symbols not provided, LM file should contain integers.
+ if (!ConvertStringToInteger(col[1 + index], &word) || word < 0) {
+ PARSE_ERR << "invalid symbol '" << col[1 + index] << "'";
+ }
+ }
+ // Whichever way we got it, an epsilon is invalid.
+ if (word == 0) {
+ PARSE_ERR << "epsilon symbol '" << col[1 + index]
+ << "' is illegal in ARPA LM";
+ }
+ ngram.words[index] = word;
+ }
+ if (!skip_ngram) {
+ ConsumeNGram(ngram);
+ }
+ }
+ if (ngram_count > ngram_counts_[cur_order - 1]) {
+ PARSE_ERR << "header said there would be " << ngram_counts_[cur_order - 1]
+ << " n-grams of order " << cur_order
+ << ", but we saw more already.";
+ }
+ }
+
+ if (current_line_ != "\\end\\") {
+ PARSE_ERR << "invalid or unexpected directive line, expecting \\end\\";
+ }
+
+ if (warning_count_ > 0 &&
+ warning_count_ > static_cast<uint32>(options_.max_warnings)) {
+ KALDI_WARN << "Of " << warning_count_ << " parse warnings, "
+ << options_.max_warnings << " were reported. Run program with "
+ << "--max-arpa-warnings=-1 to see all warnings";
+ }
+
+ current_line_.clear();
+ ReadComplete();
+
+#undef PARSE_ERR
+}
+
+std::string ArpaFileParser::LineReference() const {
+ std::ostringstream ss;
+ ss << "line " << line_number_ << " [" << current_line_ << "]";
+ return ss.str();
+}
+
+bool ArpaFileParser::ShouldWarn() {
+ return (warning_count_ != -1) &&
+ (++warning_count_ <= static_cast<uint32>(options_.max_warnings));
+}
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/arpa-file-parser.h b/runtime/onnxruntime/third_party/kaldi/lm/arpa-file-parser.h
new file mode 100644
index 000000000..47eb4dc58
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/arpa-file-parser.h
@@ -0,0 +1,146 @@
+// lm/arpa-file-parser.h
+
+// Copyright 2014 Guoguo Chen
+// Copyright 2016 Smart Action Company LLC (kkm)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_LM_ARPA_FILE_PARSER_H_
+#define KALDI_LM_ARPA_FILE_PARSER_H_
+
+#include <fst/fst-decl.h>
+
+#include <string>
+#include <vector>
+
+#include "base/kaldi-types.h"
+#include "itf/options-itf.h"
+
+namespace kaldi {
+
+/**
+ Options that control ArpaFileParser
+*/
+struct ArpaParseOptions {
+ enum OovHandling {
+ kRaiseError, ///< Abort on OOV words
+ kAddToSymbols, ///< Add novel words to the symbol table.
+ kReplaceWithUnk, ///< Replace OOV words with <unk>.
+ kSkipNGram ///< Skip n-gram with OOV word and continue.
+ };
+
+ ArpaParseOptions():
+ bos_symbol(-1), eos_symbol(-1), unk_symbol(-1),
+ oov_handling(kRaiseError), max_warnings(30) { }
+
+ void Register(OptionsItf *opts) {
+ // Registering only the max_warnings count, since other options are
+ // treated differently by client programs: some want integer symbols,
+ // while other are passed words in their command line.
+ opts->Register("max-arpa-warnings", &max_warnings,
+ "Maximum warnings to report on ARPA parsing, "
+ "0 to disable, -1 to show all");
+ }
+
+ int32 bos_symbol; ///< Symbol for <s>, Required non-epsilon.
+ int32 eos_symbol; ///< Symbol for </s>, Required non-epsilon.
+ int32 unk_symbol; ///< Symbol for <unk>, Required for kReplaceWithUnk.
+ OovHandling oov_handling; ///< How to handle OOV words in the file.
+ int32 max_warnings; ///< Maximum warnings to report, <0 unlimited.
+};
+
+/**
+ A parsed n-gram from ARPA LM file.
+*/
+struct NGram {
+ NGram() : logprob(0.0), backoff(0.0) { }
+ std::vector<int32> words; ///< Symbols in left to right order.
+ float logprob; ///< Log-prob of the n-gram.
+ float backoff; ///< log-backoff weight of the n-gram.
+ ///< Defaults to zero if not specified.
+};
+
+/**
+ ArpaFileParser is an abstract base class for ARPA LM file conversion.
+
+ See ConstArpaLmBuilder and ArpaLmCompiler for usage examples.
+*/
+class ArpaFileParser {
+ public:
+ /// Constructs the parser with the given options and optional symbol table.
+ /// If symbol table is provided, then the file should contain text n-grams,
+ /// and the words are mapped to symbols through it. bos_symbol and
+ /// eos_symbol in the options structure must be valid symbols in the table,
+ /// and so must be unk_symbol if provided. The table is not owned by the
+ /// parser, but may be augmented, if oov_handling is set to kAddToSymbols.
+ /// If symbol table is a null pointer, the file should contain integer
+ /// symbol values, and oov_handling has no effect. bos_symbol and eos_symbol
+ /// must be valid symbols still.
+ ArpaFileParser(const ArpaParseOptions& options, fst::SymbolTable* symbols);
+ virtual ~ArpaFileParser();
+
+ /// Read ARPA LM file from a stream.
+ void Read(std::istream &is);
+
+ /// Parser options.
+ const ArpaParseOptions& Options() const { return options_; }
+
+ protected:
+ /// Override called before reading starts. This is the point to prepare
+ /// any state in the derived class.
+ virtual void ReadStarted() { }
+
+ /// Override function called to signal that ARPA header with the expected
+ /// number of n-grams has been read, and ngram_counts() is now valid.
+ virtual void HeaderAvailable() { }
+
+ /// Pure override that must be implemented to process current n-gram. The
+ /// n-grams are sent in the file order, which guarantees that all
+ /// (k-1)-grams are processed before the first k-gram is.
+ virtual void ConsumeNGram(const NGram&) = 0;
+
+ /// Override function called after the last n-gram has been consumed.
+ virtual void ReadComplete() { }
+
+ /// Read-only access to symbol table. Not owned, do not make public.
+ const fst::SymbolTable* Symbols() const { return symbols_; }
+
+ /// Inside ConsumeNGram(), provides the current line number.
+ int32 LineNumber() const { return line_number_; }
+
+ /// Inside ConsumeNGram(), returns a formatted reference to the line being
+ /// compiled, to print out as part of diagnostics.
+ std::string LineReference() const;
+
+ /// Increments warning count, and returns true if a warning should be
+ /// printed or false if the count has exceeded the set maximum.
+ bool ShouldWarn();
+
+ /// N-gram counts. Valid from the point when HeaderAvailable() is called.
+ const std::vector<int32>& NgramCounts() const { return ngram_counts_; }
+
+ private:
+ ArpaParseOptions options_;
+ fst::SymbolTable* symbols_; // the pointer is not owned here.
+ int32 line_number_;
+ uint32 warning_count_;
+ std::string current_line_;
+ std::vector<int32> ngram_counts_;
+};
+
+} // namespace kaldi
+
+#endif // KALDI_LM_ARPA_FILE_PARSER_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/arpa-lm-compiler-test.cc b/runtime/onnxruntime/third_party/kaldi/lm/arpa-lm-compiler-test.cc
new file mode 100644
index 000000000..a84258eda
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/arpa-lm-compiler-test.cc
@@ -0,0 +1,250 @@
+// lm/arpa-lm-compiler-test.cc
+
+// Copyright 2009-2011 Gilles Boulianne
+// Copyright 2016 Smart Action LLC (kkm)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include <iostream>
+#include <string>
+#include <sstream>
+
+#include "base/kaldi-error.h"
+#include "base/kaldi-math.h"
+#include "lm/arpa-lm-compiler.h"
+#include "util/kaldi-io.h"
+
+namespace kaldi {
+
+// Predefine some symbol values, because any integer is as good than any other.
+enum {
+ kEps = 0,
+ kDisambig,
+ kBos, kEos,
+};
+
+// Number of random sentences for coverage test.
+static const int kRandomSentences = 50;
+
+// Creates an FST that generates any sequence of symbols taken from given
+// symbol table. The FST is then associated with the symbol table.
+static fst::StdVectorFst* CreateGenFst(bool seps, const fst::SymbolTable* pst) {
+ fst::StdVectorFst* genFst = new fst::StdVectorFst;
+ genFst->SetInputSymbols(pst);
+ genFst->SetOutputSymbols(pst);
+
+ fst::StdArc::StateId midId = genFst->AddState();
+ if (!seps) {
+ fst::StdArc::StateId initId = genFst->AddState();
+ fst::StdArc::StateId finalId = genFst->AddState();
+ genFst->SetStart(initId);
+ genFst->SetFinal(finalId, fst::StdArc::Weight::One());
+ genFst->AddArc(initId, fst::StdArc(kBos, kBos, 0, midId));
+ genFst->AddArc(midId, fst::StdArc(kEos, kEos, 0, finalId));
+ } else {
+ genFst->SetStart(midId);
+ genFst->SetFinal(midId, fst::StdArc::Weight::One());
+ }
+
+ // Add a loop for each symbol in the table except the four special ones.
+ fst::SymbolTableIterator si(*pst);
+ for (si.Reset(); !si.Done(); si.Next()) {
+ if (si.Value() == kBos || si.Value() == kEos ||
+ si.Value() == kEps || si.Value() == kDisambig)
+ continue;
+ genFst->AddArc(midId, fst::StdArc(si.Value(), si.Value(),
+ fst::StdArc::Weight::One(), midId));
+ }
+ return genFst;
+}
+
+// Compile given ARPA file.
+ArpaLmCompiler* Compile(bool seps, const std::string &infile) {
+ ArpaParseOptions options;
+ fst::SymbolTable symbols;
+ // Use spaces on special symbols, so we rather fail than read them by mistake.
+ symbols.AddSymbol(" <eps>", kEps);
+ symbols.AddSymbol(" #0", kDisambig);
+ options.bos_symbol = symbols.AddSymbol("<s>", kBos);
+ options.eos_symbol = symbols.AddSymbol("</s>", kEos);
+ options.oov_handling = ArpaParseOptions::kAddToSymbols;
+
+ // Tests in this form cannot be run with epsilon substitution, unless every
+ // random path is also fitted with a #0-transducing self-loop.
+ ArpaLmCompiler* lm_compiler =
+ new ArpaLmCompiler(options,
+ seps ? kDisambig : 0,
+ &symbols);
+ {
+ Input ki(infile);
+ lm_compiler->Read(ki.Stream());
+ }
+ return lm_compiler;
+}
+
+// Add a state to an FSA after last_state, add a form last_state to the new
+// state, and return the new state.
+fst::StdArc::StateId AddToChainFsa(fst::StdMutableFst* fst,
+ fst::StdArc::StateId last_state,
+ int64 symbol) {
+ fst::StdArc::StateId next_state = fst->AddState();
+ fst->AddArc(last_state, fst::StdArc(symbol, symbol, 0, next_state));
+ return next_state;
+}
+
+// Add a disambiguator-generating self loop to every state of an FST.
+void AddSelfLoops(fst::StdMutableFst* fst) {
+ for (fst::StateIterator<fst::StdMutableFst> siter(*fst);
+ !siter.Done(); siter.Next()) {
+ fst->AddArc(siter.Value(),
+ fst::StdArc(kEps, kDisambig, 0, siter.Value()));
+ }
+}
+
+// Compiles infile and then runs kRandomSentences random coverage tests on the
+// compiled FST.
+bool CoverageTest(bool seps, const std::string &infile) {
+ // Compile ARPA model.
+ ArpaLmCompiler* lm_compiler = Compile(seps, infile);
+
+ // Create an FST that generates any sequence of symbols taken from the model
+ // output.
+ fst::StdVectorFst* genFst =
+ CreateGenFst(seps, lm_compiler->Fst().OutputSymbols());
+
+ int num_successes = 0;
+ for (int32 i = 0; i < kRandomSentences; ++i) {
+ // Generate a random sentence FST.
+ fst::StdVectorFst sentence;
+ RandGen(*genFst, &sentence);
+ if (seps)
+ AddSelfLoops(&sentence);
+
+ fst::ArcSort(lm_compiler->MutableFst(), fst::StdOLabelCompare());
+
+ // The past must successfully compose with the LM FST.
+ fst::StdVectorFst composition;
+ Compose(sentence, lm_compiler->Fst(), &composition);
+ if (composition.Start() != fst::kNoStateId)
+ ++num_successes;
+ }
+
+ delete genFst;
+ delete lm_compiler;
+
+ bool ok = num_successes == kRandomSentences;
+ if (!ok) {
+ KALDI_WARN << "Coverage test failed on " << infile << ": composed "
+ << num_successes << "/" << kRandomSentences;
+ }
+ return ok;
+}
+
+bool ScoringTest(bool seps, const std::string &infile, const std::string& sentence,
+ float expected) {
+ ArpaLmCompiler* lm_compiler = Compile(seps, infile);
+ const fst::SymbolTable* symbols = lm_compiler->Fst().InputSymbols();
+
+ // Create a sentence FST for scoring.
+ fst::StdVectorFst sentFst;
+ fst::StdArc::StateId state = sentFst.AddState();
+ sentFst.SetStart(state);
+ if (!seps) {
+ state = AddToChainFsa(&sentFst, state, kBos);
+ }
+ std::stringstream ss(sentence);
+ std::string word;
+ while (ss >> word) {
+ int64 word_sym = symbols->Find(word);
+ KALDI_ASSERT(word_sym != -1);
+ state = AddToChainFsa(&sentFst, state, word_sym);
+ }
+ if (!seps) {
+ state = AddToChainFsa(&sentFst, state, kEos);
+ }
+ if (seps) {
+ AddSelfLoops(&sentFst);
+ }
+ sentFst.SetFinal(state, 0);
+ sentFst.SetOutputSymbols(symbols);
+
+ // Do the composition and extract final weight.
+ fst::StdVectorFst composed;
+ fst::Compose(sentFst, lm_compiler->Fst(), &composed);
+ delete lm_compiler;
+
+ if (composed.Start() == fst::kNoStateId) {
+ KALDI_WARN << "Test sentence " << sentence << " did not compose "
+ << "with the language model FST\n";
+ return false;
+ }
+
+ std::vector<fst::StdArc::Weight> shortest;
+ fst::ShortestDistance(composed, &shortest, true);
+ float actual = shortest[composed.Start()].Value();
+
+ bool ok = ApproxEqual(expected, actual);
+ if (!ok) {
+ KALDI_WARN << "Scored " << sentence << " in " << infile
+ << ": Expected=" << expected << " actual=" << actual;
+ }
+ return ok;
+}
+
+bool ThrowsExceptionTest(bool seps, const std::string &infile) {
+ try {
+ // Make memory cleanup easy in both cases of try-catch block.
+ std::unique_ptr<ArpaLmCompiler> compiler(Compile(seps, infile));
+ return false;
+ } catch (const KaldiFatalError&) {
+ return true;
+ }
+}
+
+} // namespace kaldi
+
+bool RunAllTests(bool seps) {
+ bool ok = true;
+ ok &= kaldi::CoverageTest(seps, "test_data/missing_backoffs.arpa");
+ ok &= kaldi::CoverageTest(seps, "test_data/unused_backoffs.arpa");
+ ok &= kaldi::CoverageTest(seps, "test_data/input.arpa");
+
+ ok &= kaldi::ScoringTest(seps, "test_data/input.arpa", "b b b a", 59.2649);
+ ok &= kaldi::ScoringTest(seps, "test_data/input.arpa", "a b", 4.36082);
+
+ ok &= kaldi::ThrowsExceptionTest(seps, "test_data/missing_bos.arpa");
+
+ if (!ok) {
+ KALDI_WARN << "Tests " << (seps ? "with" : "without")
+ << " epsilon substitution FAILED";
+ }
+ return ok;
+}
+
+int main(int argc, char *argv[]) {
+ bool ok = true;
+
+ ok &= RunAllTests(false); // Without disambiguators (old behavior).
+ ok &= RunAllTests(true); // With epsilon substitution (new behavior).
+
+ if (ok) {
+ KALDI_LOG << "All tests passed";
+ return 0;
+ } else {
+ KALDI_WARN << "Test FAILED";
+ return 1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/arpa-lm-compiler.cc b/runtime/onnxruntime/third_party/kaldi/lm/arpa-lm-compiler.cc
new file mode 100644
index 000000000..e37711c5d
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/arpa-lm-compiler.cc
@@ -0,0 +1,377 @@
+// lm/arpa-lm-compiler.cc
+
+// Copyright 2009-2011 Gilles Boulianne
+// Copyright 2016 Smart Action LLC (kkm)
+// Copyright 2017 Xiaohui Zhang
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include <algorithm>
+#include <limits>
+#include <sstream>
+#include <utility>
+
+#include "base/kaldi-math.h"
+#include "lm/arpa-lm-compiler.h"
+#include "util/stl-utils.h"
+#include "util/text-utils.h"
+#include "fstext/remove-eps-local.h"
+
+namespace kaldi {
+
+class ArpaLmCompilerImplInterface {
+ public:
+ virtual ~ArpaLmCompilerImplInterface() { }
+ virtual void ConsumeNGram(const NGram& ngram, bool is_highest) = 0;
+};
+
+namespace {
+
+typedef int32 StateId;
+typedef int32 Symbol;
+
+// GeneralHistKey can represent state history in an arbitrarily large n
+// n-gram model with symbol ids fitting int32.
+class GeneralHistKey {
+ public:
+ // Construct key from being and end iterators.
+ template<class InputIt>
+ GeneralHistKey(InputIt begin, InputIt end) : vector_(begin, end) { }
+ // Construct empty history key.
+ GeneralHistKey() : vector_() { }
+ // Return tails of the key as a GeneralHistKey. The tails of an n-gram
+ // w[1..n] is the sequence w[2..n] (and the heads is w[1..n-1], but the
+ // key class does not need this operartion).
+ GeneralHistKey Tails() const {
+ return GeneralHistKey(vector_.begin() + 1, vector_.end());
+ }
+ // Keys are equal if represent same state.
+ friend bool operator==(const GeneralHistKey& a, const GeneralHistKey& b) {
+ return a.vector_ == b.vector_;
+ }
+ // Public typename HashType for hashing.
+ struct HashType {
+ size_t operator()(const GeneralHistKey& key) const {
+ return VectorHasher<Symbol>().operator()(key.vector_);
+ }
+ };
+
+ private:
+ std::vector<Symbol> vector_;
+};
+
+// OptimizedHistKey combines 3 21-bit symbol ID values into one 64-bit
+// machine word. allowing significant memory reduction and some runtime
+// benefit over GeneralHistKey. Since 3 symbols are enough to track history
+// in a 4-gram model, this optimized key is used for smaller models with up
+// to 4-gram and symbol values up to 2^21-1.
+//
+// See GeneralHistKey for interface requirements of a key class.
+class OptimizedHistKey {
+ public:
+ enum {
+ kShift = 21, // 21 * 3 = 63 bits for data.
+ kMaxData = (1 << kShift) - 1
+ };
+ template<class InputIt>
+ OptimizedHistKey(InputIt begin, InputIt end) : data_(0) {
+ for (uint32 shift = 0; begin != end; ++begin, shift += kShift) {
+ data_ |= static_cast<uint64>(*begin) << shift;
+ }
+ }
+ OptimizedHistKey() : data_(0) { }
+ OptimizedHistKey Tails() const {
+ return OptimizedHistKey(data_ >> kShift);
+ }
+ friend bool operator==(const OptimizedHistKey& a, const OptimizedHistKey& b) {
+ return a.data_ == b.data_;
+ }
+ struct HashType {
+ size_t operator()(const OptimizedHistKey& key) const { return key.data_; }
+ };
+
+ private:
+ explicit OptimizedHistKey(uint64 data) : data_(data) { }
+ uint64 data_;
+};
+
+} // namespace
+
+template <class HistKey>
+class ArpaLmCompilerImpl : public ArpaLmCompilerImplInterface {
+ public:
+ ArpaLmCompilerImpl(ArpaLmCompiler* parent, fst::StdVectorFst* fst,
+ Symbol sub_eps);
+
+ virtual void ConsumeNGram(const NGram &ngram, bool is_highest);
+
+ private:
+ StateId AddStateWithBackoff(HistKey key, float backoff);
+ void CreateBackoff(HistKey key, StateId state, float weight);
+
+ ArpaLmCompiler *parent_; // Not owned.
+ fst::StdVectorFst* fst_; // Not owned.
+ Symbol bos_symbol_;
+ Symbol eos_symbol_;
+ Symbol sub_eps_;
+
+ StateId eos_state_;
+ typedef unordered_map<HistKey, StateId,
+ typename HistKey::HashType> HistoryMap;
+ HistoryMap history_;
+};
+
+template <class HistKey>
+ArpaLmCompilerImpl<HistKey>::ArpaLmCompilerImpl(
+ ArpaLmCompiler* parent, fst::StdVectorFst* fst, Symbol sub_eps)
+ : parent_(parent), fst_(fst), bos_symbol_(parent->Options().bos_symbol),
+ eos_symbol_(parent->Options().eos_symbol), sub_eps_(sub_eps) {
+ // The algorithm maintains state per history. The 0-gram is a special state
+ // for empty history. All unigrams (including BOS) backoff into this state.
+ StateId zerogram = fst_->AddState();
+ history_[HistKey()] = zerogram;
+
+ // Also, if </s> is not treated as epsilon, create a common end state for
+ // all transitions accepting the </s>, since they do not back off. This small
+ // optimization saves about 2% states in an average grammar.
+ if (sub_eps_ == 0) {
+ eos_state_ = fst_->AddState();
+ fst_->SetFinal(eos_state_, 0);
+ }
+}
+
+template <class HistKey>
+void ArpaLmCompilerImpl<HistKey>::ConsumeNGram(const NGram &ngram,
+ bool is_highest) {
+ // Generally, we do the following. Suppose we are adding an n-gram "A B
+ // C". Then find the node for "A B", add a new node for "A B C", and connect
+ // them with the arc accepting "C" with the specified weight. Also, add a
+ // backoff arc from the new "A B C" node to its backoff state "B C".
+ //
+ // Two notable exceptions are the highest order n-grams, and final n-grams.
+ //
+ // When adding a highest order n-gram (e. g., our "A B C" is in a 3-gram LM),
+ // the following optimization is performed. There is no point adding a node
+ // for "A B C" with a "C" arc from "A B", since there will be no other
+ // arcs ingoing to this node, and an epsilon backoff arc into the backoff
+ // model "B C", with the weight of \bar{1}. To save a node, create an arc
+ // accepting "C" directly from "A B" to "B C". This saves as many nodes
+ // as there are the highest order n-grams, which is typically about half
+ // the size of a large 3-gram model.
+ //
+ // Indeed, this does not apply to n-grams ending in EOS, since they do not
+ // back off. These are special, as they do not have a back-off state, and
+ // the node for "(..anything..) </s>" is always final. These are handled
+ // in one of the two possible ways, If symbols <s> and </s> are being
+ // replaced by epsilons, neither node nor arc is created, and the logprob
+ // of the n-gram is applied to its source node as final weight. If <s> and
+ // </s> are preserved, then a special final node for </s> is allocated and
+ // used as the destination of the "</s>" acceptor arc.
+ HistKey heads(ngram.words.begin(), ngram.words.end() - 1);
+ typename HistoryMap::iterator source_it = history_.find(heads);
+ if (source_it == history_.end()) {
+ // There was no "A B", therefore the probability of "A B C" is zero.
+ // Print a warning and discard current n-gram.
+ if (parent_->ShouldWarn())
+ KALDI_WARN << parent_->LineReference()
+ << " skipped: no parent (n-1)-gram exists";
+ return;
+ }
+
+ StateId source = source_it->second;
+ StateId dest;
+ Symbol sym = ngram.words.back();
+ float weight = -ngram.logprob;
+ if (sym == sub_eps_ || sym == 0) {
+ KALDI_ERR << " <eps> or disambiguation symbol " << sym << "found in the ARPA file. ";
+ }
+ if (sym == eos_symbol_) {
+ if (sub_eps_ == 0) {
+ // Keep </s> as a real symbol when not substituting.
+ dest = eos_state_;
+ } else {
+ // Treat </s> as if it was epsilon: mark source final, with the weight
+ // of the n-gram.
+ fst_->SetFinal(source, weight);
+ return;
+ }
+ } else {
+ // For the highest order n-gram, this may find an existing state, for
+ // non-highest, will create one (unless there are duplicate n-grams
+ // in the grammar, which cannot be reliably detected if highest order,
+ // so we better do not do that at all).
+ dest = AddStateWithBackoff(
+ HistKey(ngram.words.begin() + (is_highest ? 1 : 0),
+ ngram.words.end()),
+ -ngram.backoff);
+ }
+
+ if (sym == bos_symbol_) {
+ weight = 0; // Accepting <s> is always free.
+ if (sub_eps_ == 0) {
+ // <s> is as a real symbol, only accepted in the start state.
+ source = fst_->AddState();
+ fst_->SetStart(source);
+ } else {
+ // The new state for <s> unigram history *is* the start state.
+ fst_->SetStart(dest);
+ return;
+ }
+ }
+
+ // Add arc from source to dest, whichever way it was found.
+ fst_->AddArc(source, fst::StdArc(sym, sym, weight, dest));
+ return;
+}
+
+// Find or create a new state for n-gram defined by key, and ensure it has a
+// backoff transition. The key is either the current n-gram for all but
+// highest orders, or the tails of the n-gram for the highest order. The
+// latter arises from the chain-collapsing optimization described above.
+template <class HistKey>
+StateId ArpaLmCompilerImpl<HistKey>::AddStateWithBackoff(HistKey key,
+ float backoff) {
+ typename HistoryMap::iterator dest_it = history_.find(key);
+ if (dest_it != history_.end()) {
+ // Found an existing state in the history map. Invariant: if the state in
+ // the map, then its backoff arc is in the FST. We are done.
+ return dest_it->second;
+ }
+ // Otherwise create a new state and its backoff arc, and register in the map.
+ StateId dest = fst_->AddState();
+ history_[key] = dest;
+ CreateBackoff(key.Tails(), dest, backoff);
+ return dest;
+}
+
+// Create a backoff arc for a state. Key is a backoff destination that may or
+// may not exist. When the destination is not found, naturally fall back to
+// the lower order model, and all the way down until one is found (since the
+// 0-gram model is always present, the search is guaranteed to terminate).
+template <class HistKey>
+inline void ArpaLmCompilerImpl<HistKey>::CreateBackoff(
+ HistKey key, StateId state, float weight) {
+ typename HistoryMap::iterator dest_it = history_.find(key);
+ while (dest_it == history_.end()) {
+ key = key.Tails();
+ dest_it = history_.find(key);
+ }
+
+ // The arc should transduce either <eos> or #0 to <eps>, depending on the
+ // epsilon substitution mode. This is the only case when input and output
+ // label may differ.
+ fst_->AddArc(state, fst::StdArc(sub_eps_, 0, weight, dest_it->second));
+}
+
+ArpaLmCompiler::~ArpaLmCompiler() {
+ if (impl_ != NULL)
+ delete impl_;
+}
+
+void ArpaLmCompiler::HeaderAvailable() {
+ KALDI_ASSERT(impl_ == NULL);
+ // Use optimized implementation if the grammar is 4-gram or less, and the
+ // maximum attained symbol id will fit into the optimized range.
+ int64 max_symbol = 0;
+ if (Symbols() != NULL)
+ max_symbol = Symbols()->AvailableKey() - 1;
+ // If augmenting the symbol table, assume the worst case when all words in
+ // the model being read are novel.
+ if (Options().oov_handling == ArpaParseOptions::kAddToSymbols)
+ max_symbol += NgramCounts()[0];
+
+ if (NgramCounts().size() <= 4 && max_symbol < OptimizedHistKey::kMaxData) {
+ impl_ = new ArpaLmCompilerImpl<OptimizedHistKey>(this, &fst_, sub_eps_);
+ } else {
+ impl_ = new ArpaLmCompilerImpl<GeneralHistKey>(this, &fst_, sub_eps_);
+ KALDI_LOG << "Reverting to slower state tracking because model is large: "
+ << NgramCounts().size() << "-gram with symbols up to "
+ << max_symbol;
+ }
+}
+
+void ArpaLmCompiler::ConsumeNGram(const NGram &ngram) {
+ // <s> is invalid in tails, </s> in heads of an n-gram.
+ for (int i = 0; i < ngram.words.size(); ++i) {
+ if ((i > 0 && ngram.words[i] == Options().bos_symbol) ||
+ (i + 1 < ngram.words.size()
+ && ngram.words[i] == Options().eos_symbol)) {
+ if (ShouldWarn())
+ KALDI_WARN << LineReference()
+ << " skipped: n-gram has invalid BOS/EOS placement";
+ return;
+ }
+ }
+
+ bool is_highest = ngram.words.size() == NgramCounts().size();
+ impl_->ConsumeNGram(ngram, is_highest);
+}
+
+void ArpaLmCompiler::RemoveRedundantStates() {
+ fst::StdArc::Label backoff_symbol = sub_eps_;
+ if (backoff_symbol == 0) {
+ // The method of removing redundant states implemented in this function
+ // leads to slow determinization of L o G when people use the older style of
+ // usage of arpa2fst where the --disambig-symbol option was not specified.
+ // The issue seems to be that it creates a non-deterministic FST, while G is
+ // supposed to be deterministic. By 'return'ing below, we just disable this
+ // method if people were using an older script. This method isn't really
+ // that consequential anyway, and people will move to the newer-style
+ // scripts (see current utils/format_lm.sh), so this isn't much of a
+ // problem.
+ return;
+ }
+
+ fst::StdArc::StateId num_states = fst_.NumStates();
+
+
+ // replace the #0 symbols on the input of arcs out of redundant states (states
+ // that are not final and have only a backoff arc leaving them), with <eps>.
+ for (fst::StdArc::StateId state = 0; state < num_states; state++) {
+ if (fst_.NumArcs(state) == 1 && fst_.Final(state) == fst::TropicalWeight::Zero()) {
+ fst::MutableArcIterator<fst::StdVectorFst> iter(&fst_, state);
+ fst::StdArc arc = iter.Value();
+ if (arc.ilabel == backoff_symbol) {
+ arc.ilabel = 0;
+ iter.SetValue(arc);
+ }
+ }
+ }
+
+ // we could call fst::RemoveEps, and it would have the same effect in normal
+ // cases, where backoff_symbol != 0 and there are no epsilons in unexpected
+ // places, but RemoveEpsLocal is a bit safer in case something weird is going
+ // on; it guarantees not to blow up the FST.
+ fst::RemoveEpsLocal(&fst_);
+ KALDI_LOG << "Reduced num-states from " << num_states << " to "
+ << fst_.NumStates();
+}
+
+void ArpaLmCompiler::Check() const {
+ if (fst_.Start() == fst::kNoStateId) {
+ KALDI_ERR << "Arpa file did not contain the beginning-of-sentence symbol "
+ << Symbols()->Find(Options().bos_symbol) << ".";
+ }
+}
+
+void ArpaLmCompiler::ReadComplete() {
+ fst_.SetInputSymbols(Symbols());
+ fst_.SetOutputSymbols(Symbols());
+ RemoveRedundantStates();
+ Check();
+}
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/arpa-lm-compiler.h b/runtime/onnxruntime/third_party/kaldi/lm/arpa-lm-compiler.h
new file mode 100644
index 000000000..67a18273f
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/arpa-lm-compiler.h
@@ -0,0 +1,65 @@
+// lm/arpa-lm-compiler.h
+
+// Copyright 2009-2011 Gilles Boulianne
+// Copyright 2016 Smart Action LLC (kkm)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_LM_ARPA_LM_COMPILER_H_
+#define KALDI_LM_ARPA_LM_COMPILER_H_
+
+#include <fst/fstlib.h>
+
+#include "lm/arpa-file-parser.h"
+
+namespace kaldi {
+
+class ArpaLmCompilerImplInterface;
+
+class ArpaLmCompiler : public ArpaFileParser {
+ public:
+ ArpaLmCompiler(const ArpaParseOptions& options, int sub_eps,
+ fst::SymbolTable* symbols)
+ : ArpaFileParser(options, symbols),
+ sub_eps_(sub_eps), impl_(NULL) {
+ }
+ ~ArpaLmCompiler();
+
+ const fst::StdVectorFst& Fst() const { return fst_; }
+ fst::StdVectorFst* MutableFst() { return &fst_; }
+
+ protected:
+ // ArpaFileParser overrides.
+ virtual void HeaderAvailable();
+ virtual void ConsumeNGram(const NGram& ngram);
+ virtual void ReadComplete();
+
+
+ private:
+ // this function removes states that only have a backoff arc coming
+ // out of them.
+ void RemoveRedundantStates();
+ void Check() const;
+
+ int sub_eps_;
+ ArpaLmCompilerImplInterface* impl_; // Owned.
+ fst::StdVectorFst fst_;
+ template <class HistKey> friend class ArpaLmCompilerImpl;
+};
+
+} // namespace kaldi
+
+#endif // KALDI_LM_ARPA_LM_COMPILER_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/const-arpa-lm.cc b/runtime/onnxruntime/third_party/kaldi/lm/const-arpa-lm.cc
new file mode 100644
index 000000000..a12e411fb
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/const-arpa-lm.cc
@@ -0,0 +1,1085 @@
+// lm/const-arpa-lm.cc
+
+// Copyright 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include <algorithm>
+#include <limits>
+#include <sstream>
+#include <utility>
+
+#include "base/kaldi-math.h"
+#include "lm/arpa-file-parser.h"
+#include "lm/const-arpa-lm.h"
+#include "util/stl-utils.h"
+#include "util/text-utils.h"
+
+
+namespace kaldi {
+
+// Auxiliary struct for converting ConstArpaLm format langugae model to Arpa
+// format.
+struct ArpaLine {
+ std::vector<int32> words; // Sequence of words to be printed.
+ float logprob; // Logprob corresponds to word sequence.
+ float backoff_logprob; // Backoff_logprob corresponds to word sequence.
+ // Comparison function for sorting.
+ bool operator < (const ArpaLine &other) const {
+ if (words.size() < other.words.size()) {
+ return true;
+ } else if (words.size() > other.words.size()) {
+ return false;
+ } else {
+ return words < other.words;
+ }
+ }
+};
+
+// Auxiliary class to build ConstArpaLm. We first use this class to figure out
+// the relative address of different LmStates, and then put everything into one
+// block in memory.
+class LmState {
+ public:
+ union ChildType {
+ // If child is not the final order, we keep the pointer to its LmState.
+ LmState* state;
+
+ // If child is the final order, we only keep the log probability for it.
+ float prob;
+ };
+
+ struct ChildrenVectorLessThan {
+ bool operator()(
+ const std::pair<int32, union ChildType>& lhs,
+ const std::pair<int32, union ChildType>& rhs) const {
+ return lhs.first < rhs.first;
+ }
+ };
+
+ LmState(const bool is_unigram, const bool is_child_final_order,
+ const float logprob, const float backoff_logprob) :
+ is_unigram_(is_unigram), is_child_final_order_(is_child_final_order),
+ logprob_(logprob), backoff_logprob_(backoff_logprob) {}
+
+ void SetMyAddress(const int64 address) {
+ my_address_ = address;
+ }
+
+ void AddChild(const int32 word, LmState* child_state) {
+ KALDI_ASSERT(!is_child_final_order_);
+ ChildType child;
+ child.state = child_state;
+ children_.push_back(std::make_pair(word, child));
+ }
+
+ void AddChild(const int32 word, const float child_prob) {
+ KALDI_ASSERT(is_child_final_order_);
+ ChildType child;
+ child.prob = child_prob;
+ children_.push_back(std::make_pair(word, child));
+ }
+
+ int64 MyAddress() const {
+ return my_address_;
+ }
+
+ bool IsUnigram() const {
+ return is_unigram_;
+ }
+
+ bool IsChildFinalOrder() const {
+ return is_child_final_order_;
+ }
+
+ float Logprob() const {
+ return logprob_;
+ }
+
+ float BackoffLogprob() const {
+ return backoff_logprob_;
+ }
+
+ int32 NumChildren() const {
+ return children_.size();
+ }
+
+ std::pair<int32, union ChildType> GetChild(const int32 index) {
+ KALDI_ASSERT(index < children_.size());
+ KALDI_ASSERT(index >= 0);
+ return children_[index];
+ }
+
+ void SortChildren() {
+ std::sort(children_.begin(), children_.end(), ChildrenVectorLessThan());
+ }
+
+ // Checks if the current LmState is a leaf.
+ bool IsLeaf() const {
+ return (backoff_logprob_ == 0.0 && children_.empty());
+ }
+
+ // Computes the size of the memory that the current LmState would take in
+ // <lm_states> array. It's the number of 4-byte chunks.
+ int32 MemSize() const {
+ if (IsLeaf() && !is_unigram_) {
+ // We don't create an entry in this case; the logprob will be stored in
+ // the same int32 that we would normally store the pointer in.
+ return 0;
+ } else {
+ // We store the following information:
+ // logprob, backoff_logprob, children.size() and children data.
+ return (3 + 2 * children_.size());
+ }
+ }
+
+ private:
+ // Unigram states will have LmStates even if they are leaves, therefore we
+ // need to note when this is a unigram or not.
+ bool is_unigram_;
+
+ // If the current LmState has an order of (final_order - 1), then its child
+ // must be the final order. We only keep the log probability for its child.
+ bool is_child_final_order_;
+
+ // When we compute the addresses of the LmStates as offsets into <lm_states_>
+ // pointer, and put the offsets here. Note that this is just offset, not
+ // actual pointer.
+ int64 my_address_;
+
+ // Language model log probability of the current sequence. For example, if
+ // this state is "A B", then it would be the logprob of "A -> B".
+ float logprob_;
+
+ // Language model backoff log probability of the current sequence, e.g., state
+ // "A B -> X" backing off to "B -> X".
+ float backoff_logprob_;
+
+ // List of children.
+ std::vector<std::pair<int32, union ChildType> > children_;
+};
+
+// Class to build ConstArpaLm from Arpa format language model. It relies on the
+// auxiliary class LmState above.
+class ConstArpaLmBuilder : public ArpaFileParser {
+ public:
+ explicit ConstArpaLmBuilder(ArpaParseOptions options)
+ : ArpaFileParser(options, NULL) {
+ ngram_order_ = 0;
+ num_words_ = 0;
+ overflow_buffer_size_ = 0;
+ lm_states_size_ = 0;
+ max_address_offset_ = pow(2, 30) - 1;
+ is_built_ = false;
+ lm_states_ = NULL;
+ unigram_states_ = NULL;
+ overflow_buffer_ = NULL;
+ }
+
+ ~ConstArpaLmBuilder() {
+ unordered_map<std::vector<int32>,
+ LmState*, VectorHasher<int32> >::iterator iter;
+ for (iter = seq_to_state_.begin(); iter != seq_to_state_.end(); ++iter) {
+ delete iter->second;
+ }
+ if (is_built_) {
+ delete[] lm_states_;
+ delete[] unigram_states_;
+ delete[] overflow_buffer_;
+ }
+ }
+
+ // Writes ConstArpaLm.
+ void Write(std::ostream &os, bool binary) const;
+
+ void SetMaxAddressOffset(const int32 max_address_offset) {
+ KALDI_WARN << "You are changing <max_address_offset_>; the default should "
+ << "not be changed unless you are in testing mode.";
+ max_address_offset_ = max_address_offset;
+ }
+
+ protected:
+ // ArpaFileParser overrides.
+ virtual void HeaderAvailable();
+ virtual void ConsumeNGram(const NGram& ngram);
+ virtual void ReadComplete();
+
+ private:
+ struct WordsAndLmStatePairLessThan {
+ bool operator()(
+ const std::pair<std::vector<int32>*, LmState*>& lhs,
+ const std::pair<std::vector<int32>*, LmState*>& rhs) const {
+ return *(lhs.first) < *(rhs.first);
+ }
+ };
+
+ private:
+ // Indicating if ConstArpaLm has been built or not.
+ bool is_built_;
+
+ // Maximum relative address for the child. We put it here just for testing.
+ // The default value is 30-bits and should not be changed except for testing.
+ int32 max_address_offset_;
+
+ // N-gram order of language model. This can be figured out from "/data/"
+ // section in Arpa format language model.
+ int32 ngram_order_;
+
+ // Index of largest word-id plus one. It defines the end of <unigram_states_>
+ // array.
+ int32 num_words_;
+
+ // Number of entries in the overflow buffer for pointers that couldn't be
+ // represented as a 30-bit relative index.
+ int32 overflow_buffer_size_;
+
+ // Size of the <lm_states_> array, which will be needed by I/O.
+ int64 lm_states_size_;
+
+ // Memory blcok for storing LmStates.
+ int32* lm_states_;
+
+ // Memory block for storing pointers of unigram LmStates.
+ int32** unigram_states_;
+
+ // Memory block for storing pointers of the LmStates that have large relative
+ // address to their parents.
+ int32** overflow_buffer_;
+
+ // Hash table from word sequences to LmStates.
+ unordered_map<std::vector<int32>,
+ LmState*, VectorHasher<int32> > seq_to_state_;
+};
+
+void ConstArpaLmBuilder::HeaderAvailable() {
+ ngram_order_ = NgramCounts().size();
+}
+
+void ConstArpaLmBuilder::ConsumeNGram(const NGram &ngram) {
+ int32 cur_order = ngram.words.size();
+ // If <ngram_order_> is larger than 1, then we do not create LmState for
+ // the final order entry. We only keep the log probability for it.
+ LmState *lm_state = NULL;
+ if (cur_order != ngram_order_ || ngram_order_ == 1) {
+ lm_state = new LmState(cur_order == 1,
+ cur_order == ngram_order_ - 1,
+ ngram.logprob, ngram.backoff);
+
+ if (seq_to_state_.find(ngram.words) != seq_to_state_.end()) {
+ std::ostringstream os;
+ os << "[ ";
+ for (size_t i = 0; i < ngram.words.size(); i++) {
+ os << ngram.words[i] << " ";
+ }
+ os <<"]";
+
+ KALDI_ERR << "N-gram " << os.str() << " appears twice in the arpa file";
+ }
+ seq_to_state_[ngram.words] = lm_state;
+ }
+
+ // If n-gram order is larger than 1, we have to add possible child to
+ // existing LmStates. We have the following two assumptions:
+ // 1. N-grams are processed from small order to larger ones, i.e., from
+ // 1, 2, ... to the highest order.
+ // 2. If a n-gram exists in the Arpa format language model, then the
+ // "history" n-gram also exists. For example, if "A B C" is a valid
+ // n-gram, then "A B" is also a valid n-gram.
+ int32 last_word = ngram.words[cur_order - 1];
+ if (cur_order > 1) {
+ std::vector<int32> hist(ngram.words.begin(), ngram.words.end() - 1);
+ unordered_map<std::vector<int32>,
+ LmState*, VectorHasher<int32> >::iterator hist_iter;
+ hist_iter = seq_to_state_.find(hist);
+ if (hist_iter == seq_to_state_.end()) {
+ std::ostringstream ss;
+ for (int i = 0; i < cur_order; ++i)
+ ss << (i == 0 ? '[' : ' ') << ngram.words[i];
+ KALDI_ERR << "In line " << LineNumber() << ": "
+ << cur_order << "-gram " << ss.str() << "] does not have "
+ << "a parent model " << cur_order << "-gram.";
+ }
+ if (cur_order != ngram_order_ || ngram_order_ == 1) {
+ KALDI_ASSERT(lm_state != NULL);
+ KALDI_ASSERT(!hist_iter->second->IsChildFinalOrder());
+ hist_iter->second->AddChild(last_word, lm_state);
+ } else {
+ KALDI_ASSERT(lm_state == NULL);
+ KALDI_ASSERT(hist_iter->second->IsChildFinalOrder());
+ hist_iter->second->AddChild(last_word, ngram.logprob);
+ }
+ } else {
+ // Figures out <max_word_id>.
+ num_words_ = std::max(num_words_, last_word + 1);
+ }
+}
+
+// ConstArpaLm can be built in the following steps, assuming we have already
+// created LmStates <seq_to_state_>:
+// 1. Sort LmStates lexicographically.
+// This enables us to compute relative address. When we say lexicographic, we
+// treat the word-ids as letters. After sorting, the LmStates are in the
+// following order:
+// ...
+// A B
+// A B A
+// A B B
+// A B C
+// ...
+// where each line represents a LmState.
+// 2. Update <my_address> in LmState, which is relative to the first element in
+// <sorted_vec>.
+// 3. Put the following structure into the memory block
+// struct LmState {
+// float logprob;
+// float backoff_logprob;
+// int32 num_children;
+// std::pair<int32, int32> [] children;
+// }
+//
+// At the same time, we will also create two special buffers:
+// <unigram_states_>
+// <overflow_buffer_>
+void ConstArpaLmBuilder::ReadComplete() {
+ // STEP 1: sorting LmStates lexicographically.
+ // Vector for holding the sorted LmStates.
+ std::vector<std::pair<std::vector<int32>*, LmState*> > sorted_vec;
+ unordered_map<std::vector<int32>,
+ LmState*, VectorHasher<int32> >::iterator iter;
+ for (iter = seq_to_state_.begin(); iter != seq_to_state_.end(); ++iter) {
+ if (iter->second->MemSize() > 0) {
+ sorted_vec.push_back(
+ std::make_pair(const_cast<std::vector<int32>*>(&(iter->first)),
+ iter->second));
+ }
+ }
+
+ std::sort(sorted_vec.begin(), sorted_vec.end(),
+ WordsAndLmStatePairLessThan());
+
+ // STEP 2: updating <my_address> in LmState.
+ for (int32 i = 0; i < sorted_vec.size(); ++i) {
+ lm_states_size_ += sorted_vec[i].second->MemSize();
+ if (i == 0) {
+ sorted_vec[i].second->SetMyAddress(0);
+ } else {
+ sorted_vec[i].second->SetMyAddress(sorted_vec[i - 1].second->MyAddress()
+ + sorted_vec[i - 1].second->MemSize());
+ }
+ }
+
+ // STEP 3: creating memory block to store LmStates.
+ // Reserves a memory block for LmStates.
+ int64 lm_states_index = 0;
+ try {
+ lm_states_ = new int32[lm_states_size_];
+ } catch(const std::exception &e) {
+ KALDI_ERR << e.what();
+ }
+
+ // Puts data into memory block.
+ unigram_states_ = new int32*[num_words_];
+ std::vector<int32*> overflow_buffer_vec;
+ for (int32 i = 0; i < num_words_; ++i) {
+ unigram_states_[i] = NULL;
+ }
+ for (int32 i = 0; i < sorted_vec.size(); ++i) {
+ // Current address.
+ int32* parent_address = lm_states_ + lm_states_index;
+
+ // Adds logprob.
+ Int32AndFloat logprob_f(sorted_vec[i].second->Logprob());
+ lm_states_[lm_states_index++] = logprob_f.i;
+
+ // Adds backoff_logprob.
+ Int32AndFloat backoff_logprob_f(sorted_vec[i].second->BackoffLogprob());
+ lm_states_[lm_states_index++] = backoff_logprob_f.i;
+
+ // Adds num_children.
+ lm_states_[lm_states_index++] = sorted_vec[i].second->NumChildren();
+
+ // Adds children, there are 3 cases:
+ // 1. Child is a leaf and not unigram
+ // 2. Child is not a leaf or is unigram
+ // 2.1 Relative address can be represented by 30 bits
+ // 2.2 Relative address cannot be represented by 30 bits
+ sorted_vec[i].second->SortChildren();
+ for (int32 j = 0; j < sorted_vec[i].second->NumChildren(); ++j) {
+ int32 child_info;
+ if (sorted_vec[i].second->IsChildFinalOrder() ||
+ sorted_vec[i].second->GetChild(j).second.state->MemSize() == 0) {
+ // Child is a leaf and not unigram. In this case we will not create an
+ // entry in <lm_states_>; instead, we put the logprob in the place where
+ // we normally store the poitner.
+ Int32AndFloat child_logprob_f;
+ if (sorted_vec[i].second->IsChildFinalOrder()) {
+ child_logprob_f.f = sorted_vec[i].second->GetChild(j).second.prob;
+ } else {
+ child_logprob_f.f =
+ sorted_vec[i].second->GetChild(j).second.state->Logprob();
+ }
+ child_info = child_logprob_f.i;
+ child_info &= ~1; // Sets the last bit to 0 so <child_info> is even.
+ } else {
+ // Child is not a leaf or is unigram.
+ int64 offset =
+ sorted_vec[i].second->GetChild(j).second.state->MyAddress()
+ - sorted_vec[i].second->MyAddress();
+ KALDI_ASSERT(offset > 0);
+ if (offset <= max_address_offset_) {
+ // Relative address can be represented by 30 bits.
+ child_info = offset * 2;
+ child_info |= 1;
+ } else {
+ // Relative address cannot be represented by 30 bits, we have to put
+ // the child address into <overflow_buffer_>.
+ int32* abs_address = parent_address + offset;
+ overflow_buffer_vec.push_back(abs_address);
+ int32 overflow_buffer_index = overflow_buffer_vec.size() - 1;
+ child_info = overflow_buffer_index * 2;
+ child_info |= 1;
+ child_info *= -1;
+ }
+ }
+ // Child word.
+ lm_states_[lm_states_index++] = sorted_vec[i].second->GetChild(j).first;
+ // Child info.
+ lm_states_[lm_states_index++] = child_info;
+ }
+
+ // If the current state corresponds to an unigram, then create a separate
+ // loop up table to improve efficiency, since those will be looked up pretty
+ // frequently.
+ if (sorted_vec[i].second->IsUnigram()) {
+ KALDI_ASSERT(sorted_vec[i].first->size() == 1);
+ unigram_states_[(*sorted_vec[i].first)[0]] = parent_address;
+ }
+ }
+ KALDI_ASSERT(lm_states_size_ == lm_states_index);
+
+ // Move <overflow_buffer_> from vector holder to array.
+ overflow_buffer_size_ = overflow_buffer_vec.size();
+ overflow_buffer_ = new int32*[overflow_buffer_size_];
+ for (int32 i = 0; i < overflow_buffer_size_; ++i) {
+ overflow_buffer_[i] = overflow_buffer_vec[i];
+ }
+
+ is_built_ = true;
+}
+
+void ConstArpaLmBuilder::Write(std::ostream &os, bool binary) const {
+ if (!binary) {
+ KALDI_ERR << "text-mode writing is not implemented for ConstArpaLmBuilder.";
+ }
+ KALDI_ASSERT(is_built_);
+
+ // Creates ConstArpaLm.
+ ConstArpaLm const_arpa_lm(
+ Options().bos_symbol, Options().eos_symbol, Options().unk_symbol,
+ ngram_order_, num_words_, overflow_buffer_size_, lm_states_size_,
+ unigram_states_, overflow_buffer_, lm_states_);
+ const_arpa_lm.Write(os, binary);
+}
+
+void ConstArpaLm::Write(std::ostream &os, bool binary) const {
+ KALDI_ASSERT(initialized_);
+ if (!binary) {
+ KALDI_ERR << "text-mode writing is not implemented for ConstArpaLm.";
+ }
+
+ WriteToken(os, binary, "<ConstArpaLm>");
+
+ // Misc info.
+ WriteToken(os, binary, "<LmInfo>");
+ WriteBasicType(os, binary, bos_symbol_);
+ WriteBasicType(os, binary, eos_symbol_);
+ WriteBasicType(os, binary, unk_symbol_);
+ WriteBasicType(os, binary, ngram_order_);
+ WriteToken(os, binary, "</LmInfo>");
+
+ // LmStates section.
+ WriteToken(os, binary, "<LmStates>");
+ WriteBasicType(os, binary, lm_states_size_);
+ os.write(reinterpret_cast<char *>(lm_states_),
+ sizeof(int32) * lm_states_size_);
+ if (!os.good()) {
+ KALDI_ERR << "ConstArpaLm <LmStates> section writing failed.";
+ }
+ WriteToken(os, binary, "</LmStates>");
+
+ // Unigram section. We write memory offset to disk instead of the absolute
+ // pointers.
+ WriteToken(os, binary, "<LmUnigram>");
+ WriteBasicType(os, binary, num_words_);
+ int64* tmp_unigram_address = new int64[num_words_];
+ for (int32 i = 0; i < num_words_; ++i) {
+ // The relative address here is a little bit tricky:
+ // 1. If the original address is NULL, then we set the relative address to
+ // zero.
+ // 2. If the original address is not NULL, we set it to the following:
+ // unigram_states_[i] - lm_states_ + 1
+ // we plus 1 to ensure that the above value is positive.
+ tmp_unigram_address[i] = (unigram_states_[i] == NULL) ? 0 :
+ unigram_states_[i] - lm_states_ + 1;
+ }
+ os.write(reinterpret_cast<char *>(tmp_unigram_address),
+ sizeof(int64) * num_words_);
+ if (!os.good()) {
+ KALDI_ERR << "ConstArpaLm <LmUnigram> section writing failed.";
+ }
+ delete[] tmp_unigram_address; // Releases the memory.
+ tmp_unigram_address = NULL;
+ WriteToken(os, binary, "</LmUnigram>");
+
+ // Overflow section. We write memory offset to disk instead of the absolute
+ // pointers.
+ WriteToken(os, binary, "<LmOverflow>");
+ WriteBasicType(os, binary, overflow_buffer_size_);
+ int64* tmp_overflow_address = new int64[overflow_buffer_size_];
+ for (int32 i = 0; i < overflow_buffer_size_; ++i) {
+ // The relative address here is a little bit tricky:
+ // 1. If the original address is NULL, then we set the relative address to
+ // zero.
+ // 2. If the original address is not NULL, we set it to the following:
+ // overflow_buffer_[i] - lm_states_ + 1
+ // we plus 1 to ensure that the above value is positive.
+ tmp_overflow_address[i] = (overflow_buffer_[i] == NULL) ? 0 :
+ overflow_buffer_[i] - lm_states_ + 1;
+ }
+ os.write(reinterpret_cast<char *>(tmp_overflow_address),
+ sizeof(int64) * overflow_buffer_size_);
+ if (!os.good()) {
+ KALDI_ERR << "ConstArpaLm <LmOverflow> section writing failed.";
+ }
+ delete[] tmp_overflow_address;
+ tmp_overflow_address = NULL;
+ WriteToken(os, binary, "</LmOverflow>");
+ WriteToken(os, binary, "</ConstArpaLm>");
+}
+
+void ConstArpaLm::Read(std::istream &is, bool binary) {
+ KALDI_ASSERT(!initialized_);
+ if (!binary) {
+ KALDI_ERR << "text-mode reading is not implemented for ConstArpaLm.";
+ }
+
+ int first_char = is.peek();
+ if (first_char == 4) { // Old on-disk format starts with length of int32.
+ ReadInternalOldFormat(is, binary);
+ } else { // New on-disk format starts with token <ConstArpaLm>.
+ ReadInternal(is, binary);
+ }
+}
+
+void ConstArpaLm::ReadInternal(std::istream &is, bool binary) {
+ KALDI_ASSERT(!initialized_);
+ if (!binary) {
+ KALDI_ERR << "text-mode reading is not implemented for ConstArpaLm.";
+ }
+
+ ExpectToken(is, binary, "<ConstArpaLm>");
+
+ // Misc info.
+ ExpectToken(is, binary, "<LmInfo>");
+ ReadBasicType(is, binary, &bos_symbol_);
+ ReadBasicType(is, binary, &eos_symbol_);
+ ReadBasicType(is, binary, &unk_symbol_);
+ ReadBasicType(is, binary, &ngram_order_);
+ ExpectToken(is, binary, "</LmInfo>");
+
+ // LmStates section.
+ ExpectToken(is, binary, "<LmStates>");
+ ReadBasicType(is, binary, &lm_states_size_);
+ lm_states_ = new int32[lm_states_size_];
+ is.read(reinterpret_cast<char *>(lm_states_),
+ sizeof(int32) * lm_states_size_);
+ if (!is.good()) {
+ KALDI_ERR << "ConstArpaLm <LmStates> section reading failed.";
+ }
+ ExpectToken(is, binary, "</LmStates>");
+
+ // Unigram section. We write memory offset to disk instead of the absolute
+ // pointers.
+ ExpectToken(is, binary, "<LmUnigram>");
+ ReadBasicType(is, binary, &num_words_);
+ unigram_states_ = new int32*[num_words_];
+ int64* tmp_unigram_address = new int64[num_words_];
+ is.read(reinterpret_cast<char *>(tmp_unigram_address),
+ sizeof(int64) * num_words_);
+ if (!is.good()) {
+ KALDI_ERR << "ConstArpaLm <LmUnigram> section reading failed.";
+ }
+ for (int32 i = 0; i < num_words_; ++i) {
+ // Check out how we compute the relative address in ConstArpaLm::Write().
+ unigram_states_[i] = (tmp_unigram_address[i] == 0) ? NULL
+ : lm_states_ + tmp_unigram_address[i] - 1;
+ }
+ delete[] tmp_unigram_address;
+ tmp_unigram_address = NULL;
+ ExpectToken(is, binary, "</LmUnigram>");
+
+ // Overflow section. We write memory offset to disk instead of the absolute
+ // pointers.
+ ExpectToken(is, binary, "<LmOverflow>");
+ ReadBasicType(is, binary, &overflow_buffer_size_);
+ overflow_buffer_ = new int32*[overflow_buffer_size_];
+ int64* tmp_overflow_address = new int64[overflow_buffer_size_];
+ is.read(reinterpret_cast<char *>(tmp_overflow_address),
+ sizeof(int64) * overflow_buffer_size_);
+ if (!is.good()) {
+ KALDI_ERR << "ConstArpaLm <LmOverflow> section reading failed.";
+ }
+ for (int32 i = 0; i < overflow_buffer_size_; ++i) {
+ // Check out how we compute the relative address in ConstArpaLm::Write().
+ overflow_buffer_[i] = (tmp_overflow_address[i] == 0) ? NULL
+ : lm_states_ + tmp_overflow_address[i] - 1;
+ }
+ delete[] tmp_overflow_address;
+ tmp_overflow_address = NULL;
+ ExpectToken(is, binary, "</LmOverflow>");
+ ExpectToken(is, binary, "</ConstArpaLm>");
+
+ KALDI_ASSERT(ngram_order_ > 0);
+ KALDI_ASSERT(bos_symbol_ < num_words_ && bos_symbol_ > 0);
+ KALDI_ASSERT(eos_symbol_ < num_words_ && eos_symbol_ > 0);
+ KALDI_ASSERT(unk_symbol_ < num_words_ &&
+ (unk_symbol_ > 0 || unk_symbol_ == -1));
+ lm_states_end_ = lm_states_ + lm_states_size_ - 1;
+ memory_assigned_ = true;
+ initialized_ = true;
+}
+
+void ConstArpaLm::ReadInternalOldFormat(std::istream &is, bool binary) {
+ KALDI_ASSERT(!initialized_);
+ if (!binary) {
+ KALDI_ERR << "text-mode reading is not implemented for ConstArpaLm.";
+ }
+
+ // Misc info.
+ ReadBasicType(is, binary, &bos_symbol_);
+ ReadBasicType(is, binary, &eos_symbol_);
+ ReadBasicType(is, binary, &unk_symbol_);
+ ReadBasicType(is, binary, &ngram_order_);
+
+ // LmStates section.
+ // In the deprecated version, <lm_states_size_> used to be type of int32,
+ // which was a bug. We therefore use int32 for read for back-compatibility.
+ int32 lm_states_size_int32;
+ ReadBasicType(is, binary, &lm_states_size_int32);
+ lm_states_size_ = static_cast<int64>(lm_states_size_int32);
+ lm_states_ = new int32[lm_states_size_];
+ for (int64 i = 0; i < lm_states_size_; ++i) {
+ ReadBasicType(is, binary, &lm_states_[i]);
+ }
+
+ // Unigram section. We write memory offset to disk instead of the absolute
+ // pointers.
+ ReadBasicType(is, binary, &num_words_);
+ unigram_states_ = new int32*[num_words_];
+ for (int32 i = 0; i < num_words_; ++i) {
+ int64 tmp_address;
+ ReadBasicType(is, binary, &tmp_address);
+ // Check out how we compute the relative address in ConstArpaLm::Write().
+ unigram_states_[i] =
+ (tmp_address == 0) ? NULL : lm_states_ + tmp_address - 1;
+ }
+
+ // Overflow section. We write memory offset to disk instead of the absolute
+ // pointers.
+ ReadBasicType(is, binary, &overflow_buffer_size_);
+ overflow_buffer_ = new int32*[overflow_buffer_size_];
+ for (int32 i = 0; i < overflow_buffer_size_; ++i) {
+ int64 tmp_address;
+ ReadBasicType(is, binary, &tmp_address);
+ // Check out how we compute the relative address in ConstArpaLm::Write().
+ overflow_buffer_[i] =
+ (tmp_address == 0) ? NULL : lm_states_ + tmp_address - 1;
+ }
+ KALDI_ASSERT(ngram_order_ > 0);
+ KALDI_ASSERT(bos_symbol_ < num_words_ && bos_symbol_ > 0);
+ KALDI_ASSERT(eos_symbol_ < num_words_ && eos_symbol_ > 0);
+ KALDI_ASSERT(unk_symbol_ < num_words_ &&
+ (unk_symbol_ > 0 || unk_symbol_ == -1));
+ lm_states_end_ = lm_states_ + lm_states_size_ - 1;
+ memory_assigned_ = true;
+ initialized_ = true;
+}
+
+bool ConstArpaLm::HistoryStateExists(const std::vector<int32>& hist) const {
+ // We do not create LmState for empty word sequence, but technically it is the
+ // history state of all unigrams.
+ if (hist.size() == 0) {
+ return true;
+ }
+
+ // Tries to locate the LmState of the given word sequence.
+ int32* lm_state = GetLmState(hist);
+ if (lm_state == NULL) {
+ // <lm_state> does not exist means <hist> has no child.
+ return false;
+ } else {
+ // Note that we always create LmState for unigrams, so even if <lm_state> is
+ // not NULL, we still have to check if it has child.
+ KALDI_ASSERT(lm_state >= lm_states_);
+ KALDI_ASSERT(lm_state + 2 <= lm_states_end_);
+ // <lm_state + 2> points to <num_children>.
+ if (*(lm_state + 2) > 0) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ return true;
+}
+
+float ConstArpaLm::GetNgramLogprob(const int32 word,
+ const std::vector<int32>& hist) const {
+ KALDI_ASSERT(initialized_);
+
+ // If the history size plus one is larger than <ngram_order_>, remove the old
+ // words.
+ std::vector<int32> mapped_hist(hist);
+ while (mapped_hist.size() >= ngram_order_) {
+ mapped_hist.erase(mapped_hist.begin(), mapped_hist.begin() + 1);
+ }
+ KALDI_ASSERT(mapped_hist.size() + 1 <= ngram_order_);
+
+ // TODO(guoguo): check with Dan if this is reasonable.
+ // Maps possible out-of-vocabulary words to <unk>. If a word does not have a
+ // corresponding LmState, we treat it as <unk>. We map it to <unk> if <unk> is
+ // specified.
+ int32 mapped_word = word;
+ if (unk_symbol_ != -1) {
+ KALDI_ASSERT(mapped_word >= 0);
+ if (mapped_word >= num_words_ || unigram_states_[mapped_word] == NULL) {
+ mapped_word = unk_symbol_;
+ }
+ for (int32 i = 0; i < mapped_hist.size(); ++i) {
+ KALDI_ASSERT(mapped_hist[i] >= 0);
+ if (mapped_hist[i] >= num_words_ ||
+ unigram_states_[mapped_hist[i]] == NULL) {
+ mapped_hist[i] = unk_symbol_;
+ }
+ }
+ }
+
+ // Loops up n-gram probability.
+ return GetNgramLogprobRecurse(mapped_word, mapped_hist);
+}
+
+float ConstArpaLm::GetNgramLogprobRecurse(
+ const int32 word, const std::vector<int32>& hist) const {
+ KALDI_ASSERT(initialized_);
+ KALDI_ASSERT(hist.size() + 1 <= ngram_order_);
+
+ // Unigram case.
+ if (hist.size() == 0) {
+ if (word >= num_words_ || unigram_states_[word] == NULL) {
+ // If <unk> is defined, then the word sequence should have already been
+ // mapped to <unk> is necessary; this is for the case where <unk> is not
+ // defined.
+ return -std::numeric_limits<float>::infinity();
+ } else {
+ Int32AndFloat logprob_i(*unigram_states_[word]);
+ return logprob_i.f;
+ }
+ }
+
+ // High n-gram orders.
+ float logprob = 0.0;
+ float backoff_logprob = 0.0;
+ int32* state;
+ if ((state = GetLmState(hist)) != NULL) {
+ int32 child_info;
+ int32* child_lm_state = NULL;
+ if (GetChildInfo(word, state, &child_info)) {
+ DecodeChildInfo(child_info, state, &child_lm_state, &logprob);
+ return logprob;
+ } else {
+ Int32AndFloat backoff_logprob_i(*(state + 1));
+ backoff_logprob = backoff_logprob_i.f;
+ }
+ }
+ std::vector<int32> new_hist(hist);
+ new_hist.erase(new_hist.begin(), new_hist.begin() + 1);
+ return backoff_logprob + GetNgramLogprobRecurse(word, new_hist);
+}
+
+int32* ConstArpaLm::GetLmState(const std::vector<int32>& seq) const {
+ KALDI_ASSERT(initialized_);
+
+ // No LmState exists for empty word sequence.
+ if (seq.size() == 0) return NULL;
+
+ // If <unk> is defined, then the word sequence should have already been mapped
+ // to <unk> is necessary; this is for the case where <unk> is not defined.
+ if (seq[0] >= num_words_ || unigram_states_[seq[0]] == NULL) return NULL;
+ int32* parent = unigram_states_[seq[0]];
+
+ int32 child_info;
+ int32* child_lm_state = NULL;
+ float logprob;
+ for (int32 i = 1; i < seq.size(); ++i) {
+ if (!GetChildInfo(seq[i], parent, &child_info)) {
+ return NULL;
+ }
+ DecodeChildInfo(child_info, parent, &child_lm_state, &logprob);
+ if (child_lm_state == NULL) {
+ return NULL;
+ } else {
+ parent = child_lm_state;
+ }
+ }
+ return parent;
+}
+
+bool ConstArpaLm::GetChildInfo(const int32 word,
+ int32* parent, int32* child_info) const {
+ KALDI_ASSERT(initialized_);
+
+ KALDI_ASSERT(parent != NULL);
+ KALDI_ASSERT(parent >= lm_states_);
+ KALDI_ASSERT(child_info != NULL);
+
+ KALDI_ASSERT(parent + 2 <= lm_states_end_);
+ int32 num_children = *(parent + 2);
+ KALDI_ASSERT(parent + 2 + 2 * num_children <= lm_states_end_);
+
+ if (num_children == 0) return false;
+
+ // A binary search into the children memory block.
+ int32 start_index = 1;
+ int32 end_index = num_children;
+ while (start_index <= end_index) {
+ int32 mid_index = round((start_index + end_index) / 2);
+ int32 mid_word = *(parent + 1 + 2 * mid_index);
+ if (mid_word == word) {
+ *child_info = *(parent + 2 + 2 * mid_index);
+ return true;
+ } else if (mid_word < word) {
+ start_index = mid_index + 1;
+ } else {
+ end_index = mid_index - 1;
+ }
+ }
+
+ return false;
+}
+
+void ConstArpaLm::DecodeChildInfo(const int32 child_info,
+ int32* parent,
+ int32** child_lm_state,
+ float* logprob) const {
+ KALDI_ASSERT(initialized_);
+
+ KALDI_ASSERT(logprob != NULL);
+ if (child_info % 2 == 0) {
+ // Child is a leaf, only returns the log probability.
+ *child_lm_state = NULL;
+ Int32AndFloat logprob_i(child_info);
+ *logprob = logprob_i.f;
+ } else {
+ int32 child_offset = child_info / 2;
+ if (child_offset > 0) {
+ *child_lm_state = parent + child_offset;
+ Int32AndFloat logprob_i(**child_lm_state);
+ *logprob = logprob_i.f;
+ } else {
+ KALDI_ASSERT(-child_offset < overflow_buffer_size_);
+ *child_lm_state = overflow_buffer_[-child_offset];
+ Int32AndFloat logprob_i(**child_lm_state);
+ *logprob = logprob_i.f;
+ }
+ KALDI_ASSERT(*child_lm_state >= lm_states_);
+ KALDI_ASSERT(*child_lm_state <= lm_states_end_);
+ }
+}
+
+void ConstArpaLm::WriteArpaRecurse(int32* lm_state,
+ const std::vector<int32>& seq,
+ std::vector<ArpaLine> *output) const {
+ if (lm_state == NULL) return;
+
+ KALDI_ASSERT(lm_state >= lm_states_);
+ KALDI_ASSERT(lm_state + 2 <= lm_states_end_);
+
+ // Inserts the current LmState to <output>.
+ ArpaLine arpa_line;
+ arpa_line.words = seq;
+ Int32AndFloat logprob_i(*lm_state);
+ arpa_line.logprob = logprob_i.f;
+ Int32AndFloat backoff_logprob_i(*(lm_state + 1));
+ arpa_line.backoff_logprob = backoff_logprob_i.f;
+ output->push_back(arpa_line);
+
+ // Scans for possible children, and recursively adds child to <output>.
+ int32 num_children = *(lm_state + 2);
+ KALDI_ASSERT(lm_state + 2 + 2 * num_children <= lm_states_end_);
+ for (int32 i = 0; i < num_children; ++i) {
+ std::vector<int32> new_seq(seq);
+ new_seq.push_back(*(lm_state + 3 + 2 * i));
+ int32 child_info = *(lm_state + 4 + 2 * i);
+ float logprob;
+ int32* child_lm_state = NULL;
+ DecodeChildInfo(child_info, lm_state, &child_lm_state, &logprob);
+
+ if (child_lm_state == NULL) {
+ // Leaf case.
+ ArpaLine child_arpa_line;
+ child_arpa_line.words = new_seq;
+ child_arpa_line.logprob = logprob;
+ child_arpa_line.backoff_logprob = 0.0;
+ output->push_back(child_arpa_line);
+ } else {
+ WriteArpaRecurse(child_lm_state, new_seq, output);
+ }
+ }
+}
+
+void ConstArpaLm::WriteArpa(std::ostream &os) const {
+ KALDI_ASSERT(initialized_);
+
+ std::vector<ArpaLine> tmp_output;
+ for (int32 i = 0; i < num_words_; ++i) {
+ if (unigram_states_[i] != NULL) {
+ std::vector<int32> seq(1, i);
+ WriteArpaRecurse(unigram_states_[i], seq, &tmp_output);
+ }
+ }
+
+ // Sorts ArpaLines and collects head information.
+ std::sort(tmp_output.begin(), tmp_output.end());
+ std::vector<int32> ngram_count(1, 0);
+ for (int32 i = 0; i < tmp_output.size(); ++i) {
+ if (tmp_output[i].words.size() >= ngram_count.size()) {
+ ngram_count.resize(tmp_output[i].words.size() + 1);
+ ngram_count[tmp_output[i].words.size()] = 1;
+ } else {
+ ngram_count[tmp_output[i].words.size()] += 1;
+ }
+ }
+
+ // Writes the header.
+ os << std::endl;
+ os << "\\data\\" << std::endl;
+ for (int32 i = 1; i < ngram_count.size(); ++i) {
+ os << "ngram " << i << "=" << ngram_count[i] << std::endl;
+ }
+
+ // Writes n-grams.
+ int32 current_order = 0;
+ for (int32 i = 0; i < tmp_output.size(); ++i) {
+ // Beginning of a n-gram section.
+ if (tmp_output[i].words.size() != current_order) {
+ current_order = tmp_output[i].words.size();
+ os << std::endl;
+ os << "\\" << current_order << "-grams:" << std::endl;
+ }
+
+ // Writes logprob.
+ os << tmp_output[i].logprob << '\t';
+
+ // Writes word sequence.
+ for (int32 j = 0; j < tmp_output[i].words.size(); ++j) {
+ os << tmp_output[i].words[j];
+ if (j != tmp_output[i].words.size() - 1) {
+ os << " ";
+ }
+ }
+
+ // Writes backoff_logprob if it is not zero.
+ if (tmp_output[i].backoff_logprob != 0.0) {
+ os << '\t' << tmp_output[i].backoff_logprob;
+ }
+ os << std::endl;
+ }
+
+ os << std::endl << "\\end\\" << std::endl;
+}
+
+ConstArpaLmDeterministicFst::ConstArpaLmDeterministicFst(
+ const ConstArpaLm& lm) : lm_(lm) {
+ // Creates a history state for <s>.
+ std::vector<Label> bos_state(1, lm_.BosSymbol());
+ state_to_wseq_.push_back(bos_state);
+ wseq_to_state_[bos_state] = 0;
+ start_state_ = 0;
+}
+
+fst::StdArc::Weight ConstArpaLmDeterministicFst::Final(StateId s) {
+ // At this point, we should have created the state.
+ KALDI_ASSERT(static_cast<size_t>(s) < state_to_wseq_.size());
+ const std::vector<Label>& wseq = state_to_wseq_[s];
+ float logprob = lm_.GetNgramLogprob(lm_.EosSymbol(), wseq);
+ return Weight(-logprob);
+}
+
+bool ConstArpaLmDeterministicFst::GetArc(StateId s,
+ Label ilabel, fst::StdArc *oarc) {
+ // At this point, we should have created the state.
+ KALDI_ASSERT(static_cast<size_t>(s) < state_to_wseq_.size());
+ std::vector<Label> wseq = state_to_wseq_[s];
+
+ float logprob = lm_.GetNgramLogprob(ilabel, wseq);
+ if (logprob == -std::numeric_limits<float>::infinity()) {
+ return false;
+ }
+
+ // Locates the next state in ConstArpaLm. Note that OOV and backoff have been
+ // taken care of in ConstArpaLm.
+ wseq.push_back(ilabel);
+ while (wseq.size() >= lm_.NgramOrder()) {
+ // History state has at most lm_.NgramOrder() -1 words in the state.
+ wseq.erase(wseq.begin(), wseq.begin() + 1);
+ }
+ while (!lm_.HistoryStateExists(wseq)) {
+ KALDI_ASSERT(wseq.size() > 0);
+ wseq.erase(wseq.begin(), wseq.begin() + 1);
+ }
+
+ std::pair<const std::vector<Label>, StateId> wseq_state_pair(
+ wseq, static_cast<Label>(state_to_wseq_.size()));
+
+ // Attemps to insert the current <wseq_state_pair>. If the pair already exists
+ // then it returns false.
+ typedef MapType::iterator IterType;
+ std::pair<IterType, bool> result = wseq_to_state_.insert(wseq_state_pair);
+
+ // If the pair was just inserted, then also add it to <state_to_wseq_>.
+ if (result.second == true)
+ state_to_wseq_.push_back(wseq);
+
+ // Creates the arc.
+ oarc->ilabel = ilabel;
+ oarc->olabel = ilabel;
+ oarc->nextstate = result.first->second;
+ oarc->weight = Weight(-logprob);
+
+ return true;
+}
+
+bool BuildConstArpaLm(const ArpaParseOptions& options,
+ const std::string& arpa_rxfilename,
+ const std::string& const_arpa_wxfilename) {
+ ConstArpaLmBuilder lm_builder(options);
+ KALDI_LOG << "Reading " << arpa_rxfilename;
+ Input ki(arpa_rxfilename);
+ lm_builder.Read(ki.Stream());
+ WriteKaldiObject(lm_builder, const_arpa_wxfilename, true);
+ return true;
+}
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/const-arpa-lm.h b/runtime/onnxruntime/third_party/kaldi/lm/const-arpa-lm.h
new file mode 100644
index 000000000..c2d5e0069
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/const-arpa-lm.h
@@ -0,0 +1,430 @@
+// lm/const-arpa-lm.h
+
+// Copyright 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_LM_CONST_ARPA_LM_H_
+#define KALDI_LM_CONST_ARPA_LM_H_
+
+#include <string>
+#include <vector>
+
+#include "base/kaldi-common.h"
+#include "fstext/deterministic-fst.h"
+#include "lm/arpa-file-parser.h"
+#include "util/common-utils.h"
+
+namespace kaldi {
+
+/**
+ The following explains how the const arpa LM works. We will start from a toy
+ example, and gradually get to the existing framework. Related classes are:
+ LmState, ConstArpaLmBuilder and ConstArpaLm.
+
+ First, let's explain how we can compute LM scores from an Arpa file. Suppose
+ we want to get the N-gram prob for "A B C". We can code the lookup something
+ very roughly like this:
+
+ float GetNgramLogprob(hist, word) { // hist = "A B", word = "C"
+ backoff_logprob = 0.0;
+ if ((state = GetLmState(hist)) != NULL) {
+ // "A B" exists as a prefix in the LM
+ if (state->HasWord(word)) {
+ return state->Logprob(word);
+ } else {
+ // We'll need to backoff to "B C", but include the backoff penalty.
+ backoff_logprob = state->BackoffLogprob();
+ }
+ }
+ return backoff_logprob + GetNgramLogprob(hist_minus_first_word, word);
+ }
+
+ In terms of data-structures, in the most abstract form of it would be
+ something like the following (note, we assume words in the lexicon can be
+ represented as int32, and that these indexes are nonnegative):
+
+ class LmState { // e.g., LmState for "A B"
+ // This is the actual LM-prob of this sequence, e.g. if this state is
+ // "A B" then it would be the logprob of "A -> B".
+ float logprob_;
+
+ // Backoff probability for LM-state "A B" -> "X" backing off to "B" -> "X"
+ // if "A B X" is not present in the language model.
+ float backoff_logprob_;
+
+ // e.g. "C" -> LmState of "A B C".
+ std::unordered_map<int32, LmState*> children_;
+ };
+
+ The above design is very memory inefficient for two reasons:
+ 1. Suppose "A B" has no children, i.e. no C such that "A B C" is an n-gram.
+ In this case the backoff_logprob will be zero and the 'children' vector
+ will be empty. So all we need is the "float logprob_". Let's call "A B" a
+ leaf in this case.
+ 2. The map std::unordered_map uses a lot of memory.
+
+ A first iteration of making this efficient is to get rid of the map as
+ follows:
+
+ class LmState {
+ float logprob_;
+ float backoff_logprob_;
+ std::vector<std::pair<int32, int32> > children_;
+ };
+
+ Here, the 'children_' vector contains pairs (child_word, child_info), sorted
+ by 'child_word' so we can use binary search to locate the entry. We have to
+ do some fancy bit-work to avoid having to allocate an LmState if a given
+ N-gram is a leaf. We design the child_info in the children_ vector as
+ follows:
+ 1. If it's an even number, then it represents a float (i.e. we
+ reinterpret_cast to float), and the associated N-gram is a leaf. This
+ requires losing the least significant bit of information in the float.
+ 2. If it's an odd number, then it will be used to represent a pointer to the
+ LmState of the child. In order to use a 32-bit number to represent a
+ possibly 64-bit pointer, we store the LmState structures in memory in
+ a way that's sorted lexicographically by the vector of words, so that
+ following "A B" will be the LmStates for "A B A", "A B B", "A B C" and so
+ on (note, we actually deal with integers instead of letters). So if we
+ make the pointers relative to the current LmState, most of them will be
+ quite small (and all will be positive, due to the lexicographic sorting).
+ As for the pointers that are too large, if any, we can have an "overflow
+ buffer" indexed by a 30-bit index that stores, directly as pointers, the
+ child LmStates. We use the first bit to distinguish the relative pointer
+ case and the overflow pointer case, i.e.,
+ a. If (child_info / 2) is positive, then (current_lmstate_pointer +
+ child_info / 2) is the address of the child LmState.
+ b. If (child_info / 2) is negative, then -1 * (child_info / 2) is the
+ index into the overflow buffer which gives the address of the child
+ LmState.
+
+ Note that unigram LM-states are usually frequently accessed, so it makes
+ sense to assign one LmState to each single word even if it would otherwise
+ be "leaf" as defined above. We then can have an array of those unigram
+ LM-states for efficient lookup.
+
+ Also, we define the class LmState just to set up data structure for Arpa
+ LM. In the end, we have a class like the following:
+
+ class ConstArpaLm {
+ public:
+ // Some public functions.
+ private:
+ // Index of largest word-id, plus one; defines end of "unigram_states_"
+ // array.
+ int32 num_words_;
+
+ // Loopup table for pointers of unigrams. The pointer could be NULL, for
+ // example for those words that are in words.txt, but not in the language
+ // model.
+ int32 **unigram_states_;
+
+ // Number of entries in the overflow buffer for pointers that couldn't be
+ // represented as a 30-bit relative index
+ int32 overflow_buffer_size_;
+
+ // Technically a 32-bit number cannot represent a possibly 64-bit pointer.
+ // We therefore use "relative" address instead of "absolute" address,
+ // which will be a small number most of the time. This buffer is for the
+ // case where the relative address has more than 30-bits.
+ int32 **overflow_buffer_;
+
+ // Size of the array lm_states_. This is required only for I/O.
+ int64 lm_states_size_;
+
+ // Data block for LmState.
+ int32 *lm_states_;
+ };
+
+ Note, when we do I/O, we don't write out the arrays of pointers
+ "overflow_buffer_" and "unigram_states_" directly. Instead we subtract
+ "lm_states_" from each one before writing them out, so we are writing out
+ indexes. Then, when we read them back in, after we allocate "lm_states_"
+ we can convert them back to pointers. When we create these temporary arrays
+ of indexes while reading and writing, we use int64, even if the pointer type
+ of the machine is int32. This way the I/O is independent of the pointer size
+ of the machine.
+
+ Now it is time to put things together.
+
+ ConstArpaLmBuilder takes charge of reading in the Arpa LM and building the
+ ConstArpaLm.
+
+ ConstArpaLM holds the Arpa LM in memory, and provides interfaces for LM
+ operations, such as GetNgramLogprob().
+
+ LmState is an auxiliary class that computes the relative pointers for
+ ConstArpaLmBuilder and ConstArpaLm. It will only be called once during the
+ building process, so it doesn't have to be very efficient.
+
+ In summary, the general building process is as follows:
+ 1. In ConstArpaLmBuilder, read in the Arpa format LM. While reading, we keep
+ in memory something like this:
+ std::unordered_map<std::vector<int32>,
+ LmState*, VectorHasher<int32> > seq_to_state_;
+ The map helps us to convert n-gram entries into LmState (including
+ setting up the parent-children relationship, see above about LmState).
+ Note that at this stage, we don't work on the relative pointers yet.
+ 2. In ConstArpaLmBuilder, create a sorted vector from <seq_to_state_>
+ std::vector<std::pair<std::vector<int32>*, LmState*> > sorted_vec;
+ Note, only LmState with non-zero MemSize() should be put into the sorted
+ vector, and we sort it lexicographically according to the word.
+ 3. In ConstArpaLmBuilder, update the address for each LmState, relative to
+ the first LmState in the sorted vector (i.e. assume the first LmState has
+ address 0, and work out the rest LmState address using the MemSize() of
+ each LmState).
+ 4. In ConstArpaLmBuilder, create a memory block for all the LmStates (after
+ sorting and updating the address). This includes <lm_state_> that stores
+ all the LmStates in an int32 array, <unigram_states_> that keeps the
+ address of unigram LmStates, <overflow_buffer_> that keeps the address
+ of LmState whose address differs too much from the parent address. See
+ above how we handle the leaf case.
+ 5. With the information in step 4, create the class ConstArpaLm.
+*/
+
+// Forward declaration of Auxiliary struct ArpaLine.
+struct ArpaLine;
+
+union Int32AndFloat {
+ int32 i;
+ float f;
+
+ Int32AndFloat() {}
+ Int32AndFloat(int32 input_i) : i(input_i) {}
+ Int32AndFloat(float input_f) : f(input_f) {}
+};
+
+class ConstArpaLm {
+ public:
+
+ // Default constructor, will be used if you are going to load the ConstArpaLm
+ // format language model from disk.
+ ConstArpaLm() {
+ lm_states_ = NULL;
+ unigram_states_ = NULL;
+ overflow_buffer_ = NULL;
+ memory_assigned_ = false;
+ initialized_ = false;
+ ngram_order_ = 0;
+ }
+
+ // Special constructor, will be used when you initialize ConstArpaLm from
+ // scratch through this constructor.
+ ConstArpaLm(const int32 bos_symbol, const int32 eos_symbol,
+ const int32 unk_symbol, const int32 ngram_order,
+ const int32 num_words, const int32 overflow_buffer_size,
+ const int64 lm_states_size, int32** unigram_states,
+ int32** overflow_buffer, int32* lm_states) :
+ bos_symbol_(bos_symbol), eos_symbol_(eos_symbol),
+ unk_symbol_(unk_symbol), ngram_order_(ngram_order),
+ num_words_(num_words), overflow_buffer_size_(overflow_buffer_size),
+ lm_states_size_(lm_states_size), unigram_states_(unigram_states),
+ overflow_buffer_(overflow_buffer), lm_states_(lm_states) {
+ KALDI_ASSERT(unigram_states_ != NULL);
+ KALDI_ASSERT(overflow_buffer_ != NULL);
+ KALDI_ASSERT(lm_states_ != NULL);
+ KALDI_ASSERT(ngram_order_ > 0);
+ KALDI_ASSERT(bos_symbol_ < num_words_ && bos_symbol_ > 0);
+ KALDI_ASSERT(eos_symbol_ < num_words_ && eos_symbol_ > 0);
+ KALDI_ASSERT(unk_symbol_ < num_words_ &&
+ (unk_symbol_ > 0 || unk_symbol_ == -1));
+ lm_states_end_ = lm_states_ + lm_states_size_ - 1;
+ memory_assigned_ = false;
+ initialized_ = true;
+ }
+
+ ~ConstArpaLm() {
+ if (memory_assigned_) {
+ delete[] lm_states_;
+ delete[] unigram_states_;
+ delete[] overflow_buffer_;
+ }
+ }
+
+ // Reads the ConstArpaLm format language model. It calls ReadInternal() or
+ // ReadInternalOldFormat() to do the actual reading.
+ void Read(std::istream &is, bool binary);
+
+ // Writes the language model in ConstArpaLm format.
+ void Write(std::ostream &os, bool binary) const;
+
+ // Creates Arpa format language model from ConstArpaLm format, and writes it
+ // to output stream. This will be useful in testing.
+ void WriteArpa(std::ostream &os) const;
+
+ // Wrapper of GetNgramLogprobRecurse. It first maps possible out-of-vocabulary
+ // words to <unk>, if <unk> is defined, and then calls GetNgramLogprobRecurse.
+ float GetNgramLogprob(const int32 word, const std::vector<int32>& hist) const;
+
+ // Returns true if the history word sequence <hist> has successor, which means
+ // <hist> will be a state in the FST format language model.
+ bool HistoryStateExists(const std::vector<int32>& hist) const;
+
+ int32 BosSymbol() const { return bos_symbol_; }
+ int32 EosSymbol() const { return eos_symbol_; }
+ int32 UnkSymbol() const { return unk_symbol_; }
+ int32 NgramOrder() const { return ngram_order_; }
+ bool Initialized() const { return initialized_; }
+
+ private:
+ // Function that loads data from stream to the class.
+ void ReadInternal(std::istream &is, bool binary);
+
+ // Function that loads data from stream to the class. This is a deprecated one
+ // that handles the old on-disk format. We keep this for back-compatibility
+ // purpose. We have modified the Write() function so for all the new on-disk
+ // format, ReadInternal() will be called.
+ void ReadInternalOldFormat(std::istream &is, bool binary);
+
+ // Loops up n-gram probability for given word sequence. Backoff is handled by
+ // recursively calling this function.
+ float GetNgramLogprobRecurse(const int32 word,
+ const std::vector<int32>& hist) const;
+
+ // Given a word sequence, find the address of the corresponding LmState.
+ // Returns NULL if no corresponding LmState is found.
+ //
+ // If the word sequence exists in n-gram language model, but it is a leaf and
+ // is not an unigram, we still return NULL, since there is no LmState struct
+ // reserved for this sequence.
+ int32* GetLmState(const std::vector<int32>& seq) const;
+
+ // Given a pointer to the parent, find the child_info that corresponds to
+ // given word. The parent has the following structure:
+ // struct LmState {
+ // float logprob;
+ // float backoff_logprob;
+ // int32 num_children;
+ // std::pair<int32, int32> [] children;
+ // }
+ // It returns false if the child is not found.
+ bool GetChildInfo(const int32 word, int32* parent, int32* child_info) const;
+
+ // Decodes <child_info> to get log probability and child LmState. In the leaf
+ // case, only <logprob> will be returned, and <child_address> will be NULL.
+ void DecodeChildInfo(const int32 child_info, int32* parent,
+ int32** child_lm_state, float* logprob) const;
+
+ void WriteArpaRecurse(int32* lm_state,
+ const std::vector<int32>& seq,
+ std::vector<ArpaLine> *output) const;
+
+ // We assign memory in Read(). If it is called, we have to release memory in
+ // the destructor.
+ bool memory_assigned_;
+
+ // Makes sure that the language model has been loaded before using it.
+ bool initialized_;
+
+ // Integer corresponds to <s>.
+ int32 bos_symbol_;
+
+ // Integer corresponds to </s>.
+ int32 eos_symbol_;
+
+ // Integer corresponds to unknown-word. -1 if no unknown-word symbol is
+ // provided.
+ int32 unk_symbol_;
+
+ // N-gram order of the language model.
+ int32 ngram_order_;
+
+ // Index of largest word-id plus one. It defines the end of <unigram_states_>
+ // array.
+ int32 num_words_;
+
+ // Number of entries in the overflow buffer for pointers that couldn't be
+ // represented as a 30-bit relative index.
+ int32 overflow_buffer_size_;
+
+ // Size of the <lm_states_> array, which will be needed by I/O.
+ int64 lm_states_size_;
+
+ // Points to the end of <lm_states_>. We use this information to check if
+ // there is any illegal visit to the un-reserved memory.
+ int32* lm_states_end_;
+
+ // Loopup table for pointers of unigrams. The pointer could be NULL, for
+ // example for those words that are in words.txt, but not in the language
+ // model.
+ int32** unigram_states_;
+
+ // Technically a 32-bit number cannot represent a possibly 64-bit pointer. We
+ // therefore use "relative" address instead of "absolute" address, which will
+ // be a small number most of the time. This buffer is for the case where the
+ // relative address has more than 30-bits.
+ int32** overflow_buffer_;
+
+ // Memory chunk that contains the actual LmStates. One LmState has the
+ // following structure:
+ //
+ // struct LmState {
+ // float logprob;
+ // float backoff_logprob;
+ // int32 num_children;
+ // std::pair<int32, int32> [] children;
+ // }
+ //
+ // Note that the floating point representation has 4 bytes, int32 also has 4
+ // bytes, therefore one LmState will occupy the following number of bytes:
+ //
+ // x = 1 + 1 + 1 + 2 * children.size() = 3 + 2 * children.size()
+ int32* lm_states_;
+};
+
+/**
+ This class wraps a ConstArpaLm format language model with the interface defined
+ in DeterministicOnDemandFst.
+ */
+class ConstArpaLmDeterministicFst
+ : public fst::DeterministicOnDemandFst<fst::StdArc> {
+ public:
+ typedef fst::StdArc::Weight Weight;
+ typedef fst::StdArc::StateId StateId;
+ typedef fst::StdArc::Label Label;
+
+ explicit ConstArpaLmDeterministicFst(const ConstArpaLm& lm);
+
+ // We cannot use "const" because the pure virtual function in the interface is
+ // not const.
+ virtual StateId Start() { return start_state_; }
+
+ // We cannot use "const" because the pure virtual function in the interface is
+ // not const.
+ virtual Weight Final(StateId s);
+
+ virtual bool GetArc(StateId s, Label ilabel, fst::StdArc* oarc);
+
+ private:
+ typedef unordered_map<std::vector<Label>,
+ StateId, VectorHasher<Label> > MapType;
+ StateId start_state_;
+ MapType wseq_to_state_;
+ std::vector<std::vector<Label> > state_to_wseq_;
+ const ConstArpaLm& lm_;
+};
+
+// Reads in an Arpa format language model and converts it into ConstArpaLm
+// format. We assume that the words in the input Arpa format language model have
+// been converted into integers.
+bool BuildConstArpaLm(const ArpaParseOptions& options,
+ const std::string& arpa_rxfilename,
+ const std::string& const_arpa_wxfilename);
+
+} // namespace kaldi
+
+#endif // KALDI_LM_CONST_ARPA_LM_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/examples/CREATURE.txt b/runtime/onnxruntime/third_party/kaldi/lm/examples/CREATURE.txt
new file mode 100644
index 000000000..fb8ce7dc1
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/examples/CREATURE.txt
@@ -0,0 +1,17 @@
+boy
+boy
+boy
+boy
+boy
+boy
+boy
+girl
+girl
+pretty girl
+cat
+dog
+dog
+dog
+rat
+red faced clown
+green caterpillar
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/examples/DAYOFMONTH.txt b/runtime/onnxruntime/third_party/kaldi/lm/examples/DAYOFMONTH.txt
new file mode 100644
index 000000000..78c7cf6a0
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/examples/DAYOFMONTH.txt
@@ -0,0 +1,5 @@
+first
+second
+third
+fourth
+fifth
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/examples/MONTH.txt b/runtime/onnxruntime/third_party/kaldi/lm/examples/MONTH.txt
new file mode 100644
index 000000000..0ba97bbe7
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/examples/MONTH.txt
@@ -0,0 +1,5 @@
+January
+February
+March
+April
+May
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/examples/YEAR.txt b/runtime/onnxruntime/third_party/kaldi/lm/examples/YEAR.txt
new file mode 100644
index 000000000..ea424468e
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/examples/YEAR.txt
@@ -0,0 +1,4 @@
+two thousand and ten
+two zero one zero
+two thousand and nine
+two zero zero nine
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/examples/YEARDATE.txt b/runtime/onnxruntime/third_party/kaldi/lm/examples/YEARDATE.txt
new file mode 100644
index 000000000..c63d397c9
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/examples/YEARDATE.txt
@@ -0,0 +1 @@
+%#MONTH#% %#DAYOFMONTH#% %#YEAR#%
diff --git a/funasr/runtime/python/__init__.py b/runtime/onnxruntime/third_party/kaldi/lm/examples/input3.fst
similarity index 100%
rename from funasr/runtime/python/__init__.py
rename to runtime/onnxruntime/third_party/kaldi/lm/examples/input3.fst
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/examples/input3.txt b/runtime/onnxruntime/third_party/kaldi/lm/examples/input3.txt
new file mode 100644
index 000000000..287142040
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/examples/input3.txt
@@ -0,0 +1 @@
+<s> the %#CREATURE#% crossed the street </s>
diff --git a/funasr/runtime/python/libtorch/__init__.py b/runtime/onnxruntime/third_party/kaldi/lm/examples/input4.fst
similarity index 100%
rename from funasr/runtime/python/libtorch/__init__.py
rename to runtime/onnxruntime/third_party/kaldi/lm/examples/input4.fst
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/examples/input4.txt b/runtime/onnxruntime/third_party/kaldi/lm/examples/input4.txt
new file mode 100644
index 000000000..607ba5dec
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/examples/input4.txt
@@ -0,0 +1 @@
+<s> He came here on %#YEARDATE#% </s>
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/irstlm.mk b/runtime/onnxruntime/third_party/kaldi/lm/irstlm.mk
new file mode 100644
index 000000000..6755fc731
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/irstlm.mk
@@ -0,0 +1,7 @@
+# Additionnal definitions needed to make with IRSTLM toolkit
+
+# Assumes IRSTLM includes and libraries have been installed under
+# $(SRCDIR)/../lmtoolkit/include/irstlm and $(SRCDIR)/../lmtoolkit/lib/irstlm
+
+EXTRA_CXXFLAGS = -DHAVE_IRSTLM -I$(SRCDIR)/../lmtoolkit/include -Wno-sign-compare
+EXTRA_LDLIBS = $(SRCDIR)/../lmtoolkit/lib/irstlm/x86_64-apple-darwin10.0/libirstlm.a -lz
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/kaldi-rnnlm.cc b/runtime/onnxruntime/third_party/kaldi/lm/kaldi-rnnlm.cc
new file mode 100644
index 000000000..63e76e459
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/kaldi-rnnlm.cc
@@ -0,0 +1,140 @@
+// lm/kaldi-rnnlm.cc
+
+// Copyright 2015 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include <utility>
+
+#include "lm/kaldi-rnnlm.h"
+#include "util/stl-utils.h"
+#include "util/text-utils.h"
+
+namespace kaldi {
+
+KaldiRnnlmWrapper::KaldiRnnlmWrapper(
+ const KaldiRnnlmWrapperOpts &opts,
+ const std::string &unk_prob_rspecifier,
+ const std::string &word_symbol_table_rxfilename,
+ const std::string &rnnlm_rxfilename) {
+ rnnlm_.setRnnLMFile(rnnlm_rxfilename);
+ rnnlm_.setRandSeed(1);
+ rnnlm_.setUnkSym(opts.unk_symbol);
+ rnnlm_.setUnkPenalty(unk_prob_rspecifier);
+ rnnlm_.restoreNet();
+
+ // Reads symbol table.
+ fst::SymbolTable *word_symbols = NULL;
+ if (!(word_symbols =
+ fst::SymbolTable::ReadText(word_symbol_table_rxfilename))) {
+ KALDI_ERR << "Could not read symbol table from file "
+ << word_symbol_table_rxfilename;
+ }
+ label_to_word_.resize(word_symbols->NumSymbols() + 1);
+ for (int32 i = 0; i < label_to_word_.size() - 1; ++i) {
+ label_to_word_[i] = word_symbols->Find(i);
+ if (label_to_word_[i] == "") {
+ KALDI_ERR << "Could not find word for integer " << i << "in the word "
+ << "symbol table, mismatched symbol table or you have discontinuous "
+ << "integers in your symbol table?";
+ }
+ }
+ label_to_word_[label_to_word_.size() - 1] = opts.eos_symbol;
+ eos_ = label_to_word_.size() - 1;
+}
+
+BaseFloat KaldiRnnlmWrapper::GetLogProb(
+ int32 word, const std::vector<int32> &wseq,
+ const std::vector<float> &context_in,
+ std::vector<float> *context_out) {
+
+ std::vector<std::string> wseq_symbols(wseq.size());
+ for (int32 i = 0; i < wseq_symbols.size(); ++i) {
+ KALDI_ASSERT(wseq[i] < label_to_word_.size());
+ wseq_symbols[i] = label_to_word_[wseq[i]];
+ }
+
+ return rnnlm_.computeConditionalLogprob(label_to_word_[word], wseq_symbols,
+ context_in, context_out);
+}
+
+RnnlmDeterministicFst::RnnlmDeterministicFst(int32 max_ngram_order,
+ KaldiRnnlmWrapper *rnnlm) {
+ KALDI_ASSERT(rnnlm != NULL);
+ max_ngram_order_ = max_ngram_order;
+ rnnlm_ = rnnlm;
+
+ // Uses empty history for <s>.
+ std::vector<Label> bos;
+ std::vector<float> bos_context(rnnlm->GetHiddenLayerSize(), 1.0);
+ state_to_wseq_.push_back(bos);
+ state_to_context_.push_back(bos_context);
+ wseq_to_state_[bos] = 0;
+ start_state_ = 0;
+}
+
+fst::StdArc::Weight RnnlmDeterministicFst::Final(StateId s) {
+ // At this point, we should have created the state.
+ KALDI_ASSERT(static_cast<size_t>(s) < state_to_wseq_.size());
+
+ std::vector<Label> wseq = state_to_wseq_[s];
+ BaseFloat logprob = rnnlm_->GetLogProb(rnnlm_->GetEos(), wseq,
+ state_to_context_[s], NULL);
+ return Weight(-logprob);
+}
+
+bool RnnlmDeterministicFst::GetArc(StateId s, Label ilabel, fst::StdArc *oarc) {
+ // At this point, we should have created the state.
+ KALDI_ASSERT(static_cast<size_t>(s) < state_to_wseq_.size());
+
+ std::vector<Label> wseq = state_to_wseq_[s];
+ std::vector<float> new_context(rnnlm_->GetHiddenLayerSize());
+ BaseFloat logprob = rnnlm_->GetLogProb(ilabel, wseq,
+ state_to_context_[s], &new_context);
+
+ wseq.push_back(ilabel);
+ if (max_ngram_order_ > 0) {
+ while (wseq.size() >= max_ngram_order_) {
+ // History state has at most <max_ngram_order_> - 1 words in the state.
+ wseq.erase(wseq.begin(), wseq.begin() + 1);
+ }
+ }
+
+ std::pair<const std::vector<Label>, StateId> wseq_state_pair(
+ wseq, static_cast<Label>(state_to_wseq_.size()));
+
+ // Attemps to insert the current <lseq_state_pair>. If the pair already exists
+ // then it returns false.
+ typedef MapType::iterator IterType;
+ std::pair<IterType, bool> result = wseq_to_state_.insert(wseq_state_pair);
+
+ // If the pair was just inserted, then also add it to <state_to_wseq_> and
+ // <state_to_context_>.
+ if (result.second == true) {
+ state_to_wseq_.push_back(wseq);
+ state_to_context_.push_back(new_context);
+ }
+
+ // Creates the arc.
+ oarc->ilabel = ilabel;
+ oarc->olabel = ilabel;
+ oarc->nextstate = result.first->second;
+ oarc->weight = Weight(-logprob);
+
+ return true;
+}
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/kaldi-rnnlm.h b/runtime/onnxruntime/third_party/kaldi/lm/kaldi-rnnlm.h
new file mode 100644
index 000000000..dd7de9662
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/kaldi-rnnlm.h
@@ -0,0 +1,104 @@
+// lm/kaldi-rnnlm.h
+
+// Copyright 2015 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_LM_KALDI_RNNLM_H_
+#define KALDI_LM_KALDI_RNNLM_H_
+
+#include <string>
+#include <vector>
+
+#include "base/kaldi-common.h"
+#include "fstext/deterministic-fst.h"
+#include "lm/mikolov-rnnlm-lib.h"
+#include "util/common-utils.h"
+
+namespace kaldi {
+
+struct KaldiRnnlmWrapperOpts {
+ std::string unk_symbol;
+ std::string eos_symbol;
+
+ KaldiRnnlmWrapperOpts() : unk_symbol("<RNN_UNK>"), eos_symbol("</s>") {}
+
+ void Register(OptionsItf *opts) {
+ opts->Register("unk-symbol", &unk_symbol, "Symbol for out-of-vocabulary "
+ "words in rnnlm.");
+ opts->Register("eos-symbol", &eos_symbol, "End of sentence symbol in "
+ "rnnlm.");
+ }
+};
+
+class KaldiRnnlmWrapper {
+ public:
+ KaldiRnnlmWrapper(const KaldiRnnlmWrapperOpts &opts,
+ const std::string &unk_prob_rspecifier,
+ const std::string &word_symbol_table_rxfilename,
+ const std::string &rnnlm_rxfilename);
+
+ int32 GetHiddenLayerSize() const { return rnnlm_.getHiddenLayerSize(); }
+
+ int32 GetEos() const { return eos_; }
+
+ BaseFloat GetLogProb(int32 word, const std::vector<int32> &wseq,
+ const std::vector<float> &context_in,
+ std::vector<float> *context_out);
+
+ private:
+ rnnlm::CRnnLM rnnlm_;
+ std::vector<std::string> label_to_word_;
+ int32 eos_;
+
+ KALDI_DISALLOW_COPY_AND_ASSIGN(KaldiRnnlmWrapper);
+};
+
+class RnnlmDeterministicFst
+ : public fst::DeterministicOnDemandFst<fst::StdArc> {
+ public:
+ typedef fst::StdArc::Weight Weight;
+ typedef fst::StdArc::StateId StateId;
+ typedef fst::StdArc::Label Label;
+
+ // Does not take ownership.
+ RnnlmDeterministicFst(int32 max_ngram_order, KaldiRnnlmWrapper *rnnlm);
+
+ // We cannot use "const" because the pure virtual function in the interface is
+ // not const.
+ virtual StateId Start() { return start_state_; }
+
+ // We cannot use "const" because the pure virtual function in the interface is
+ // not const.
+ virtual Weight Final(StateId s);
+
+ virtual bool GetArc(StateId s, Label ilabel, fst::StdArc* oarc);
+
+ private:
+ typedef unordered_map<std::vector<Label>,
+ StateId, VectorHasher<Label> > MapType;
+ StateId start_state_;
+ MapType wseq_to_state_;
+ std::vector<std::vector<Label> > state_to_wseq_;
+
+ KaldiRnnlmWrapper *rnnlm_;
+ int32 max_ngram_order_;
+ std::vector<std::vector<float> > state_to_context_;
+};
+
+} // namespace kaldi
+
+#endif // KALDI_LM_KALDI_RNNLM_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/kenlm-test.cc b/runtime/onnxruntime/third_party/kaldi/lm/kenlm-test.cc
new file mode 100644
index 000000000..cab016eb0
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/kenlm-test.cc
@@ -0,0 +1,84 @@
+#ifdef HAVE_KENLM
+#include "util/text-utils.h"
+#include "util/kaldi-io.h"
+#include "lm/kenlm.h"
+
+namespace kaldi {
+
+void UnitTestKenLm() {
+ // construct symbol_to_symbol_id to map word string to kaldi symbol index,
+ // in practice, hypothesis is already intergerized, no need for this mapping.
+ std::unordered_map<std::string, int32> symbol_to_symbol_id;
+ std::ifstream symbol_table_stream("test_data/words.txt");
+ std::string line;
+ while (std::getline(symbol_table_stream, line)) {
+ std::vector<std::string> fields;
+ SplitStringToVector(line, " ", true, &fields);
+ if (fields.size() == 2) {
+ std::string symbol = fields[0];
+ uint32 symbol_id = -1;
+ ConvertStringToInteger(fields[1], &symbol_id);
+ symbol_to_symbol_id[symbol] = symbol_id;
+ }
+ }
+
+ // open testing stream, one sentence per line, in raw text form
+ std::ifstream is("test_data/sentences.txt");
+
+ KenLm lm;
+ lm.Load("test_data/lm.kenlm", "test_data/words.txt");
+ KenLmDeterministicOnDemandFst<fst::StdArc> lm_fst(&lm);
+
+ std::string sentence;
+ while(std::getline(is, sentence)) {
+ std::vector<std::string> words;
+ SplitStringToVector(sentence, " ", true, &words);
+ words.push_back("</s>");
+
+ // 1. test KenLm interface: this is only for test purpose,
+ // you should not use kenlm this way in Kaldi.
+ std::string sentence_log = "[KENLM]";
+
+ KenLm::State state[2];
+ KenLm::State* istate = &state[0];
+ KenLm::State* ostate = &state[1];
+
+ lm.SetStateToBeginOfSentence(istate);
+
+ for (int i = 0; i < words.size(); i++) {
+ std::string word = words[i];
+ BaseFloat log10_word_score = lm.Score(istate, lm.GetWordIndex(word), ostate);
+ sentence_log += " " + word +
+ "[" + std::to_string(lm.GetWordIndex(word)) + "]=" +
+ std::to_string(-log10_word_score * M_LN10); //convert to -ln()
+ std::swap(istate, ostate);
+ }
+ KALDI_LOG << sentence_log;
+
+ // 2. test Fst wrapper interface (KenLmDeterministicFst),
+ // this is the recommanded way to interact with Kaldi's Fst framework.
+ sentence_log = "(KALDI)";
+ KenLmDeterministicOnDemandFst<fst::StdArc>::StateId s = lm_fst.Start();
+ for (int i = 0; i < words.size(); i++) {
+ int32 symbol_id = symbol_to_symbol_id[words[i]];
+ sentence_log += " " + words[i] + "(" + std::to_string(symbol_id) + ")=";
+ if (words[i] == "</s>") {
+ sentence_log += std::to_string(lm_fst.Final(s).Value());
+ } else {
+ fst::StdArc arc;
+ lm_fst.GetArc(s, symbol_id, &arc);
+ s = arc.nextstate;
+ sentence_log += std::to_string(arc.weight.Value());
+ }
+ }
+ KALDI_LOG << sentence_log;
+ }
+}
+} // namespace kaldi
+
+int main(int argc, char *argv[]) {
+ using namespace kaldi;
+ UnitTestKenLm();
+ return 0;
+}
+#endif
\ No newline at end of file
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/kenlm.cc b/runtime/onnxruntime/third_party/kaldi/lm/kenlm.cc
new file mode 100644
index 000000000..2663775ad
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/kenlm.cc
@@ -0,0 +1,99 @@
+// Copyright 2020 Jiayu DU
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#ifdef HAVE_KENLM
+#include "lm/kenlm.h"
+
+namespace kaldi {
+
+void KenLm::ComputeSymbolToWordIndexMapping(std::string symbol_table_filename) {
+ // count symbol table size
+ int num_syms = 0;
+ std::string line;
+ std::ifstream is(symbol_table_filename);
+ while(std::getline(is, line)) {
+ if (!line.empty()) num_syms++;
+ }
+
+ symid_to_wid_.clear();
+ symid_to_wid_.resize(num_syms, 0);
+
+ is.clear();
+ is.seekg(0);
+ int num_mapped = 0;
+ while (std::getline(is, line)) {
+ std::vector<std::string> fields;
+ SplitStringToVector(line, " ", true, &fields);
+ if (fields.size() == 2) {
+ std::string sym = fields[0];
+ int32 symid = 0; ConvertStringToInteger(fields[1], &symid);
+ // mark special LM word
+ if (sym == bos_sym_) {
+ bos_symid_ = symid;
+ } else if (sym == eos_sym_) {
+ eos_symid_ = symid;
+ } else if (sym == "<unk>" || sym == "<UNK>") {
+ unk_sym_ = sym;
+ unk_symid_ = symid;
+ }
+ // check vocabulary consistency between kaldi and kenlm.
+ // note we always handle <unk> & <UNK> as a pair,
+ // so don't worry about the literal mismatch
+ // between Kaldi and kenlm arpa (<UNK> vs <unk>)
+ WordIndex wid = vocab_->Index(sym.c_str());
+ if ((wid == vocab_->Index("<unk>") || wid == vocab_->Index("<UNK>"))
+ && sym != "<unk>" && sym != "<UNK>"
+ && sym != "<eps>"
+ && sym != "#0") {
+ KALDI_ERR << "found mismatched symbol: " << sym
+ << ", this symbol is in Kaldi, but is unseen in KenLm"
+ << ", they should have strictly consistent vocabulary.";
+ } else {
+ symid_to_wid_[symid] = wid;
+ num_mapped += 1;
+ }
+ }
+ }
+ KALDI_ASSERT(num_mapped == symid_to_wid_.size());
+ KALDI_LOG << "Successfully mapped " << num_mapped
+ << " Kaldi symbols to KenLm words";
+}
+
+int KenLm::Load(std::string kenlm_filename,
+ std::string symbol_table_filename,
+ util::LoadMethod load_method) {
+ if (model_ != nullptr) { delete model_; }
+ model_ = nullptr;
+ vocab_ = nullptr;
+
+ // load KenLm model
+ lm::ngram::Config config;
+ config.load_method = load_method;
+ model_ = lm::ngram::LoadVirtual(kenlm_filename.c_str(), config);
+ if (model_ == nullptr) { KALDI_ERR << "Failed to load KenLm model"; }
+
+ // KenLm holds vocabulary internally with ownership,
+ // vocab_ here is just for concise reference
+ vocab_ = &model_->BaseVocabulary();
+ if (vocab_ == nullptr) { KALDI_ERR << "Failed to get vocabulary from KenLm model"; }
+
+ // compute the index mapping from Kaldi symbol to KenLm word
+ ComputeSymbolToWordIndexMapping(symbol_table_filename);
+ return 0;
+}
+
+} // namespace kaldi
+#endif
\ No newline at end of file
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/kenlm.h b/runtime/onnxruntime/third_party/kaldi/lm/kenlm.h
new file mode 100644
index 000000000..652259bb5
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/kenlm.h
@@ -0,0 +1,207 @@
+// Copyright 2020 Jiayu DU
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#ifdef HAVE_KENLM
+#ifndef KALDI_LM_KENLM_H
+#define KALDI_LM_KENLM_H
+
+#include <base/kaldi-common.h>
+#include <fst/fstlib.h>
+#include <fst/fst-decl.h>
+#include <fstext/deterministic-fst.h>
+
+#include "lm/model.hh"
+#include "util/murmur_hash.hh"
+
+namespace kaldi {
+
+// KenLm class wraps kenlm model(supporting both "trie" or "probing" models):
+// 1. provides interface for loading binary LM, and holds it with ownership
+// 2. provides interface for ngram score query at runtime
+// 3. handles the index mapping between kaldi's symbols & kenlm's words
+// KenLm object is heavy, stateless and thread-safe,
+// can be shared by Fst wrapper class(i.e. KenLmDeterministicOnDemandFst)
+class KenLm {
+ public:
+ typedef lm::WordIndex WordIndex;
+ typedef lm::ngram::State State;
+
+ public:
+ KenLm() :
+ model_(nullptr), vocab_(nullptr),
+ bos_sym_("<s>"), eos_sym_("</s>"), unk_sym_("<unk>"),
+ bos_symid_(0), eos_symid_(0), unk_symid_(0)
+ { }
+
+ ~KenLm() {
+ if (model_ != nullptr) {
+ delete model_;
+ }
+ model_ = nullptr;
+ vocab_ = nullptr;
+ symid_to_wid_.clear();
+ }
+
+ // If you have big LM on SSD hard-drive,
+ // you can set load_method to util::LoadMethod::LAZY,
+ // which enables "on-demand" model reading(via POSIX mmap) at runtime.
+ // Refer to tools/kenlm/util/mmap.hh for more load methods.
+ int Load(std::string kenlm_filename,
+ std::string kaldi_symbol_table_filename,
+ util::LoadMethod load_method = util::LoadMethod::POPULATE_OR_READ);
+
+ inline WordIndex GetWordIndex(std::string word) const {
+ return vocab_->Index(word.c_str());
+ }
+
+ inline WordIndex GetWordIndex(int32 symbol_id) const {
+ return symid_to_wid_[symbol_id];
+ }
+
+ void SetStateToBeginOfSentence(State *s) const { model_->BeginSentenceWrite(s); }
+ void SetStateToNull(State *s) const { model_->NullContextWrite(s); }
+
+ int32 BosSymbolIndex() const { return bos_symid_; }
+ int32 EosSymbolIndex() const { return eos_symid_; }
+ int32 UnkSymbolIndex() const { return unk_symid_; }
+
+ inline BaseFloat Score(const State *in_state,
+ WordIndex word,
+ State *out_state) const {
+ return model_->BaseScore(in_state, word, out_state);
+ }
+
+ // This provides a fast state hashing,
+ // KenLmDeterministicOnDemandFst needs this for Fst states managing.
+ struct StateHasher {
+ inline size_t operator()(const State &s) const noexcept {
+ return util::MurmurHashNative(s.words, sizeof(WordIndex) * s.Length());
+ }
+ };
+
+ private:
+ void ComputeSymbolToWordIndexMapping(std::string symbol_table);
+
+ private:
+ lm::base::Model *model_; // with ownership
+
+ // without ownership, points to internal vocabulary of model_
+ const lm::base::Vocabulary* vocab_;
+
+ // There are two integerized indexing systems here:
+ // 1. Kaldi's fst output *symbol index*(defined in words.txt),
+ // 2. KenLm's *word index*(defined by word string hashing).
+ // In order to rescore kaldi hypotheses with kenlm ngrams,
+ // we need to know the index mapping from symbol to word.
+ // KenLm class precomputes (during model loading) and stores this mapping,
+ // and apply the mapping at runtime.
+ // This is slower, but at least we don't need
+ // to modify/convert runtime resources.(e.g. HCLG/lattices or kenlm models)
+ //
+ // In the mapping, <eps> and #0 symbols are special:
+ // They do not correspond to any word in KenLm,
+ // so the mapping of these two symbols are logically undefined,
+ // we just map them to KenLm's <unk> to avoid random invalid mapping.
+
+ // symid_to_wid_[kaldi_symbol_index] -> kenlm word index
+ std::vector<WordIndex> symid_to_wid_;
+
+ // special lm symbols
+ std::string bos_sym_;
+ std::string eos_sym_;
+ std::string unk_sym_;
+
+ int32 bos_symid_;
+ int32 eos_symid_;
+ int32 unk_symid_;
+}; // class KenLm
+
+
+// DeterministicOnDemandFst wraps a KenLm object as a deteministic Fst.
+// Internally, it manages dynamically expanded Fst states(so not thread-safe),
+// different threads should create their own instances of this class.
+// They are lightweight and can share the same KenLm object.
+template<class Arc>
+class KenLmDeterministicOnDemandFst : public fst::DeterministicOnDemandFst<Arc> {
+ public:
+ typedef typename Arc::Weight Weight;
+ typedef typename Arc::StateId StateId;
+ typedef typename Arc::Label Label;
+ typedef typename KenLm::State State;
+ typedef typename KenLm::WordIndex WordIndex;
+
+ explicit KenLmDeterministicOnDemandFst(const KenLm *lm)
+ : lm_(lm), num_states_(0), bos_state_id_(0)
+ {
+ // create bos to be FST start state
+ MapElem e;
+ lm->SetStateToBeginOfSentence(&e.first);
+ e.second = bos_state_id_;
+ std::pair<IterType, bool> r = state_map_.insert(e);
+ KALDI_ASSERT(r.second == true); // bos successfully inserted into state map
+ state_vec_.push_back(&r.first->first);
+ num_states_++;
+
+ eos_symbol_id_ = lm_->EosSymbolIndex();
+ }
+ virtual ~KenLmDeterministicOnDemandFst() { }
+
+ virtual StateId Start() {
+ return bos_state_id_;
+ }
+
+ virtual bool GetArc(StateId s, Label label, Arc *oarc) {
+ KALDI_ASSERT(s < static_cast<StateId>(state_vec_.size()));
+ const State* istate = state_vec_[s];
+ MapElem e;
+ WordIndex word = lm_->GetWordIndex(label);
+ BaseFloat log_10_prob = lm_->Score(istate, word, &e.first);
+ e.second = num_states_;
+ std::pair<IterType, bool> r = state_map_.insert(e);
+ if (r.second == true) { // new state
+ state_vec_.push_back(&(r.first->first));
+ num_states_++;
+ }
+
+ oarc->ilabel = label;
+ oarc->olabel = oarc->ilabel;
+ oarc->nextstate = r.first->second;
+ oarc->weight = Weight(-log_10_prob * M_LN10); // KenLm log10() -> Kaldi ln()
+
+ return true;
+ }
+
+ virtual Weight Final(StateId s) {
+ Arc oarc;
+ GetArc(s, eos_symbol_id_, &oarc);
+ return oarc.weight;
+ }
+
+ private:
+ typedef std::pair<State, StateId> MapElem;
+ typedef unordered_map<State, StateId, KenLm::StateHasher> MapType;
+ typedef typename MapType::iterator IterType;
+
+ const KenLm *lm_; // no ownership
+ MapType state_map_;
+ std::vector<const State*> state_vec_;
+ StateId num_states_; // state vector index range, [0, num_states_)
+ StateId bos_state_id_; // fst start state id
+ Label eos_symbol_id_;
+}; // class KenLmDeterministicOnDemandFst
+} // namespace kaldi
+#endif
+#endif
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/mikolov-rnnlm-lib.cc b/runtime/onnxruntime/third_party/kaldi/lm/mikolov-rnnlm-lib.cc
new file mode 100644
index 000000000..d867dcb4b
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/mikolov-rnnlm-lib.cc
@@ -0,0 +1,1232 @@
+// lm/mikolov-rnnlm-lib.cc
+
+// Copyright 2015 Guoguo Chen Hainan Xu
+// 2010-2012 Tomas Mikolov
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// This file is based on version 0.3e of the RNNLM language modeling
+// toolkit by Tomas Mikolov. Changes made by authors other than
+// Tomas Mikolov are licensed under the Apache License, the short form
+// os which is below. The original code by Tomas Mikolov is licensed
+// under the BSD 3-clause license, whose text is further below.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+//
+//
+// Original BSD 3-clause license text:
+// Copyright (c) 2010-2012 Tomas Mikolov
+//
+// All rights reserved. Redistribution and use in source and binary forms, with
+// or without modification, are permitted provided that the following conditions
+// are met: 1. Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following
+// disclaimer. 2. Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the
+// distribution. 3. Neither name of copyright holders nor the names of its
+// contributors may be used to endorse or promote products derived from this
+// software without specific prior written permission. THIS SOFTWARE IS PROVIDED
+// BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
+// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+// EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#include "lm/mikolov-rnnlm-lib.h"
+#include "util/table-types.h"
+
+namespace rnnlm {
+
+///// fast exp() implementation
+static union {
+ double d;
+ struct {
+ int j, i;
+ } n;
+} d2i;
+#define EXP_A (1048576 / M_LN2)
+#define EXP_C 60801
+#define FAST_EXP(y) (d2i.n.i = EXP_A * (y) + (1072693248 - EXP_C), d2i.d)
+
+CRnnLM::CRnnLM() {
+ version = 10;
+ filetype = TEXT;
+
+ use_lmprob = 0;
+ gradient_cutoff = 15;
+ dynamic = 0;
+
+ train_file[0] = 0;
+ valid_file[0] = 0;
+ test_file[0] = 0;
+ rnnlm_file[0] = 0;
+
+ alpha_set = 0;
+ train_file_set = 0;
+
+ alpha = 0.1;
+ beta = 0.0000001;
+ // beta = 0.00000;
+ alpha_divide = 0;
+ logp = 0;
+ llogp = -100000000;
+ iter = 0;
+
+ min_improvement = 1.003;
+
+ train_words = 0;
+ vocab_max_size = 100;
+ vocab_size = 0;
+ vocab = (struct vocab_word *)calloc(vocab_max_size,
+ sizeof(struct vocab_word));
+
+ layer1_size = 30;
+
+ direct_size = 0;
+ direct_order = 0;
+
+ bptt = 0;
+ bptt_block = 10;
+ bptt_history = NULL;
+ bptt_hidden = NULL;
+ bptt_syn0 = NULL;
+
+ gen = 0;
+
+ independent = 0;
+
+ neu0 = NULL;
+ neu1 = NULL;
+ neuc = NULL;
+ neu2 = NULL;
+
+ syn0 = NULL;
+ syn1 = NULL;
+ sync = NULL;
+ syn_d = NULL;
+ syn_db = NULL;
+ // backup
+ neu0b = NULL;
+ neu1b = NULL;
+ neucb = NULL;
+ neu2b = NULL;
+
+ neu1b2 = NULL;
+
+ syn0b = NULL;
+ syn1b = NULL;
+ syncb = NULL;
+
+ rand_seed = 1;
+
+ class_size = 100;
+ old_classes = 0;
+
+ srand(rand_seed);
+
+ vocab_hash_size = 100000000;
+ vocab_hash = reinterpret_cast<int *>(calloc(vocab_hash_size, sizeof(int)));
+}
+
+CRnnLM::~CRnnLM() {
+ int i;
+
+ if (neu0 != NULL) {
+ free(neu0);
+ free(neu1);
+ if (neuc != NULL) free(neuc);
+ free(neu2);
+
+ free(syn0);
+ free(syn1);
+ if (sync != NULL) free(sync);
+
+ if (syn_d != NULL) free(syn_d);
+
+ if (syn_db != NULL) free(syn_db);
+
+ free(neu0b);
+ free(neu1b);
+ if (neucb != NULL) free(neucb);
+ free(neu2b);
+
+ free(neu1b2);
+
+ free(syn0b);
+ free(syn1b);
+ if (syncb != NULL) free(syncb);
+
+ for (i = 0; i < class_size; i++) {
+ free(class_words[i]);
+ }
+ free(class_max_cn);
+ free(class_cn);
+ free(class_words);
+
+ free(vocab);
+ free(vocab_hash);
+
+ if (bptt_history != NULL) free(bptt_history);
+ if (bptt_hidden != NULL) free(bptt_hidden);
+ if (bptt_syn0 != NULL) free(bptt_syn0);
+
+ // todo: free bptt variables too
+ }
+}
+
+real CRnnLM::random(real min, real max) {
+ return rand() / (real)RAND_MAX * (max - min) + min;
+}
+
+void CRnnLM::setRnnLMFile(const std::string &str) {
+ strcpy(rnnlm_file, str.c_str());
+}
+
+void CRnnLM::setRandSeed(int newSeed) {
+ rand_seed = newSeed;
+ srand(rand_seed);
+}
+
+void CRnnLM::readWord(char *word, FILE *fin) {
+ int a = 0, ch;
+
+ while (!feof(fin)) {
+ ch = fgetc(fin);
+
+ if (ch == 13) continue;
+
+ if ((ch == ' ') || (ch == '\t') || (ch == '\n')) {
+ if (a > 0) {
+ if (ch == '\n') ungetc(ch, fin);
+ break;
+ }
+
+ if (ch == '\n') {
+ strcpy(word, const_cast<char *>("</s>"));
+ return;
+ } else {
+ continue;
+ }
+ }
+
+ word[a] = ch;
+ a++;
+
+ if (a >= MAX_STRING) {
+ // printf("Too long word found!\n"); //truncate too long words
+ a--;
+ }
+ }
+ word[a] = 0;
+}
+
+int CRnnLM::getWordHash(const char *word) {
+ unsigned int hash, a;
+
+ hash = 0;
+ for (a = 0; a < strlen(word); a++) {
+ hash = hash * 237 + word[a];
+ }
+ hash = hash % vocab_hash_size;
+
+ return hash;
+}
+
+int CRnnLM::searchVocab(const char *word) {
+ int a;
+ unsigned int hash;
+
+ hash = getWordHash(word);
+
+ if (vocab_hash[hash] == -1) return -1;
+ if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash];
+
+ for (a = 0; a < vocab_size; a++) { // search in vocabulary
+ if (!strcmp(word, vocab[a].word)) {
+ vocab_hash[hash] = a;
+ return a;
+ }
+ }
+
+ return -1; // return OOV if not found
+}
+
+void CRnnLM::sortVocab() {
+ int a, b, max;
+ vocab_word swap;
+
+ for (a = 1; a < vocab_size; a++) {
+ max = a;
+ for (b = a + 1; b < vocab_size; b++) {
+ if (vocab[max].cn < vocab[b].cn) max = b;
+ }
+
+ swap = vocab[max];
+ vocab[max] = vocab[a];
+ vocab[a] = swap;
+ }
+}
+
+void CRnnLM::saveWeights() { // saves current weights and unit activations
+ int a, b;
+
+ for (a = 0; a < layer0_size; a++) {
+ neu0b[a].ac = neu0[a].ac;
+ neu0b[a].er = neu0[a].er;
+ }
+
+ for (a = 0; a < layer1_size; a++) {
+ neu1b[a].ac = neu1[a].ac;
+ neu1b[a].er = neu1[a].er;
+ }
+
+ for (a = 0; a < layerc_size; a++) {
+ neucb[a].ac = neuc[a].ac;
+ neucb[a].er = neuc[a].er;
+ }
+
+ for (a = 0; a < layer2_size; a++) {
+ neu2b[a].ac = neu2[a].ac;
+ neu2b[a].er = neu2[a].er;
+ }
+
+ for (b = 0; b < layer1_size; b++) {
+ for (a = 0; a < layer0_size; a++) {
+ syn0b[a + b * layer0_size].weight = syn0[a + b * layer0_size].weight;
+ }
+ }
+
+ if (layerc_size > 0) {
+ for (b = 0; b < layerc_size; b++) {
+ for (a = 0; a < layer1_size; a++) {
+ syn1b[a + b * layer1_size].weight = syn1[a + b * layer1_size].weight;
+ }
+ }
+
+ for (b = 0; b < layer2_size; b++) {
+ for (a = 0; a < layerc_size; a++) {
+ syncb[a + b * layerc_size].weight = sync[a + b * layerc_size].weight;
+ }
+ }
+ } else {
+ for (b = 0; b < layer2_size; b++) {
+ for (a = 0; a < layer1_size; a++) {
+ syn1b[a + b * layer1_size].weight = syn1[a + b * layer1_size].weight;
+ }
+ }
+ }
+
+ // for (a = 0; a < direct_size; a++) syn_db[a].weight = syn_d[a].weight;
+}
+
+void CRnnLM::initNet() {
+ int a, b, cl;
+
+ layer0_size = vocab_size + layer1_size;
+ layer2_size = vocab_size + class_size;
+
+ neu0 = (struct neuron *)calloc(layer0_size, sizeof(struct neuron));
+ neu1 = (struct neuron *)calloc(layer1_size, sizeof(struct neuron));
+ neuc = (struct neuron *)calloc(layerc_size, sizeof(struct neuron));
+ neu2 = (struct neuron *)calloc(layer2_size, sizeof(struct neuron));
+
+ syn0 = (struct synapse *)calloc(layer0_size * layer1_size,
+ sizeof(struct synapse));
+ if (layerc_size == 0) {
+ syn1 = (struct synapse *)calloc(layer1_size * layer2_size,
+ sizeof(struct synapse));
+ } else {
+ syn1 = (struct synapse *)calloc(layer1_size * layerc_size,
+ sizeof(struct synapse));
+ sync = (struct synapse *)calloc(layerc_size * layer2_size,
+ sizeof(struct synapse));
+ }
+
+ if (syn1 == NULL) {
+ printf("Memory allocation failed\n");
+ exit(1);
+ }
+
+ if (layerc_size > 0)
+ if (sync == NULL) {
+ printf("Memory allocation failed\n");
+ exit(1);
+ }
+
+ syn_d =
+ reinterpret_cast<direct_t *>(calloc(static_cast<long long>(direct_size),
+ sizeof(direct_t)));
+
+ if (syn_d == NULL) {
+ printf("Memory allocation for direct"
+ " connections failed (requested %lld bytes)\n",
+ static_cast<long long>(direct_size) * static_cast<long long>(sizeof(direct_t)));
+ exit(1);
+ }
+
+ neu0b = (struct neuron *)calloc(layer0_size, sizeof(struct neuron));
+ neu1b = (struct neuron *)calloc(layer1_size, sizeof(struct neuron));
+ neucb = (struct neuron *)calloc(layerc_size, sizeof(struct neuron));
+ neu1b2 = (struct neuron *)calloc(layer1_size, sizeof(struct neuron));
+ neu2b = (struct neuron *)calloc(layer2_size, sizeof(struct neuron));
+
+ syn0b = (struct synapse *)calloc(layer0_size * layer1_size,
+ sizeof(struct synapse));
+ // syn1b = (struct synapse *)calloc(layer1_size*layer2_size,
+ // sizeof(struct synapse));
+ if (layerc_size == 0) {
+ syn1b = (struct synapse *)calloc(layer1_size * layer2_size,
+ sizeof(struct synapse));
+ } else {
+ syn1b = (struct synapse *)calloc(layer1_size * layerc_size,
+ sizeof(struct synapse));
+ syncb = (struct synapse *)calloc(layerc_size * layer2_size,
+ sizeof(struct synapse));
+ }
+
+ if (syn1b == NULL) {
+ printf("Memory allocation failed\n");
+ exit(1);
+ }
+
+ for (a = 0; a < layer0_size; a++) {
+ neu0[a].ac = 0;
+ neu0[a].er = 0;
+ }
+
+ for (a = 0; a < layer1_size; a++) {
+ neu1[a].ac = 0;
+ neu1[a].er = 0;
+ }
+
+ for (a = 0; a < layerc_size; a++) {
+ neuc[a].ac = 0;
+ neuc[a].er = 0;
+ }
+
+ for (a = 0; a < layer2_size; a++) {
+ neu2[a].ac = 0;
+ neu2[a].er = 0;
+ }
+
+ for (b = 0; b < layer1_size; b++) {
+ for (a = 0; a < layer0_size; a++) {
+ syn0[a + b * layer0_size].weight =
+ random(-0.1, 0.1) + random(-0.1, 0.1) + random(-0.1, 0.1);
+ }
+ }
+
+ if (layerc_size > 0) {
+ for (b = 0; b < layerc_size; b++) {
+ for (a = 0; a < layer1_size; a++) {
+ syn1[a + b * layer1_size].weight =
+ random(-0.1, 0.1) + random(-0.1, 0.1) + random(-0.1, 0.1);
+ }
+ }
+
+ for (b = 0; b < layer2_size; b++) {
+ for (a = 0; a < layerc_size; a++) {
+ sync[a + b * layerc_size].weight =
+ random(-0.1, 0.1) + random(-0.1, 0.1) + random(-0.1, 0.1);
+ }
+ }
+ } else {
+ for (b = 0; b < layer2_size; b++) {
+ for (a = 0; a < layer1_size; a++) {
+ syn1[a + b * layer1_size].weight =
+ random(-0.1, 0.1) + random(-0.1, 0.1) + random(-0.1, 0.1);
+ }
+ }
+ }
+
+ long long aa;
+ for (aa = 0; aa < direct_size; aa++) {
+ syn_d[aa] = 0;
+ }
+
+ if (bptt > 0) {
+ bptt_history = reinterpret_cast<int *>(calloc((bptt + bptt_block + 10),
+ sizeof(int)));
+ for (a = 0; a < bptt + bptt_block; a++) {
+ bptt_history[a] = -1;
+ }
+ bptt_hidden = reinterpret_cast<neuron *>(calloc(
+ (bptt + bptt_block + 1) * layer1_size, sizeof(neuron)));
+ for (a = 0; a < (bptt + bptt_block) * layer1_size; a++) {
+ bptt_hidden[a].ac = 0;
+ bptt_hidden[a].er = 0;
+ }
+ bptt_syn0 = (struct synapse *)calloc(layer0_size * layer1_size,
+ sizeof(struct synapse));
+ if (bptt_syn0 == NULL) {
+ printf("Memory allocation failed\n");
+ exit(1);
+ }
+ }
+
+ saveWeights();
+
+ double df, dd;
+ int i;
+
+ df = 0;
+ dd = 0;
+ a = 0;
+ b = 0;
+
+ if (old_classes) { // old classes
+ for (i = 0; i < vocab_size; i++) {
+ b += vocab[i].cn;
+ }
+ for (i = 0; i < vocab_size; i++) {
+ df += vocab[i].cn / static_cast<double>(b);
+ if (df > 1) df = 1;
+ if (df > (a + 1) / static_cast<double>(class_size)) {
+ vocab[i].class_index = a;
+ if (a < class_size - 1) a++;
+ } else {
+ vocab[i].class_index = a;
+ }
+ }
+ } else { // new classes
+ for (i = 0; i < vocab_size; i++) {
+ b += vocab[i].cn;
+ }
+ for (i = 0; i < vocab_size; i++) {
+ dd += sqrt(vocab[i].cn / static_cast<double>(b));
+ }
+ for (i = 0; i < vocab_size; i++) {
+ df += sqrt(vocab[i].cn / static_cast<double>(b)) / dd;
+ if (df > 1) df = 1;
+ if (df > (a + 1) / static_cast<double>(class_size)) {
+ vocab[i].class_index = a;
+ if (a < class_size - 1) a++;
+ } else {
+ vocab[i].class_index = a;
+ }
+ }
+ }
+
+ // allocate auxiliary class variables (for faster search when
+ // normalizing probability at output layer)
+
+ class_words = reinterpret_cast<int **>(calloc(class_size, sizeof(int *)));
+ class_cn = reinterpret_cast<int *>(calloc(class_size, sizeof(int)));
+ class_max_cn = reinterpret_cast<int *>(calloc(class_size, sizeof(int)));
+
+ for (i = 0; i < class_size; i++) {
+ class_cn[i] = 0;
+ class_max_cn[i] = 10;
+ class_words[i] = reinterpret_cast<int *>(calloc(class_max_cn[i], sizeof(int)));
+ }
+
+ for (i = 0; i < vocab_size; i++) {
+ cl = vocab[i].class_index;
+ class_words[cl][class_cn[cl]] = i;
+ class_cn[cl]++;
+ if (class_cn[cl] + 2 >= class_max_cn[cl]) {
+ class_max_cn[cl] += 10;
+ class_words[cl] = reinterpret_cast<int *>(realloc(class_words[cl],
+ class_max_cn[cl] * sizeof(int)));
+ }
+ }
+}
+
+void CRnnLM::goToDelimiter(int delim, FILE *fi) {
+ int ch = 0;
+
+ while (ch != delim) {
+ ch = fgetc(fi);
+ if (feof(fi)) {
+ printf("Unexpected end of file\n");
+ exit(1);
+ }
+ }
+}
+
+void CRnnLM::restoreNet() { // will read whole network structure
+ FILE *fi;
+ int a, b, ver, unused_size;
+ float fl;
+ char str[MAX_STRING];
+ double d;
+
+ fi = fopen(rnnlm_file, "rb");
+ if (fi == NULL) {
+ printf("ERROR: model file '%s' not found!\n", rnnlm_file);
+ exit(1);
+ }
+
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &ver);
+ if ((ver == 4) && (version == 5)) {
+ /* we will solve this later.. */
+ } else {
+ if (ver != version) {
+ printf("Unknown version of file %s\n", rnnlm_file);
+ exit(1);
+ }
+ }
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &filetype);
+ goToDelimiter(':', fi);
+ if (train_file_set == 0) {
+ unused_size = fscanf(fi, "%s", train_file);
+ } else {
+ unused_size = fscanf(fi, "%s", str);
+ }
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%s", valid_file);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%lf", &llogp);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &iter);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &train_cur_pos);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%lf", &logp);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &anti_k);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &train_words);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &layer0_size);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &layer1_size);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &layerc_size);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &layer2_size);
+ if (ver > 5) {
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%lld", &direct_size);
+ }
+ if (ver > 6) {
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &direct_order);
+ }
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &bptt);
+ if (ver > 4) {
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &bptt_block);
+ } else {
+ bptt_block = 10;
+ }
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &vocab_size);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &class_size);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &old_classes);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &independent);
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%lf", &d);
+ starting_alpha = d;
+ goToDelimiter(':', fi);
+ if (alpha_set == 0) {
+ unused_size = fscanf(fi, "%lf", &d);
+ alpha = d;
+ } else {
+ unused_size = fscanf(fi, "%lf", &d);
+ }
+ goToDelimiter(':', fi);
+ unused_size = fscanf(fi, "%d", &alpha_divide);
+
+ // read normal vocabulary
+ if (vocab_max_size < vocab_size) {
+ if (vocab != NULL) free(vocab);
+ vocab_max_size = vocab_size + 1000;
+ // initialize memory for vocabulary
+ vocab = (struct vocab_word *)calloc(vocab_max_size,
+ sizeof(struct vocab_word));
+ }
+ goToDelimiter(':', fi);
+ for (a = 0; a < vocab_size; a++) {
+ // unused_size = fscanf(fi, "%d%d%s%d", &b, &vocab[a].cn,
+ // vocab[a].word, &vocab[a].class_index);
+ unused_size = fscanf(fi, "%d%d", &b, &vocab[a].cn);
+ readWord(vocab[a].word, fi);
+ unused_size = fscanf(fi, "%d", &vocab[a].class_index);
+ // printf("%d %d %s %d\n", b, vocab[a].cn,
+ // vocab[a].word, vocab[a].class_index);
+ }
+ if (neu0 == NULL) initNet(); // memory allocation here
+
+ if (filetype == TEXT) {
+ goToDelimiter(':', fi);
+ for (a = 0; a < layer1_size; a++) {
+ unused_size = fscanf(fi, "%lf", &d);
+ neu1[a].ac = d;
+ }
+ }
+ if (filetype == BINARY) {
+ fgetc(fi);
+ for (a = 0; a < layer1_size; a++) {
+ unused_size = fread(&fl, 4, 1, fi);
+ neu1[a].ac = fl;
+ }
+ }
+ if (filetype == TEXT) {
+ goToDelimiter(':', fi);
+ for (b = 0; b < layer1_size; b++) {
+ for (a = 0; a < layer0_size; a++) {
+ unused_size = fscanf(fi, "%lf", &d);
+ syn0[a + b * layer0_size].weight = d;
+ }
+ }
+ }
+ if (filetype == BINARY) {
+ for (b = 0; b < layer1_size; b++) {
+ for (a = 0; a < layer0_size; a++) {
+ unused_size = fread(&fl, 4, 1, fi);
+ syn0[a + b * layer0_size].weight = fl;
+ }
+ }
+ }
+ if (filetype == TEXT) {
+ goToDelimiter(':', fi);
+ if (layerc_size == 0) { // no compress layer
+ for (b = 0; b < layer2_size; b++) {
+ for (a = 0; a < layer1_size; a++) {
+ unused_size = fscanf(fi, "%lf", &d);
+ syn1[a + b * layer1_size].weight = d;
+ }
+ }
+ } else { // with compress layer
+ for (b = 0; b < layerc_size; b++) {
+ for (a = 0; a < layer1_size; a++) {
+ unused_size = fscanf(fi, "%lf", &d);
+ syn1[a + b * layer1_size].weight = d;
+ }
+ }
+
+ goToDelimiter(':', fi);
+
+ for (b = 0; b < layer2_size; b++) {
+ for (a = 0; a < layerc_size; a++) {
+ unused_size = fscanf(fi, "%lf", &d);
+ sync[a + b * layerc_size].weight = d;
+ }
+ }
+ }
+ }
+ if (filetype == BINARY) {
+ if (layerc_size == 0) { // no compress layer
+ for (b = 0; b < layer2_size; b++) {
+ for (a = 0; a < layer1_size; a++) {
+ unused_size = fread(&fl, 4, 1, fi);
+ syn1[a + b * layer1_size].weight = fl;
+ }
+ }
+ } else { // with compress layer
+ for (b = 0; b < layerc_size; b++) {
+ for (a = 0; a < layer1_size; a++) {
+ unused_size = fread(&fl, 4, 1, fi);
+ syn1[a + b * layer1_size].weight = fl;
+ }
+ }
+
+ for (b = 0; b < layer2_size; b++) {
+ for (a = 0; a < layerc_size; a++) {
+ unused_size = fread(&fl, 4, 1, fi);
+ sync[a + b * layerc_size].weight = fl;
+ }
+ }
+ }
+ }
+ if (filetype == TEXT) {
+ goToDelimiter(':', fi); // direct connections
+ long long aa;
+ for (aa = 0; aa < direct_size; aa++) {
+ unused_size = fscanf(fi, "%lf", &d);
+ syn_d[aa] = d;
+ }
+ }
+ if (filetype == BINARY) {
+ long long aa;
+ for (aa = 0; aa < direct_size; aa++) {
+ unused_size = fread(&fl, 4, 1, fi);
+ syn_d[aa] = fl;
+
+ /*unused_size = fread(&si, 2, 1, fi);
+ fl = si/(float)(4*256);
+ syn_d[aa] = fl;*/
+ }
+ }
+
+ saveWeights();
+
+ // idiom to "use" an unused variable
+ (void) unused_size;
+
+ fclose(fi);
+}
+
+void CRnnLM::netReset() { // cleans hidden layer activation + bptt history
+ int a, b;
+
+ for (a = 0; a < layer1_size; a++) {
+ neu1[a].ac = 1.0;
+ }
+
+ copyHiddenLayerToInput();
+
+ if (bptt > 0) {
+ for (a = 1; a < bptt + bptt_block; a++) {
+ bptt_history[a] = 0;
+ }
+ for (a = bptt + bptt_block - 1; a > 1; a--) {
+ for (b = 0; b < layer1_size; b++) {
+ bptt_hidden[a * layer1_size + b].ac = 0;
+ bptt_hidden[a * layer1_size + b].er = 0;
+ }
+ }
+ }
+
+ for (a = 0; a < MAX_NGRAM_ORDER; a++) {
+ history[a] = 0;
+ }
+}
+
+void CRnnLM::matrixXvector(struct neuron *dest, struct neuron *srcvec,
+ struct synapse *srcmatrix, int matrix_width,
+ int from, int to, int from2, int to2, int type) {
+ int a, b;
+ real val1, val2, val3, val4;
+ real val5, val6, val7, val8;
+
+ if (type == 0) { // ac mod
+ for (b = 0; b < (to - from) / 8; b++) {
+ val1 = 0;
+ val2 = 0;
+ val3 = 0;
+ val4 = 0;
+
+ val5 = 0;
+ val6 = 0;
+ val7 = 0;
+ val8 = 0;
+
+ for (a = from2; a < to2; a++) {
+ val1 += srcvec[a].ac * srcmatrix[a + (b * 8 + from + 0) * matrix_width].weight;
+ val2 += srcvec[a].ac * srcmatrix[a + (b * 8 + from + 1) * matrix_width].weight;
+ val3 += srcvec[a].ac * srcmatrix[a + (b * 8 + from + 2) * matrix_width].weight;
+ val4 += srcvec[a].ac * srcmatrix[a + (b * 8 + from + 3) * matrix_width].weight;
+
+ val5 += srcvec[a].ac * srcmatrix[a + (b * 8 + from + 4) * matrix_width].weight;
+ val6 += srcvec[a].ac * srcmatrix[a + (b * 8 + from + 5) * matrix_width].weight;
+ val7 += srcvec[a].ac * srcmatrix[a + (b * 8 + from + 6) * matrix_width].weight;
+ val8 += srcvec[a].ac * srcmatrix[a + (b * 8 + from + 7) * matrix_width].weight;
+ }
+ dest[b * 8 + from + 0].ac += val1;
+ dest[b * 8 + from + 1].ac += val2;
+ dest[b * 8 + from + 2].ac += val3;
+ dest[b * 8 + from + 3].ac += val4;
+
+ dest[b * 8 + from + 4].ac += val5;
+ dest[b * 8 + from + 5].ac += val6;
+ dest[b * 8 + from + 6].ac += val7;
+ dest[b * 8 + from + 7].ac += val8;
+ }
+
+ for (b = b * 8; b < to - from; b++) {
+ for (a = from2; a < to2; a++) {
+ dest[b+from].ac +=
+ srcvec[a].ac * srcmatrix[a + (b + from) * matrix_width].weight;
+ }
+ }
+ } else { // er mod
+ for (a = 0; a < (to2 - from2) / 8; a++) {
+ val1 = 0;
+ val2 = 0;
+ val3 = 0;
+ val4 = 0;
+
+ val5 = 0;
+ val6 = 0;
+ val7 = 0;
+ val8 = 0;
+
+ for (b = from; b < to; b++) {
+ val1 += srcvec[b].er * srcmatrix[a * 8 + from2 + 0 + b * matrix_width].weight;
+ val2 += srcvec[b].er * srcmatrix[a * 8 + from2 + 1 + b * matrix_width].weight;
+ val3 += srcvec[b].er * srcmatrix[a * 8 + from2 + 2 + b * matrix_width].weight;
+ val4 += srcvec[b].er * srcmatrix[a * 8 + from2 + 3 + b * matrix_width].weight;
+
+ val5 += srcvec[b].er * srcmatrix[a * 8 + from2 + 4 + b * matrix_width].weight;
+ val6 += srcvec[b].er * srcmatrix[a * 8 + from2 + 5 + b * matrix_width].weight;
+ val7 += srcvec[b].er * srcmatrix[a * 8 + from2 + 6 + b * matrix_width].weight;
+ val8 += srcvec[b].er * srcmatrix[a * 8 + from2 + 7 + b * matrix_width].weight;
+ }
+ dest[a * 8 + from2 + 0].er += val1;
+ dest[a * 8 + from2 + 1].er += val2;
+ dest[a * 8 + from2 + 2].er += val3;
+ dest[a * 8 + from2 + 3].er += val4;
+
+ dest[a * 8 + from2 + 4].er += val5;
+ dest[a * 8 + from2 + 5].er += val6;
+ dest[a * 8 + from2 + 6].er += val7;
+ dest[a * 8 + from2 + 7].er += val8;
+ }
+
+ for (a = a * 8; a < to2 - from2; a++) {
+ for (b = from; b < to; b++) {
+ dest[a + from2].er
+ += srcvec[b].er * srcmatrix[a + from2 + b * matrix_width].weight;
+ }
+ }
+
+ if (gradient_cutoff > 0)
+ for (a = from2; a < to2; a++) {
+ if (dest[a].er > gradient_cutoff) dest[a].er = gradient_cutoff;
+ if (dest[a].er < -gradient_cutoff) dest[a].er = -gradient_cutoff;
+ }
+ }
+
+ // this is normal implementation (about 3x slower):
+
+ /*if (type == 0) { //ac mod
+ for (b = from; b < to; b++) {
+ for (a = from2; a < to2; a++) {
+ dest[b].ac += srcvec[a].ac * srcmatrix[a+b*matrix_width].weight;
+ }
+ }
+ }
+ else //er mod
+ if (type == 1) {
+ for (a = from2; a < to2; a++) {
+ for (b = from; b < to; b++) {
+ dest[a].er += srcvec[b].er * srcmatrix[a+b*matrix_width].weight;
+ }
+ }
+ }*/
+}
+
+void CRnnLM::computeNet(int last_word, int word) {
+ int a, b, c;
+ real val;
+ double sum; // sum is used for normalization: it's better to have larger
+ // precision as many numbers are summed together here
+
+ if (last_word != -1) neu0[last_word].ac = 1;
+
+ // propagate 0->1
+ for (a = 0; a < layer1_size; a++) {
+ neu1[a].ac = 0;
+ }
+ for (a = 0; a < layerc_size; a++) {
+ neuc[a].ac = 0;
+ }
+
+ matrixXvector(neu1, neu0, syn0, layer0_size, 0, layer1_size,
+ layer0_size - layer1_size, layer0_size, 0);
+
+ for (b = 0; b < layer1_size; b++) {
+ a = last_word;
+ if (a != -1) neu1[b].ac += neu0[a].ac * syn0[a + b * layer0_size].weight;
+ }
+
+ // activate 1 --sigmoid
+ for (a = 0; a < layer1_size; a++) {
+ if (neu1[a].ac > 50) neu1[a].ac = 50; // for numerical stability
+ if (neu1[a].ac < -50) neu1[a].ac = -50; // for numerical stability
+ val = -neu1[a].ac;
+ neu1[a].ac = 1 / (1 + FAST_EXP(val));
+ }
+
+ if (layerc_size > 0) {
+ matrixXvector(neuc, neu1, syn1, layer1_size,
+ 0, layerc_size, 0, layer1_size, 0);
+ // activate compression --sigmoid
+ for (a = 0; a < layerc_size; a++) {
+ if (neuc[a].ac > 50) neuc[a].ac = 50; // for numerical stability
+ if (neuc[a].ac < -50) neuc[a].ac = -50; // for numerical stability
+ val = -neuc[a].ac;
+ neuc[a].ac = 1 / (1 + FAST_EXP(val));
+ }
+ }
+
+ // 1->2 class
+ for (b = vocab_size; b < layer2_size; b++) {
+ neu2[b].ac = 0;
+ }
+
+ if (layerc_size > 0) {
+ matrixXvector(neu2, neuc, sync, layerc_size,
+ vocab_size, layer2_size, 0, layerc_size, 0);
+ } else {
+ matrixXvector(neu2, neu1, syn1, layer1_size,
+ vocab_size, layer2_size, 0, layer1_size, 0);
+ }
+
+ // apply direct connections to classes
+ if (direct_size > 0) {
+ unsigned long long hash[MAX_NGRAM_ORDER];
+ // this will hold pointers to syn_d that contains hash parameters
+
+ for (a = 0; a < direct_order; a++) {
+ hash[a] = 0;
+ }
+
+ for (a = 0; a < direct_order; a++) {
+ b = 0;
+ if (a > 0) if (history[a - 1] == -1) break;
+ // if OOV was in history, do not use this N-gram feature and higher orders
+ hash[a] = PRIMES[0] * PRIMES[1];
+
+ for (b = 1; b <= a; b++) {
+ hash[a] += PRIMES[(a * PRIMES[b] + b) % PRIMES_SIZE]
+ * static_cast<unsigned long long>(history[b - 1] + 1);
+ }
+ // update hash value based on words from the history
+
+ hash[a] = hash[a] % (direct_size / 2);
+ // make sure that starting hash index is in the first
+ // half of syn_d (second part is reserved for history->words features)
+ }
+
+ for (a = vocab_size; a < layer2_size; a++) {
+ for (b = 0; b < direct_order; b++) {
+ if (hash[b]) {
+ neu2[a].ac += syn_d[hash[b]];
+ // apply current parameter and move to the next one
+
+ hash[b]++;
+ } else {
+ break;
+ }
+ }
+ }
+ }
+
+ // activation 2 --softmax on classes
+ sum = 0;
+ for (a = vocab_size; a < layer2_size; a++) {
+ if (neu2[a].ac > 50) neu2[a].ac = 50; // for numerical stability
+ if (neu2[a].ac < -50) neu2[a].ac = -50; // for numerical stability
+ val = FAST_EXP(neu2[a].ac);
+ sum+= val;
+ neu2[a].ac = val;
+ }
+ for (a = vocab_size; a < layer2_size; a++) {
+ neu2[a].ac /= sum;
+ }
+ // output layer activations now sum exactly to 1
+
+ if (gen > 0) return; // if we generate words, we don't know what current word
+ // is -> only classes are estimated and word is selected
+ // in testGen()
+
+
+ // 1->2 word
+ if (word != -1) {
+ for (c = 0; c < class_cn[vocab[word].class_index]; c++) {
+ neu2[class_words[vocab[word].class_index][c]].ac = 0;
+ }
+ if (layerc_size > 0) {
+ matrixXvector(neu2, neuc, sync, layerc_size,
+ class_words[vocab[word].class_index][0],
+ class_words[vocab[word].class_index][0]
+ + class_cn[vocab[word].class_index],
+ 0, layerc_size, 0);
+ } else {
+ matrixXvector(neu2, neu1, syn1, layer1_size,
+ class_words[vocab[word].class_index][0],
+ class_words[vocab[word].class_index][0]
+ + class_cn[vocab[word].class_index],
+ 0, layer1_size, 0);
+ }
+ }
+
+ // apply direct connections to words
+ if (word != -1) if (direct_size > 0) {
+ unsigned long long hash[MAX_NGRAM_ORDER];
+
+ for (a = 0; a < direct_order; a++) {
+ hash[a] = 0;
+ }
+
+ for (a = 0; a < direct_order; a++) {
+ b = 0;
+ if (a > 0) if (history[a - 1] == -1) break;
+ hash[a] =
+ PRIMES[0] * PRIMES[1] *
+ static_cast<unsigned long long>(vocab[word].class_index + 1);
+
+ for (b = 1; b <= a; b++) {
+ hash[a] += PRIMES[(a * PRIMES[b] + b) % PRIMES_SIZE]
+ * static_cast<unsigned long long>(history[b - 1] + 1);
+ }
+ hash[a] = (hash[a] % (direct_size / 2)) + (direct_size) / 2;
+ }
+
+ for (c = 0; c < class_cn[vocab[word].class_index]; c++) {
+ a = class_words[vocab[word].class_index][c];
+
+ for (b = 0; b < direct_order; b++) if (hash[b]) {
+ neu2[a].ac += syn_d[hash[b]];
+ hash[b]++;
+ hash[b] = hash[b] % direct_size;
+ } else {
+ break;
+ }
+ }
+ }
+
+ // activation 2 --softmax on words
+ sum = 0;
+ if (word != -1) {
+ for (c = 0; c < class_cn[vocab[word].class_index]; c++) {
+ a = class_words[vocab[word].class_index][c];
+ if (neu2[a].ac > 50) neu2[a].ac = 50; // for numerical stability
+ if (neu2[a].ac < -50) neu2[a].ac = -50; // for numerical stability
+ val = FAST_EXP(neu2[a].ac);
+ sum+= val;
+ neu2[a].ac = val;
+ }
+ for (c = 0; c < class_cn[vocab[word].class_index]; c++) {
+ neu2[class_words[vocab[word].class_index][c]].ac /= sum;
+ }
+ }
+}
+
+void CRnnLM::copyHiddenLayerToInput() {
+ int a;
+
+ for (a = 0; a < layer1_size; a++) {
+ neu0[a + layer0_size - layer1_size].ac = neu1[a].ac;
+ }
+}
+
+void CRnnLM::restoreContextFromVector(const std::vector <float> &context_in) {
+ assert(context_in.size() == layer1_size);
+ for (int i = 0; i < layer1_size; ++i) {
+ neu1[i].ac = context_in[i];
+ }
+}
+
+void CRnnLM::saveContextToVector(std::vector <float> *context_out) {
+ assert(context_out != NULL);
+ context_out->resize(layer1_size);
+ for (int i = 0; i < layer1_size; ++i) {
+ (*context_out)[i] = neu1[i].ac;
+ }
+}
+
+float CRnnLM::computeConditionalLogprob(
+ std::string current_word,
+ const std::vector < std::string > &history_words,
+ const std::vector < float > &context_in,
+ std::vector < float > *context_out) {
+ // We assume the network has been restored.
+ netReset();
+ restoreContextFromVector(context_in);
+ copyHiddenLayerToInput();
+
+ // Maps unk to the unk symbol.
+ std::vector <std::string> history_words_nounk(history_words);
+ std::string current_word_nounk = current_word;
+ if (isUnk(current_word_nounk)) {
+ current_word_nounk = unk_sym;
+ }
+ for (int i = 0; i < history_words_nounk.size(); ++i) {
+ if (isUnk(history_words_nounk[i])) {
+ history_words_nounk[i] = unk_sym;
+ }
+ }
+
+ // Handles history for n-gram features.
+ for (int i = 0; i < MAX_NGRAM_ORDER; i++) {
+ history[i] = 0;
+ }
+ for (int i = 0; i < history_words_nounk.size() && i < MAX_NGRAM_ORDER; i++) {
+ history[i] = searchVocab(
+ history_words_nounk[history_words_nounk.size() - 1 - i].c_str());
+ }
+
+ int word = 0, last_word = 0;
+ float logprob = 0;
+ if (current_word_nounk == unk_sym) {
+ logprob += getUnkPenalty(current_word);
+ }
+ word = searchVocab(current_word_nounk.c_str());
+ if (history_words_nounk.size() > 0) {
+ last_word = searchVocab(
+ history_words_nounk[history_words_nounk.size() - 1].c_str());
+ }
+ computeNet(last_word, word);
+
+ if (word != -1) {
+ logprob +=
+ log(neu2[vocab[word].class_index + vocab_size].ac * neu2[word].ac);
+ } else {
+ logprob += -16.118;
+ }
+
+ if (context_out != NULL) {
+ saveContextToVector(context_out);
+ }
+
+ if (last_word != -1) {
+ neu0[last_word].ac = 0;
+ }
+
+ return logprob;
+}
+
+bool CRnnLM::isUnk(const std::string &word) {
+ int word_int = searchVocab(word.c_str());
+ if (word_int == -1)
+ return true;
+ return false;
+}
+
+void CRnnLM::setUnkSym(const std::string &unk) {
+ unk_sym = unk;
+}
+
+float CRnnLM::getUnkPenalty(const std::string &word) {
+ unordered_map <std::string, float>::const_iterator iter =
+ unk_penalty.find(word);
+ if (iter != unk_penalty.end())
+ return iter->second;
+ return -16.118; // Fixed penalty.
+}
+
+void CRnnLM::setUnkPenalty(const std::string &filename) {
+ if (filename.empty())
+ return;
+ kaldi::SequentialBaseFloatReader unk_reader(filename);
+ for (; !unk_reader.Done(); unk_reader.Next()) {
+ std::string key = unk_reader.Key();
+ float prob = unk_reader.Value();
+ unk_reader.FreeCurrent();
+ unk_penalty[key] = log(prob);
+ }
+}
+
+} // namespace rnnlm
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/mikolov-rnnlm-lib.h b/runtime/onnxruntime/third_party/kaldi/lm/mikolov-rnnlm-lib.h
new file mode 100644
index 000000000..36d88a0a5
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/mikolov-rnnlm-lib.h
@@ -0,0 +1,239 @@
+// lm/mikolov-rnnlm-lib.h
+
+// Copyright 2015 Guoguo Chen Hainan Xu
+// 2010-2012 Tomas Mikolov
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// This file is based on version 0.3e of the RNNLM language modeling
+// toolkit by Tomas Mikolov. Changes made by authors other than
+// Tomas Mikolov are licensed under the Apache License, the short form
+// os which is below. The original code by Tomas Mikolov is licensed
+// under the BSD 3-clause license, whose text is further below.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+//
+//
+// Original BSD 3-clause license text:
+// Copyright (c) 2010-2012 Tomas Mikolov
+//
+// All rights reserved. Redistribution and use in source and binary forms, with
+// or without modification, are permitted provided that the following conditions
+// are met: 1. Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following
+// disclaimer. 2. Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the
+// distribution. 3. Neither name of copyright holders nor the names of its
+// contributors may be used to endorse or promote products derived from this
+// software without specific prior written permission. THIS SOFTWARE IS PROVIDED
+// BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR
+// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+// EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef KALDI_LM_MIKOLOV_RNNLM_LIB_H_
+#define KALDI_LM_MIKOLOV_RNNLM_LIB_H_
+
+#include <string>
+#include <vector>
+#include "util/stl-utils.h"
+
+namespace rnnlm {
+
+#define MAX_STRING 100
+#define MAX_FILENAME_STRING 300
+
+typedef double real; // doubles for NN weights
+typedef double direct_t; // doubles for ME weights;
+
+struct neuron {
+ real ac; // actual value stored in neuron
+ real er; // error value in neuron, used by learning algorithm
+};
+
+struct synapse {
+ real weight; // weight of synapse
+};
+
+struct vocab_word {
+ int cn;
+ char word[MAX_STRING];
+
+ real prob;
+ int class_index;
+};
+
+const unsigned int PRIMES[] = {108641969, 116049371, 125925907, 133333309,
+ 145678979, 175308587, 197530793, 234567803, 251851741, 264197411,
+ 330864029, 399999781,
+ 407407183, 459258997, 479012069, 545678687, 560493491, 607407037, 629629243,
+ 656789717, 716048933, 718518067, 725925469, 733332871, 753085943, 755555077,
+ 782715551, 790122953, 812345159, 814814293, 893826581, 923456189, 940740127,
+ 953085797, 985184539, 990122807};
+const unsigned int PRIMES_SIZE = sizeof(PRIMES) / sizeof(PRIMES[0]);
+
+const int MAX_NGRAM_ORDER = 20;
+
+enum FileTypeEnum {TEXT, BINARY, COMPRESSED}; // COMPRESSED not yet implemented
+
+class CRnnLM {
+ protected:
+ char train_file[MAX_FILENAME_STRING];
+ char valid_file[MAX_FILENAME_STRING];
+ char test_file[MAX_FILENAME_STRING];
+ char rnnlm_file[MAX_FILENAME_STRING];
+ char lmprob_file[MAX_FILENAME_STRING];
+
+ int rand_seed;
+ int version;
+ int filetype;
+
+ int use_lmprob;
+ real gradient_cutoff;
+
+ real dynamic;
+
+ real alpha;
+ real starting_alpha;
+ int alpha_divide;
+ double logp, llogp;
+ float min_improvement;
+ int iter;
+ int vocab_max_size;
+ int vocab_size;
+ int train_words;
+ int train_cur_pos;
+ int counter;
+
+ int anti_k;
+
+ real beta;
+
+ int class_size;
+ int **class_words;
+ int *class_cn;
+ int *class_max_cn;
+ int old_classes;
+
+ struct vocab_word *vocab;
+ void sortVocab();
+ int *vocab_hash;
+ int vocab_hash_size;
+
+ int layer0_size;
+ int layer1_size;
+ int layerc_size;
+ int layer2_size;
+
+ long long direct_size;
+ int direct_order;
+ int history[MAX_NGRAM_ORDER];
+
+ int bptt;
+ int bptt_block;
+ int *bptt_history;
+ neuron *bptt_hidden;
+ struct synapse *bptt_syn0;
+
+ int gen;
+
+ int independent;
+
+ struct neuron *neu0; // neurons in input layer
+ struct neuron *neu1; // neurons in hidden layer
+ struct neuron *neuc; // neurons in hidden layer
+ struct neuron *neu2; // neurons in output layer
+
+ struct synapse *syn0; // weights between input and hidden layer
+ struct synapse *syn1; // weights between hidden and output layer
+ // (or hidden and compression if compression>0)
+ struct synapse *sync; // weights between hidden and compression layer
+ direct_t *syn_d; // direct parameters between input and output layer
+ // (similar to Maximum Entropy model parameters)
+
+ // backup used in training:
+ struct neuron *neu0b;
+ struct neuron *neu1b;
+ struct neuron *neucb;
+ struct neuron *neu2b;
+
+ struct synapse *syn0b;
+ struct synapse *syn1b;
+ struct synapse *syncb;
+ direct_t *syn_db;
+
+ // backup used in n-bset rescoring:
+ struct neuron *neu1b2;
+
+ unordered_map<std::string, float> unk_penalty;
+ std::string unk_sym;
+
+ public:
+
+ int alpha_set, train_file_set;
+
+ CRnnLM();
+
+ ~CRnnLM();
+
+ real random(real min, real max);
+
+ void setRnnLMFile(const std::string &str);
+ int getHiddenLayerSize() const { return layer1_size; }
+ void setRandSeed(int newSeed);
+
+ int getWordHash(const char *word);
+ void readWord(char *word, FILE *fin);
+ int searchVocab(const char *word);
+
+ void saveWeights(); // saves current weights and unit activations
+ void initNet();
+ void goToDelimiter(int delim, FILE *fi);
+ void restoreNet();
+ void netReset(); // will erase just hidden layer state + bptt history
+ // + maxent history (called at end of sentences in
+ // the independent mode)
+
+ void computeNet(int last_word, int word);
+ void copyHiddenLayerToInput();
+
+ void matrixXvector(struct neuron *dest, struct neuron *srcvec,
+ struct synapse *srcmatrix, int matrix_width,
+ int from, int to, int from2, int to2, int type);
+
+ void restoreContextFromVector(const std::vector<float> &context_in);
+ void saveContextToVector(std::vector<float> *context_out);
+
+ float computeConditionalLogprob(
+ std::string current_word,
+ const std::vector<std::string> &history_words,
+ const std::vector<float> &context_in,
+ std::vector<float> *context_out);
+
+ void setUnkSym(const std::string &unk);
+ void setUnkPenalty(const std::string &filename);
+ float getUnkPenalty(const std::string &word);
+ bool isUnk(const std::string &word);
+};
+
+} // namespace rnnlm
+
+#endif // KALDI_LM_MIKOLOV_RNNLM_LIB_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/test_data/input.arpa b/runtime/onnxruntime/third_party/kaldi/lm/test_data/input.arpa
new file mode 100644
index 000000000..e4f9283a8
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/test_data/input.arpa
@@ -0,0 +1,21 @@
+
+\data\
+ngram 1=4
+ngram 2=2
+ngram 3=2
+
+\1-grams:
+-5.234679 a -3.3
+-3.456783 b
+0.0000000 <s> -2.5
+-4.333333 </s>
+
+\2-grams:
+-1.45678 a b -3.23
+-1.30490 <s> a -4.2
+
+\3-grams:
+-0.34958 <s> a b
+-0.23940 a b </s>
+
+\end\
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/test_data/missing_backoffs.arpa b/runtime/onnxruntime/third_party/kaldi/lm/test_data/missing_backoffs.arpa
new file mode 100644
index 000000000..30c0e3835
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/test_data/missing_backoffs.arpa
@@ -0,0 +1,20 @@
+
+\data\
+ngram 1=4
+ngram 2=1
+ngram 3=2
+
+\1-grams:
+-5.234679 a -3.3
+-3.456783 b
+0.0000000 <s> -2.5
+-4.333333 </s>
+
+\2-grams:
+-1.30490 <s> a -4.2
+
+\3-grams:
+-0.34958 <s> a b
+-0.23940 a b </s>
+
+\end\
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/test_data/missing_bos.arpa b/runtime/onnxruntime/third_party/kaldi/lm/test_data/missing_bos.arpa
new file mode 100644
index 000000000..487061a49
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/test_data/missing_bos.arpa
@@ -0,0 +1,18 @@
+
+\data\
+ngram 1=3
+ngram 2=1
+ngram 3=1
+
+\1-grams:
+-5.234679 a -3.3
+-3.456783 b -3.0
+-4.333333 </s>
+
+\2-grams:
+-1.45678 a b -3.23
+
+\3-grams:
+-0.23940 a b </s>
+
+\end\
diff --git a/runtime/onnxruntime/third_party/kaldi/lm/test_data/unused_backoffs.arpa b/runtime/onnxruntime/third_party/kaldi/lm/test_data/unused_backoffs.arpa
new file mode 100644
index 000000000..b66b98417
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lm/test_data/unused_backoffs.arpa
@@ -0,0 +1,26 @@
+
+\data\
+ngram 1=4
+ngram 2=2
+ngram 3=2
+ngram 4=2
+
+\1-grams:
+-5.234679 a -3.3
+-3.456783 b
+0.0000000 <s> -2.5
+-4.333333 </s>
+
+\2-grams:
+-1.45678 a b -3.23
+-1.30490 <s> a -4.2
+
+\3-grams:
+-0.34958 <s> a b
+-0.23940 a b </s>
+
+\4-grams:
+-0.01888 <s> a b b
+-0.03333 <s> b b b
+
+\end\
diff --git a/runtime/onnxruntime/third_party/kaldi/lmbin/Makefile b/runtime/onnxruntime/third_party/kaldi/lmbin/Makefile
new file mode 100644
index 000000000..1e8139109
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lmbin/Makefile
@@ -0,0 +1,16 @@
+
+all:
+
+EXTRA_CXXFLAGS = -Wno-sign-compare
+include ../kaldi.mk
+
+BINFILES = arpa2fst arpa-to-const-arpa
+
+OBJFILES =
+
+TESTFILES =
+
+ADDLIBS = ../lm/kaldi-lm.a ../util/kaldi-util.a ../matrix/kaldi-matrix.a \
+ ../base/kaldi-base.a
+
+include ../makefiles/default_rules.mk
diff --git a/runtime/onnxruntime/third_party/kaldi/lmbin/arpa-to-const-arpa.cc b/runtime/onnxruntime/third_party/kaldi/lmbin/arpa-to-const-arpa.cc
new file mode 100644
index 000000000..33d1cb70a
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lmbin/arpa-to-const-arpa.cc
@@ -0,0 +1,88 @@
+// lmbin/arpa-to-const-arpa.cc
+
+// Copyright 2014 Guoguo Chen
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABILITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include <string>
+
+#include "lm/const-arpa-lm.h"
+#include "util/parse-options.h"
+
+int main(int argc, char *argv[]) {
+ using namespace kaldi;
+ typedef kaldi::int32 int32;
+ try {
+ const char *usage =
+ "Converts an Arpa format language model into ConstArpaLm format,\n"
+ "which is an in-memory representation of the pre-built Arpa language\n"
+ "model. The output language model can then be read in by a program\n"
+ "that wants to rescore lattices. We assume that the words in the\n"
+ "input arpa language model has been converted to integers.\n"
+ "\n"
+ "The program is used jointly with utils/map_arpa_lm.pl to build\n"
+ "ConstArpaLm format language model. We first map the words in an Arpa\n"
+ "format language model to integers using utils/map_arpa_m.pl, and\n"
+ "then use this program to build a ConstArpaLm format language model.\n"
+ "\n"
+ "Usage: arpa-to-const-arpa [opts] <input-arpa> <const-arpa>\n"
+ " e.g.: arpa-to-const-arpa --bos-symbol=1 --eos-symbol=2 \\\n"
+ " arpa.txt const_arpa";
+
+ kaldi::ParseOptions po(usage);
+
+ ArpaParseOptions options;
+ options.Register(&po);
+
+ // Ideally, these registrations would be in ArpaParseOptions, but some
+ // programs want integers and other want symbols, so we register them
+ // outside instead.
+ po.Register("unk-symbol", &options.unk_symbol,
+ "Integer corresponds to unknown-word in language model. -1 if "
+ "no such word is provided.");
+ po.Register("bos-symbol", &options.bos_symbol,
+ "Integer corresponds to <s>. You must set this to your actual "
+ "BOS integer.");
+ po.Register("eos-symbol", &options.eos_symbol,
+ "Integer corresponds to </s>. You must set this to your actual "
+ "EOS integer.");
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() != 2) {
+ po.PrintUsage();
+ exit(1);
+ }
+
+ if (options.bos_symbol == -1 || options.eos_symbol == -1) {
+ KALDI_ERR << "Please set --bos-symbol and --eos-symbol.";
+ exit(1);
+ }
+
+ std::string arpa_rxfilename = po.GetArg(1),
+ const_arpa_wxfilename = po.GetOptArg(2);
+
+ bool ans = BuildConstArpaLm(options, arpa_rxfilename,
+ const_arpa_wxfilename);
+ if (ans)
+ return 0;
+ else
+ return 1;
+ } catch(const std::exception &e) {
+ std::cerr << e.what() << '\n';
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/lmbin/arpa2fst.cc b/runtime/onnxruntime/third_party/kaldi/lmbin/arpa2fst.cc
new file mode 100644
index 000000000..811e623ad
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/lmbin/arpa2fst.cc
@@ -0,0 +1,149 @@
+// bin/arpa2fst.cc
+//
+// Copyright 2009-2011 Gilles Boulianne.
+//
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABILITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include <string>
+
+#include "lm/arpa-lm-compiler.h"
+#include "util/kaldi-io.h"
+#include "util/parse-options.h"
+
+
+int main(int argc, char *argv[]) {
+ using namespace kaldi;
+ try {
+ const char *usage =
+ "Convert an ARPA format language model into an FST\n"
+ "Usage: arpa2fst [opts] <input-arpa> <output-fst>\n"
+ " e.g.: arpa2fst --disambig-symbol=#0 --read-symbol-table="
+ "data/lang/words.txt lm/input.arpa G.fst\n\n"
+ "Note: When called without switches, the output G.fst will contain\n"
+ "an embedded symbol table. This is compatible with the way a previous\n"
+ "version of arpa2fst worked.\n";
+
+ ParseOptions po(usage);
+
+ ArpaParseOptions options;
+ options.Register(&po);
+
+ // Option flags.
+ std::string bos_symbol = "<s>";
+ std::string eos_symbol = "</s>";
+ std::string disambig_symbol;
+ std::string read_syms_filename;
+ std::string write_syms_filename;
+ bool keep_symbols = false;
+ bool ilabel_sort = true;
+
+ po.Register("bos-symbol", &bos_symbol,
+ "Beginning of sentence symbol");
+ po.Register("eos-symbol", &eos_symbol,
+ "End of sentence symbol");
+ po.Register("disambig-symbol", &disambig_symbol,
+ "Disambiguator. If provided (e. g. #0), used on input side of "
+ "backoff links, and <s> and </s> are replaced with epsilons");
+ po.Register("read-symbol-table", &read_syms_filename,
+ "Use existing symbol table");
+ po.Register("write-symbol-table", &write_syms_filename,
+ "Write generated symbol table to a file");
+ po.Register("keep-symbols", &keep_symbols,
+ "Store symbol table with FST. Symbols always saved to FST if "
+ "symbol tables are neither read or written (otherwise symbols "
+ "would be lost entirely)");
+ po.Register("ilabel-sort", &ilabel_sort,
+ "Ilabel-sort the output FST");
+
+ po.Read(argc, argv);
+
+ if (po.NumArgs() != 1 && po.NumArgs() != 2) {
+ po.PrintUsage();
+ exit(1);
+ }
+ std::string arpa_rxfilename = po.GetArg(1),
+ fst_wxfilename = po.GetOptArg(2);
+
+ int64 disambig_symbol_id = 0;
+
+ fst::SymbolTable* symbols;
+ if (!read_syms_filename.empty()) {
+ // Use existing symbols. Required symbols must be in the table.
+ kaldi::Input kisym(read_syms_filename);
+ symbols = fst::SymbolTable::ReadText(
+ kisym.Stream(), PrintableWxfilename(read_syms_filename));
+ if (symbols == NULL)
+ KALDI_ERR << "Could not read symbol table from file "
+ << read_syms_filename;
+
+ options.oov_handling = ArpaParseOptions::kSkipNGram;
+ if (!disambig_symbol.empty()) {
+ disambig_symbol_id = symbols->Find(disambig_symbol);
+ if (disambig_symbol_id == -1) // fst::kNoSymbol
+ KALDI_ERR << "Symbol table " << read_syms_filename
+ << " has no symbol for " << disambig_symbol;
+ }
+ } else {
+ // Create a new symbol table and populate it from ARPA file.
+ symbols = new fst::SymbolTable(PrintableWxfilename(fst_wxfilename));
+ options.oov_handling = ArpaParseOptions::kAddToSymbols;
+ symbols->AddSymbol("<eps>", 0);
+ if (!disambig_symbol.empty()) {
+ disambig_symbol_id = symbols->AddSymbol(disambig_symbol);
+ }
+ }
+
+ // Add or use existing BOS and EOS.
+ options.bos_symbol = symbols->AddSymbol(bos_symbol);
+ options.eos_symbol = symbols->AddSymbol(eos_symbol);
+
+ // If producing new (not reading existing) symbols and not saving them,
+ // need to keep symbols with FST, otherwise they would be lost.
+ if (read_syms_filename.empty() && write_syms_filename.empty())
+ keep_symbols = true;
+
+ // Actually compile LM.
+ KALDI_ASSERT (symbols != NULL);
+ ArpaLmCompiler lm_compiler(options, disambig_symbol_id, symbols);
+ {
+ Input ki(arpa_rxfilename);
+ lm_compiler.Read(ki.Stream());
+ }
+
+ // Sort the FST in-place if requested by options.
+ if (ilabel_sort) {
+ fst::ArcSort(lm_compiler.MutableFst(), fst::StdILabelCompare());
+ }
+
+ // Write symbols if requested.
+ if (!write_syms_filename.empty()) {
+ kaldi::Output kosym(write_syms_filename, false);
+ symbols->WriteText(kosym.Stream());
+ }
+
+ // Write LM FST.
+ bool write_binary = true, write_header = false;
+ kaldi::Output kofst(fst_wxfilename, write_binary, write_header);
+ fst::FstWriteOptions wopts(PrintableWxfilename(fst_wxfilename));
+ wopts.write_isymbols = wopts.write_osymbols = keep_symbols;
+ lm_compiler.Fst().Write(kofst.Stream(), wopts);
+
+ delete symbols;
+ } catch(const std::exception &e) {
+ std::cerr << e.what();
+ return -1;
+ }
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/util/Makefile b/runtime/onnxruntime/third_party/kaldi/util/Makefile
new file mode 100644
index 000000000..acfab8b8d
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/Makefile
@@ -0,0 +1,20 @@
+
+
+all:
+
+
+include ../kaldi.mk
+
+TESTFILES = const-integer-set-test stl-utils-test text-utils-test \
+ edit-distance-test hash-list-test kaldi-io-test parse-options-test \
+ kaldi-table-test simple-options-test kaldi-thread-test
+
+OBJFILES = text-utils.o kaldi-io.o kaldi-holder.o kaldi-table.o \
+ parse-options.o simple-options.o simple-io-funcs.o \
+ kaldi-semaphore.o kaldi-thread.o
+
+LIBNAME = kaldi-util
+
+ADDLIBS = ../matrix/kaldi-matrix.a ../base/kaldi-base.a
+
+include ../makefiles/default_rules.mk
diff --git a/runtime/onnxruntime/third_party/kaldi/util/basic-filebuf.h b/runtime/onnxruntime/third_party/kaldi/util/basic-filebuf.h
new file mode 100644
index 000000000..51cf12f40
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/basic-filebuf.h
@@ -0,0 +1,994 @@
+///////////////////////////////////////////////////////////////////////////////
+// This is a modified version of the std::basic_filebuf from libc++
+// (http://libcxx.llvm.org/).
+// It allows one to create basic_filebuf from an existing FILE* handle or file
+// descriptor.
+//
+// This file is dual licensed under the MIT and the University of Illinois Open
+// Source License licenses. See LICENSE.TXT for details (included at the
+// bottom).
+///////////////////////////////////////////////////////////////////////////////
+#ifndef KALDI_UTIL_BASIC_FILEBUF_H_
+#define KALDI_UTIL_BASIC_FILEBUF_H_
+
+///////////////////////////////////////////////////////////////////////////////
+#include <fstream>
+#include <cstdio>
+#include <cstring>
+#include <string>
+#include <algorithm>
+
+///////////////////////////////////////////////////////////////////////////////
+namespace kaldi {
+///////////////////////////////////////////////////////////////////////////////
+template <typename CharT, typename Traits = std::char_traits<CharT> >
+class basic_filebuf : public std::basic_streambuf<CharT, Traits> {
+ public:
+ typedef CharT char_type;
+ typedef Traits traits_type;
+ typedef typename traits_type::int_type int_type;
+ typedef typename traits_type::pos_type pos_type;
+ typedef typename traits_type::off_type off_type;
+ typedef typename traits_type::state_type state_type;
+
+ basic_filebuf();
+ basic_filebuf(basic_filebuf&& rhs);
+ virtual ~basic_filebuf();
+
+ basic_filebuf& operator=(basic_filebuf&& rhs);
+ void swap(basic_filebuf& rhs);
+
+ bool is_open() const;
+ basic_filebuf* open(const char* s, std::ios_base::openmode mode);
+ basic_filebuf* open(const std::string& s, std::ios_base::openmode mode);
+ basic_filebuf* open(int fd, std::ios_base::openmode mode);
+ basic_filebuf* open(FILE* f, std::ios_base::openmode mode);
+ basic_filebuf* close();
+
+ FILE* file() { return this->_M_file; }
+ int fd() { return fileno(this->_M_file); }
+
+ protected:
+ int_type underflow() override;
+ int_type pbackfail(int_type c = traits_type::eof()) override;
+ int_type overflow(int_type c = traits_type::eof()) override;
+ std::basic_streambuf<char_type, traits_type>*
+ setbuf(char_type* s, std::streamsize n) override;
+ pos_type seekoff(off_type off, std::ios_base::seekdir way,
+ std::ios_base::openmode wch =
+ std::ios_base::in | std::ios_base::out) override;
+ pos_type seekpos(pos_type sp,
+ std::ios_base::openmode wch =
+ std::ios_base::in | std::ios_base::out) override;
+ int sync() override;
+ void imbue(const std::locale& loc) override;
+
+ protected:
+ char* _M_extbuf;
+ const char* _M_extbufnext;
+ const char* _M_extbufend;
+ char _M_extbuf_min[8];
+ size_t _M_ebs;
+ char_type* _M_intbuf;
+ size_t _M_ibs;
+ FILE* _M_file;
+ const std::codecvt<char_type, char, state_type>* _M_cv;
+ state_type _M_st;
+ state_type _M_st_last;
+ std::ios_base::openmode _M_om;
+ std::ios_base::openmode _M_cm;
+ bool _M_owns_eb;
+ bool _M_owns_ib;
+ bool _M_always_noconv;
+
+ const char* _M_get_mode(std::ios_base::openmode mode);
+ bool _M_read_mode();
+ void _M_write_mode();
+};
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+basic_filebuf<CharT, Traits>::basic_filebuf()
+ : _M_extbuf(nullptr),
+ _M_extbufnext(nullptr),
+ _M_extbufend(nullptr),
+ _M_ebs(0),
+ _M_intbuf(nullptr),
+ _M_ibs(0),
+ _M_file(nullptr),
+ _M_cv(nullptr),
+ _M_st(),
+ _M_st_last(),
+ _M_om(std::ios_base::openmode(0)),
+ _M_cm(std::ios_base::openmode(0)),
+ _M_owns_eb(false),
+ _M_owns_ib(false),
+ _M_always_noconv(false) {
+ if (std::has_facet<std::codecvt<char_type, char, state_type> >
+ (this->getloc())) {
+ _M_cv = &std::use_facet<std::codecvt<char_type, char, state_type> >
+ (this->getloc());
+ _M_always_noconv = _M_cv->always_noconv();
+ }
+ setbuf(0, 4096);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+basic_filebuf<CharT, Traits>::basic_filebuf(basic_filebuf&& rhs)
+ : std::basic_streambuf<CharT, Traits>(rhs) {
+ if (rhs._M_extbuf == rhs._M_extbuf_min) {
+ _M_extbuf = _M_extbuf_min;
+ _M_extbufnext = _M_extbuf + (rhs._M_extbufnext - rhs._M_extbuf);
+ _M_extbufend = _M_extbuf + (rhs._M_extbufend - rhs._M_extbuf);
+ } else {
+ _M_extbuf = rhs._M_extbuf;
+ _M_extbufnext = rhs._M_extbufnext;
+ _M_extbufend = rhs._M_extbufend;
+ }
+ _M_ebs = rhs._M_ebs;
+ _M_intbuf = rhs._M_intbuf;
+ _M_ibs = rhs._M_ibs;
+ _M_file = rhs._M_file;
+ _M_cv = rhs._M_cv;
+ _M_st = rhs._M_st;
+ _M_st_last = rhs._M_st_last;
+ _M_om = rhs._M_om;
+ _M_cm = rhs._M_cm;
+ _M_owns_eb = rhs._M_owns_eb;
+ _M_owns_ib = rhs._M_owns_ib;
+ _M_always_noconv = rhs._M_always_noconv;
+ if (rhs.pbase()) {
+ if (rhs.pbase() == rhs._M_intbuf)
+ this->setp(_M_intbuf, _M_intbuf + (rhs. epptr() - rhs.pbase()));
+ else
+ this->setp(reinterpret_cast<char_type*>(_M_extbuf),
+ reinterpret_cast<char_type*>(_M_extbuf)
+ + (rhs. epptr() - rhs.pbase()));
+ this->pbump(rhs. pptr() - rhs.pbase());
+ } else if (rhs.eback()) {
+ if (rhs.eback() == rhs._M_intbuf)
+ this->setg(_M_intbuf, _M_intbuf + (rhs.gptr() - rhs.eback()),
+ _M_intbuf + (rhs.egptr() - rhs.eback()));
+ else
+ this->setg(reinterpret_cast<char_type*>(_M_extbuf),
+ reinterpret_cast<char_type*>(_M_extbuf) +
+ (rhs.gptr() - rhs.eback()),
+ reinterpret_cast<char_type*>(_M_extbuf) +
+ (rhs.egptr() - rhs.eback()));
+ }
+ rhs._M_extbuf = nullptr;
+ rhs._M_extbufnext = nullptr;
+ rhs._M_extbufend = nullptr;
+ rhs._M_ebs = 0;
+ rhs._M_intbuf = nullptr;
+ rhs._M_ibs = 0;
+ rhs._M_file = nullptr;
+ rhs._M_st = state_type();
+ rhs._M_st_last = state_type();
+ rhs._M_om = std::ios_base::openmode(0);
+ rhs._M_cm = std::ios_base::openmode(0);
+ rhs._M_owns_eb = false;
+ rhs._M_owns_ib = false;
+ rhs.setg(0, 0, 0);
+ rhs.setp(0, 0);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+inline
+basic_filebuf<CharT, Traits>&
+basic_filebuf<CharT, Traits>::operator=(basic_filebuf&& rhs) {
+ close();
+ swap(rhs);
+ return *this;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+basic_filebuf<CharT, Traits>::~basic_filebuf() {
+ // try
+ // {
+ // close();
+ // }
+ // catch (...)
+ // {
+ // }
+ if (_M_owns_eb)
+ delete [] _M_extbuf;
+ if (_M_owns_ib)
+ delete [] _M_intbuf;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+void
+basic_filebuf<CharT, Traits>::swap(basic_filebuf& rhs) {
+ std::basic_streambuf<char_type, traits_type>::swap(rhs);
+ if (_M_extbuf != _M_extbuf_min && rhs._M_extbuf != rhs._M_extbuf_min) {
+ std::swap(_M_extbuf, rhs._M_extbuf);
+ std::swap(_M_extbufnext, rhs._M_extbufnext);
+ std::swap(_M_extbufend, rhs._M_extbufend);
+ } else {
+ ptrdiff_t ln = _M_extbufnext - _M_extbuf;
+ ptrdiff_t le = _M_extbufend - _M_extbuf;
+ ptrdiff_t rn = rhs._M_extbufnext - rhs._M_extbuf;
+ ptrdiff_t re = rhs._M_extbufend - rhs._M_extbuf;
+ if (_M_extbuf == _M_extbuf_min && rhs._M_extbuf != rhs._M_extbuf_min) {
+ _M_extbuf = rhs._M_extbuf;
+ rhs._M_extbuf = rhs._M_extbuf_min;
+ } else if (_M_extbuf != _M_extbuf_min &&
+ rhs._M_extbuf == rhs._M_extbuf_min) {
+ rhs._M_extbuf = _M_extbuf;
+ _M_extbuf = _M_extbuf_min;
+ }
+ _M_extbufnext = _M_extbuf + rn;
+ _M_extbufend = _M_extbuf + re;
+ rhs._M_extbufnext = rhs._M_extbuf + ln;
+ rhs._M_extbufend = rhs._M_extbuf + le;
+ }
+ std::swap(_M_ebs, rhs._M_ebs);
+ std::swap(_M_intbuf, rhs._M_intbuf);
+ std::swap(_M_ibs, rhs._M_ibs);
+ std::swap(_M_file, rhs._M_file);
+ std::swap(_M_cv, rhs._M_cv);
+ std::swap(_M_st, rhs._M_st);
+ std::swap(_M_st_last, rhs._M_st_last);
+ std::swap(_M_om, rhs._M_om);
+ std::swap(_M_cm, rhs._M_cm);
+ std::swap(_M_owns_eb, rhs._M_owns_eb);
+ std::swap(_M_owns_ib, rhs._M_owns_ib);
+ std::swap(_M_always_noconv, rhs._M_always_noconv);
+ if (this->eback() == reinterpret_cast<char_type*>(rhs._M_extbuf_min)) {
+ ptrdiff_t n = this->gptr() - this->eback();
+ ptrdiff_t e = this->egptr() - this->eback();
+ this->setg(reinterpret_cast<char_type*>(_M_extbuf_min),
+ reinterpret_cast<char_type*>(_M_extbuf_min) + n,
+ reinterpret_cast<char_type*>(_M_extbuf_min) + e);
+ } else if (this->pbase() ==
+ reinterpret_cast<char_type*>(rhs._M_extbuf_min)) {
+ ptrdiff_t n = this->pptr() - this->pbase();
+ ptrdiff_t e = this->epptr() - this->pbase();
+ this->setp(reinterpret_cast<char_type*>(_M_extbuf_min),
+ reinterpret_cast<char_type*>(_M_extbuf_min) + e);
+ this->pbump(n);
+ }
+ if (rhs.eback() == reinterpret_cast<char_type*>(_M_extbuf_min)) {
+ ptrdiff_t n = rhs.gptr() - rhs.eback();
+ ptrdiff_t e = rhs.egptr() - rhs.eback();
+ rhs.setg(reinterpret_cast<char_type*>(rhs._M_extbuf_min),
+ reinterpret_cast<char_type*>(rhs._M_extbuf_min) + n,
+ reinterpret_cast<char_type*>(rhs._M_extbuf_min) + e);
+ } else if (rhs.pbase() == reinterpret_cast<char_type*>(_M_extbuf_min)) {
+ ptrdiff_t n = rhs.pptr() - rhs.pbase();
+ ptrdiff_t e = rhs.epptr() - rhs.pbase();
+ rhs.setp(reinterpret_cast<char_type*>(rhs._M_extbuf_min),
+ reinterpret_cast<char_type*>(rhs._M_extbuf_min) + e);
+ rhs.pbump(n);
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+inline
+void
+swap(basic_filebuf<CharT, Traits>& x, basic_filebuf<CharT, Traits>& y) {
+ x.swap(y);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+inline
+bool
+basic_filebuf<CharT, Traits>::is_open() const {
+ return _M_file != nullptr;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+const char* basic_filebuf<CharT, Traits>::
+_M_get_mode(std::ios_base::openmode mode) {
+ switch ((mode & ~std::ios_base::ate) | 0) {
+ case std::ios_base::out:
+ case std::ios_base::out | std::ios_base::trunc:
+ return "w";
+ case std::ios_base::out | std::ios_base::app:
+ case std::ios_base::app:
+ return "a";
+ break;
+ case std::ios_base::in:
+ return "r";
+ case std::ios_base::in | std::ios_base::out:
+ return "r+";
+ case std::ios_base::in | std::ios_base::out | std::ios_base::trunc:
+ return "w+";
+ case std::ios_base::in | std::ios_base::out | std::ios_base::app:
+ case std::ios_base::in | std::ios_base::app:
+ return "a+";
+ case std::ios_base::out | std::ios_base::binary:
+ case std::ios_base::out | std::ios_base::trunc | std::ios_base::binary:
+ return "wb";
+ case std::ios_base::out | std::ios_base::app | std::ios_base::binary:
+ case std::ios_base::app | std::ios_base::binary:
+ return "ab";
+ case std::ios_base::in | std::ios_base::binary:
+ return "rb";
+ case std::ios_base::in | std::ios_base::out | std::ios_base::binary:
+ return "r+b";
+ case std::ios_base::in | std::ios_base::out | std::ios_base::trunc |
+ std::ios_base::binary:
+ return "w+b";
+ case std::ios_base::in | std::ios_base::out | std::ios_base::app |
+ std::ios_base::binary:
+ case std::ios_base::in | std::ios_base::app | std::ios_base::binary:
+ return "a+b";
+ default:
+ return nullptr;
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+basic_filebuf<CharT, Traits>*
+basic_filebuf<CharT, Traits>::
+open(const char* s, std::ios_base::openmode mode) {
+ basic_filebuf<CharT, Traits>* rt = nullptr;
+ if (_M_file == nullptr) {
+ const char* md= _M_get_mode(mode);
+ if (md) {
+ _M_file = fopen(s, md);
+ if (_M_file) {
+ rt = this;
+ _M_om = mode;
+ if (mode & std::ios_base::ate) {
+ if (fseek(_M_file, 0, SEEK_END)) {
+ fclose(_M_file);
+ _M_file = nullptr;
+ rt = nullptr;
+ }
+ }
+ }
+ }
+ }
+ return rt;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+inline
+basic_filebuf<CharT, Traits>*
+basic_filebuf<CharT, Traits>::open(const std::string& s,
+ std::ios_base::openmode mode) {
+ return open(s.c_str(), mode);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+basic_filebuf<CharT, Traits>*
+basic_filebuf<CharT, Traits>::open(int fd, std::ios_base::openmode mode) {
+ const char* md= this->_M_get_mode(mode);
+ if (md) {
+ this->_M_file= fdopen(fd, md);
+ this->_M_om = mode;
+ return this;
+ } else {
+ return nullptr;
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+basic_filebuf<CharT, Traits>*
+basic_filebuf<CharT, Traits>::open(FILE* f, std::ios_base::openmode mode) {
+ this->_M_file = f;
+ this->_M_om = mode;
+ return this;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+basic_filebuf<CharT, Traits>*
+basic_filebuf<CharT, Traits>::close() {
+ basic_filebuf<CharT, Traits>* rt = nullptr;
+ if (_M_file) {
+ rt = this;
+ std::unique_ptr<FILE, int(*)(FILE*)> h(_M_file, fclose);
+ if (sync())
+ rt = nullptr;
+ if (fclose(h.release()) == 0)
+ _M_file = nullptr;
+ else
+ rt = nullptr;
+ }
+ return rt;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+typename basic_filebuf<CharT, Traits>::int_type
+basic_filebuf<CharT, Traits>::underflow() {
+ if (_M_file == nullptr)
+ return traits_type::eof();
+ bool initial = _M_read_mode();
+ char_type buf;
+ if (this->gptr() == nullptr)
+ this->setg(&buf, &buf+1, &buf+1);
+ const size_t unget_sz = initial ? 0 : std::
+ min<size_t>((this->egptr() - this->eback()) / 2, 4);
+ int_type c = traits_type::eof();
+ if (this->gptr() == this->egptr()) {
+ memmove(this->eback(), this->egptr() - unget_sz,
+ unget_sz * sizeof(char_type));
+ if (_M_always_noconv) {
+ size_t nmemb = static_cast<size_t>
+ (this->egptr() - this->eback() - unget_sz);
+ nmemb = fread(this->eback() + unget_sz, 1, nmemb, _M_file);
+ if (nmemb != 0) {
+ this->setg(this->eback(),
+ this->eback() + unget_sz,
+ this->eback() + unget_sz + nmemb);
+ c = traits_type::to_int_type(*this->gptr());
+ }
+ } else {
+ memmove(_M_extbuf, _M_extbufnext, _M_extbufend - _M_extbufnext);
+ _M_extbufnext = _M_extbuf + (_M_extbufend - _M_extbufnext);
+ _M_extbufend = _M_extbuf +
+ (_M_extbuf == _M_extbuf_min ? sizeof(_M_extbuf_min) : _M_ebs);
+ size_t nmemb = std::min(static_cast<size_t>(_M_ibs - unget_sz),
+ static_cast<size_t>
+ (_M_extbufend - _M_extbufnext));
+ std::codecvt_base::result r;
+ _M_st_last = _M_st;
+ size_t nr = fread(
+ reinterpret_cast<void*>(const_cast<char_type*>(_M_extbufnext)),
+ 1, nmemb, _M_file);
+ if (nr != 0) {
+ if (!_M_cv)
+ throw std::bad_cast();
+ _M_extbufend = _M_extbufnext + nr;
+ char_type* inext;
+ r = _M_cv->in(_M_st, _M_extbuf, _M_extbufend, _M_extbufnext,
+ this->eback() + unget_sz,
+ this->eback() + _M_ibs, inext);
+ if (r == std::codecvt_base::noconv) {
+ this->setg(reinterpret_cast<char_type*>(_M_extbuf),
+ reinterpret_cast<char_type*>(_M_extbuf),
+ const_cast<char_type*>(_M_extbufend));
+ c = traits_type::to_int_type(*this->gptr());
+ } else if (inext != this->eback() + unget_sz) {
+ this->setg(this->eback(), this->eback() + unget_sz, inext);
+ c = traits_type::to_int_type(*this->gptr());
+ }
+ }
+ }
+ } else {
+ c = traits_type::to_int_type(*this->gptr());
+ }
+ if (this->eback() == &buf)
+ this->setg(0, 0, 0);
+ return c;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+typename basic_filebuf<CharT, Traits>::int_type
+basic_filebuf<CharT, Traits>::pbackfail(int_type c) {
+ if (_M_file && this->eback() < this->gptr()) {
+ if (traits_type::eq_int_type(c, traits_type::eof())) {
+ this->gbump(-1);
+ return traits_type::not_eof(c);
+ }
+ if ((_M_om & std::ios_base::out) ||
+ traits_type::eq(traits_type::to_char_type(c), this->gptr()[-1])) {
+ this->gbump(-1);
+ *this->gptr() = traits_type::to_char_type(c);
+ return c;
+ }
+ }
+ return traits_type::eof();
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+typename basic_filebuf<CharT, Traits>::int_type
+basic_filebuf<CharT, Traits>::overflow(int_type c) {
+ if (_M_file == nullptr)
+ return traits_type::eof();
+ _M_write_mode();
+ char_type buf;
+ char_type* pb_save = this->pbase();
+ char_type* epb_save = this->epptr();
+ if (!traits_type::eq_int_type(c, traits_type::eof())) {
+ if (this->pptr() == nullptr)
+ this->setp(&buf, &buf+1);
+ *this->pptr() = traits_type::to_char_type(c);
+ this->pbump(1);
+ }
+ if (this->pptr() != this->pbase()) {
+ if (_M_always_noconv) {
+ size_t nmemb = static_cast<size_t>(this->pptr() - this->pbase());
+ if (fwrite(this->pbase(), sizeof(char_type),
+ nmemb, _M_file) != nmemb)
+ return traits_type::eof();
+ } else {
+ char* extbe = _M_extbuf;
+ std::codecvt_base::result r;
+ do {
+ if (!_M_cv)
+ throw std::bad_cast();
+ const char_type* e;
+ r = _M_cv->out(_M_st, this->pbase(), this->pptr(), e,
+ _M_extbuf, _M_extbuf + _M_ebs, extbe);
+ if (e == this->pbase())
+ return traits_type::eof();
+ if (r == std::codecvt_base::noconv) {
+ size_t nmemb = static_cast<size_t>
+ (this->pptr() - this->pbase());
+ if (fwrite(this->pbase(), 1, nmemb, _M_file) != nmemb)
+ return traits_type::eof();
+ } else if (r == std::codecvt_base::ok ||
+ r == std::codecvt_base::partial) {
+ size_t nmemb = static_cast<size_t>(extbe - _M_extbuf);
+ if (fwrite(_M_extbuf, 1, nmemb, _M_file) != nmemb)
+ return traits_type::eof();
+ if (r == std::codecvt_base::partial) {
+ this->setp(const_cast<char_type*>(e),
+ this->pptr());
+ this->pbump(this->epptr() - this->pbase());
+ }
+ } else {
+ return traits_type::eof();
+ }
+ } while (r == std::codecvt_base::partial);
+ }
+ this->setp(pb_save, epb_save);
+ }
+ return traits_type::not_eof(c);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+std::basic_streambuf<CharT, Traits>*
+basic_filebuf<CharT, Traits>::setbuf(char_type* s, std::streamsize n) {
+ this->setg(0, 0, 0);
+ this->setp(0, 0);
+ if (_M_owns_eb)
+ delete [] _M_extbuf;
+ if (_M_owns_ib)
+ delete [] _M_intbuf;
+ _M_ebs = n;
+ if (_M_ebs > sizeof(_M_extbuf_min)) {
+ if (_M_always_noconv && s) {
+ _M_extbuf = reinterpret_cast<char*>(s);
+ _M_owns_eb = false;
+ } else {
+ _M_extbuf = new char[_M_ebs];
+ _M_owns_eb = true;
+ }
+ } else {
+ _M_extbuf = _M_extbuf_min;
+ _M_ebs = sizeof(_M_extbuf_min);
+ _M_owns_eb = false;
+ }
+ if (!_M_always_noconv) {
+ _M_ibs = std::max<std::streamsize>(n, sizeof(_M_extbuf_min));
+ if (s && _M_ibs >= sizeof(_M_extbuf_min)) {
+ _M_intbuf = s;
+ _M_owns_ib = false;
+ } else {
+ _M_intbuf = new char_type[_M_ibs];
+ _M_owns_ib = true;
+ }
+ } else {
+ _M_ibs = 0;
+ _M_intbuf = 0;
+ _M_owns_ib = false;
+ }
+ return this;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+typename basic_filebuf<CharT, Traits>::pos_type
+basic_filebuf<CharT, Traits>::seekoff(off_type off, std::ios_base::seekdir way,
+ std::ios_base::openmode) {
+ if (!_M_cv)
+ throw std::bad_cast();
+ int width = _M_cv->encoding();
+ if (_M_file == nullptr || (width <= 0 && off != 0) || sync())
+ return pos_type(off_type(-1));
+ // width > 0 || off == 0
+ int whence;
+ switch (way) {
+ case std::ios_base::beg:
+ whence = SEEK_SET;
+ break;
+ case std::ios_base::cur:
+ whence = SEEK_CUR;
+ break;
+ case std::ios_base::end:
+ whence = SEEK_END;
+ break;
+ default:
+ return pos_type(off_type(-1));
+ }
+#if _WIN32
+ if (fseek(_M_file, width > 0 ? width * off : 0, whence))
+ return pos_type(off_type(-1));
+ pos_type r = ftell(_M_file);
+#else
+ if (fseeko(_M_file, width > 0 ? width * off : 0, whence))
+ return pos_type(off_type(-1));
+ pos_type r = ftello(_M_file);
+#endif
+ r.state(_M_st);
+ return r;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+typename basic_filebuf<CharT, Traits>::pos_type
+basic_filebuf<CharT, Traits>::seekpos(pos_type sp, std::ios_base::openmode) {
+ if (_M_file == nullptr || sync())
+ return pos_type(off_type(-1));
+#if _WIN32
+ if (fseek(_M_file, sp, SEEK_SET))
+ return pos_type(off_type(-1));
+#else
+ if (fseeko(_M_file, sp, SEEK_SET))
+ return pos_type(off_type(-1));
+#endif
+ _M_st = sp.state();
+ return sp;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+int
+basic_filebuf<CharT, Traits>::sync() {
+ if (_M_file == nullptr)
+ return 0;
+ if (!_M_cv)
+ throw std::bad_cast();
+ if (_M_cm & std::ios_base::out) {
+ if (this->pptr() != this->pbase())
+ if (overflow() == traits_type::eof())
+ return -1;
+ std::codecvt_base::result r;
+ do {
+ char* extbe;
+ r = _M_cv->unshift(_M_st, _M_extbuf, _M_extbuf + _M_ebs, extbe);
+ size_t nmemb = static_cast<size_t>(extbe - _M_extbuf);
+ if (fwrite(_M_extbuf, 1, nmemb, _M_file) != nmemb)
+ return -1;
+ } while (r == std::codecvt_base::partial);
+ if (r == std::codecvt_base::error)
+ return -1;
+ if (fflush(_M_file))
+ return -1;
+ } else if (_M_cm & std::ios_base::in) {
+ off_type c;
+ state_type state = _M_st_last;
+ bool update_st = false;
+ if (_M_always_noconv) {
+ c = this->egptr() - this->gptr();
+ } else {
+ int width = _M_cv->encoding();
+ c = _M_extbufend - _M_extbufnext;
+ if (width > 0) {
+ c += width * (this->egptr() - this->gptr());
+ } else {
+ if (this->gptr() != this->egptr()) {
+ const int off = _M_cv->length(state, _M_extbuf,
+ _M_extbufnext,
+ this->gptr() - this->eback());
+ c += _M_extbufnext - _M_extbuf - off;
+ update_st = true;
+ }
+ }
+ }
+#if _WIN32
+ if (fseek(_M_file_, -c, SEEK_CUR))
+ return -1;
+#else
+ if (fseeko(_M_file, -c, SEEK_CUR))
+ return -1;
+#endif
+ if (update_st)
+ _M_st = state;
+ _M_extbufnext = _M_extbufend = _M_extbuf;
+ this->setg(0, 0, 0);
+ _M_cm = std::ios_base::openmode(0);
+ }
+ return 0;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+void
+basic_filebuf<CharT, Traits>::imbue(const std::locale& loc) {
+ sync();
+ _M_cv = &std::use_facet<std::codecvt<char_type, char, state_type> >(loc);
+ bool old_anc = _M_always_noconv;
+ _M_always_noconv = _M_cv->always_noconv();
+ if (old_anc != _M_always_noconv) {
+ this->setg(0, 0, 0);
+ this->setp(0, 0);
+ // invariant, char_type is char, else we couldn't get here
+ // need to dump _M_intbuf
+ if (_M_always_noconv) {
+ if (_M_owns_eb)
+ delete [] _M_extbuf;
+ _M_owns_eb = _M_owns_ib;
+ _M_ebs = _M_ibs;
+ _M_extbuf = reinterpret_cast<char*>(_M_intbuf);
+ _M_ibs = 0;
+ _M_intbuf = nullptr;
+ _M_owns_ib = false;
+ } else { // need to obtain an _M_intbuf.
+ // If _M_extbuf is user-supplied, use it, else new _M_intbuf
+ if (!_M_owns_eb && _M_extbuf != _M_extbuf_min) {
+ _M_ibs = _M_ebs;
+ _M_intbuf = reinterpret_cast<char_type*>(_M_extbuf);
+ _M_owns_ib = false;
+ _M_extbuf = new char[_M_ebs];
+ _M_owns_eb = true;
+ } else {
+ _M_ibs = _M_ebs;
+ _M_intbuf = new char_type[_M_ibs];
+ _M_owns_ib = true;
+ }
+ }
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+bool
+basic_filebuf<CharT, Traits>::_M_read_mode() {
+ if (!(_M_cm & std::ios_base::in)) {
+ this->setp(0, 0);
+ if (_M_always_noconv)
+ this->setg(reinterpret_cast<char_type*>(_M_extbuf),
+ reinterpret_cast<char_type*>(_M_extbuf) + _M_ebs,
+ reinterpret_cast<char_type*>(_M_extbuf) + _M_ebs);
+ else
+ this->setg(_M_intbuf, _M_intbuf + _M_ibs, _M_intbuf + _M_ibs);
+ _M_cm = std::ios_base::in;
+ return true;
+ }
+ return false;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+template <class CharT, class Traits>
+void
+basic_filebuf<CharT, Traits>::_M_write_mode() {
+ if (!(_M_cm & std::ios_base::out)) {
+ this->setg(0, 0, 0);
+ if (_M_ebs > sizeof(_M_extbuf_min)) {
+ if (_M_always_noconv)
+ this->setp(reinterpret_cast<char_type*>(_M_extbuf),
+ reinterpret_cast<char_type*>(_M_extbuf) +
+ (_M_ebs - 1));
+ else
+ this->setp(_M_intbuf, _M_intbuf + (_M_ibs - 1));
+ } else {
+ this->setp(0, 0);
+ }
+ _M_cm = std::ios_base::out;
+ }
+}
+
+///////////////////////////////////////////////////////////////////////////////
+}
+
+///////////////////////////////////////////////////////////////////////////////
+#endif // KALDI_UTIL_BASIC_FILEBUF_H_
+
+///////////////////////////////////////////////////////////////////////////////
+
+/*
+ * ============================================================================
+ * libc++ License
+ * ============================================================================
+ *
+ * The libc++ library is dual licensed under both the University of Illinois
+ * "BSD-Like" license and the MIT license. As a user of this code you may
+ * choose to use it under either license. As a contributor, you agree to allow
+ * your code to be used under both.
+ *
+ * Full text of the relevant licenses is included below.
+ *
+ * ============================================================================
+ *
+ * University of Illinois/NCSA
+ * Open Source License
+ *
+ * Copyright (c) 2009-2014 by the contributors listed in CREDITS.TXT (included below)
+ *
+ * All rights reserved.
+ *
+ * Developed by:
+ *
+ * LLVM Team
+ *
+ * University of Illinois at Urbana-Champaign
+ *
+ * http://llvm.org
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the "Software"), to deal with
+ * the Software without restriction, including without limitation the rights to
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is furnished to do
+ * so, subject to the following conditions:
+ *
+ * * Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimers.
+ *
+ * * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimers in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * * Neither the names of the LLVM Team, University of Illinois at
+ * Urbana-Champaign, nor the names of its contributors may be used to
+ * endorse or promote products derived from this Software without specific
+ * prior written permission.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+ * SOFTWARE.
+ *
+ * ==============================================================================
+ *
+ * Copyright (c) 2009-2014 by the contributors listed in CREDITS.TXT (included below)
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * ==============================================================================
+ *
+ * This file is a partial list of people who have contributed to the LLVM/libc++
+ * project. If you have contributed a patch or made some other contribution to
+ * LLVM/libc++, please submit a patch to this file to add yourself, and it will be
+ * done!
+ *
+ * The list is sorted by surname and formatted to allow easy grepping and
+ * beautification by scripts. The fields are: name (N), email (E), web-address
+ * (W), PGP key ID and fingerprint (P), description (D), and snail-mail address
+ * (S).
+ *
+ * N: Saleem Abdulrasool
+ * D: Minor patches and Linux fixes.
+ *
+ * N: Dimitry Andric
+ * D: Visibility fixes, minor FreeBSD portability patches.
+ *
+ * N: Holger Arnold
+ * D: Minor fix.
+ *
+ * N: Ruben Van Boxem
+ * E: vanboxem dot ruben at gmail dot com
+ * D: Initial Windows patches.
+ *
+ * N: David Chisnall
+ * E: theraven at theravensnest dot org
+ * D: FreeBSD and Solaris ports, libcxxrt support, some atomics work.
+ *
+ * N: Marshall Clow
+ * D: C++14 support, patches and bug fixes.
+ *
+ * N: Bill Fisher
+ * D: Regex bug fixes.
+ *
+ * N: Matthew Dempsky
+ * D: Minor patches and bug fixes.
+ *
+ * N: Google Inc.
+ * D: Copyright owner and contributor of the CityHash algorithm
+ *
+ * N: Howard Hinnant
+ * D: Architect and primary author of libc++
+ *
+ * N: Hyeon-bin Jeong
+ * D: Minor patches and bug fixes.
+ *
+ * N: Argyrios Kyrtzidis
+ * D: Bug fixes.
+ *
+ * N: Bruce Mitchener, Jr.
+ * D: Emscripten-related changes.
+ *
+ * N: Michel Morin
+ * D: Minor patches to is_convertible.
+ *
+ * N: Andrew Morrow
+ * D: Minor patches and Linux fixes.
+ *
+ * N: Arvid Picciani
+ * E: aep at exys dot org
+ * D: Minor patches and musl port.
+ *
+ * N: Bjorn Reese
+ * D: Initial regex prototype
+ *
+ * N: Nico Rieck
+ * D: Windows fixes
+ *
+ * N: Jonathan Sauer
+ * D: Minor patches, mostly related to constexpr
+ *
+ * N: Craig Silverstein
+ * D: Implemented Cityhash as the string hash function on 64-bit machines
+ *
+ * N: Richard Smith
+ * D: Minor patches.
+ *
+ * N: Joerg Sonnenberger
+ * D: NetBSD port.
+ *
+ * N: Stephan Tolksdorf
+ * D: Minor <atomic> fix
+ *
+ * N: Michael van der Westhuizen
+ * E: r1mikey at gmail dot com
+ *
+ * N: Klaas de Vries
+ * E: klaas at klaasgaaf dot nl
+ * D: Minor bug fix.
+ *
+ * N: Zhang Xiongpang
+ * D: Minor patches and bug fixes.
+ *
+ * N: Xing Xue
+ * D: AIX port
+ *
+ * N: Zhihao Yuan
+ * D: Standard compatibility fixes.
+ *
+ * N: Jeffrey Yasskin
+ * D: Linux fixes.
+ */
diff --git a/runtime/onnxruntime/third_party/kaldi/util/const-integer-set-inl.h b/runtime/onnxruntime/third_party/kaldi/util/const-integer-set-inl.h
new file mode 100644
index 000000000..325605350
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/const-integer-set-inl.h
@@ -0,0 +1,91 @@
+// util/const-integer-set-inl.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_UTIL_CONST_INTEGER_SET_INL_H_
+#define KALDI_UTIL_CONST_INTEGER_SET_INL_H_
+
+// Do not include this file directly. It is included by const-integer-set.h
+
+
+namespace kaldi {
+
+template<class I>
+void ConstIntegerSet<I>::InitInternal() {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ quick_set_.clear(); // just in case we previously had data.
+ if (slow_set_.size() == 0) {
+ lowest_member_=(I) 1;
+ highest_member_=(I) 0;
+ contiguous_ = false;
+ quick_ = false;
+ } else {
+ lowest_member_ = slow_set_.front();
+ highest_member_ = slow_set_.back();
+ size_t range = highest_member_ + 1 - lowest_member_;
+ if (range == slow_set_.size()) {
+ contiguous_ = true;
+ quick_= false;
+ } else {
+ contiguous_ = false;
+ // If it would be more compact to store as bool
+ if (range < slow_set_.size() * 8 * sizeof(I)) {
+ // (assuming 1 bit per element)...
+ quick_set_.resize(range, false);
+ for (size_t i = 0;i < slow_set_.size();i++)
+ quick_set_[slow_set_[i] - lowest_member_] = true;
+ quick_ = true;
+ } else {
+ quick_ = false;
+ }
+ }
+ }
+}
+
+template<class I>
+int ConstIntegerSet<I>::count(I i) const {
+ if (i < lowest_member_ || i > highest_member_) {
+ return 0;
+ } else {
+ if (contiguous_) return true;
+ if (quick_) {
+ return (quick_set_[i-lowest_member_] ? 1 : 0);
+ } else {
+ bool ans = std::binary_search(slow_set_.begin(), slow_set_.end(), i);
+ return (ans ? 1 : 0);
+ }
+ }
+}
+
+template<class I>
+void ConstIntegerSet<I>::Write(std::ostream &os, bool binary) const {
+ WriteIntegerVector(os, binary, slow_set_);
+}
+
+template<class I>
+void ConstIntegerSet<I>::Read(std::istream &is, bool binary) {
+ ReadIntegerVector(is, binary, &slow_set_);
+ InitInternal();
+}
+
+
+
+} // end namespace kaldi
+
+#endif // KALDI_UTIL_CONST_INTEGER_SET_INL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/const-integer-set-test.cc b/runtime/onnxruntime/third_party/kaldi/util/const-integer-set-test.cc
new file mode 100644
index 000000000..a863e7034
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/const-integer-set-test.cc
@@ -0,0 +1,145 @@
+// util/const-integer-set-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "util/const-integer-set.h"
+#include <set> // for baseline.
+#include <cassert>
+#include <cstdlib>
+#include <iostream>
+#include "util/kaldi-io.h"
+
+namespace kaldi {
+
+template<class Int> void TestSetOfNumbers(bool binary) {
+ std::set<Int> baseline_set;
+ size_t n_in_set = (Rand() % 3) * 50 + (Rand() % 4); // may be less than this.
+ size_t max = (Int) (Rand() % 100) + 1;
+ for (size_t i = 0; i < n_in_set; i++) {
+ Int to_add((Int) (Rand() % max));
+ baseline_set.insert(to_add);
+ }
+
+ std::vector<Int> vector_set;
+ for (typename std::set<Int>::iterator iter = baseline_set.begin();
+ iter!= baseline_set.end();iter++)
+ vector_set.push_back(*iter);
+ if (vector_set.size() != 0) {
+ for (size_t i = 0;i < 10;i++) // randomize order.
+ std::swap(vector_set[Rand()%vector_set.size()],
+ vector_set[Rand()%vector_set.size()]);
+ }
+
+ ConstIntegerSet<Int> my_set1(baseline_set);
+
+ ConstIntegerSet<Int> my_set2(vector_set);
+
+ ConstIntegerSet<Int> my_set3;
+ my_set3.Init(baseline_set);
+
+ ConstIntegerSet<Int> my_set4;
+ my_set4.Init(vector_set);
+
+ {
+ my_set4.Write(Output("tmpf", binary).Stream(), binary);
+ }
+
+ ConstIntegerSet<Int> my_set5;
+ {
+ bool binary_in;
+ Input ki("tmpf", &binary_in);
+ my_set5.Read(ki.Stream(), binary_in);
+ }
+
+
+ // if (enable_iterators) {
+ size_t sz = baseline_set.size(), sz1 = my_set1.size(), sz2 = my_set2.size(),
+ sz3 = my_set3.size(), sz4 = my_set4.size(), sz5 = my_set5.size();
+ KALDI_ASSERT(sz == sz1 && sz == sz2 && sz == sz3 && sz == sz4 && sz == sz5);
+ // }
+ for (size_t i = 0;i < 100;i++) {
+ Int some_int;
+ if (i%2 == 0 && vector_set.size() != 0)
+ some_int = vector_set[Rand()%vector_set.size()];
+ else
+ some_int = Rand() % max;
+ bool in_baseline = (baseline_set.count(some_int) != 0);
+ bool in_my_set1 = (my_set1.count(some_int) != 0);
+ bool in_my_set2 = (my_set2.count(some_int) != 0);
+ bool in_my_set3 = (my_set3.count(some_int) != 0);
+ bool in_my_set4 = (my_set4.count(some_int) != 0);
+ bool in_my_set5 = (my_set5.count(some_int) != 0);
+
+ if (in_baseline) {
+ KALDI_ASSERT(in_my_set1&&in_my_set2&&in_my_set3&&in_my_set4&&in_my_set5);
+ } else {
+ KALDI_ASSERT(!in_my_set1&&!in_my_set2&&!in_my_set3&&!in_my_set4&&
+ !in_my_set5);
+ }
+ }
+
+ // if (enable_iterators) {
+ typename std::set<Int>::iterator baseline_iter = baseline_set.begin();
+ typename ConstIntegerSet<Int>::iterator my_iter1 = my_set1.begin();
+ typename ConstIntegerSet<Int>::iterator my_iter2 = my_set2.begin();
+ typename ConstIntegerSet<Int>::iterator my_iter3 = my_set3.begin();
+ typename ConstIntegerSet<Int>::iterator my_iter4 = my_set4.begin();
+ typename ConstIntegerSet<Int>::iterator my_iter5 = my_set5.begin();
+ while (baseline_iter != baseline_set.end()) {
+ KALDI_ASSERT(my_iter1 != my_set1.end());
+ KALDI_ASSERT(my_iter2 != my_set2.end());
+ KALDI_ASSERT(my_iter3 != my_set3.end());
+ KALDI_ASSERT(my_iter4 != my_set4.end());
+ KALDI_ASSERT(my_iter5 != my_set5.end());
+ KALDI_ASSERT(*baseline_iter == *my_iter1);
+ KALDI_ASSERT(*baseline_iter == *my_iter2);
+ KALDI_ASSERT(*baseline_iter == *my_iter3);
+ KALDI_ASSERT(*baseline_iter == *my_iter4);
+ KALDI_ASSERT(*baseline_iter == *my_iter5);
+ baseline_iter++;
+ my_iter1++;
+ my_iter2++;
+ my_iter3++;
+ my_iter4++;
+ my_iter5++;
+ }
+ KALDI_ASSERT(my_iter1 == my_set1.end());
+ KALDI_ASSERT(my_iter2 == my_set2.end());
+ KALDI_ASSERT(my_iter3 == my_set3.end());
+ KALDI_ASSERT(my_iter4 == my_set4.end());
+ KALDI_ASSERT(my_iter5 == my_set5.end());
+ // }
+}
+
+} // end namespace kaldi
+
+
+
+int main() {
+ using namespace kaldi;
+ for (size_t i = 0;i < 10;i++) {
+ TestSetOfNumbers<int>(Rand()%2);
+ TestSetOfNumbers<unsigned int>(Rand()%2);
+ TestSetOfNumbers<int16>(Rand()%2);
+ TestSetOfNumbers<int16>(Rand()%2);
+ TestSetOfNumbers<char>(Rand()%2);
+ TestSetOfNumbers<unsigned char>(Rand()%2);
+ }
+ std::cout << "Test OK.\n";
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/util/const-integer-set.h b/runtime/onnxruntime/third_party/kaldi/util/const-integer-set.h
new file mode 100644
index 000000000..bb10a5043
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/const-integer-set.h
@@ -0,0 +1,96 @@
+// util/const-integer-set.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_UTIL_CONST_INTEGER_SET_H_
+#define KALDI_UTIL_CONST_INTEGER_SET_H_
+#include <vector>
+#include <set>
+#include <algorithm>
+#include <limits>
+#include <cassert>
+#include "util/stl-utils.h"
+
+ /* ConstIntegerSet is a way to efficiently test whether something is in a
+ supplied set of integers. It can be initialized from a vector or set, but
+ never changed after that. It either uses a sorted vector or an array of
+ bool, depending on the input. It behaves like a const version of an STL set, with
+ only a subset of the functionality, except all the member functions are
+ upper-case.
+
+ Note that we could get rid of the member slow_set_, but we'd have to
+ do more work to implement an iterator type. This would save memory.
+ */
+
+namespace kaldi {
+
+template<class I> class ConstIntegerSet {
+ public:
+ ConstIntegerSet(): lowest_member_(1), highest_member_(0) { }
+
+ void Init(const std::vector<I> &input) {
+ slow_set_ = input;
+ SortAndUniq(&slow_set_);
+ InitInternal();
+ }
+
+ void Init(const std::set<I> &input) {
+ CopySetToVector(input, &slow_set_);
+ InitInternal();
+ }
+
+ explicit ConstIntegerSet(const std::vector<I> &input): slow_set_(input) {
+ SortAndUniq(&slow_set_);
+ InitInternal();
+ }
+ explicit ConstIntegerSet(const std::set<I> &input) {
+ CopySetToVector(input, &slow_set_);
+ InitInternal();
+ }
+ explicit ConstIntegerSet(const ConstIntegerSet<I> &other):
+ slow_set_(other.slow_set_) {
+ InitInternal();
+ }
+
+ int count(I i) const; // returns 1 or 0.
+
+ typedef typename std::vector<I>::const_iterator iterator;
+ iterator begin() const { return slow_set_.begin(); }
+ iterator end() const { return slow_set_.end(); }
+ size_t size() const { return slow_set_.size(); }
+ bool empty() const { return slow_set_.empty(); }
+
+ void Write(std::ostream &os, bool binary) const;
+ void Read(std::istream &is, bool binary);
+
+ private:
+ I lowest_member_;
+ I highest_member_;
+ bool contiguous_;
+ bool quick_;
+ std::vector<bool> quick_set_;
+ std::vector<I> slow_set_;
+ void InitInternal();
+};
+
+} // end namespace kaldi
+
+#include "util/const-integer-set-inl.h"
+
+#endif // KALDI_UTIL_CONST_INTEGER_SET_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/edit-distance-inl.h b/runtime/onnxruntime/third_party/kaldi/util/edit-distance-inl.h
new file mode 100644
index 000000000..3304b27d0
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/edit-distance-inl.h
@@ -0,0 +1,200 @@
+// util/edit-distance-inl.h
+
+// Copyright 2009-2011 Microsoft Corporation; Haihua Xu; Yanmin Qian
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_UTIL_EDIT_DISTANCE_INL_H_
+#define KALDI_UTIL_EDIT_DISTANCE_INL_H_
+#include <algorithm>
+#include <utility>
+#include <vector>
+#include "util/stl-utils.h"
+
+namespace kaldi {
+
+template<class T>
+int32 LevenshteinEditDistance(const std::vector<T> &a,
+ const std::vector<T> &b) {
+ // Algorithm:
+ // write A and B for the sequences, with elements a_0 ..
+ // let |A| = M and |B| = N be the lengths, and have
+ // elements a_0 ... a_{M-1} and b_0 ... b_{N-1}.
+ // We are computing the recursion
+ // E(m, n) = min( E(m-1, n-1) + (1-delta(a_{m-1}, b_{n-1})),
+ // E(m-1, n) + 1,
+ // E(m, n-1) + 1).
+ // where E(m, n) is defined for m = 0..M and n = 0..N and out-of-
+ // bounds quantities are considered to be infinity (i.e. the
+ // recursion does not visit them).
+
+ // We do this computation using a vector e of size N+1.
+ // The outer iterations range over m = 0..M.
+
+ int M = a.size(), N = b.size();
+ std::vector<int32> e(N+1);
+ std::vector<int32> e_tmp(N+1);
+ // initialize e.
+ for (size_t i = 0; i < e.size(); i++)
+ e[i] = i;
+ for (int32 m = 1; m <= M; m++) {
+ // computing E(m, .) from E(m-1, .)
+ // handle special case n = 0:
+ e_tmp[0] = e[0] + 1;
+
+ for (int32 n = 1; n <= N; n++) {
+ int32 term1 = e[n-1] + (a[m-1] == b[n-1] ? 0 : 1);
+ int32 term2 = e[n] + 1;
+ int32 term3 = e_tmp[n-1] + 1;
+ e_tmp[n] = std::min(term1, std::min(term2, term3));
+ }
+ e = e_tmp;
+ }
+ return e.back();
+}
+//
+struct error_stats {
+ int32 ins_num;
+ int32 del_num;
+ int32 sub_num;
+ int32 total_cost; // minimum total cost to the current alignment.
+};
+// Note that both hyp and ref should not contain noise word in
+// the following implementation.
+
+template<class T>
+int32 LevenshteinEditDistance(const std::vector<T> &ref,
+ const std::vector<T> &hyp,
+ int32 *ins, int32 *del, int32 *sub) {
+ // temp sequence to remember error type and stats.
+ std::vector<error_stats> e(ref.size()+1);
+ std::vector<error_stats> cur_e(ref.size()+1);
+ // initialize the first hypothesis aligned to the reference at each
+ // position:[hyp_index =0][ref_index]
+ for (size_t i =0; i < e.size(); i ++) {
+ e[i].ins_num = 0;
+ e[i].sub_num = 0;
+ e[i].del_num = i;
+ e[i].total_cost = i;
+ }
+
+ // for other alignments
+ for (size_t hyp_index = 1; hyp_index <= hyp.size(); hyp_index ++) {
+ cur_e[0] = e[0];
+ cur_e[0].ins_num++;
+ cur_e[0].total_cost++;
+ for (size_t ref_index = 1; ref_index <= ref.size(); ref_index ++) {
+ int32 ins_err = e[ref_index].total_cost + 1;
+ int32 del_err = cur_e[ref_index-1].total_cost + 1;
+ int32 sub_err = e[ref_index-1].total_cost;
+ if (hyp[hyp_index-1] != ref[ref_index-1])
+ sub_err++;
+
+ if (sub_err < ins_err && sub_err < del_err) {
+ cur_e[ref_index] =e[ref_index-1];
+ if (hyp[hyp_index-1] != ref[ref_index-1])
+ cur_e[ref_index].sub_num++; // substitution error should be increased
+ cur_e[ref_index].total_cost = sub_err;
+ } else if (del_err < ins_err) {
+ cur_e[ref_index] = cur_e[ref_index-1];
+ cur_e[ref_index].total_cost = del_err;
+ cur_e[ref_index].del_num++; // deletion number is increased.
+ } else {
+ cur_e[ref_index] = e[ref_index];
+ cur_e[ref_index].total_cost = ins_err;
+ cur_e[ref_index].ins_num++; // insertion number is increased.
+ }
+ }
+ e = cur_e; // alternate for the next recursion.
+ }
+ size_t ref_index = e.size()-1;
+ *ins = e[ref_index].ins_num, *del =
+ e[ref_index].del_num, *sub = e[ref_index].sub_num;
+ return e[ref_index].total_cost;
+}
+
+template<class T>
+int32 LevenshteinAlignment(const std::vector<T> &a,
+ const std::vector<T> &b,
+ T eps_symbol,
+ std::vector<std::pair<T, T> > *output) {
+ // Check inputs:
+ {
+ KALDI_ASSERT(output != NULL);
+ for (size_t i = 0; i < a.size(); i++) KALDI_ASSERT(a[i] != eps_symbol);
+ for (size_t i = 0; i < b.size(); i++) KALDI_ASSERT(b[i] != eps_symbol);
+ }
+ output->clear();
+ // This is very memory-inefficiently implemented using a vector of vectors.
+ size_t M = a.size(), N = b.size();
+ size_t m, n;
+ std::vector<std::vector<int32> > e(M+1);
+ for (m = 0; m <=M; m++) e[m].resize(N+1);
+ for (n = 0; n <= N; n++)
+ e[0][n] = n;
+ for (m = 1; m <= M; m++) {
+ e[m][0] = e[m-1][0] + 1;
+ for (n = 1; n <= N; n++) {
+ int32 sub_or_ok = e[m-1][n-1] + (a[m-1] == b[n-1] ? 0 : 1);
+ int32 del = e[m-1][n] + 1; // assumes a == ref, b == hyp.
+ int32 ins = e[m][n-1] + 1;
+ e[m][n] = std::min(sub_or_ok, std::min(del, ins));
+ }
+ }
+ // get time-reversed output first: trace back.
+ m = M;
+ n = N;
+ while (m != 0 || n != 0) {
+ size_t last_m, last_n;
+ if (m == 0) {
+ last_m = m;
+ last_n = n-1;
+ } else if (n == 0) {
+ last_m = m-1;
+ last_n = n;
+ } else {
+ int32 sub_or_ok = e[m-1][n-1] + (a[m-1] == b[n-1] ? 0 : 1);
+ int32 del = e[m-1][n] + 1; // assumes a == ref, b == hyp.
+ int32 ins = e[m][n-1] + 1;
+ // choose sub_or_ok if all else equal.
+ if (sub_or_ok <= std::min(del, ins)) {
+ last_m = m-1;
+ last_n = n-1;
+ } else {
+ if (del <= ins) { // choose del over ins if equal.
+ last_m = m-1;
+ last_n = n;
+ } else {
+ last_m = m;
+ last_n = n-1;
+ }
+ }
+ }
+ T a_sym, b_sym;
+ a_sym = (last_m == m ? eps_symbol : a[last_m]);
+ b_sym = (last_n == n ? eps_symbol : b[last_n]);
+ output->push_back(std::make_pair(a_sym, b_sym));
+ m = last_m;
+ n = last_n;
+ }
+ ReverseVector(output);
+ return e[M][N];
+}
+
+
+} // end namespace kaldi
+
+#endif // KALDI_UTIL_EDIT_DISTANCE_INL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/edit-distance-test.cc b/runtime/onnxruntime/third_party/kaldi/util/edit-distance-test.cc
new file mode 100644
index 000000000..f0acaf5e6
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/edit-distance-test.cc
@@ -0,0 +1,267 @@
+// util/edit-distance-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation; Haihua Xu
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/edit-distance.h"
+
+namespace kaldi {
+
+void TestEditDistance() {
+ std::vector<int32> a;
+ std::vector<int32> b;
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 0);
+
+ a.push_back(1);
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 1);
+
+ b.push_back(1);
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 0);
+
+ b.push_back(2);
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 1);
+
+ a.push_back(2);
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 0);
+
+ a.push_back(3);
+ a.push_back(4);
+ b.push_back(4);
+
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 1);
+
+ a.push_back(5);
+
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 2);
+
+ b.push_back(6);
+
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 2);
+
+ a.push_back(1);
+ b.push_back(1);
+
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 2);
+
+ b.push_back(10);
+
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 3);
+}
+
+
+void TestEditDistanceString() {
+ std::vector<std::string> a;
+ std::vector<std::string> b;
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 0);
+
+ a.push_back("1");
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 1);
+
+ b.push_back("1");
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 0);
+
+ b.push_back("2");
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 1);
+
+ a.push_back("2");
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 0);
+
+ a.push_back("3");
+ a.push_back("4");
+ b.push_back("4");
+
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 1);
+
+ a.push_back("5");
+
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 2);
+
+ b.push_back("6");
+
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 2);
+
+ a.push_back("1");
+ b.push_back("1");
+
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 2);
+
+ b.push_back("10");
+
+ KALDI_ASSERT(LevenshteinEditDistance(a, b) == 3);
+}
+
+
+
+// edit distance calculate
+void TestEditDistance2() {
+ std::vector<int32> hyp;
+ std::vector<int32> ref;
+ int32 ins, del, sub, total_cost;
+ // initialize hypothesis
+ hyp.push_back(1);
+ hyp.push_back(3);
+ hyp.push_back(4);
+ hyp.push_back(5);
+ // initialize reference
+ ref.push_back(2);
+ ref.push_back(3);
+ ref.push_back(4);
+ ref.push_back(5);
+ ref.push_back(6);
+ ref.push_back(7);
+ total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
+ KALDI_ASSERT(total_cost == 3 && ins == 0 && del == 2 && sub == 1);
+
+ std::swap(hyp, ref);
+ total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
+ KALDI_ASSERT(total_cost == 3 && ins == 2 && del == 0 && sub == 1);
+
+ hyp.clear();
+ ref.clear();
+ hyp.push_back(1);
+ ref.push_back(1);
+ total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
+ KALDI_ASSERT(total_cost == 0 && ins+del+sub == 0);
+ hyp.push_back(2);
+ ref.push_back(3);
+ total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
+ KALDI_ASSERT(total_cost == 1 && ins == 0 && del == 0 && sub == 1);
+ // randomized test
+ size_t num = 0;
+ for (; num < 1000; num ++) {
+ int32 hyp_len = Rand()%11;
+ int32 ref_len = Rand()%3;
+ hyp.resize(hyp_len);
+ ref.resize(ref_len);
+
+ int32 index = 0;
+ for (; index < hyp_len; index ++)
+ hyp[index] = Rand()%4;
+ for (index = 0; index < ref_len; index ++)
+ ref[index] = Rand()%4;
+ // current version
+ total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
+ // previous version
+ int32 total_cost2 = LevenshteinEditDistance(hyp, ref);
+ // verify both are the same
+ KALDI_ASSERT(total_cost == total_cost2);
+ KALDI_ASSERT(ins+del+sub == total_cost);
+ KALDI_ASSERT(del-ins == static_cast<int32>(ref.size() -hyp.size()));
+ }
+ return;
+}
+
+
+// edit distance calculate
+void TestEditDistance2String() {
+ std::vector<std::string> hyp;
+ std::vector<std::string> ref;
+ int32 ins, del, sub, total_cost;
+ // initialize hypothesis
+ hyp.push_back("1");
+ hyp.push_back("3");
+ hyp.push_back("4");
+ hyp.push_back("5");
+ // initialize reference
+ ref.push_back("2");
+ ref.push_back("3");
+ ref.push_back("4");
+ ref.push_back("5");
+ ref.push_back("6");
+ ref.push_back("7");
+ total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
+ KALDI_ASSERT(total_cost == 3 && ins == 0 && del == 2 && sub == 1);
+
+ std::swap(hyp, ref);
+ total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
+ KALDI_ASSERT(total_cost == 3 && ins == 2 && del == 0 && sub == 1);
+
+ hyp.clear();
+ ref.clear();
+ hyp.push_back("1");
+ ref.push_back("1");
+ total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
+ KALDI_ASSERT(total_cost == 0 && ins+del+sub == 0);
+ hyp.push_back("2");
+ ref.push_back("3");
+ total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
+ KALDI_ASSERT(total_cost == 1 && ins == 0 && del == 0 && sub == 1);
+ // randomized test
+ size_t num = 0;
+ for (; num < 1000; num ++) {
+ int32 hyp_len = Rand()%11;
+ int32 ref_len = Rand()%3;
+ hyp.resize(hyp_len);
+ ref.resize(ref_len);
+
+ int32 index = 0;
+ for (; index < hyp_len; index ++)
+ hyp[index] = Rand()%4;
+ for (index = 0; index < ref_len; index ++)
+ ref[index] = Rand()%4;
+ // current version
+ total_cost = LevenshteinEditDistance(ref, hyp, &ins, &del, &sub);
+ // previous version
+ int32 total_cost2 = LevenshteinEditDistance(hyp, ref);
+ // verify both are the same
+ KALDI_ASSERT(total_cost == total_cost2);
+ KALDI_ASSERT(ins+del+sub == total_cost);
+ KALDI_ASSERT(del-ins == static_cast<int32>(ref.size() -hyp.size()));
+ }
+ return;
+}
+
+
+void TestLevenshteinAlignment() {
+ for (size_t i = 0; i < 100; i++) {
+ size_t a_sz = Rand() % 5, b_sz = Rand() % 5;
+ std::vector<int32> a, b;
+ for (size_t j = 0; j < a_sz; j++) a.push_back(Rand() % 10);
+ for (size_t j = 0; j < b_sz; j++) b.push_back(Rand() % 10);
+ int32 eps_sym = -1;
+ std::vector<std::pair<int32, int32> > ans;
+
+ int32 e1 = LevenshteinEditDistance(a, b),
+ e2 = LevenshteinAlignment(a, b, eps_sym, &ans);
+ KALDI_ASSERT(e1 == e2);
+
+ std::vector<int32> a2, b2;
+ for (size_t i = 0; i < ans.size(); i++) {
+ if (ans[i].first != eps_sym) a2.push_back(ans[i].first);
+ if (ans[i].second != eps_sym) b2.push_back(ans[i].second);
+ }
+ KALDI_ASSERT(a == a2);
+ KALDI_ASSERT(b == b2);
+ }
+}
+
+} // end namespace kaldi
+
+int main() {
+ using namespace kaldi;
+ TestEditDistance();
+ TestEditDistanceString();
+ TestEditDistance2();
+ TestEditDistance2String();
+ TestLevenshteinAlignment();
+ std::cout << "Test OK\n";
+}
+
+
+
diff --git a/runtime/onnxruntime/third_party/kaldi/util/edit-distance.h b/runtime/onnxruntime/third_party/kaldi/util/edit-distance.h
new file mode 100644
index 000000000..5eac4aea1
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/edit-distance.h
@@ -0,0 +1,64 @@
+// util/edit-distance.h
+
+// Copyright 2009-2011 Microsoft Corporation; Haihua Xu
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_UTIL_EDIT_DISTANCE_H_
+#define KALDI_UTIL_EDIT_DISTANCE_H_
+#include <vector>
+#include <set>
+#include <algorithm>
+#include <limits>
+#include <cassert>
+#include <utility>
+#include "util/edit-distance-inl.h"
+#include "base/kaldi-types.h"
+
+namespace kaldi {
+
+// Compute the edit-distance between two strings.
+template<class T>
+int32 LevenshteinEditDistance(const std::vector<T> &a,
+ const std::vector<T> &b);
+
+
+// edit distance calculation with conventional method.
+// note: noise word must be filtered out from the hypothesis and
+// reference sequence
+// before the following procedure conducted.
+template<class T>
+int32 LevenshteinEditDistance(const std::vector<T> &ref,
+ const std::vector<T> &hyp,
+ int32 *ins, int32 *del, int32 *sub);
+
+// This version of the edit-distance computation outputs the alignment
+// between the two. This is a vector of pairs of (symbol a, symbol b).
+// The epsilon symbol (eps_symbol) must not occur in sequences a or b.
+// Where one aligned to no symbol in the other (insertion or deletion),
+// epsilon will be the corresponding member of the pair.
+// It returns the edit-distance between the two strings.
+
+template<class T>
+int32 LevenshteinAlignment(const std::vector<T> &a,
+ const std::vector<T> &b,
+ T eps_symbol,
+ std::vector<std::pair<T, T> > *output);
+
+} // end namespace kaldi
+
+#endif // KALDI_UTIL_EDIT_DISTANCE_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/hash-list-inl.h b/runtime/onnxruntime/third_party/kaldi/util/hash-list-inl.h
new file mode 100644
index 000000000..da6165af7
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/hash-list-inl.h
@@ -0,0 +1,194 @@
+// util/hash-list-inl.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_UTIL_HASH_LIST_INL_H_
+#define KALDI_UTIL_HASH_LIST_INL_H_
+
+// Do not include this file directly. It is included by fast-hash.h
+
+
+namespace kaldi {
+
+template<class I, class T> HashList<I, T>::HashList() {
+ list_head_ = NULL;
+ bucket_list_tail_ = static_cast<size_t>(-1); // invalid.
+ hash_size_ = 0;
+ freed_head_ = NULL;
+}
+
+template<class I, class T> void HashList<I, T>::SetSize(size_t size) {
+ hash_size_ = size;
+ KALDI_ASSERT(list_head_ == NULL &&
+ bucket_list_tail_ == static_cast<size_t>(-1)); // make sure empty.
+ if (size > buckets_.size())
+ buckets_.resize(size, HashBucket(0, NULL));
+}
+
+template<class I, class T>
+typename HashList<I, T>::Elem* HashList<I, T>::Clear() {
+ // Clears the hashtable and gives ownership of the currently contained list
+ // to the user.
+ for (size_t cur_bucket = bucket_list_tail_;
+ cur_bucket != static_cast<size_t>(-1);
+ cur_bucket = buckets_[cur_bucket].prev_bucket) {
+ buckets_[cur_bucket].last_elem = NULL; // this is how we indicate "empty".
+ }
+ bucket_list_tail_ = static_cast<size_t>(-1);
+ Elem *ans = list_head_;
+ list_head_ = NULL;
+ return ans;
+}
+
+template<class I, class T>
+const typename HashList<I, T>::Elem* HashList<I, T>::GetList() const {
+ return list_head_;
+}
+
+template<class I, class T>
+inline void HashList<I, T>::Delete(Elem *e) {
+ e->tail = freed_head_;
+ freed_head_ = e;
+}
+
+template<class I, class T>
+inline typename HashList<I, T>::Elem* HashList<I, T>::Find(I key) {
+ size_t index = (static_cast<size_t>(key) % hash_size_);
+ HashBucket &bucket = buckets_[index];
+ if (bucket.last_elem == NULL) {
+ return NULL; // empty bucket.
+ } else {
+ Elem *head = (bucket.prev_bucket == static_cast<size_t>(-1) ?
+ list_head_ :
+ buckets_[bucket.prev_bucket].last_elem->tail),
+ *tail = bucket.last_elem->tail;
+ for (Elem *e = head; e != tail; e = e->tail)
+ if (e->key == key) return e;
+ return NULL; // Not found.
+ }
+}
+
+template<class I, class T>
+inline typename HashList<I, T>::Elem* HashList<I, T>::New() {
+ if (freed_head_) {
+ Elem *ans = freed_head_;
+ freed_head_ = freed_head_->tail;
+ return ans;
+ } else {
+ Elem *tmp = new Elem[allocate_block_size_];
+ for (size_t i = 0; i+1 < allocate_block_size_; i++)
+ tmp[i].tail = tmp+i+1;
+ tmp[allocate_block_size_-1].tail = NULL;
+ freed_head_ = tmp;
+ allocated_.push_back(tmp);
+ return this->New();
+ }
+}
+
+template<class I, class T>
+HashList<I, T>::~HashList() {
+ // First test whether we had any memory leak within the
+ // HashList, i.e. things for which the user did not call Delete().
+ size_t num_in_list = 0, num_allocated = 0;
+ for (Elem *e = freed_head_; e != NULL; e = e->tail)
+ num_in_list++;
+ for (size_t i = 0; i < allocated_.size(); i++) {
+ num_allocated += allocate_block_size_;
+ delete[] allocated_[i];
+ }
+ if (num_in_list != num_allocated) {
+ KALDI_WARN << "Possible memory leak: " << num_in_list
+ << " != " << num_allocated
+ << ": you might have forgotten to call Delete on "
+ << "some Elems";
+ }
+}
+
+template<class I, class T>
+inline typename HashList<I, T>::Elem* HashList<I, T>::Insert(I key, T val) {
+ size_t index = (static_cast<size_t>(key) % hash_size_);
+ HashBucket &bucket = buckets_[index];
+ // Check the element is existing or not.
+ if (bucket.last_elem != NULL) {
+ Elem *head = (bucket.prev_bucket == static_cast<size_t>(-1) ?
+ list_head_ :
+ buckets_[bucket.prev_bucket].last_elem->tail),
+ *tail = bucket.last_elem->tail;
+ for (Elem *e = head; e != tail; e = e->tail)
+ if (e->key == key) return e;
+ }
+
+ // This is a new element. Insert it.
+ Elem *elem = New();
+ elem->key = key;
+ elem->val = val;
+ if (bucket.last_elem == NULL) { // Unoccupied bucket. Insert at
+ // head of bucket list (which is tail of regular list, they go in
+ // opposite directions).
+ if (bucket_list_tail_ == static_cast<size_t>(-1)) {
+ // list was empty so this is the first elem.
+ KALDI_ASSERT(list_head_ == NULL);
+ list_head_ = elem;
+ } else {
+ // link in to the chain of Elems
+ buckets_[bucket_list_tail_].last_elem->tail = elem;
+ }
+ elem->tail = NULL;
+ bucket.last_elem = elem;
+ bucket.prev_bucket = bucket_list_tail_;
+ bucket_list_tail_ = index;
+ } else {
+ // Already-occupied bucket. Insert at tail of list of elements within
+ // the bucket.
+ elem->tail = bucket.last_elem->tail;
+ bucket.last_elem->tail = elem;
+ bucket.last_elem = elem;
+ }
+ return elem;
+}
+
+template<class I, class T>
+void HashList<I, T>::InsertMore(I key, T val) {
+ size_t index = (static_cast<size_t>(key) % hash_size_);
+ HashBucket &bucket = buckets_[index];
+ Elem *elem = New();
+ elem->key = key;
+ elem->val = val;
+
+ KALDI_ASSERT(bucket.last_elem != NULL); // assume one element is already here
+ if (bucket.last_elem->key == key) { // standard behavior: add as last element
+ elem->tail = bucket.last_elem->tail;
+ bucket.last_elem->tail = elem;
+ bucket.last_elem = elem;
+ return;
+ }
+ Elem *e = (bucket.prev_bucket == static_cast<size_t>(-1) ?
+ list_head_ : buckets_[bucket.prev_bucket].last_elem->tail);
+ // find place to insert in linked list
+ while (e != bucket.last_elem->tail && e->key != key) e = e->tail;
+ KALDI_ASSERT(e->key == key); // not found? - should not happen
+ elem->tail = e->tail;
+ e->tail = elem;
+}
+
+
+} // end namespace kaldi
+
+#endif // KALDI_UTIL_HASH_LIST_INL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/hash-list-test.cc b/runtime/onnxruntime/third_party/kaldi/util/hash-list-test.cc
new file mode 100644
index 000000000..ee37c7003
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/hash-list-test.cc
@@ -0,0 +1,107 @@
+// util/hash-list-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "util/hash-list.h"
+#include <map> // for baseline.
+#include <cstdlib>
+#include <iostream>
+
+namespace kaldi {
+
+template<class Int, class T> void TestHashList() {
+ typedef typename HashList<Int, T>::Elem Elem;
+
+ HashList<Int, T> hash;
+ hash.SetSize(200); // must be called before use.
+ std::map<Int, T> m1;
+ for (size_t j = 0; j < 50; j++) {
+ Int key = Rand() % 200;
+ T val = Rand() % 50;
+ m1[key] = val;
+ Elem *e = hash.Find(key);
+ if (e) e->val = val;
+ else hash.Insert(key, val);
+ }
+
+
+ std::map<Int, T> m2;
+
+ for (int i = 0; i < 100; i++) {
+ m2.clear();
+ for (typename std::map<Int, T>::const_iterator iter = m1.begin();
+ iter != m1.end();
+ iter++) {
+ m2[iter->first + 1] = iter->second;
+ }
+ std::swap(m1, m2);
+
+ Elem *h = hash.Clear(), *tmp;
+
+ hash.SetSize(100 + Rand() % 100); // note, SetSize is relatively cheap
+ // operation as long as we are not increasing the size more than it's ever
+ // previously been increased to.
+
+ for (; h != NULL; h = tmp) {
+ hash.Insert(h->key + 1, h->val);
+ tmp = h->tail;
+ hash.Delete(h); // think of this like calling delete.
+ }
+
+ // Now make sure h and m2 are the same.
+ const Elem *list = hash.GetList();
+ size_t count = 0;
+ for (; list != NULL; list = list->tail, count++) {
+ KALDI_ASSERT(m1[list->key] == list->val);
+ }
+
+ for (size_t j = 0; j < 10; j++) {
+ Int key = Rand() % 200;
+ bool found_m1 = (m1.find(key) != m1.end());
+ if (found_m1) m1[key];
+ Elem *e = hash.Find(key);
+ KALDI_ASSERT((e != NULL) == found_m1);
+ if (found_m1)
+ KALDI_ASSERT(m1[key] == e->val);
+ }
+
+ KALDI_ASSERT(m1.size() == count);
+ }
+}
+
+
+
+
+} // end namespace kaldi
+
+
+
+int main() {
+ using namespace kaldi;
+ for (size_t i = 0;i < 3;i++) {
+ TestHashList<int, unsigned int>();
+ TestHashList<unsigned int, int>();
+ TestHashList<int16, int32>();
+ TestHashList<int16, int32>();
+ TestHashList<char, unsigned char>();
+ TestHashList<unsigned char, int>();
+ }
+ std::cout << "Test OK.\n";
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/util/hash-list.h b/runtime/onnxruntime/third_party/kaldi/util/hash-list.h
new file mode 100644
index 000000000..9ae0043f0
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/hash-list.h
@@ -0,0 +1,147 @@
+// util/hash-list.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2013 Johns Hopkins University (author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_UTIL_HASH_LIST_H_
+#define KALDI_UTIL_HASH_LIST_H_
+#include <vector>
+#include <set>
+#include <algorithm>
+#include <limits>
+#include <cassert>
+#include "util/stl-utils.h"
+
+
+/* This header provides utilities for a structure that's used in a decoder (but
+ is quite generic in nature so we implement and test it separately).
+ Basically it's a singly-linked list, but implemented in such a way that we
+ can quickly search for elements in the list. We give it a slightly richer
+ interface than just a hash and a list. The idea is that we want to separate
+ the hash part and the list part: basically, in the decoder, we want to have a
+ single hash for the current frame and the next frame, because by the time we
+ need to access the hash for the next frame we no longer need the hash for the
+ previous frame. So we have an operation that clears the hash but leaves the
+ list structure intact. We also control memory management inside this object,
+ to avoid repeated new's/deletes.
+
+ See hash-list-test.cc for an example of how to use this object.
+*/
+
+
+namespace kaldi {
+
+template<class I, class T> class HashList {
+ public:
+ struct Elem {
+ I key;
+ T val;
+ Elem *tail;
+ };
+
+ /// Constructor takes no arguments.
+ /// Call SetSize to inform it of the likely size.
+ HashList();
+
+ /// Clears the hash and gives the head of the current list to the user;
+ /// ownership is transferred to the user (the user must call Delete()
+ /// for each element in the list, at his/her leisure).
+ Elem *Clear();
+
+ /// Gives the head of the current list to the user. Ownership retained in the
+ /// class. Caution: in December 2013 the return type was changed to const
+ /// Elem* and this function was made const. You may need to change some types
+ /// of local Elem* variables to const if this produces compilation errors.
+ const Elem *GetList() const;
+
+ /// Think of this like delete(). It is to be called for each Elem in turn
+ /// after you "obtained ownership" by doing Clear(). This is not the opposite
+ /// of. Insert, it is the opposite of New. It's really a memory operation.
+ inline void Delete(Elem *e);
+
+ /// This should probably not be needed to be called directly by the user.
+ /// Think of it as opposite
+ /// to Delete();
+ inline Elem *New();
+
+ /// Find tries to find this element in the current list using the hashtable.
+ /// It returns NULL if not present. The Elem it returns is not owned by the
+ /// user, it is part of the internal list owned by this object, but the user
+ /// is free to modify the "val" element.
+ inline Elem *Find(I key);
+
+ /// Insert inserts a new element into the hashtable/stored list.
+ /// Because element keys in a hashtable are unique, this operation checks
+ /// whether each inserted element has a key equivalent to the one of an
+ /// element already in the hashtable. If so, the element is not inserted,
+ /// returning an pointer to this existing element.
+ inline Elem *Insert(I key, T val);
+
+ /// Insert inserts another element with same key into the hashtable/
+ /// stored list.
+ /// By calling this, the user asserts that one element with that key is
+ /// already present.
+ /// We insert it that way, that all elements with the same key
+ /// follow each other.
+ /// Find() will return the first one of the elements with the same key.
+ inline void InsertMore(I key, T val);
+
+ /// SetSize tells the object how many hash buckets to allocate (should
+ /// typically be at least twice the number of objects we expect to go in the
+ /// structure, for fastest performance). It must be called while the hash
+ /// is empty (e.g. after Clear() or after initializing the object, but before
+ /// adding anything to the hash.
+ void SetSize(size_t sz);
+
+ /// Returns current number of hash buckets.
+ inline size_t Size() { return hash_size_; }
+
+ ~HashList();
+ private:
+
+ struct HashBucket {
+ size_t prev_bucket; // index to next bucket (-1 if list tail). Note:
+ // list of buckets goes in opposite direction to list of Elems.
+ Elem *last_elem; // pointer to last element in this bucket (NULL if empty)
+ inline HashBucket(size_t i, Elem *e): prev_bucket(i), last_elem(e) {}
+ };
+
+ Elem *list_head_; // head of currently stored list.
+ size_t bucket_list_tail_; // tail of list of active hash buckets.
+
+ size_t hash_size_; // number of hash buckets.
+
+ std::vector<HashBucket> buckets_;
+
+ Elem *freed_head_; // head of list of currently freed elements. [ready for
+ // allocation]
+
+ std::vector<Elem*> allocated_; // list of allocated blocks.
+
+ static const size_t allocate_block_size_ = 1024; // Number of Elements to
+ // allocate in one block. Must be largish so storing allocated_ doesn't
+ // become a problem.
+};
+
+
+} // end namespace kaldi
+
+#include "util/hash-list-inl.h"
+
+#endif // KALDI_UTIL_HASH_LIST_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/kaldi-cygwin-io-inl.h b/runtime/onnxruntime/third_party/kaldi/util/kaldi-cygwin-io-inl.h
new file mode 100644
index 000000000..8a3cd91ac
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/kaldi-cygwin-io-inl.h
@@ -0,0 +1,129 @@
+// util/kaldi-cygwin-io-inl.h
+
+// Copyright 2015 Smart Action Company LLC (author: Kirill Katsnelson)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#ifndef KALDI_UTIL_KALDI_CYGWIN_IO_INL_H_
+#define KALDI_UTIL_KALDI_CYGWIN_IO_INL_H_
+
+#ifndef _MSC_VER
+#error This is a Windows-compatibility file. Something went wery wrong.
+#endif
+
+#include <string>
+
+// This file is included only into kaldi-io.cc, and only if
+// KALDI_CYGWIN_COMPAT is enabled.
+//
+// The routines map unix-ey paths passed to Windows programs from shell
+// scripts in egs. Since shell scripts run under cygwin, they use cygwin's
+// own mount table and a mapping to the file system. It is quite possible to
+// create quite an intricate mapping that only own cygwin API would be able
+// to untangle. Unfortunately, the API to map between filenames is not
+// available to non-cygwin programs. Running cygpath for every file operation
+// would as well be cumbersome. So this is only a simplistic path resolution,
+// assuming that the default cygwin prefix /cygdrive is used, and that all
+// resolved unix-style full paths end up prefixed with /cygdrive. This is
+// quite a sensible approach. We'll also try to map /dev/null and /tmp/**,
+// die on all other /dev/** and warn about all other rooted paths.
+
+namespace kaldi {
+
+static bool prefixp(const std::string& pfx, const std::string& str) {
+ return pfx.length() <= str.length() &&
+ std::equal(pfx.begin(), pfx.end(), str.begin());
+}
+
+static std::string cygprefix("/cygdrive/");
+
+static std::string MapCygwinPathNoTmp(const std::string &filename) {
+ // UNC(?), relative, native Windows and empty paths are ok already.
+ if (prefixp("//", filename) || !prefixp("/", filename))
+ return filename;
+
+ // /dev/...
+ if (filename == "/dev/null")
+ return "\\\\.\\nul";
+ if (prefixp("/dev/", filename)) {
+ KALDI_ERR << "Unable to resolve path '" << filename
+ << "' - only have /dev/null here.";
+ return "\\\\.\\invalid";
+ }
+
+ // /cygdrive/?[/....]
+ int preflen = cygprefix.size();
+ if (prefixp(cygprefix, filename)
+ && filename.size() >= preflen + 1 && isalpha(filename[preflen])
+ && (filename.size() == preflen + 1 || filename[preflen + 1] == '/')) {
+ return std::string() + filename[preflen] + ':' +
+ (filename.size() > preflen + 1 ? filename.substr(preflen + 1) : "/");
+ }
+
+ KALDI_WARN << "Unable to resolve path '" << filename
+ << "' - cannot map unix prefix. "
+ << "Will go on, but breakage will likely ensue.";
+ return filename;
+}
+
+// extern for unit testing.
+std::string MapCygwinPath(const std::string &filename) {
+ // /tmp[/....]
+ if (filename != "/tmp" && !prefixp("/tmp/", filename)) {
+ return MapCygwinPathNoTmp(filename);
+ }
+ char *tmpdir = std::getenv("TMP");
+ if (tmpdir == nullptr)
+ tmpdir = std::getenv("TEMP");
+ if (tmpdir == nullptr) {
+ KALDI_ERR << "Unable to resolve path '" << filename
+ << "' - unable to find temporary directory. Set TMP.";
+ return filename;
+ }
+ // Map the value of tmpdir again, as cygwin environment actually may contain
+ // unix-style paths.
+ return MapCygwinPathNoTmp(std::string(tmpdir) + filename.substr(4));
+}
+
+// A popen implementation that passes the command line through cygwin
+// bash.exe. This is necessary since some piped commands are cygwin links
+// (e. g. fgrep is a soft link to grep), and some are #!-files, such as
+// gunzip which is a shell script that invokes gzip, or kaldi's own run.pl
+// which is a perl script.
+//
+// _popen uses cmd.exe or whatever shell is specified via the COMSPEC
+// variable. Unfortunately, it adds a hardcoded " /c " to it, so we cannot
+// just substitute the environment variable COMSPEC to point to bash.exe.
+// Instead, quote the command and pass it to bash via its -c switch.
+static FILE *CygwinCompatPopen(const char* command, const char* mode) {
+ // To speed up command launch marginally, optionally accept full path
+ // to bash.exe. This will not work if the path contains spaces, but
+ // no sane person would install cygwin into a space-ridden path.
+ const char* bash_exe = std::getenv("BASH_EXE");
+ std::string qcmd(bash_exe != nullptr ? bash_exe : "bash.exe");
+ qcmd += " -c \"";
+ for (; *command; ++command) {
+ if (*command == '\"')
+ qcmd += '\"';
+ qcmd += *command;
+ }
+ qcmd += '\"';
+
+ return _popen(qcmd.c_str(), mode);
+}
+
+} // namespace kaldi
+
+#endif // KALDI_UTIL_KALDI_CYGWIN_IO_INL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/kaldi-io-inl.h b/runtime/onnxruntime/third_party/kaldi/util/kaldi-io-inl.h
new file mode 100644
index 000000000..2474f7014
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/kaldi-io-inl.h
@@ -0,0 +1,46 @@
+// util/kaldi-io-inl.h
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#ifndef KALDI_UTIL_KALDI_IO_INL_H_
+#define KALDI_UTIL_KALDI_IO_INL_H_
+
+#include<string>
+
+namespace kaldi {
+
+bool Input::Open(const std::string &rxfilename, bool *binary) {
+ return OpenInternal(rxfilename, true, binary);
+}
+
+bool Input::OpenTextMode(const std::string &rxfilename) {
+ return OpenInternal(rxfilename, false, NULL);
+}
+
+bool Input::IsOpen() {
+ return impl_ != NULL;
+}
+
+bool Output::IsOpen() {
+ return impl_ != NULL;
+}
+
+
+} // end namespace kaldi.
+
+
+#endif // KALDI_UTIL_KALDI_IO_INL_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/kaldi-io-test.cc b/runtime/onnxruntime/third_party/kaldi/util/kaldi-io-test.cc
new file mode 100644
index 000000000..7bfbfb22c
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/kaldi-io-test.cc
@@ -0,0 +1,370 @@
+// util/kaldi-io-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#ifndef _MSC_VER
+#include <unistd.h>
+#endif
+#include "base/io-funcs.h"
+#include "util/kaldi-io.h"
+#include "base/kaldi-math.h"
+#include "base/kaldi-utils.h"
+
+namespace kaldi {
+
+
+
+void UnitTestClassifyRxfilename() {
+ KALDI_ASSERT(ClassifyRxfilename("") == kStandardInput);
+ KALDI_ASSERT(ClassifyRxfilename(" ") == kNoInput);
+ KALDI_ASSERT(ClassifyRxfilename(" a ") == kNoInput);
+ KALDI_ASSERT(ClassifyRxfilename("a ") == kNoInput);
+ KALDI_ASSERT(ClassifyRxfilename("a") == kFileInput);
+ KALDI_ASSERT(ClassifyRxfilename("-") == kStandardInput);
+ KALDI_ASSERT(ClassifyRxfilename("b|") == kPipeInput);
+ KALDI_ASSERT(ClassifyRxfilename("|b") == kNoInput);
+ KALDI_ASSERT(ClassifyRxfilename("b c|") == kPipeInput);
+ KALDI_ASSERT(ClassifyRxfilename(" b c|") == kPipeInput);
+ KALDI_ASSERT(ClassifyRxfilename("a b c:123") == kOffsetFileInput);
+ KALDI_ASSERT(ClassifyRxfilename("a b c:3") == kOffsetFileInput);
+ KALDI_ASSERT(ClassifyRxfilename("a b c:") == kFileInput);
+ KALDI_ASSERT(ClassifyRxfilename("a b c/3") == kFileInput);
+ KALDI_ASSERT(ClassifyRxfilename("ark,s,cs:a b c") == kNoInput);
+ KALDI_ASSERT(ClassifyRxfilename("scp:a b c") == kNoInput);
+
+}
+
+
+void UnitTestClassifyWxfilename() {
+ KALDI_ASSERT(ClassifyWxfilename("") == kStandardOutput);
+ KALDI_ASSERT(ClassifyWxfilename(" ") == kNoOutput);
+ KALDI_ASSERT(ClassifyWxfilename(" a ") == kNoOutput);
+ KALDI_ASSERT(ClassifyWxfilename("a ") == kNoOutput);
+ KALDI_ASSERT(ClassifyWxfilename("a") == kFileOutput);
+ KALDI_ASSERT(ClassifyWxfilename("-") == kStandardOutput);
+ KALDI_ASSERT(ClassifyWxfilename("b|") == kNoOutput);
+ KALDI_ASSERT(ClassifyWxfilename("|b") == kPipeOutput);
+ KALDI_ASSERT(ClassifyWxfilename("| b ") == kPipeOutput);
+ KALDI_ASSERT(ClassifyWxfilename("b c|") == kNoOutput);
+ KALDI_ASSERT(ClassifyWxfilename("a b c:123") == kNoOutput);
+ KALDI_ASSERT(ClassifyWxfilename("ark,s,cs:a b c") == kNoOutput);
+ KALDI_ASSERT(ClassifyWxfilename("scp:a b c") == kNoOutput);
+ KALDI_ASSERT(ClassifyWxfilename("a b c:3") == kNoOutput);
+ KALDI_ASSERT(ClassifyWxfilename("a b c:") == kFileOutput);
+ KALDI_ASSERT(ClassifyWxfilename("a b c/3") == kFileOutput);
+}
+
+void UnitTestIoNew(bool binary) {
+ {
+ const char *filename = "tmpf";
+
+ Output ko(filename, binary);
+ std::ostream &outfile = ko.Stream();
+ if (!binary) outfile << "\t";
+ int64 i1 = Rand() % 10000;
+ WriteBasicType(outfile, binary, i1);
+ uint16 i2 = Rand() % 10000;
+ WriteBasicType(outfile, binary, i2);
+ if (!binary) outfile << "\t";
+ char c = Rand();
+ WriteBasicType(outfile, binary, c);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ std::vector<int32> vec1;
+ WriteIntegerVector(outfile, binary, vec1);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ std::vector<uint16> vec2;
+ for (size_t i = 0; i < 10; i++) vec2.push_back(Rand()%100 - 10);
+ WriteIntegerVector(outfile, binary, vec2);
+ if (!binary) outfile << " \n";
+ std::vector<char> vec3;
+ for (size_t i = 0; i < 10; i++) vec3.push_back(Rand()%100);
+ WriteIntegerVector(outfile, binary, vec3);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ const char *token1 = "Hi";
+ WriteToken(outfile, binary, token1);
+ if (!binary) outfile << " \n";
+ std::string token2 = "There.";
+ WriteToken(outfile, binary, token2);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ std::string token3 = "You.";
+ WriteToken(outfile, binary, token3);
+ if (!binary && Rand()%2 == 0) outfile << " ";
+ float f1 = RandUniform();
+ WriteBasicType(outfile, binary, f1);
+ if (!binary && Rand()%2 == 0) outfile << "\t";
+ float f2 = RandUniform();
+ WriteBasicType(outfile, binary, f2);
+ double d1 = RandUniform();
+ WriteBasicType(outfile, binary, d1);
+ if (!binary && Rand()%2 == 0) outfile << "\t";
+ double d2 = RandUniform();
+ WriteBasicType(outfile, binary, d2);
+ if (!binary && Rand()%2 == 0) outfile << "\t";
+ ko.Close();
+
+ {
+ bool binary_in;
+ Input ki(filename, &binary_in);
+ std::istream &infile = ki.Stream();
+ int64 i1_in;
+ ReadBasicType(infile, binary_in, &i1_in);
+ KALDI_ASSERT(i1_in == i1);
+ uint16 i2_in;
+ ReadBasicType(infile, binary_in, &i2_in);
+ KALDI_ASSERT(i2_in == i2);
+ char c_in;
+ ReadBasicType(infile, binary_in, &c_in);
+ KALDI_ASSERT(c_in == c);
+ std::vector<int32> vec1_in;
+ ReadIntegerVector(infile, binary_in, &vec1_in);
+ KALDI_ASSERT(vec1_in == vec1);
+ std::vector<uint16> vec2_in;
+ ReadIntegerVector(infile, binary_in, &vec2_in);
+ KALDI_ASSERT(vec2_in == vec2);
+ std::vector<char> vec3_in;
+ ReadIntegerVector(infile, binary_in, &vec3_in);
+ KALDI_ASSERT(vec3_in == vec3);
+ std::string token1_in, token2_in;
+ KALDI_ASSERT(Peek(infile, binary_in) == static_cast<int>(*token1));
+ ReadToken(infile, binary_in, &token1_in);
+ KALDI_ASSERT(token1_in == (std::string)token1);
+ ReadToken(infile, binary_in, &token2_in);
+ KALDI_ASSERT(token2_in == token2);
+ if (Rand() % 2 == 0)
+ ExpectToken(infile, binary_in, token3.c_str());
+ else
+ ExpectToken(infile, binary_in, token3);
+ float f1_in; // same type.
+ ReadBasicType(infile, binary_in, &f1_in);
+ AssertEqual(f1_in, f1);
+ double f2_in; // wrong type.
+ ReadBasicType(infile, binary_in, &f2_in);
+ AssertEqual(f2_in, f2);
+ double d1_in; // same type.
+ ReadBasicType(infile, binary_in, &d1_in);
+ AssertEqual(d1_in, d1);
+ float d2_in; // wrong type.
+ ReadBasicType(infile, binary_in, &d2_in);
+ AssertEqual(d2_in, d2);
+ KALDI_ASSERT(Peek(infile, binary_in) == -1);
+ }
+ unlink(filename);
+ }
+}
+
+void UnitTestIoPipe(bool binary) {
+ // This is as UnitTestIoNew except with different filenames.
+ {
+#if defined(_MSC_VER) && !defined(KALDI_CYGWIN_COMPAT)
+ // self-invocation on Windows that emulates cat(1)
+ const char *filename_out = "|kaldi-io-test cat > tmpf.gz",
+ *filename_in = "kaldi-io-test cat tmpf.gz|";
+#else
+ const char *filename_out = "|gzip -c > tmpf.gz",
+ *filename_in = "gunzip -c tmpf.gz |";
+#endif
+
+ Output ko(filename_out, binary);
+ std::ostream &outfile = ko.Stream();
+ if (!binary) outfile << "\t";
+ int64 i1 = Rand() % 10000;
+ WriteBasicType(outfile, binary, i1);
+ uint16 i2 = Rand() % 10000;
+ WriteBasicType(outfile, binary, i2);
+ if (!binary) outfile << "\t";
+ char c = Rand();
+ WriteBasicType(outfile, binary, c);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ std::vector<int32> vec1;
+ WriteIntegerVector(outfile, binary, vec1);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ std::vector<uint16> vec2;
+ for (size_t i = 0; i < 10; i++) vec2.push_back(Rand()%100 - 10);
+ WriteIntegerVector(outfile, binary, vec2);
+ if (!binary) outfile << " \n";
+ WriteToken(outfile, binary, "<foo>");
+ std::vector<char> vec3;
+ for (size_t i = 0; i < 10; i++) vec3.push_back(Rand()%100);
+ WriteIntegerVector(outfile, binary, vec3);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ const char *token1 = "Hi";
+ WriteToken(outfile, binary, token1);
+ if (!binary) outfile << " \n";
+ std::string token2 = "There.";
+ WriteToken(outfile, binary, token2);
+ if (!binary && Rand()%2 == 0) outfile << " \n";
+ std::string token3 = "You.";
+ WriteToken(outfile, binary, token3);
+ if (!binary && Rand()%2 == 0) outfile << " ";
+ float f1 = RandUniform();
+ WriteBasicType(outfile, binary, f1);
+ if (!binary && Rand()%2 == 0) outfile << "\t";
+ float f2 = RandUniform();
+ WriteBasicType(outfile, binary, f2);
+ double d1 = RandUniform();
+ WriteBasicType(outfile, binary, d1);
+ if (!binary && Rand()%2 == 0) outfile << "\t";
+ double d2 = RandUniform();
+ WriteBasicType(outfile, binary, d2);
+ if (!binary && Rand()%2 == 0) outfile << "\t";
+ bool ans = ko.Close();
+ KALDI_ASSERT(ans);
+#ifndef _MSC_VER
+ Sleep(1); // This test does not work without this sleep:
+ // seems to be some kind of file-system latency.
+#endif
+ {
+ bool binary_in;
+ Input ki(filename_in, &binary_in);
+ std::istream &infile = ki.Stream();
+ int64 i1_in;
+ ReadBasicType(infile, binary_in, &i1_in);
+ KALDI_ASSERT(i1_in == i1);
+ uint16 i2_in;
+ ReadBasicType(infile, binary_in, &i2_in);
+ KALDI_ASSERT(i2_in == i2);
+ char c_in;
+ ReadBasicType(infile, binary_in, &c_in);
+ KALDI_ASSERT(c_in == c);
+ std::vector<int32> vec1_in;
+ ReadIntegerVector(infile, binary_in, &vec1_in);
+ KALDI_ASSERT(vec1_in == vec1);
+ std::vector<uint16> vec2_in;
+ ReadIntegerVector(infile, binary_in, &vec2_in);
+ KALDI_ASSERT(vec2_in == vec2);
+ std::vector<char> vec3_in;
+ KALDI_ASSERT(PeekToken(infile, binary_in) == static_cast<int>('f'));
+ ExpectToken(infile, binary_in, "<foo>");
+ ReadIntegerVector(infile, binary_in, &vec3_in);
+ KALDI_ASSERT(vec3_in == vec3);
+ std::string token1_in, token2_in;
+ KALDI_ASSERT(Peek(infile, binary_in) == static_cast<int>(*token1));
+ ReadToken(infile, binary_in, &token1_in);
+ KALDI_ASSERT(token1_in == (std::string)token1);
+ ReadToken(infile, binary_in, &token2_in);
+ KALDI_ASSERT(token2_in == token2);
+ if (Rand() % 2 == 0)
+ ExpectToken(infile, binary_in, token3.c_str());
+ else
+ ExpectToken(infile, binary_in, token3);
+ float f1_in; // same type.
+ ReadBasicType(infile, binary_in, &f1_in);
+ AssertEqual(f1_in, f1);
+ double f2_in; // wrong type.
+ ReadBasicType(infile, binary_in, &f2_in);
+ AssertEqual(f2_in, f2);
+ double d1_in; // same type.
+ ReadBasicType(infile, binary_in, &d1_in);
+ AssertEqual(d1_in, d1);
+ float d2_in; // wrong type.
+ ReadBasicType(infile, binary_in, &d2_in);
+ AssertEqual(d2_in, d2);
+ KALDI_ASSERT(Peek(infile, binary_in) == -1);
+ }
+ }
+ unlink("tmpf.txt");
+ unlink("tmpf.gz");
+}
+
+void UnitTestIoStandard() {
+ /*
+ Don't do the the following part because it requires
+ to pipe from an empty file, for it to not hang.
+ {
+ Input inp("", NULL); // standard input.
+ KALDI_ASSERT(inp.Stream().get() == -1);
+ }
+ {
+ Input inp("-", NULL); // standard input.
+ KALDI_ASSERT(inp.Stream().get() == -1);
+ }*/
+
+ {
+ std::cout << "Should see: foo\n";
+ Output out("", false);
+ out.Stream() << "foo\n";
+ }
+ {
+ std::cout << "Should see: bar\n";
+ Output out("-", false);
+ out.Stream() << "bar\n";
+ }
+}
+
+// This is Windows-specific.
+void UnitTestNativeFilename() {
+#ifdef KALDI_CYGWIN_COMPAT
+ extern std::string MapCygwinPath(const std::string &filename);
+
+ KALDI_ASSERT(MapCygwinPath("") == "");
+ KALDI_ASSERT(MapCygwinPath(".") == ".");
+ KALDI_ASSERT(MapCygwinPath("..") == "..");
+ KALDI_ASSERT(MapCygwinPath("/dev/null")[0] != '/');
+ KALDI_ASSERT(MapCygwinPath("/tmp")[1] == ':');
+ KALDI_ASSERT(MapCygwinPath("/tmp/")[1] == ':');
+ KALDI_ASSERT(MapCygwinPath("/tmp/foo")[1] == ':');
+ KALDI_ASSERT(MapCygwinPath("/cygdrive/c") == "c:/");
+ KALDI_ASSERT(MapCygwinPath("/cygdrive/c/") == "c:/");
+ KALDI_ASSERT(MapCygwinPath("/cygdrive/c/foo") == "c:/foo");
+#endif
+}
+
+} // end namespace kaldi.
+
+#if defined(_MSC_VER) && !defined(KALDI_CYGWIN_COMPAT)
+// Windows has no cat! There is probably no suitable tool to test popen I/O on
+// Windows, so we emulate a lame version of cat(1).
+static int TinyCat(int argc, const char** argv) {
+ const char* name_in = argc > 0 && strcmp(argv[0], "-") ? argv[0] : NULL;
+ int fd_in = name_in ? _open(name_in, _O_RDONLY) : _fileno(stdin);
+ if (fd_in < 0)
+ return 1;
+
+ int fd_out = _fileno(stdout);
+ _setmode(fd_in, _O_BINARY);
+ _setmode(fd_out, _O_BINARY);
+
+ char buffer[100];
+ int last_read;
+ while ((last_read = _read(fd_in, buffer, sizeof(buffer))) > 0)
+ _write(fd_out, buffer, last_read);
+
+ if (name_in) _close(fd_in);
+ return 0;
+}
+#endif
+
+int main(int argc, const char** argv) {
+ using namespace kaldi;
+#if defined(_MSC_VER) && !defined(KALDI_CYGWIN_COMPAT)
+ if (argc > 1 && strcmp(argv[1], "cat") == 0)
+ return TinyCat(argc - 2, argv + 2);
+#endif
+
+ UnitTestNativeFilename();
+ UnitTestIoNew(false);
+ UnitTestIoNew(true);
+ UnitTestIoPipe(true);
+ UnitTestIoPipe(false);
+ UnitTestIoStandard();
+ UnitTestClassifyRxfilename();
+ UnitTestClassifyWxfilename();
+
+ KALDI_ASSERT(1); // just wanted to check that KALDI_ASSERT does not fail
+ // for 1.
+ return 0;
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/util/kaldi-io.cc b/runtime/onnxruntime/third_party/kaldi/util/kaldi-io.cc
new file mode 100644
index 000000000..f45f878f9
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/kaldi-io.cc
@@ -0,0 +1,880 @@
+// util/kaldi-io.cc
+
+// Copyright 2009-2011 Microsoft Corporation; Jan Silovsky
+// 2016 Xiaohui Zhang
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#include "util/kaldi-io.h"
+#include <errno.h>
+#include <cstdlib>
+#include "base/kaldi-math.h"
+#include "util/text-utils.h"
+#include "util/parse-options.h"
+#include "util/kaldi-pipebuf.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+#ifdef KALDI_CYGWIN_COMPAT
+#include "util/kaldi-cygwin-io-inl.h"
+#define MapOsPath(x) MapCygwinPath(x)
+#else // KALDI_CYGWIN_COMPAT
+#define MapOsPath(x) x
+#endif // KALDI_CYGWIN_COMPAT
+
+
+#if defined(_MSC_VER)
+static FILE *popen(const char* command, const char* mode) {
+#ifdef KALDI_CYGWIN_COMPAT
+ return kaldi::CygwinCompatPopen(command, mode);
+#else // KALDI_CYGWIN_COMPAT
+ return _popen(command, mode);
+#endif // KALDI_CYGWIN_COMPAT
+}
+#endif // _MSC_VER
+
+namespace kaldi {
+
+#ifndef _MSC_VER // on VS, we don't need this type.
+// could replace basic_pipebuf<char> with stdio_filebuf<char> on some platforms.
+// Would mean we could use less of our own code.
+typedef basic_pipebuf<char> PipebufType;
+#endif
+}
+
+namespace kaldi {
+
+std::string PrintableRxfilename(const std::string &rxfilename) {
+ if (rxfilename == "" || rxfilename == "-") {
+ return "standard input";
+ } else {
+ // If this call to Escape later causes compilation issues,
+ // just replace it with "return rxfilename"; it's only a
+ // pretty-printing issue.
+ return ParseOptions::Escape(rxfilename);
+ }
+}
+
+
+std::string PrintableWxfilename(const std::string &wxfilename) {
+ if (wxfilename == "" || wxfilename == "-") {
+ return "standard output";
+ } else {
+ // If this call to Escape later causes compilation issues,
+ // just replace it with "return wxfilename"; it's only a
+ // pretty-printing issue.
+ return ParseOptions::Escape(wxfilename);
+ }
+}
+
+
+OutputType ClassifyWxfilename(const std::string &filename) {
+ const char *c = filename.c_str();
+ size_t length = filename.length();
+ char first_char = c[0],
+ last_char = (length == 0 ? '\0' : c[filename.length()-1]);
+
+ // if 'filename' is "" or "-", return kStandardOutput.
+ if (length == 0 || (length == 1 && first_char == '-'))
+ return kStandardOutput;
+ else if (first_char == '|') return kPipeOutput; // An output pipe like "|blah".
+ else if (isspace(first_char) || isspace(last_char) || last_char == '|') {
+ return kNoOutput; // Leading or trailing space: can't interpret this.
+ // Final '|' would represent an input pipe, not an
+ // output pipe.
+ //} else if ((first_char == 'a' || first_char == 's') &&
+ // strchr(c, ':') != NULL &&
+ // (ClassifyWspecifier(filename, NULL, NULL, NULL) != kNoWspecifier ||
+ // ClassifyRspecifier(filename, NULL, NULL) != kNoRspecifier)) {
+ // // e.g. ark:something or scp:something... this is almost certainly a
+ // // scripting error, so call it an error rather than treating it as a file.
+ // // In practice in modern kaldi scripts all (r,w)filenames begin with "ark"
+ // // or "scp", even though technically speaking options like "b", "t", "s" or
+ // // "cs" can appear before the ark or scp, like "b,ark". For efficiency,
+ // // and because this code is really just a nicety to catch errors earlier
+ // // than they would otherwise be caught, we only call those extra functions
+ // // for filenames beginning with 'a' or 's'.
+ // return kNoOutput;
+ } else if (isdigit(last_char)) {
+ // This could be a file, but we have to see if it's an offset into a file
+ // (like foo.ark:4314328), which is not allowed for writing (but is
+ // allowed for reaching). This eliminates some things which would be
+ // valid UNIX filenames but are not allowed by Kaldi. (Even if we allowed
+ // such filenames for writing, we woudln't be able to correctly read them).
+ const char *d = c + length - 1;
+ while (isdigit(*d) && d > c) d--;
+ if (*d == ':') return kNoOutput;
+ // else it could still be a filename; continue to the next check.
+ }
+
+ // At this point it matched no other pattern so we assume a filename, but we
+ // check for internal '|' as it's a common source of errors to have pipe
+ // commands without the pipe in the right place. Say that it can't be
+ // classified.
+ if (strchr(c, '|') != NULL) {
+ KALDI_WARN << "Trying to classify wxfilename with pipe symbol in the"
+ " wrong place (pipe without | at the beginning?): " <<
+ filename;
+ return kNoOutput;
+ }
+ return kFileOutput; // It matched no other pattern: assume it's a filename.
+}
+
+
+InputType ClassifyRxfilename(const std::string &filename) {
+ const char *c = filename.c_str();
+ size_t length = filename.length();
+ char first_char = c[0],
+ last_char = (length == 0 ? '\0' : c[filename.length()-1]);
+
+ // if 'filename' is "" or "-", return kStandardInput.
+ if (length == 0 || (length == 1 && first_char == '-')) {
+ return kStandardInput;
+ } else if (first_char == '|') {
+ return kNoInput; // An output pipe like "|blah": not
+ // valid for input.
+ } else if (last_char == '|') {
+ return kPipeInput;
+ } else if (isspace(first_char) || isspace(last_char)) {
+ return kNoInput; // We don't allow leading or trailing space in a filename.
+ //} else if ((first_char == 'a' || first_char == 's') &&
+ // strchr(c, ':') != NULL &&
+ // (ClassifyWspecifier(filename, NULL, NULL, NULL) != kNoWspecifier ||
+ // ClassifyRspecifier(filename, NULL, NULL) != kNoRspecifier)) {
+ // // e.g. ark:something or scp:something... this is almost certainly a
+ // // scripting error, so call it an error rather than treating it as a file.
+ // // In practice in modern kaldi scripts all (r,w)filenames begin with "ark"
+ // // or "scp", even though technically speaking options like "b", "t", "s" or
+ // // "cs" can appear before the ark or scp, like "b,ark". For efficiency,
+ // // and because this code is really just a nicety to catch errors earlier
+ // // than they would otherwise be caught, we only call those extra functions
+ // // for filenames beginning with 'a' or 's'.
+ // return kNoInput;
+ } else if (isdigit(last_char)) {
+ const char *d = c + length - 1;
+ while (isdigit(*d) && d > c) d--;
+ if (*d == ':') return kOffsetFileInput; // Filename is like
+ // some_file:12345
+ // otherwise it could still be a filename; continue to the next check.
+ }
+
+
+ // At this point it matched no other pattern so we assume a filename, but
+ // we check for '|' as it's a common source of errors to have pipe
+ // commands without the pipe in the right place. Say that it can't be
+ // classified in this case.
+ if (strchr(c, '|') != NULL) {
+ KALDI_WARN << "Trying to classify rxfilename with pipe symbol in the"
+ " wrong place (pipe without | at the end?): " << filename;
+ return kNoInput;
+ }
+ return kFileInput; // It matched no other pattern: assume it's a filename.
+}
+
+class OutputImplBase {
+ public:
+ // Open will open it as a file (no header), and return true
+ // on success. It cannot be called on an already open stream.
+ virtual bool Open(const std::string &filename, bool binary) = 0;
+ virtual std::ostream &Stream() = 0;
+ virtual bool Close() = 0;
+ virtual ~OutputImplBase() { }
+};
+
+
+class FileOutputImpl: public OutputImplBase {
+ public:
+ virtual bool Open(const std::string &filename, bool binary) {
+ if (os_.is_open()) KALDI_ERR << "FileOutputImpl::Open(), "
+ << "open called on already open file.";
+ filename_ = filename;
+ os_.open(MapOsPath(filename_).c_str(),
+ binary ? std::ios_base::out | std::ios_base::binary
+ : std::ios_base::out);
+ return os_.is_open();
+ }
+
+ virtual std::ostream &Stream() {
+ if (!os_.is_open())
+ KALDI_ERR << "FileOutputImpl::Stream(), file is not open.";
+ // I believe this error can only arise from coding error.
+ return os_;
+ }
+
+ virtual bool Close() {
+ if (!os_.is_open())
+ KALDI_ERR << "FileOutputImpl::Close(), file is not open.";
+ // I believe this error can only arise from coding error.
+ os_.close();
+ return !(os_.fail());
+ }
+ virtual ~FileOutputImpl() {
+ if (os_.is_open()) {
+ os_.close();
+ if (os_.fail())
+ KALDI_ERR << "Error closing output file " << filename_;
+ }
+ }
+ private:
+ std::string filename_;
+ std::ofstream os_;
+};
+
+class StandardOutputImpl: public OutputImplBase {
+ public:
+ StandardOutputImpl(): is_open_(false) { }
+
+ virtual bool Open(const std::string &filename, bool binary) {
+ if (is_open_) KALDI_ERR << "StandardOutputImpl::Open(), "
+ "open called on already open file.";
+#ifdef _MSC_VER
+ _setmode(_fileno(stdout), binary ? _O_BINARY : _O_TEXT);
+#endif
+ is_open_ = std::cout.good();
+ return is_open_;
+ }
+
+ virtual std::ostream &Stream() {
+ if (!is_open_)
+ KALDI_ERR << "StandardOutputImpl::Stream(), object not initialized.";
+ // I believe this error can only arise from coding error.
+ return std::cout;
+ }
+
+ virtual bool Close() {
+ if (!is_open_)
+ KALDI_ERR << "StandardOutputImpl::Close(), file is not open.";
+ is_open_ = false;
+ std::cout << std::flush;
+ return !(std::cout.fail());
+ }
+ virtual ~StandardOutputImpl() {
+ if (is_open_) {
+ std::cout << std::flush;
+ if (std::cout.fail())
+ KALDI_ERR << "Error writing to standard output";
+ }
+ }
+ private:
+ bool is_open_;
+};
+
+class PipeOutputImpl: public OutputImplBase {
+ public:
+ PipeOutputImpl(): f_(NULL), os_(NULL) { }
+
+ virtual bool Open(const std::string &wxfilename, bool binary) {
+ filename_ = wxfilename;
+ KALDI_ASSERT(f_ == NULL); // Make sure closed.
+ KALDI_ASSERT(wxfilename.length() != 0 && wxfilename[0] == '|'); // should
+ // start with '|'
+ std::string cmd_name(wxfilename, 1);
+#if defined(_MSC_VER) || defined(__CYGWIN__)
+ f_ = popen(cmd_name.c_str(), (binary ? "wb" : "w"));
+#else
+ f_ = popen(cmd_name.c_str(), "w");
+#endif
+ if (!f_) { // Failure.
+ KALDI_WARN << "Failed opening pipe for writing, command is: "
+ << cmd_name << ", errno is " << strerror(errno);
+ return false;
+ } else {
+#ifndef _MSC_VER
+ fb_ = new PipebufType(f_, // Using this constructor won't make the
+ // destructor try to close the stream when
+ // we're done.
+ (binary ? std::ios_base::out|
+ std::ios_base::binary
+ :std::ios_base::out));
+ KALDI_ASSERT(fb_ != NULL); // or would be alloc error.
+ os_ = new std::ostream(fb_);
+#else
+ os_ = new std::ofstream(f_);
+#endif
+ return os_->good();
+ }
+ }
+
+ virtual std::ostream &Stream() {
+ if (os_ == NULL) KALDI_ERR << "PipeOutputImpl::Stream(),"
+ " object not initialized.";
+ // I believe this error can only arise from coding error.
+ return *os_;
+ }
+
+ virtual bool Close() {
+ if (os_ == NULL) KALDI_ERR << "PipeOutputImpl::Close(), file is not open.";
+ bool ok = true;
+ os_->flush();
+ if (os_->fail()) ok = false;
+ delete os_;
+ os_ = NULL;
+ int status;
+#ifdef _MSC_VER
+ status = _pclose(f_);
+#else
+ status = pclose(f_);
+#endif
+ if (status)
+ KALDI_WARN << "Pipe " << filename_ << " had nonzero return status "
+ << status;
+ f_ = NULL;
+#ifndef _MSC_VER
+ delete fb_;
+ fb_ = NULL;
+#endif
+ return ok;
+ }
+ virtual ~PipeOutputImpl() {
+ if (os_) {
+ if (!Close())
+ KALDI_ERR << "Error writing to pipe " << PrintableWxfilename(filename_);
+ }
+ }
+ private:
+ std::string filename_;
+ FILE *f_;
+#ifndef _MSC_VER
+ PipebufType *fb_;
+#endif
+ std::ostream *os_;
+};
+
+
+
+class InputImplBase {
+ public:
+ // Open will open it as a file, and return true on success.
+ // May be called twice only for kOffsetFileInput (otherwise,
+ // if called twice, we just create a new Input object, to avoid
+ // having to deal with the extra hassle of reopening with the
+ // same object.
+ // Note that we will to call Open with true (binary) for
+ // for text-mode Kaldi files; the only actual text-mode input
+ // is for non-Kaldi files.
+ virtual bool Open(const std::string &filename, bool binary) = 0;
+ virtual std::istream &Stream() = 0;
+ virtual int32 Close() = 0; // We only need to check failure in the case of
+ // kPipeInput.
+ // on close for input streams.
+ virtual InputType MyType() = 0; // Because if it's kOffsetFileInput, we may
+ // call Open twice
+ // (has efficiency benefits).
+
+ virtual ~InputImplBase() { }
+};
+
+class FileInputImpl: public InputImplBase {
+ public:
+ virtual bool Open(const std::string &filename, bool binary) {
+ if (is_.is_open()) KALDI_ERR << "FileInputImpl::Open(), "
+ << "open called on already open file.";
+ is_.open(MapOsPath(filename).c_str(),
+ binary ? std::ios_base::in | std::ios_base::binary
+ : std::ios_base::in);
+ return is_.is_open();
+ }
+
+ virtual std::istream &Stream() {
+ if (!is_.is_open())
+ KALDI_ERR << "FileInputImpl::Stream(), file is not open.";
+ // I believe this error can only arise from coding error.
+ return is_;
+ }
+
+ virtual int32 Close() {
+ if (!is_.is_open())
+ KALDI_ERR << "FileInputImpl::Close(), file is not open.";
+ // I believe this error can only arise from coding error.
+ is_.close();
+ // Don't check status.
+ return 0;
+ }
+
+ virtual InputType MyType() { return kFileInput; }
+
+ virtual ~FileInputImpl() {
+ // Stream will automatically be closed, and we don't care about
+ // whether it fails.
+ }
+ private:
+ std::ifstream is_;
+};
+
+
+class StandardInputImpl: public InputImplBase {
+ public:
+ StandardInputImpl(): is_open_(false) { }
+
+ virtual bool Open(const std::string &filename, bool binary) {
+ if (is_open_) KALDI_ERR << "StandardInputImpl::Open(), "
+ "open called on already open file.";
+ is_open_ = true;
+#ifdef _MSC_VER
+ _setmode(_fileno(stdin), binary ? _O_BINARY : _O_TEXT);
+#endif
+ return true; // Don't check good() because would be false if
+ // eof, which may be valid input.
+ }
+
+ virtual std::istream &Stream() {
+ if (!is_open_)
+ KALDI_ERR << "StandardInputImpl::Stream(), object not initialized.";
+ // I believe this error can only arise from coding error.
+ return std::cin;
+ }
+
+ virtual InputType MyType() { return kStandardInput; }
+
+ virtual int32 Close() {
+ if (!is_open_) KALDI_ERR << "StandardInputImpl::Close(), file is not open.";
+ is_open_ = false;
+ return 0;
+ }
+ virtual ~StandardInputImpl() { }
+ private:
+ bool is_open_;
+};
+
+class PipeInputImpl: public InputImplBase {
+ public:
+ PipeInputImpl(): f_(NULL), is_(NULL) { }
+
+ virtual bool Open(const std::string &rxfilename, bool binary) {
+ filename_ = rxfilename;
+ KALDI_ASSERT(f_ == NULL); // Make sure closed.
+ KALDI_ASSERT(rxfilename.length() != 0 &&
+ rxfilename[rxfilename.length()-1] == '|'); // should end with '|'
+ std::string cmd_name(rxfilename, 0, rxfilename.length()-1);
+#if defined(_MSC_VER) || defined(__CYGWIN__)
+ f_ = popen(cmd_name.c_str(), (binary ? "rb" : "r"));
+#else
+ f_ = popen(cmd_name.c_str(), "r");
+#endif
+
+ if (!f_) { // Failure.
+ KALDI_WARN << "Failed opening pipe for reading, command is: "
+ << cmd_name << ", errno is " << strerror(errno);
+ return false;
+ } else {
+#ifndef _MSC_VER
+ fb_ = new PipebufType(f_, // Using this constructor won't lead the
+ // destructor to close the stream.
+ (binary ? std::ios_base::in|
+ std::ios_base::binary
+ :std::ios_base::in));
+ KALDI_ASSERT(fb_ != NULL); // or would be alloc error.
+ is_ = new std::istream(fb_);
+#else
+ is_ = new std::ifstream(f_);
+#endif
+ if (is_->fail() || is_->bad()) return false;
+ if (is_->eof()) {
+ KALDI_WARN << "Pipe opened with command "
+ << PrintableRxfilename(rxfilename)
+ << " is empty.";
+ // don't return false: empty may be valid.
+ }
+ return true;
+ }
+ }
+
+ virtual std::istream &Stream() {
+ if (is_ == NULL)
+ KALDI_ERR << "PipeInputImpl::Stream(), object not initialized.";
+ // I believe this error can only arise from coding error.
+ return *is_;
+ }
+
+ virtual int32 Close() {
+ if (is_ == NULL)
+ KALDI_ERR << "PipeInputImpl::Close(), file is not open.";
+ delete is_;
+ is_ = NULL;
+ int32 status;
+#ifdef _MSC_VER
+ status = _pclose(f_);
+#else
+ status = pclose(f_);
+#endif
+ if (status)
+ KALDI_WARN << "Pipe " << filename_ << " had nonzero return status "
+ << status;
+ f_ = NULL;
+#ifndef _MSC_VER
+ delete fb_;
+ fb_ = NULL;
+#endif
+ return status;
+ }
+ virtual ~PipeInputImpl() {
+ if (is_)
+ Close();
+ }
+ virtual InputType MyType() { return kPipeInput; }
+ private:
+ std::string filename_;
+ FILE *f_;
+#ifndef _MSC_VER
+ PipebufType *fb_;
+#endif
+ std::istream *is_;
+};
+
+/*
+#else
+
+// Just have an empty implementation of the pipe input that crashes if
+// called.
+class PipeInputImpl: public InputImplBase {
+ public:
+ PipeInputImpl() { KALDI_ASSERT(0 && "Pipe input not yet supported on this
+ platform."); }
+ virtual bool Open(const std::string, bool) { return 0; }
+ virtual std::istream &Stream() const { return NULL; }
+ virtual void Close() {}
+ virtual InputType MyType() { return kPipeInput; }
+};
+
+#endif
+*/
+
+class OffsetFileInputImpl: public InputImplBase {
+ // This class is a bit more complicated than the
+
+ public:
+ // splits a filename like /my/file:123 into /my/file and the
+ // number 123. Crashes if not this format.
+ static void SplitFilename(const std::string &rxfilename,
+ std::string *filename,
+ size_t *offset) {
+ size_t pos = rxfilename.find_last_of(':');
+ KALDI_ASSERT(pos != std::string::npos); // would indicate error in calling
+ // code, as the filename is supposed to be of the correct form at this
+ // point.
+ *filename = std::string(rxfilename, 0, pos);
+ std::string number(rxfilename, pos+1);
+ bool ans = ConvertStringToInteger(number, offset);
+ if (!ans)
+ KALDI_ERR << "Cannot get offset from filename " << rxfilename
+ << " (possibly you compiled in 32-bit and have a >32-bit"
+ << " byte offset into a file; you'll have to compile 64-bit.";
+ }
+
+ bool Seek(size_t offset) {
+ size_t cur_pos = is_.tellg();
+ if (cur_pos == offset) return true;
+ else if (cur_pos<offset && cur_pos+100 > offset) {
+ // We're close enough that it may be faster to just
+ // read that data, rather than seek.
+ for (size_t i = cur_pos; i < offset; i++)
+ is_.get();
+ return (is_.tellg() == std::streampos(offset));
+ }
+ // Try to actually seek.
+ is_.seekg(offset, std::ios_base::beg);
+ if (is_.fail()) { // failbit or badbit is set [error happened]
+ is_.close();
+ return false; // failure.
+ } else {
+ is_.clear(); // Clear any failure bits (e.g. eof).
+ return true; // success.
+ }
+ }
+
+ // This Open routine is unusual in that it is designed to work even
+ // if it was already open. This for efficiency when seeking multiple
+ // times.
+ virtual bool Open(const std::string &rxfilename, bool binary) {
+ if (is_.is_open()) {
+ // We are opening when we have an already-open file.
+ // We may have to seek within this file, or else close it and
+ // open a different one.
+ std::string tmp_filename;
+ size_t offset;
+ SplitFilename(rxfilename, &tmp_filename, &offset);
+ if (tmp_filename == filename_ && binary == binary_) { // Just seek
+ is_.clear(); // clear fail bit, etc.
+ return Seek(offset);
+ } else {
+ is_.close(); // don't bother checking error status of is_.
+ filename_ = tmp_filename;
+ is_.open(MapOsPath(filename_).c_str(),
+ binary ? std::ios_base::in | std::ios_base::binary
+ : std::ios_base::in);
+ if (!is_.is_open()) return false;
+ else
+ return Seek(offset);
+ }
+ } else {
+ size_t offset;
+ SplitFilename(rxfilename, &filename_, &offset);
+ binary_ = binary;
+ is_.open(MapOsPath(filename_).c_str(),
+ binary ? std::ios_base::in | std::ios_base::binary
+ : std::ios_base::in);
+ if (!is_.is_open()) return false;
+ else
+ return Seek(offset);
+ }
+ }
+
+ virtual std::istream &Stream() {
+ if (!is_.is_open())
+ KALDI_ERR << "FileInputImpl::Stream(), file is not open.";
+ // I believe this error can only arise from coding error.
+ return is_;
+ }
+
+ virtual int32 Close() {
+ if (!is_.is_open())
+ KALDI_ERR << "FileInputImpl::Close(), file is not open.";
+ // I believe this error can only arise from coding error.
+ is_.close();
+ // Don't check status.
+ return 0;
+ }
+
+ virtual InputType MyType() { return kOffsetFileInput; }
+
+ virtual ~OffsetFileInputImpl() {
+ // Stream will automatically be closed, and we don't care about
+ // whether it fails.
+ }
+ private:
+ std::string filename_; // the actual filename
+ bool binary_; // true if was opened in binary mode.
+ std::ifstream is_;
+};
+
+
+Output::Output(const std::string &wxfilename, bool binary,
+ bool write_header):impl_(NULL) {
+ if (!Open(wxfilename, binary, write_header)) {
+ if (impl_) {
+ delete impl_;
+ impl_ = NULL;
+ }
+ KALDI_ERR << "Error opening output stream " <<
+ PrintableWxfilename(wxfilename);
+ }
+}
+
+bool Output::Close() {
+ if (!impl_) {
+ return false; // error to call Close if not open.
+ } else {
+ bool ans = impl_->Close();
+ delete impl_;
+ impl_ = NULL;
+ return ans;
+ }
+}
+
+Output::~Output() {
+ if (impl_) {
+ bool ok = impl_->Close();
+ delete impl_;
+ impl_ = NULL;
+ if (!ok)
+ KALDI_ERR << "Error closing output file "
+ << PrintableWxfilename(filename_)
+ << (ClassifyWxfilename(filename_) == kFileOutput ?
+ " (disk full?)" : "");
+ }
+}
+
+std::ostream &Output::Stream() { // will throw if not open; else returns
+ // stream.
+ if (!impl_) KALDI_ERR << "Output::Stream() called but not open.";
+ return impl_->Stream();
+}
+
+bool Output::Open(const std::string &wxfn, bool binary, bool header) {
+ if (IsOpen()) {
+ if (!Close()) { // Throw here rather than return status, as it's an error
+ // about something else: if the user wanted to avoid the exception he/she
+ // could have called Close().
+ KALDI_ERR << "Output::Open(), failed to close output stream: "
+ << PrintableWxfilename(filename_);
+ }
+ }
+
+ filename_ = wxfn;
+
+ OutputType type = ClassifyWxfilename(wxfn);
+ KALDI_ASSERT(impl_ == NULL);
+
+ if (type == kFileOutput) {
+ impl_ = new FileOutputImpl();
+ } else if (type == kStandardOutput) {
+ impl_ = new StandardOutputImpl();
+ } else if (type == kPipeOutput) {
+ impl_ = new PipeOutputImpl();
+ } else { // type == kNoOutput
+ KALDI_WARN << "Invalid output filename format "<<
+ PrintableWxfilename(wxfn);
+ return false;
+ }
+ if (!impl_->Open(wxfn, binary)) {
+ delete impl_;
+ impl_ = NULL;
+ return false; // failed to open.
+ } else { // successfully opened it.
+ if (header) {
+ InitKaldiOutputStream(impl_->Stream(), binary);
+ bool ok = impl_->Stream().good(); // still OK?
+ if (!ok) {
+ delete impl_;
+ impl_ = NULL;
+ return false;
+ }
+ return true;
+ } else {
+ return true;
+ }
+ }
+}
+
+
+Input::Input(const std::string &rxfilename, bool *binary): impl_(NULL) {
+ if (!Open(rxfilename, binary)) {
+ KALDI_ERR << "Error opening input stream "
+ << PrintableRxfilename(rxfilename);
+ }
+}
+
+int32 Input::Close() {
+ if (impl_) {
+ int32 ans = impl_->Close();
+ delete impl_;
+ impl_ = NULL;
+ return ans;
+ } else {
+ return 0;
+ }
+}
+
+bool Input::OpenInternal(const std::string &rxfilename,
+ bool file_binary,
+ bool *contents_binary) {
+ InputType type = ClassifyRxfilename(rxfilename);
+ if (IsOpen()) {
+ // May have to close the stream first.
+ if (type == kOffsetFileInput && impl_->MyType() == kOffsetFileInput) {
+ // We want to use the same object to Open... this is in case
+ // the files are the same, so we can just seek.
+ if (!impl_->Open(rxfilename, file_binary)) { // true is binary mode--
+ // always open in binary.
+ delete impl_;
+ impl_ = NULL;
+ return false;
+ }
+ // read the binary header, if requested.
+ if (contents_binary != NULL)
+ return InitKaldiInputStream(impl_->Stream(), contents_binary);
+ else
+ return true;
+ } else {
+ Close();
+ // and fall through to code below which actually opens the file.
+ }
+ }
+ if (type == kFileInput) {
+ impl_ = new FileInputImpl();
+ } else if (type == kStandardInput) {
+ impl_ = new StandardInputImpl();
+ } else if (type == kPipeInput) {
+ impl_ = new PipeInputImpl();
+ } else if (type == kOffsetFileInput) {
+ impl_ = new OffsetFileInputImpl();
+ } else { // type == kNoInput
+ KALDI_WARN << "Invalid input filename format "<<
+ PrintableRxfilename(rxfilename);
+ return false;
+ }
+ if (!impl_->Open(rxfilename, file_binary)) { // true is binary mode--
+ // always read in binary.
+ delete impl_;
+ impl_ = NULL;
+ return false;
+ }
+ if (contents_binary != NULL)
+ return InitKaldiInputStream(impl_->Stream(), contents_binary);
+ else
+ return true;
+}
+
+
+Input::~Input() { if (impl_) Close(); }
+
+
+std::istream &Input::Stream() {
+ if (!IsOpen()) KALDI_ERR << "Input::Stream(), not open.";
+ return impl_->Stream();
+}
+
+
+//template <> void ReadKaldiObject(const std::string &filename,
+// Matrix<float> *m) {
+// if (!filename.empty() && filename[filename.size() - 1] == ']') {
+// // This filename seems to have a 'range'... like foo.ark:4312423[20:30].
+// // (the bit in square brackets is the range).
+// std::string rxfilename, range;
+// if (!ExtractRangeSpecifier(filename, &rxfilename, &range)) {
+// KALDI_ERR << "Could not make sense of possible range specifier in filename "
+// << "while reading matrix: " << filename;
+// }
+// Matrix<float> temp;
+// bool binary_in;
+// Input ki(rxfilename, &binary_in);
+// temp.Read(ki.Stream(), binary_in);
+// if (!ExtractObjectRange(temp, range, m)) {
+// KALDI_ERR << "Error extracting range of object: " << filename;
+// }
+// } else {
+// // The normal case, there is no range.
+// bool binary_in;
+// Input ki(filename, &binary_in);
+// m->Read(ki.Stream(), binary_in);
+// }
+//}
+//
+//template <> void ReadKaldiObject(const std::string &filename,
+// Matrix<double> *m) {
+// if (!filename.empty() && filename[filename.size() - 1] == ']') {
+// // This filename seems to have a 'range'... like foo.ark:4312423[20:30].
+// // (the bit in square brackets is the range).
+// std::string rxfilename, range;
+// if (!ExtractRangeSpecifier(filename, &rxfilename, &range)) {
+// KALDI_ERR << "Could not make sense of possible range specifier in filename "
+// << "while reading matrix: " << filename;
+// }
+// Matrix<double> temp;
+// bool binary_in;
+// Input ki(rxfilename, &binary_in);
+// temp.Read(ki.Stream(), binary_in);
+// if (!ExtractObjectRange(temp, range, m)) {
+// KALDI_ERR << "Error extracting range of object: " << filename;
+// }
+// } else {
+// // The normal case, there is no range.
+// bool binary_in;
+// Input ki(filename, &binary_in);
+// m->Read(ki.Stream(), binary_in);
+// }
+//}
+
+} // end namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/util/kaldi-io.h b/runtime/onnxruntime/third_party/kaldi/util/kaldi-io.h
new file mode 100644
index 000000000..2bf2060bb
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/kaldi-io.h
@@ -0,0 +1,280 @@
+// util/kaldi-io.h
+
+// Copyright 2009-2011 Microsoft Corporation; Jan Silovsky
+// 2016 Xiaohui Zhang
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#ifndef KALDI_UTIL_KALDI_IO_H_
+#define KALDI_UTIL_KALDI_IO_H_
+
+#ifdef _MSC_VER
+# include <fcntl.h>
+# include <io.h>
+#endif
+#include <cctype> // For isspace.
+#include <limits>
+#include <string>
+#include "base/kaldi-common.h"
+//#include "matrix/kaldi-matrix.h"
+
+
+namespace kaldi {
+
+class OutputImplBase; // Forward decl; defined in a .cc file
+class InputImplBase; // Forward decl; defined in a .cc file
+
+/// \addtogroup io_group
+/// @{
+
+// The Output and Input classes handle stream-opening for "extended" filenames
+// that include actual files, standard-input/standard-output, pipes, and
+// offsets into actual files. They also handle reading and writing the
+// binary-mode headers for Kaldi files, where applicable. The classes have
+// versions of the Open routines that throw and do not throw, depending whether
+// the calling code wants to catch the errors or not; there are also versions
+// that write (or do not write) the Kaldi binary-mode header that says if it's
+// binary mode. Generally files that contain Kaldi objects will have the header
+// on, so we know upon reading them whether they have the header. So you would
+// use the OpenWithHeader routines for these (or the constructor); but other
+// types of objects (e.g. FSTs) would have files without a header so you would
+// use OpenNoHeader.
+
+// We now document the types of extended filenames that we use.
+//
+// A "wxfilename" is an extended filename for writing. It can take three forms:
+// (1) Filename: e.g. "/some/filename", "./a/b/c", "c:\Users\dpovey\My
+// Documents\\boo"
+// (whatever the actual file-system interprets)
+// (2) Standard output: "" or "-"
+// (3) A pipe: e.g. "| gzip -c > /tmp/abc.gz"
+//
+//
+// A "rxfilename" is an extended filename for reading. It can take four forms:
+// (1) An actual filename, whatever the file-system can read, e.g. "/my/file".
+// (2) Standard input: "" or "-"
+// (3) A pipe: e.g. "gunzip -c /tmp/abc.gz |"
+// (4) An offset into a file, e.g.: "/mnt/blah/data/1.ark:24871"
+// [these are created by the Table and TableWriter classes; I may also write
+// a program that creates them for arbitrary files]
+//
+
+
+// Typical usage:
+// ...
+// bool binary;
+// MyObject.Write(Output(some_filename, binary).Stream(), binary);
+//
+// ... more extensive example:
+// {
+// Output ko(some_filename, binary);
+// MyObject1.Write(ko.Stream(), binary);
+// MyObject2.Write(ko.Stream(), binary);
+// }
+
+
+
+enum OutputType {
+ kNoOutput,
+ kFileOutput,
+ kStandardOutput,
+ kPipeOutput
+};
+
+/// ClassifyWxfilename interprets filenames as follows:
+/// - kNoOutput: invalid filenames (leading or trailing space, things that look
+/// like wspecifiers and rspecifiers or like pipes to read from with leading
+/// |.
+/// - kFileOutput: Normal filenames
+/// - kStandardOutput: The empty string or "-", interpreted as standard output
+/// - kPipeOutput: pipes, e.g. "| gzip -c > /tmp/abc.gz"
+OutputType ClassifyWxfilename(const std::string &wxfilename);
+
+enum InputType {
+ kNoInput,
+ kFileInput,
+ kStandardInput,
+ kOffsetFileInput,
+ kPipeInput
+};
+
+/// ClassifyRxfilenames interprets filenames for reading as follows:
+/// - kNoInput: invalid filenames (leading or trailing space, things that
+/// look like wspecifiers and rspecifiers or pipes to write to
+/// with trailing |.
+/// - kFileInput: normal filenames
+/// - kStandardInput: the empty string or "-"
+/// - kPipeInput: e.g. "gunzip -c /tmp/abc.gz |"
+/// - kOffsetFileInput: offsets into files, e.g. /some/filename:12970
+InputType ClassifyRxfilename(const std::string &rxfilename);
+
+
+class Output {
+ public:
+ // The normal constructor, provided for convenience.
+ // Equivalent to calling with default constructor then Open()
+ // with these arguments.
+ Output(const std::string &filename, bool binary, bool write_header = true);
+
+ Output(): impl_(NULL) {}
+
+ /// This opens the stream, with the given mode (binary or text). It returns
+ /// true on success and false on failure. However, it will throw if something
+ /// was already open and could not be closed (to avoid this, call Close()
+ /// first. if write_header == true and binary == true, it writes the Kaldi
+ /// binary-mode header ('\0' then 'B'). You may call Open even if it is
+ /// already open; it will close the existing stream and reopen (however if
+ /// closing the old stream failed it will throw).
+ bool Open(const std::string &wxfilename, bool binary, bool write_header);
+
+ inline bool IsOpen(); // return true if we have an open stream. Does not
+ // imply stream is good for writing.
+
+ std::ostream &Stream(); // will throw if not open; else returns stream.
+
+ // Close closes the stream. Calling Close is never necessary unless you
+ // want to avoid exceptions being thrown. There are times when calling
+ // Close will hurt efficiency (basically, when using offsets into files,
+ // and using the same Input object),
+ // but most of the time the user won't be doing this directly, it will
+ // be done in kaldi-table.{h, cc}, so you don't have to worry about it.
+ bool Close();
+
+ // This will throw if stream could not be closed (to check error status,
+ // call Close()).
+ ~Output();
+
+ private:
+ OutputImplBase *impl_; // non-NULL if open.
+ std::string filename_;
+ KALDI_DISALLOW_COPY_AND_ASSIGN(Output);
+};
+
+
+// bool binary_in;
+// Input ki(some_filename, &binary_in);
+// MyObject.Read(ki.Stream(), binary_in);
+//
+// ... more extensive example:
+//
+// {
+// bool binary_in;
+// Input ki(some_filename, &binary_in);
+// MyObject1.Read(ki.Stream(), &binary_in);
+// MyObject2.Write(ki.Stream(), &binary_in);
+// }
+// Note that to catch errors you need to use try.. catch.
+// Input communicates errors by throwing exceptions.
+
+
+// Input interprets four kinds of filenames:
+// (1) Normal filenames
+// (2) The empty string or "-", interpreted as standard output
+// (3) A pipe: e.g. "gunzip -c /tmp/abc.gz |"
+// (4) Offsets into [real] files, e.g. "/my/filename:12049"
+// The last one has no correspondence in Output.
+
+
+class Input {
+ public:
+ /// The normal constructor. Opens the stream in binary mode.
+ /// Equivalent to calling the default constructor followed by Open(); then, if
+ /// binary != NULL, it calls ReadHeader(), putting the output in "binary"; it
+ /// throws on error.
+ Input(const std::string &rxfilename, bool *contents_binary = NULL);
+
+ Input(): impl_(NULL) {}
+
+ // Open opens the stream for reading (the mode, where relevant, is binary; use
+ // OpenTextMode for text-mode, we made this a separate function rather than a
+ // boolean argument, to avoid confusion with Kaldi's text/binary distinction,
+ // since reading in the file system's text mode is unusual.) If
+ // contents_binary != NULL, it reads the binary-mode header and puts it in the
+ // "binary" variable. Returns true on success. If it returns false it will
+ // not be open. You may call Open even if it is already open; it will close
+ // the existing stream and reopen (however if closing the old stream failed it
+ // will throw).
+ inline bool Open(const std::string &rxfilename, bool *contents_binary = NULL);
+
+ // As Open but (if the file system has text/binary modes) opens in text mode;
+ // you shouldn't ever have to use this as in Kaldi we read even text files in
+ // binary mode (and ignore the \r).
+ inline bool OpenTextMode(const std::string &rxfilename);
+
+ // Return true if currently open for reading and Stream() will
+ // succeed. Does not guarantee that the stream is good.
+ inline bool IsOpen();
+
+ // It is never necessary or helpful to call Close, except if
+ // you are concerned about to many filehandles being open.
+ // Close does not throw. It returns the exit code as int32
+ // in the case of a pipe [kPipeInput], and always zero otherwise.
+ int32 Close();
+
+ // Returns the underlying stream. Throws if !IsOpen()
+ std::istream &Stream();
+
+ // Destructor does not throw: input streams may legitimately fail so we
+ // don't worry about the status when we close them.
+ ~Input();
+ private:
+ bool OpenInternal(const std::string &rxfilename, bool file_binary,
+ bool *contents_binary);
+ InputImplBase *impl_;
+ KALDI_DISALLOW_COPY_AND_ASSIGN(Input);
+};
+
+template <class C> void ReadKaldiObject(const std::string &filename,
+ C *c) {
+ bool binary_in;
+ Input ki(filename, &binary_in);
+ c->Read(ki.Stream(), binary_in);
+}
+
+// Specialize the template for reading matrices, because we want to be able to
+// support reading 'ranges' (row and column ranges), like foo.mat[10:20].
+//template <> void ReadKaldiObject(const std::string &filename,
+// Matrix<float> *m);
+//
+//
+//template <> void ReadKaldiObject(const std::string &filename,
+// Matrix<double> *m);
+
+
+
+template <class C> inline void WriteKaldiObject(const C &c,
+ const std::string &filename,
+ bool binary) {
+ Output ko(filename, binary);
+ c.Write(ko.Stream(), binary);
+}
+
+/// PrintableRxfilename turns the rxfilename into a more human-readable
+/// form for error reporting, i.e. it does quoting and escaping and
+/// replaces "" or "-" with "standard input".
+std::string PrintableRxfilename(const std::string &rxfilename);
+
+/// PrintableWxfilename turns the wxfilename into a more human-readable
+/// form for error reporting, i.e. it does quoting and escaping and
+/// replaces "" or "-" with "standard output".
+std::string PrintableWxfilename(const std::string &wxfilename);
+
+/// @}
+
+} // end namespace kaldi.
+
+#include "util/kaldi-io-inl.h"
+
+#endif // KALDI_UTIL_KALDI_IO_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/kaldi-pipebuf.h b/runtime/onnxruntime/third_party/kaldi/util/kaldi-pipebuf.h
new file mode 100644
index 000000000..61034ac27
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/kaldi-pipebuf.h
@@ -0,0 +1,87 @@
+// util/kaldi-pipebuf.h
+
+// Copyright 2009-2011 Ondrej Glembek
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+/** @file kaldi-pipebuf.h
+ * This is an Kaldi C++ Library header.
+ */
+
+#ifndef KALDI_UTIL_KALDI_PIPEBUF_H_
+#define KALDI_UTIL_KALDI_PIPEBUF_H_
+
+#include<string>
+#if !defined(_LIBCPP_VERSION) // libc++
+#include <fstream>
+#else
+#include "util/basic-filebuf.h"
+#endif
+
+namespace kaldi {
+// This class provides a way to initialize a filebuf with a FILE* pointer
+// directly; it will not close the file pointer when it is deleted.
+// The C++ standard does not allow implementations of C++ to provide
+// this constructor within basic_filebuf, which makes it hard to deal
+// with pipes using completely native C++. This is a workaround
+
+#ifdef _MSC_VER
+#elif defined(_LIBCPP_VERSION) // libc++
+template<class CharType, class Traits = std::char_traits<CharType> >
+class basic_pipebuf : public basic_filebuf<CharType, Traits> {
+ public:
+ typedef basic_pipebuf<CharType, Traits> ThisType;
+
+ public:
+ basic_pipebuf(FILE *fptr, std::ios_base::openmode mode)
+ : basic_filebuf<CharType, Traits>() {
+ this->open(fptr, mode);
+ if (!this->is_open()) {
+ KALDI_WARN << "Error initializing pipebuf"; // probably indicates
+ // code error, if the fptr was good.
+ return;
+ }
+ }
+}; // class basic_pipebuf
+#else
+template<class CharType, class Traits = std::char_traits<CharType> >
+class basic_pipebuf : public std::basic_filebuf<CharType, Traits> {
+ public:
+ typedef basic_pipebuf<CharType, Traits> ThisType;
+
+ public:
+ basic_pipebuf(FILE *fptr, std::ios_base::openmode mode)
+ : std::basic_filebuf<CharType, Traits>() {
+ this->_M_file.sys_open(fptr, mode);
+ if (!this->is_open()) {
+ KALDI_WARN << "Error initializing pipebuf"; // probably indicates
+ // code error, if the fptr was good.
+ return;
+ }
+ this->_M_mode = mode;
+ this->_M_buf_size = BUFSIZ;
+ this->_M_allocate_internal_buffer();
+ this->_M_reading = false;
+ this->_M_writing = false;
+ this->_M_set_buffer(-1);
+ }
+}; // class basic_pipebuf
+#endif // _MSC_VER
+
+} // namespace kaldi
+
+#endif // KALDI_UTIL_KALDI_PIPEBUF_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/kaldi-semaphore.cc b/runtime/onnxruntime/third_party/kaldi/util/kaldi-semaphore.cc
new file mode 100644
index 000000000..f0829ac0f
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/kaldi-semaphore.cc
@@ -0,0 +1,57 @@
+// util/kaldi-semaphore.cc
+
+// Copyright 2012 Karel Vesely (Brno University of Technology)
+// 2017 Dogan Can (University of Southern California)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+
+#include "base/kaldi-error.h"
+#include "util/kaldi-semaphore.h"
+
+namespace kaldi {
+
+Semaphore::Semaphore(int32 count) {
+ KALDI_ASSERT(count >= 0);
+ count_ = count;
+}
+
+Semaphore::~Semaphore() {}
+
+bool Semaphore::TryWait() {
+ std::unique_lock<std::mutex> lock(mutex_);
+ if(count_) {
+ count_--;
+ return true;
+ }
+ return false;
+}
+
+void Semaphore::Wait() {
+ std::unique_lock<std::mutex> lock(mutex_);
+ while(!count_)
+ condition_variable_.wait(lock);
+ count_--;
+}
+
+void Semaphore::Signal() {
+ std::unique_lock<std::mutex> lock(mutex_);
+ count_++;
+ condition_variable_.notify_one();
+}
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/util/kaldi-semaphore.h b/runtime/onnxruntime/third_party/kaldi/util/kaldi-semaphore.h
new file mode 100644
index 000000000..2562053cf
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/kaldi-semaphore.h
@@ -0,0 +1,50 @@
+// util/kaldi-semaphore.h
+
+// Copyright 2012 Karel Vesely (Brno University of Technology)
+// 2017 Dogan Can (University of Southern California)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_THREAD_KALDI_SEMAPHORE_H_
+#define KALDI_THREAD_KALDI_SEMAPHORE_H_ 1
+
+#include <mutex>
+#include <condition_variable>
+
+namespace kaldi {
+
+class Semaphore {
+ public:
+ Semaphore(int32 count = 0);
+
+ ~Semaphore();
+
+ bool TryWait(); ///< Returns true if Wait() goes through
+ void Wait(); ///< decrease the counter
+ void Signal(); ///< increase the counter
+
+ private:
+ int32 count_; ///< the semaphore counter, 0 means block on Wait()
+
+ std::mutex mutex_;
+ std::condition_variable condition_variable_;
+ KALDI_DISALLOW_COPY_AND_ASSIGN(Semaphore);
+};
+
+} //namespace
+
+#endif // KALDI_THREAD_KALDI_SEMAPHORE_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/kaldi-thread-test.cc b/runtime/onnxruntime/third_party/kaldi/util/kaldi-thread-test.cc
new file mode 100644
index 000000000..eb6b72d1e
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/kaldi-thread-test.cc
@@ -0,0 +1,133 @@
+// util/kaldi-thread-test.cc
+
+// Copyright 2012 Johns Hopkins University (Author: Daniel Povey)
+// Frantisek Skala
+// 2017 University of Southern California (Author: Dogan Can)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include <algorithm>
+#include "base/kaldi-common.h"
+#include "util/kaldi-thread.h"
+
+namespace kaldi {
+
+// Sums up integers from 0 to max_to_count-1.
+class MyThreadClass : public MultiThreadable {
+ public:
+ MyThreadClass(int32 max_to_count, int32 *i):
+ max_to_count_(max_to_count), iptr_(i), private_counter_(0) { }
+
+ // We are defining a copy constructor to ensure that whenever an instance of
+ // this class is copied, the default *copy* constructor for MultiThreadable
+ // is called instead the default constructor for MultiThreadable.
+ MyThreadClass(const MyThreadClass &other):
+ MultiThreadable(other),
+ max_to_count_(other.max_to_count_), iptr_(other.iptr_),
+ private_counter_(0) { }
+
+ void operator() () {
+ int32 block_size = (max_to_count_+ (num_threads_-1) ) / num_threads_;
+ int32 start = block_size * thread_id_,
+ end = std::min(max_to_count_, start + block_size);
+ for (int32 j = start; j < end; j++)
+ private_counter_ += j;
+ }
+
+ ~MyThreadClass() {
+ *iptr_ += private_counter_;
+ }
+
+ private:
+ MyThreadClass() { } // Disallow empty constructor.
+ int32 max_to_count_;
+ int32 *iptr_;
+ int32 private_counter_;
+};
+
+
+void TestThreads() {
+ g_num_threads = 8;
+ // run method with temporary threads on 8 threads
+ // Note: uncomment following line for the possibility of simple benchmarking
+ // for(int i=0; i<100000; i++)
+ {
+ int32 max_to_count = 10000, tot = 0;
+ MyThreadClass c(max_to_count, &tot);
+ RunMultiThreaded(c);
+ KALDI_ASSERT(tot == (10000*(10000-1))/2);
+ }
+ g_num_threads = 1;
+ // let's try the same, but with only one thread
+ {
+ int32 max_to_count = 10000, tot = 0;
+ MyThreadClass c(max_to_count, &tot);
+ RunMultiThreaded(c);
+ KALDI_ASSERT(tot == (10000*(10000-1))/2);
+ }
+}
+
+class MyTaskClass { // spins for a while, then outputs a pre-given integer.
+ public:
+ MyTaskClass(int32 i, std::vector<int32> *vec):
+ done_(false), i_(i), vec_(vec) { }
+
+ void operator() () {
+ int32 spin = 1000000 * Rand() % 100;
+ for (int32 i = 0; i < spin; i++);
+ done_ = true;
+ }
+ ~MyTaskClass() {
+ KALDI_ASSERT(done_);
+ vec_->push_back(i_);
+ }
+
+ private:
+ bool done_;
+ int32 i_;
+ std::vector<int32> *vec_;
+};
+
+
+void TestTaskSequencer() {
+ TaskSequencerConfig config;
+ config.num_threads = 1 + Rand() % 20;
+ if (Rand() % 2 == 1 )
+ config.num_threads_total = config.num_threads + Rand() % config.num_threads;
+
+ int32 num_tasks = Rand() % 100;
+
+ std::vector<int32> task_output;
+ {
+ TaskSequencer<MyTaskClass> sequencer(config);
+ for (int32 i = 0; i < num_tasks; i++) {
+ sequencer.Run(new MyTaskClass(i, &task_output));
+ }
+ } // and let "sequencer" be destroyed, which waits for the last threads.
+ KALDI_ASSERT(task_output.size() == static_cast<size_t>(num_tasks));
+ for (int32 i = 0; i < num_tasks; i++)
+ KALDI_ASSERT(task_output[i] == i);
+}
+
+
+} // end namespace kaldi.
+
+int main() {
+ using namespace kaldi;
+ TestThreads();
+ for (int32 i = 0; i < 10; i++)
+ TestTaskSequencer();
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/util/kaldi-thread.cc b/runtime/onnxruntime/third_party/kaldi/util/kaldi-thread.cc
new file mode 100644
index 000000000..2405d01f1
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/kaldi-thread.cc
@@ -0,0 +1,33 @@
+// util/kaldi-thread.cc
+
+// Copyright 2012 Johns Hopkins University (Author: Daniel Povey)
+// Frantisek Skala
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "base/kaldi-common.h"
+#include "util/kaldi-thread.h"
+
+namespace kaldi {
+int32 g_num_threads = 8; // Initialize this global variable.
+
+MultiThreadable::~MultiThreadable() {
+ // default implementation does nothing
+}
+
+
+
+} // end namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/util/kaldi-thread.h b/runtime/onnxruntime/third_party/kaldi/util/kaldi-thread.h
new file mode 100644
index 000000000..29cfaee8a
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/kaldi-thread.h
@@ -0,0 +1,290 @@
+// util/kaldi-thread.h
+
+// Copyright 2012 Johns Hopkins University (Author: Daniel Povey)
+// Frantisek Skala
+// 2017 University of Southern California (Author: Dogan Can)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_THREAD_KALDI_THREAD_H_
+#define KALDI_THREAD_KALDI_THREAD_H_ 1
+
+#include <thread>
+#include <algorithm>
+#include "itf/options-itf.h"
+#include "util/kaldi-semaphore.h"
+
+// This header provides convenient mechanisms for parallelization.
+//
+// The class MultiThreader, and the function RunMultiThreaded provide a
+// mechanism to run a specified number of jobs in parellel and wait for them
+// all to finish. They accept objects of some class C that derives from the
+// base class MultiThreadable. C needs to define the operator () that takes
+// no arguments. See ExampleClass below.
+//
+// The class TaskSequencer addresses a different problem typically encountered
+// in Kaldi command-line programs that process a sequence of items. The items
+// to be processed are coming in. They are all of different sizes, e.g.
+// utterances with different numbers of frames. We would like them to be
+// processed in parallel to make good use of the threads available but they
+// must be output in the same order they came in. Here, we again accept objects
+// of some class C with an operator () that takes no arguments. C may also have
+// a destructor with side effects (typically some kind of output).
+// TaskSequencer is responsible for running the jobs in parallel. It has a
+// function Run() that will accept a new object of class C; this will block
+// until a thread is free, at which time it will spawn a thread that starts
+// running the operator () of the object. When threads are finished running,
+// the objects will be deleted. TaskSequencer guarantees that the destructors
+// will be called sequentially (not in parallel) and in the same order the
+// objects were given to the Run() function, so that it is safe for the
+// destructor to have side effects such as outputting data.
+// Note: the destructor of TaskSequencer will wait for any remaining jobs that
+// are still running and will call the destructors.
+
+
+namespace kaldi {
+
+extern int32 g_num_threads; // Maximum number of threads (for programs that
+// use threads, which is not many of them, e.g. the SGMM update program does.
+// This is 8 by default. You can change this on the command line, where
+// used, with --num-threads. Programs that think they will use threads
+// should register it with their ParseOptions, as something like:
+// po.Register("num-threads", &g_num_threads, "Number of threads to use.");
+
+class MultiThreadable {
+ // To create a function object that does part of the job, inherit from this
+ // class, implement a copy constructor calling the default copy constructor
+ // of this base class (so that thread_id_ and num_threads_ are copied to new
+ // instances), and finally implement the operator() that does part of the job
+ // based on thread_id_ and num_threads_ variables.
+ // Note: example implementations are in util/kaldi-thread-test.cc
+ public:
+ virtual void operator() () = 0;
+ // Does the main function of the class
+ // Subclasses have to redefine this
+ virtual ~MultiThreadable();
+ // Optional destructor. Note: the destructor of the object passed by the user
+ // will also be called, so watch out.
+
+ public:
+ // Do not redeclare thread_id_ and num_threads_ in derived classes.
+ int32 thread_id_; // 0 <= thread_id_ < num_threads_
+ int32 num_threads_;
+
+ private:
+ // Have additional member variables as needed.
+};
+
+
+class ExampleClass: public MultiThreadable {
+ public:
+ ExampleClass(int32 *foo); // Typically there will be an initializer that
+ // takes arguments.
+
+ ExampleClass(const ExampleClass &other); // A copy constructor is also needed;
+ // some example classes use the default version of this.
+
+ void operator() () {
+ // Does the main function of the class. This
+ // function will typically want to look at the values of the
+ // member variables thread_id_ and num_threads_, inherited
+ // from MultiThreadable.
+ }
+ ~ExampleClass() {
+ // Optional destructor. Sometimes useful things happen here,
+ // for example summing up of certain quantities. See code
+ // that uses RunMultiThreaded for examples.
+ }
+ private:
+ // Have additional member variables as needed.
+};
+
+
+template<class C>
+class MultiThreader {
+ public:
+ MultiThreader(int32 num_threads, const C &c_in) :
+ threads_(std::max<int32>(1, num_threads)),
+ cvec_(std::max<int32>(1, num_threads), c_in) {
+ if (num_threads == 0) {
+ // This is a special case with num_threads == 0, which behaves like with
+ // num_threads == 1 but without creating extra threads. This can be
+ // useful in GPU computations where threads cannot be used.
+ cvec_[0].thread_id_ = 0;
+ cvec_[0].num_threads_ = 1;
+ (cvec_[0])();
+ } else {
+ for (int32 i = 0; i < threads_.size(); i++) {
+ cvec_[i].thread_id_ = i;
+ cvec_[i].num_threads_ = threads_.size();
+ threads_[i] = std::thread(std::ref(cvec_[i]));
+ }
+ }
+ }
+ ~MultiThreader() {
+ for (size_t i = 0; i < threads_.size(); i++)
+ if (threads_[i].joinable())
+ threads_[i].join();
+ }
+ private:
+ std::vector<std::thread> threads_;
+ std::vector<C> cvec_;
+};
+
+/// Here, class C should inherit from MultiThreadable. Note: if you want to
+/// control the number of threads yourself, or need to do something in the main
+/// thread of the program while the objects exist, just initialize the
+/// MultiThreader<C> object yourself.
+template<class C> void RunMultiThreaded(const C &c_in) {
+ MultiThreader<C> m(g_num_threads, c_in);
+}
+
+
+struct TaskSequencerConfig {
+ int32 num_threads;
+ int32 num_threads_total;
+ TaskSequencerConfig(): num_threads(1), num_threads_total(0) { }
+ void Register(OptionsItf *opts) {
+ opts->Register("num-threads", &num_threads, "Number of actively processing "
+ "threads to run in parallel");
+ opts->Register("num-threads-total", &num_threads_total, "Total number of "
+ "threads, including those that are waiting on other threads "
+ "to produce their output. Controls memory use. If <= 0, "
+ "defaults to --num-threads plus 20. Otherwise, must "
+ "be >= num-threads.");
+ }
+};
+
+// C should have an operator () taking no arguments, that does some kind
+// of computation, and a destructor that produces some kind of output (the
+// destructors will be run sequentially in the same order Run as called.
+template<class C>
+class TaskSequencer {
+ public:
+ TaskSequencer(const TaskSequencerConfig &config):
+ num_threads_(config.num_threads),
+ threads_avail_(config.num_threads),
+ tot_threads_avail_(config.num_threads_total > 0 ? config.num_threads_total :
+ config.num_threads + 20),
+ thread_list_(NULL) {
+ KALDI_ASSERT((config.num_threads_total <= 0 ||
+ config.num_threads_total >= config.num_threads) &&
+ "num-threads-total, if specified, must be >= num-threads");
+ }
+
+ /// This function takes ownership of the pointer "c", and will delete it
+ /// in the same sequence as Run was called on the jobs.
+ void Run(C *c) {
+ // run in main thread
+ if (num_threads_ == 0) {
+ (*c)();
+ delete c;
+ return;
+ }
+
+ threads_avail_.Wait(); // wait till we have a thread for computation free.
+ tot_threads_avail_.Wait(); // this ensures we don't have too many threads
+ // waiting on I/O, and consume too much memory.
+
+ // put the new RunTaskArgsList object at head of the singly
+ // linked list thread_list_.
+ thread_list_ = new RunTaskArgsList(this, c, thread_list_);
+ thread_list_->thread = std::thread(TaskSequencer<C>::RunTask,
+ thread_list_);
+ }
+
+ void Wait() { // You call this at the end if it's more convenient
+ // than waiting for the destructor. It waits for all tasks to finish.
+ if (thread_list_ != NULL) {
+ while (!thread_list_->thread.joinable()) {
+ Sleep(1);
+ }
+ thread_list_->thread.join();
+ KALDI_ASSERT(thread_list_->tail == NULL); // thread would not
+ // have exited without setting tail to NULL.
+ delete thread_list_;
+ thread_list_ = NULL;
+ }
+ }
+
+ /// The destructor waits for the last thread to exit.
+ ~TaskSequencer() {
+ Wait();
+ }
+ private:
+ struct RunTaskArgsList {
+ TaskSequencer *me; // Think of this as a "this" pointer.
+ C *c; // Clist element of the task we're expected
+ std::thread thread;
+ RunTaskArgsList *tail;
+ RunTaskArgsList(TaskSequencer *me, C *c, RunTaskArgsList *tail):
+ me(me), c(c), tail(tail) {}
+ };
+ // This static function gets run in the threads that we create.
+ static void RunTask(RunTaskArgsList *args) {
+ // (1) run the job.
+ (*(args->c))(); // call operator () on args->c, which does the computation.
+ args->me->threads_avail_.Signal(); // Signal that the compute-intensive
+ // part of the thread is done (we want to run no more than
+ // config_.num_threads of these.)
+
+ // (2) we want to destroy the object "c" now, by deleting it. But for
+ // correct sequencing (this is the whole point of this class, it
+ // is intended to ensure the output of the program is in correct order),
+ // we first wait till the previous thread, whose details will be in "tail",
+ // is finished.
+ if (args->tail != NULL) {
+ while (!args->tail->thread.joinable()){
+ Sleep(1);
+ }
+ args->tail->thread.join();
+ }
+ delete args->c; // delete the object "c". This may cause some output,
+ // e.g. to a stream. We don't need to worry about concurrent access to
+ // the output stream, because each thread waits for the previous thread
+ // to be done, before doing this. So there is no risk of concurrent
+ // access.
+ args->c = NULL;
+
+ if (args->tail != NULL) {
+ KALDI_ASSERT(args->tail->tail == NULL); // Because we already
+ // did join on args->tail->thread, which means that
+ // thread was done, and before it exited, it would have
+ // deleted and set to NULL its tail (which is the next line of code).
+ delete args->tail;
+ args->tail = NULL;
+ }
+ // At this point we are exiting from the thread. Signal the
+ // "tot_threads_avail_" semaphore which is used to limit the total number of threads that are alive, including
+ // not onlhy those that are in active computation in c->operator (), but those
+ // that are waiting on I/O or other threads.
+ args->me->tot_threads_avail_.Signal();
+ }
+
+ int32 num_threads_; // copy of config.num_threads (since Semaphore doesn't store original count)
+
+ Semaphore threads_avail_; // Initialized to the number of threads we are
+ // supposed to run with; the function Run() waits on this.
+
+ Semaphore tot_threads_avail_; // We use this semaphore to ensure we don't
+ // consume too much memory...
+ RunTaskArgsList *thread_list_;
+
+};
+
+} // namespace kaldi
+
+#endif // KALDI_THREAD_KALDI_THREAD_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/parse-options-test.cc b/runtime/onnxruntime/third_party/kaldi/util/parse-options-test.cc
new file mode 100644
index 000000000..af1fcc008
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/parse-options-test.cc
@@ -0,0 +1,319 @@
+// util/parse-options-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+// Copyright 2012-2013 Frantisek Skala; Arnab Ghoshal
+// Copyright 2013 Tanel Alumae
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#include "util/parse-options.h"
+
+namespace kaldi {
+
+struct DummyOptions {
+ int32 my_int;
+ bool my_bool;
+ std::string my_string;
+
+ DummyOptions() {
+ my_int = 0;
+ my_bool = true;
+ my_string = "default dummy string";
+ }
+
+ void Register(ParseOptions *po) {
+ po->Register("my-int", &my_int,
+ "An int32 variable in DummyOptions.");
+ po->Register("my-bool", &my_bool,
+ "A Boolean varaible in DummyOptions.");
+ po->Register("my-str", &my_string,
+ "A string varaible in DummyOptions.");
+ }
+};
+
+void UnitTestParseOptions() {
+ int argc = 7;
+ std::string str="default_for_str";
+ int32 num = 1;
+ uint32 unum = 2;
+ const char *argv[7] = { "program_name", "--unum=5", "--num=3", "--i=boo",
+ "a", "b", "c" };
+ ParseOptions po("my usage msg");
+ po.Register("i", &str, "My variable");
+ po.Register("num", &num, "My int32 variable");
+ po.Register("unum", &unum, "My uint32 variable");
+ po.Read(argc, argv);
+ KALDI_ASSERT(po.NumArgs() == 3);
+ KALDI_ASSERT(po.GetArg(1) == "a");
+ KALDI_ASSERT(po.GetArg(2) == "b");
+ KALDI_ASSERT(po.GetArg(3) == "c");
+ KALDI_ASSERT(unum == 5);
+ KALDI_ASSERT(num == 3);
+ KALDI_ASSERT(str == "boo");
+
+ ParseOptions po2("my another msg");
+ int argc2 = 4;
+ const char *argv2[4] = { "program_name", "--i=foo",
+ "--to-be-NORMALIZED=test", "c" };
+ std::string str2 = "default_for_str2";
+ po2.Register("To_Be_Normalized", &str2,
+ "My variable (name has to be normalized)");
+ po2.Register("i", &str, "My variable");
+ po2.Read(argc2, argv2);
+ KALDI_ASSERT(po2.NumArgs() == 1);
+ KALDI_ASSERT(po2.GetArg(1) == "c");
+ KALDI_ASSERT(str2 == "test");
+ KALDI_ASSERT(str == "foo");
+
+ ParseOptions po3("now checking options with prefix");
+ ParseOptions ro3("prefix", &po3); // to register with prefix
+ ParseOptions so3("prefix2", &ro3); // to register with prefix, recursively.
+ DummyOptions dummy_opts;
+ po3.Register("str", &str, "My string variable");
+ po3.Register("num", &num, "My int32 variable");
+ // Now register with prefix
+ ro3.Register("unum", &unum, "My uint32 variable");
+ ro3.Register("str", &str2, "My other string variable");
+ uint32 unum2 = 0;
+ so3.Register("unum", &unum2, "Another uint32 variable");
+
+ int argc3 = 10;
+ const char *argv3[10] = {
+ "program_name", "--prefix.unum=5", "--num=3",
+ "--prefix.str=foo", "--str=bar", "--prefix.my-bool=false",
+ "--prefix.my-str=baz", "--prefix.prefix2.unum=42", "a", "b" };
+
+ dummy_opts.Register(&ro3);
+ po3.PrintUsage(false);
+
+ po3.Read(argc3, argv3);
+ KALDI_ASSERT(po3.NumArgs() == 2);
+ KALDI_ASSERT(po3.GetArg(1) == "a");
+ KALDI_ASSERT(po3.GetArg(2) == "b");
+ KALDI_ASSERT(unum == 5);
+ KALDI_ASSERT(unum2 == 42);
+ KALDI_ASSERT(num == 3);
+ KALDI_ASSERT(str2 == "foo");
+ KALDI_ASSERT(str == "bar");
+ KALDI_ASSERT(dummy_opts.my_bool == false);
+ KALDI_ASSERT(dummy_opts.my_string == "baz");
+
+
+ try { // test error with --option=, which is not a valid way to set
+ // boolean options.
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option="};
+ ParseOptions po4("my usage msg");
+ bool val = false;
+ po4.Register("option", &val, "My boolean");
+ po4.Read(argc4, argv4);
+ assert(false); // Should not reach this part of code.
+ } catch(std::exception e) {
+ KALDI_LOG << "Failed to read option (this is expected).";
+ }
+
+ { // test that --option sets "option" to true, if bool.
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option"};
+ ParseOptions po4("my usage msg");
+ bool val = false;
+ po4.Register("option", &val, "My boolean");
+ po4.Read(argc4, argv4);
+ KALDI_ASSERT(val == true);
+ }
+
+
+ try { // test error with --option, which is not a valid way to set
+ // string-valued options.
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option"};
+ ParseOptions po4("my usage msg");
+ std::string val;
+ po4.Register("option", &val, "My string");
+ po4.Read(argc4, argv4);
+ assert(false); // Should not reach this part of code.
+ } catch(std::exception e) {
+ KALDI_LOG << "Failed to read option (this is expected).";
+ }
+
+ { // test that --option= sets "option" to empty, if string.
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option="};
+ ParseOptions po4("my usage msg");
+ std::string val = "foo";
+ po4.Register("option", &val, "My boolean");
+ po4.Read(argc4, argv4);
+ KALDI_ASSERT(val.empty());
+ }
+
+ { // integer options test
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option=8"};
+ ParseOptions po4("my usage msg");
+ int32 val = 32;
+ po4.Register("option", &val, "My int");
+ po4.Read(argc4, argv4);
+ KALDI_ASSERT(val == 8);
+ }
+
+ { // float
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option=8.5"};
+ ParseOptions po4("my usage msg");
+ BaseFloat val = 32.0;
+ po4.Register("option", &val, "My float");
+ po4.Read(argc4, argv4);
+ KALDI_ASSERT(val == 8.5);
+ }
+ { // string options test
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option=bar"};
+ ParseOptions po4("my usage msg");
+ std::string val = "foo";
+ po4.Register("option", &val, "My string");
+ po4.Read(argc4, argv4);
+ KALDI_ASSERT(val == "bar");
+ }
+
+ try { // test error with --float=string
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option=foo"};
+ ParseOptions po4("my usage msg");
+ BaseFloat val = 32.0;
+ po4.Register("option", &val, "My float");
+ po4.Read(argc4, argv4);
+ assert(false); // Should not reach this part of code.
+ } catch(std::exception e) {
+ KALDI_LOG << "Failed to read option (this is expected).";
+ }
+
+
+ try { // test error with --int=string
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option=foo"};
+ ParseOptions po4("my usage msg");
+ int32 val = 32;
+ po4.Register("option", &val, "My int");
+ po4.Read(argc4, argv4);
+ assert(false); // Should not reach this part of code.
+ } catch(std::exception e) {
+ KALDI_LOG << "Failed to read option (this is expected).";
+ }
+
+ try { // test error with --int=int+garbage
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option=12xyz"};
+ ParseOptions po4("my usage msg");
+ int32 val = 32;
+ po4.Register("option", &val, "My int");
+ po4.Read(argc4, argv4);
+ assert(false); // Should not reach this part of code.
+ } catch(std::exception e) {
+ KALDI_LOG << "Failed to read option (this is expected).";
+ }
+
+ try { // test error with --unsigned-int=negative-number.
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option=-13"};
+ ParseOptions po4("my usage msg");
+ uint32 val = 32;
+ po4.Register("option", &val, "My int");
+ po4.Read(argc4, argv4);
+ assert(false); // Should not reach this part of code.
+ } catch(std::exception e) {
+ KALDI_LOG << "Failed to read option (this is expected)xxx.";
+ }
+
+ try { // test error with --bool=string
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--option=foo"};
+ ParseOptions po4("my usage msg");
+ bool val = false;
+ po4.Register("option", &val, "My bool");
+ po4.Read(argc4, argv4);
+ assert(false); // Should not reach this part of code.
+ } catch(std::exception e) {
+ KALDI_LOG << "Failed to read option (this is expected).";
+ }
+
+
+ // test error with --=
+ try {
+ int argc4 = 2;
+ const char *argv4[2] = { "program_name", "--=8"};
+ int32 num = 0;
+ ParseOptions po4("my usage msg");
+ po4.Register("num", &num, "My int32 variable");
+ po4.Read(argc4, argv4);
+ KALDI_ASSERT(num == 0);
+ } catch(std::exception e) {
+ KALDI_LOG << "Failed to read option (this is expected).";
+ }
+
+ // test "--" (no more options)
+ int argc4 = 5;
+ unum = 2;
+ const char *argv4[5] = { "program_name", "--unum=6", "--", "a", "b" };
+ ParseOptions po4("my usage msg");
+ po4.Register("unum", &unum, "My uint32 variable");
+ po4.Read(argc4, argv4);
+ KALDI_ASSERT(po4.NumArgs() == 2);
+ KALDI_ASSERT(po4.GetArg(1) == "a");
+ KALDI_ASSERT(po4.GetArg(2) == "b");
+ KALDI_ASSERT(unum == 6);
+
+ // test obsolete "--" (no more options)
+ int argc5 = 3;
+ unum = 2;
+ const char *argv5[3] = { "program_name", "--unum=7", "--" };
+ ParseOptions po5("my usage msg");
+ po5.Register("unum", &unum, "My uint32 variable");
+ po5.Read(argc5, argv5);
+ KALDI_ASSERT(po5.NumArgs() == 0);
+ KALDI_ASSERT(unum == 7);
+
+ // test that "--foo=bar" after "--" is interpreted as argument
+ int argc6 = 4;
+ unum = 2;
+ const char *argv6[5] = { "program_name", "--unum=8", "--", "--foo=8" };
+ ParseOptions po6("my usage msg");
+ po6.Register("unum", &unum, "My uint32 variable");
+ po6.Read(argc6, argv6);
+ KALDI_ASSERT(po6.NumArgs() == 1);
+ KALDI_ASSERT(po6.GetArg(1) == "--foo=8");
+
+ // test that a second registration is ignored
+ int argc7 = 2;
+ const char *const argv7[] = {"program_name", "--i=8"};
+ ParseOptions po7("my usage msg");
+
+ int i7 = 10, k7 = 20;
+ po7.Register("i", &i7, "My int32 variable");
+ po7.Register("i", &k7, "My int32 variable");
+
+ po7.Read(argc7, argv7);
+
+ KALDI_ASSERT(i7 == 8);
+ KALDI_ASSERT(k7 == 20);
+}
+
+
+} // end namespace kaldi.
+
+int main() {
+ using namespace kaldi;
+ UnitTestParseOptions();
+ return 0;
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/util/parse-options.cc b/runtime/onnxruntime/third_party/kaldi/util/parse-options.cc
new file mode 100644
index 000000000..edf978ab1
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/parse-options.cc
@@ -0,0 +1,669 @@
+// util/parse-options.cc
+
+// Copyright 2009-2011 Karel Vesely; Microsoft Corporation;
+// Saarland University (Author: Arnab Ghoshal);
+// Copyright 2012-2013 Johns Hopkins University (Author: Daniel Povey);
+// Frantisek Skala; Arnab Ghoshal
+// Copyright 2013 Tanel Alumae
+//
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include <iostream>
+#include <iomanip>
+#include <fstream>
+#include <algorithm>
+#include <cstdlib>
+#include <cassert>
+#include <cstring>
+
+#include "util/parse-options.h"
+#include "util/text-utils.h"
+#include "base/kaldi-common.h"
+
+namespace kaldi {
+
+
+ParseOptions::ParseOptions(const std::string &prefix,
+ OptionsItf *other):
+ print_args_(false), help_(false), usage_(""), argc_(0), argv_(NULL) {
+ ParseOptions *po = dynamic_cast<ParseOptions*>(other);
+ if (po != NULL && po->other_parser_ != NULL) {
+ // we get here if this constructor is used twice, recursively.
+ other_parser_ = po->other_parser_;
+ } else {
+ other_parser_ = other;
+ }
+ if (po != NULL && po->prefix_ != "") {
+ prefix_ = po->prefix_ + std::string(".") + prefix;
+ } else {
+ prefix_ = prefix;
+ }
+}
+
+void ParseOptions::Register(const std::string &name,
+ bool *ptr, const std::string &doc) {
+ RegisterTmpl(name, ptr, doc);
+}
+
+void ParseOptions::Register(const std::string &name,
+ int32 *ptr, const std::string &doc) {
+ RegisterTmpl(name, ptr, doc);
+}
+
+void ParseOptions::Register(const std::string &name,
+ uint32 *ptr, const std::string &doc) {
+ RegisterTmpl(name, ptr, doc);
+}
+
+void ParseOptions::Register(const std::string &name,
+ float *ptr, const std::string &doc) {
+ RegisterTmpl(name, ptr, doc);
+}
+
+void ParseOptions::Register(const std::string &name,
+ double *ptr, const std::string &doc) {
+ RegisterTmpl(name, ptr, doc);
+}
+
+void ParseOptions::Register(const std::string &name,
+ std::string *ptr, const std::string &doc) {
+ RegisterTmpl(name, ptr, doc);
+}
+
+// old-style, used for registering application-specific parameters
+template<typename T>
+void ParseOptions::RegisterTmpl(const std::string &name, T *ptr,
+ const std::string &doc) {
+ if (other_parser_ == NULL) {
+ this->RegisterCommon(name, ptr, doc, false);
+ } else {
+ KALDI_ASSERT(prefix_ != "" &&
+ "Cannot use empty prefix when registering with prefix.");
+ std::string new_name = prefix_ + '.' + name; // name becomes prefix.name
+ other_parser_->Register(new_name, ptr, doc);
+ }
+}
+
+// does the common part of the job of registering a parameter
+template<typename T>
+void ParseOptions::RegisterCommon(const std::string &name, T *ptr,
+ const std::string &doc, bool is_standard) {
+ KALDI_ASSERT(ptr != NULL);
+ std::string idx = name;
+ NormalizeArgName(&idx);
+ if (doc_map_.find(idx) != doc_map_.end())
+ KALDI_WARN << "Registering option twice, ignoring second time: " << name;
+ else
+ this->RegisterSpecific(name, idx, ptr, doc, is_standard);
+}
+
+// used to register standard parameters (those that are present in all of the
+// applications)
+template<typename T>
+void ParseOptions::RegisterStandard(const std::string &name, T *ptr,
+ const std::string &doc) {
+ this->RegisterCommon(name, ptr, doc, true);
+}
+
+void ParseOptions::RegisterSpecific(const std::string &name,
+ const std::string &idx,
+ bool *b,
+ const std::string &doc,
+ bool is_standard) {
+ bool_map_[idx] = b;
+ doc_map_[idx] = DocInfo(name, doc + " (bool, default = "
+ + ((*b)? "true)" : "false)"), is_standard);
+}
+
+void ParseOptions::RegisterSpecific(const std::string &name,
+ const std::string &idx,
+ int32 *i,
+ const std::string &doc,
+ bool is_standard) {
+ int_map_[idx] = i;
+ std::ostringstream ss;
+ ss << doc << " (int, default = " << *i << ")";
+ doc_map_[idx] = DocInfo(name, ss.str(), is_standard);
+}
+
+void ParseOptions::RegisterSpecific(const std::string &name,
+ const std::string &idx,
+ uint32 *u,
+ const std::string &doc,
+ bool is_standard) {
+ uint_map_[idx] = u;
+ std::ostringstream ss;
+ ss << doc << " (uint, default = " << *u << ")";
+ doc_map_[idx] = DocInfo(name, ss.str(), is_standard);
+}
+
+void ParseOptions::RegisterSpecific(const std::string &name,
+ const std::string &idx,
+ float *f,
+ const std::string &doc,
+ bool is_standard) {
+ float_map_[idx] = f;
+ std::ostringstream ss;
+ ss << doc << " (float, default = " << *f << ")";
+ doc_map_[idx] = DocInfo(name, ss.str(), is_standard);
+}
+
+void ParseOptions::RegisterSpecific(const std::string &name,
+ const std::string &idx,
+ double *f,
+ const std::string &doc,
+ bool is_standard) {
+ double_map_[idx] = f;
+ std::ostringstream ss;
+ ss << doc << " (double, default = " << *f << ")";
+ doc_map_[idx] = DocInfo(name, ss.str(), is_standard);
+}
+
+void ParseOptions::RegisterSpecific(const std::string &name,
+ const std::string &idx,
+ std::string *s,
+ const std::string &doc,
+ bool is_standard) {
+ string_map_[idx] = s;
+ doc_map_[idx] = DocInfo(name, doc + " (string, default = \"" + *s + "\")",
+ is_standard);
+}
+void ParseOptions::DisableOption(const std::string &name) {
+ if (argv_ != NULL)
+ KALDI_ERR << "DisableOption must not be called after calling Read().";
+ if (doc_map_.erase(name) == 0)
+ KALDI_ERR << "Option " << name
+ << " was not registered so cannot be disabled: ";
+ bool_map_.erase(name);
+ int_map_.erase(name);
+ uint_map_.erase(name);
+ float_map_.erase(name);
+ double_map_.erase(name);
+ string_map_.erase(name);
+}
+
+
+int ParseOptions::NumArgs() const {
+ return positional_args_.size();
+}
+
+std::string ParseOptions::GetArg(int i) const {
+ // use KALDI_ERR if code error
+ if (i < 1 || i > static_cast<int>(positional_args_.size()))
+ KALDI_ERR << "ParseOptions::GetArg, invalid index " << i;
+ return positional_args_[i - 1];
+}
+
+// We currently do not support any other options.
+enum ShellType { kBash = 0 };
+
+// This can be changed in the code if it ever does need to be changed (as it's
+// unlikely that one compilation of this tool-set would use both shells).
+static ShellType kShellType = kBash;
+
+// Returns true if we need to escape a string before putting it into
+// a shell (mainly thinking of bash shell, but should work for others)
+// This is for the convenience of the user so command-lines that are
+// printed out by ParseOptions::Read (with --print-args=true) are
+// paste-able into the shell and will run. If you use a different type of
+// shell, it might be necessary to change this function.
+// But it's mostly a cosmetic issue as it basically affects how
+// the program echoes its command-line arguments to the screen.
+static bool MustBeQuoted(const std::string &str, ShellType st) {
+ // Only Bash is supported (for the moment).
+ KALDI_ASSERT(st == kBash && "Invalid shell type.");
+
+ const char *c = str.c_str();
+ if (*c == '\0') {
+ return true; // Must quote empty string
+ } else {
+ const char *ok_chars[2];
+
+ // These seem not to be interpreted as long as there are no other "bad"
+ // characters involved (e.g. "," would be interpreted as part of something
+ // like a{b,c}, but not on its own.
+ ok_chars[kBash] = "[]~#^_-+=:.,/";
+
+ // Just want to make sure that a space character doesn't get automatically
+ // inserted here via an automated style-checking script, like it did before.
+ KALDI_ASSERT(!strchr(ok_chars[kBash], ' '));
+
+ for (; *c != '\0'; c++) {
+ // For non-alphanumeric characters we have a list of characters which
+ // are OK. All others are forbidden (this is easier since the shell
+ // interprets most non-alphanumeric characters).
+ if (!isalnum(*c)) {
+ const char *d;
+ for (d = ok_chars[st]; *d != '\0'; d++) if (*c == *d) break;
+ // If not alphanumeric or one of the "ok_chars", it must be escaped.
+ if (*d == '\0') return true;
+ }
+ }
+ return false; // The string was OK. No quoting or escaping.
+ }
+}
+
+// Returns a quoted and escaped version of "str"
+// which has previously been determined to need escaping.
+// Our aim is to print out the command line in such a way that if it's
+// pasted into a shell of ShellType "st" (only bash for now), it
+// will get passed to the program in the same way.
+static std::string QuoteAndEscape(const std::string &str, ShellType st) {
+ // Only Bash is supported (for the moment).
+ KALDI_ASSERT(st == kBash && "Invalid shell type.");
+
+ // For now we use the following rules:
+ // In the normal case, we quote with single-quote "'", and to escape
+ // a single-quote we use the string: '\'' (interpreted as closing the
+ // single-quote, putting an escaped single-quote from the shell, and
+ // then reopening the single quote).
+ char quote_char = '\'';
+ const char *escape_str = "'\\''"; // e.g. echo 'a'\''b' returns a'b
+
+ // If the string contains single-quotes that would need escaping this
+ // way, and we determine that the string could be safely double-quoted
+ // without requiring any escaping, then we double-quote the string.
+ // This is the case if the characters "`$\ do not appear in the string.
+ // e.g. see http://www.redhat.com/mirrors/LDP/LDP/abs/html/quotingvar.html
+ const char *c_str = str.c_str();
+ if (strchr(c_str, '\'') && !strpbrk(c_str, "\"`$\\")) {
+ quote_char = '"';
+ escape_str = "\\\""; // should never be accessed.
+ }
+
+ char buf[2];
+ buf[1] = '\0';
+
+ buf[0] = quote_char;
+ std::string ans = buf;
+ const char *c = str.c_str();
+ for (;*c != '\0'; c++) {
+ if (*c == quote_char) {
+ ans += escape_str;
+ } else {
+ buf[0] = *c;
+ ans += buf;
+ }
+ }
+ buf[0] = quote_char;
+ ans += buf;
+ return ans;
+}
+
+// static function
+std::string ParseOptions::Escape(const std::string &str) {
+ return MustBeQuoted(str, kShellType) ? QuoteAndEscape(str, kShellType) : str;
+}
+
+
+int ParseOptions::Read(int argc, const char *const argv[]) {
+ argc_ = argc;
+ argv_ = argv;
+ std::string key, value;
+ int i;
+ if (argc > 0) {
+ // set global "const char*" g_program_name (name of the program)
+ // so it can be printed out in error messages;
+ // it's useful because often the stderr of different programs will
+ // be mixed together in the same log file.
+#ifdef _MSC_VER
+ const char *c = strrchr(argv[0], '\\');
+#else
+ const char *c = strrchr(argv[0], '/');
+#endif
+ SetProgramName(c == NULL ? argv[0] : c + 1);
+ }
+ // first pass: look for config parameter, look for priority
+ for (i = 1; i < argc; i++) {
+ if (std::strncmp(argv[i], "--", 2) == 0) {
+ if (std::strcmp(argv[i], "--") == 0) {
+ // a lone "--" marks the end of named options
+ break;
+ }
+ bool has_equal_sign;
+ SplitLongArg(argv[i], &key, &value, &has_equal_sign);
+ NormalizeArgName(&key);
+ Trim(&value);
+ if (key.compare("config") == 0) {
+ ReadConfigFile(value);
+ }
+ if (key.compare("help") == 0) {
+ PrintUsage();
+ exit(0);
+ }
+ }
+ }
+ bool double_dash_seen = false;
+ // second pass: add the command line options
+ for (i = 1; i < argc; i++) {
+ if (std::strncmp(argv[i], "--", 2) == 0) {
+ if (std::strcmp(argv[i], "--") == 0) {
+ // A lone "--" marks the end of named options.
+ // Skip that option and break the processing of named options
+ i += 1;
+ double_dash_seen = true;
+ break;
+ }
+ bool has_equal_sign;
+ SplitLongArg(argv[i], &key, &value, &has_equal_sign);
+ NormalizeArgName(&key);
+ Trim(&value);
+ if (!SetOption(key, value, has_equal_sign)) {
+ PrintUsage(true);
+ KALDI_ERR << "Invalid option " << argv[i];
+ }
+ } else {
+ break;
+ }
+ }
+
+ // process remaining arguments as positional
+ for (; i < argc; i++) {
+ if ((std::strcmp(argv[i], "--") == 0) && !double_dash_seen) {
+ double_dash_seen = true;
+ } else {
+ positional_args_.push_back(std::string(argv[i]));
+ }
+ }
+
+ // if the user did not suppress this with --print-args = false....
+ if (print_args_) {
+ std::ostringstream strm;
+ for (int j = 0; j < argc; j++)
+ strm << Escape(argv[j]) << " ";
+ strm << '\n';
+ std::cerr << strm.str() << std::flush;
+ }
+ return i;
+}
+
+
+void ParseOptions::PrintUsage(bool print_command_line) {
+ std::cerr << '\n' << usage_ << '\n';
+ DocMapType::iterator it;
+ // first we print application-specific options
+ bool app_specific_header_printed = false;
+ for (it = doc_map_.begin(); it != doc_map_.end(); ++it) {
+ if (it->second.is_standard_ == false) { // application-specific option
+ if (app_specific_header_printed == false) { // header was not yet printed
+ std::cerr << "Options:" << '\n';
+ app_specific_header_printed = true;
+ }
+ std::cerr << " --" << std::setw(25) << std::left << it->second.name_
+ << " : " << it->second.use_msg_ << '\n';
+ }
+ }
+ if (app_specific_header_printed == true) {
+ std::cerr << '\n';
+ }
+
+ // then the standard options
+ std::cerr << "Standard options:" << '\n';
+ for (it = doc_map_.begin(); it != doc_map_.end(); ++it) {
+ if (it->second.is_standard_ == true) { // we have standard option
+ std::cerr << " --" << std::setw(25) << std::left << it->second.name_
+ << " : " << it->second.use_msg_ << '\n';
+ }
+ }
+ std::cerr << '\n';
+ if (print_command_line) {
+ std::ostringstream strm;
+ strm << "Command line was: ";
+ for (int j = 0; j < argc_; j++)
+ strm << Escape(argv_[j]) << " ";
+ strm << '\n';
+ std::cerr << strm.str() << std::flush;
+ }
+}
+
+void ParseOptions::PrintConfig(std::ostream &os) {
+ os << '\n' << "[[ Configuration of UI-Registered options ]]" << '\n';
+ std::string key;
+ DocMapType::iterator it;
+ for (it = doc_map_.begin(); it != doc_map_.end(); ++it) {
+ key = it->first;
+ os << it->second.name_ << " = ";
+ if (bool_map_.end() != bool_map_.find(key)) {
+ os << (*bool_map_[key] ? "true" : "false");
+ } else if (int_map_.end() != int_map_.find(key)) {
+ os << (*int_map_[key]);
+ } else if (uint_map_.end() != uint_map_.find(key)) {
+ os << (*uint_map_[key]);
+ } else if (float_map_.end() != float_map_.find(key)) {
+ os << (*float_map_[key]);
+ } else if (double_map_.end() != double_map_.find(key)) {
+ os << (*double_map_[key]);
+ } else if (string_map_.end() != string_map_.find(key)) {
+ os << "'" << *string_map_[key] << "'";
+ } else {
+ KALDI_ERR << "PrintConfig: unrecognized option " << key << "[code error]";
+ }
+ os << '\n';
+ }
+ os << '\n';
+}
+
+
+void ParseOptions::ReadConfigFile(const std::string &filename) {
+ std::ifstream is(filename.c_str(), std::ifstream::in);
+ if (!is.good()) {
+ KALDI_ERR << "Cannot open config file: " << filename;
+ }
+
+ std::string line, key, value;
+ int32 line_number = 0;
+ while (std::getline(is, line)) {
+ line_number++;
+ // trim out the comments
+ size_t pos;
+ if ((pos = line.find_first_of('#')) != std::string::npos) {
+ line.erase(pos);
+ }
+ // skip empty lines
+ Trim(&line);
+ if (line.length() == 0) continue;
+
+ if (line.substr(0, 2) != "--") {
+ KALDI_ERR << "Reading config file " << filename
+ << ": line " << line_number << " does not look like a line "
+ << "from a Kaldi command-line program's config file: should "
+ << "be of the form --x=y. Note: config files intended to "
+ << "be sourced by shell scripts lack the '--'.";
+ }
+
+ // parse option
+ bool has_equal_sign;
+ SplitLongArg(line, &key, &value, &has_equal_sign);
+ NormalizeArgName(&key);
+ Trim(&value);
+ if (!SetOption(key, value, has_equal_sign)) {
+ PrintUsage(true);
+ KALDI_ERR << "Invalid option " << line << " in config file " << filename;
+ }
+ }
+}
+
+
+
+void ParseOptions::SplitLongArg(const std::string &in,
+ std::string *key,
+ std::string *value,
+ bool *has_equal_sign) {
+ KALDI_ASSERT(in.substr(0, 2) == "--"); // precondition.
+ size_t pos = in.find_first_of('=', 0);
+ if (pos == std::string::npos) { // we allow --option for bools
+ // defaults to empty. We handle this differently in different cases.
+ *key = in.substr(2, in.size()-2); // 2 because starts with --.
+ *value = "";
+ *has_equal_sign = false;
+ } else if (pos == 2) { // we also don't allow empty keys: --=value
+ PrintUsage(true);
+ KALDI_ERR << "Invalid option (no key): " << in;
+ } else { // normal case: --option=value
+ *key = in.substr(2, pos-2); // 2 because starts with --.
+ *value = in.substr(pos + 1);
+ *has_equal_sign = true;
+ }
+}
+
+
+void ParseOptions::NormalizeArgName(std::string *str) {
+ std::string out;
+ std::string::iterator it;
+
+ for (it = str->begin(); it != str->end(); ++it) {
+ if (*it == '_')
+ out += '-'; // convert _ to -
+ else
+ out += std::tolower(*it);
+ }
+ *str = out;
+
+ KALDI_ASSERT(str->length() > 0);
+}
+
+
+
+
+bool ParseOptions::SetOption(const std::string &key,
+ const std::string &value,
+ bool has_equal_sign) {
+ if (bool_map_.end() != bool_map_.find(key)) {
+ if (has_equal_sign && value == "")
+ KALDI_ERR << "Invalid option --" << key << "=";
+ *(bool_map_[key]) = ToBool(value);
+ } else if (int_map_.end() != int_map_.find(key)) {
+ *(int_map_[key]) = ToInt(value);
+ } else if (uint_map_.end() != uint_map_.find(key)) {
+ *(uint_map_[key]) = ToUint(value);
+ } else if (float_map_.end() != float_map_.find(key)) {
+ *(float_map_[key]) = ToFloat(value);
+ } else if (double_map_.end() != double_map_.find(key)) {
+ *(double_map_[key]) = ToDouble(value);
+ } else if (string_map_.end() != string_map_.find(key)) {
+ if (!has_equal_sign)
+ KALDI_ERR << "Invalid option --" << key
+ << " (option format is --x=y).";
+ *(string_map_[key]) = value;
+ } else {
+ return false;
+ }
+ return true;
+}
+
+
+
+bool ParseOptions::ToBool(std::string str) {
+ std::transform(str.begin(), str.end(), str.begin(), ::tolower);
+
+ // allow "" as a valid option for "true", so that --x is the same as --x=true
+ if ((str.compare("true") == 0) || (str.compare("t") == 0)
+ || (str.compare("1") == 0) || (str.compare("") == 0)) {
+ return true;
+ }
+ if ((str.compare("false") == 0) || (str.compare("f") == 0)
+ || (str.compare("0") == 0)) {
+ return false;
+ }
+ // if it is neither true nor false:
+ PrintUsage(true);
+ KALDI_ERR << "Invalid format for boolean argument [expected true or false]: "
+ << str;
+ return false; // never reached
+}
+
+
+int32 ParseOptions::ToInt(const std::string &str) {
+ int32 ret;
+ if (!ConvertStringToInteger(str, &ret))
+ KALDI_ERR << "Invalid integer option \"" << str << "\"";
+ return ret;
+}
+
+uint32 ParseOptions::ToUint(const std::string &str) {
+ uint32 ret;
+ if (!ConvertStringToInteger(str, &ret))
+ KALDI_ERR << "Invalid integer option \"" << str << "\"";
+ return ret;
+}
+
+float ParseOptions::ToFloat(const std::string &str) {
+ float ret;
+ if (!ConvertStringToReal(str, &ret))
+ KALDI_ERR << "Invalid floating-point option \"" << str << "\"";
+ return ret;
+}
+
+double ParseOptions::ToDouble(const std::string &str) {
+ double ret;
+ if (!ConvertStringToReal(str, &ret))
+ KALDI_ERR << "Invalid floating-point option \"" << str << "\"";
+ return ret;
+}
+
+// instantiate templates
+template void ParseOptions::RegisterTmpl(const std::string &name, bool *ptr,
+ const std::string &doc);
+template void ParseOptions::RegisterTmpl(const std::string &name, int32 *ptr,
+ const std::string &doc);
+template void ParseOptions::RegisterTmpl(const std::string &name, uint32 *ptr,
+ const std::string &doc);
+template void ParseOptions::RegisterTmpl(const std::string &name, float *ptr,
+ const std::string &doc);
+template void ParseOptions::RegisterTmpl(const std::string &name, double *ptr,
+ const std::string &doc);
+template void ParseOptions::RegisterTmpl(const std::string &name,
+ std::string *ptr, const std::string &doc);
+
+template void ParseOptions::RegisterStandard(const std::string &name,
+ bool *ptr,
+ const std::string &doc);
+template void ParseOptions::RegisterStandard(const std::string &name,
+ int32 *ptr,
+ const std::string &doc);
+template void ParseOptions::RegisterStandard(const std::string &name,
+ uint32 *ptr,
+ const std::string &doc);
+template void ParseOptions::RegisterStandard(const std::string &name,
+ float *ptr,
+ const std::string &doc);
+template void ParseOptions::RegisterStandard(const std::string &name,
+ double *ptr,
+ const std::string &doc);
+template void ParseOptions::RegisterStandard(const std::string &name,
+ std::string *ptr,
+ const std::string &doc);
+
+template void ParseOptions::RegisterCommon(const std::string &name,
+ bool *ptr,
+ const std::string &doc, bool is_standard);
+template void ParseOptions::RegisterCommon(const std::string &name,
+ int32 *ptr,
+ const std::string &doc, bool is_standard);
+template void ParseOptions::RegisterCommon(const std::string &name,
+ uint32 *ptr,
+ const std::string &doc, bool is_standard);
+template void ParseOptions::RegisterCommon(const std::string &name,
+ float *ptr,
+ const std::string &doc, bool is_standard);
+template void ParseOptions::RegisterCommon(const std::string &name,
+ double *ptr,
+ const std::string &doc, bool is_standard);
+template void ParseOptions::RegisterCommon(const std::string &name,
+ std::string *ptr,
+ const std::string &doc, bool is_standard);
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/util/parse-options.h b/runtime/onnxruntime/third_party/kaldi/util/parse-options.h
new file mode 100644
index 000000000..6884a40c1
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/parse-options.h
@@ -0,0 +1,264 @@
+// util/parse-options.h
+
+// Copyright 2009-2011 Karel Vesely; Microsoft Corporation;
+// Saarland University (Author: Arnab Ghoshal);
+// Copyright 2012-2013 Frantisek Skala; Arnab Ghoshal
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_UTIL_PARSE_OPTIONS_H_
+#define KALDI_UTIL_PARSE_OPTIONS_H_
+
+#include <map>
+#include <string>
+#include <vector>
+
+#include "base/kaldi-common.h"
+#include "itf/options-itf.h"
+
+namespace kaldi {
+
+/// The class ParseOptions is for parsing command-line options; see
+/// \ref parse_options for more documentation.
+class ParseOptions : public OptionsItf {
+ public:
+ explicit ParseOptions(const char *usage) :
+ print_args_(true), help_(false), usage_(usage), argc_(0), argv_(NULL),
+ prefix_(""), other_parser_(NULL) {
+#if !defined(_MSC_VER) && !defined(__CYGWIN__) // This is just a convenient place to set the stderr to line
+ setlinebuf(stderr); // buffering mode, since it's called at program start.
+#endif // This helps ensure different programs' output is not mixed up.
+ RegisterStandard("config", &config_, "Configuration file to read (this "
+ "option may be repeated)");
+ RegisterStandard("print-args", &print_args_,
+ "Print the command line arguments (to stderr)");
+ RegisterStandard("help", &help_, "Print out usage message");
+ RegisterStandard("verbose", &g_kaldi_verbose_level,
+ "Verbose level (higher->more logging)");
+ }
+
+ /**
+ This is a constructor for the special case where some options are
+ registered with a prefix to avoid conflicts. The object thus created will
+ only be used temporarily to register an options class with the original
+ options parser (which is passed as the *other pointer) using the given
+ prefix. It should not be used for any other purpose, and the prefix must
+ not be the empty string. It seems to be the least bad way of implementing
+ options with prefixes at this point.
+ Example of usage is:
+ ParseOptions po; // original ParseOptions object
+ ParseOptions po_mfcc("mfcc", &po); // object with prefix.
+ MfccOptions mfcc_opts;
+ mfcc_opts.Register(&po_mfcc);
+ The options will now get registered as, e.g., --mfcc.frame-shift=10.0
+ instead of just --frame-shift=10.0
+ */
+ ParseOptions(const std::string &prefix, OptionsItf *other);
+
+ ~ParseOptions() {}
+
+ // Methods from the interface
+ void Register(const std::string &name,
+ bool *ptr, const std::string &doc);
+ void Register(const std::string &name,
+ int32 *ptr, const std::string &doc);
+ void Register(const std::string &name,
+ uint32 *ptr, const std::string &doc);
+ void Register(const std::string &name,
+ float *ptr, const std::string &doc);
+ void Register(const std::string &name,
+ double *ptr, const std::string &doc);
+ void Register(const std::string &name,
+ std::string *ptr, const std::string &doc);
+
+ /// If called after registering an option and before calling
+ /// Read(), disables that option from being used. Will crash
+ /// at runtime if that option had not been registered.
+ void DisableOption(const std::string &name);
+
+ /// This one is used for registering standard parameters of all the programs
+ template<typename T>
+ void RegisterStandard(const std::string &name,
+ T *ptr, const std::string &doc);
+
+ /**
+ Parses the command line options and fills the ParseOptions-registered
+ variables. This must be called after all the variables were registered!!!
+
+ Initially the variables have implicit values,
+ then the config file values are set-up,
+ finally the command line values given.
+ Returns the first position in argv that was not used.
+ [typically not useful: use NumParams() and GetParam(). ]
+ */
+ int Read(int argc, const char *const *argv);
+
+ /// Prints the usage documentation [provided in the constructor].
+ void PrintUsage(bool print_command_line = false);
+ /// Prints the actual configuration of all the registered variables
+ void PrintConfig(std::ostream &os);
+
+ /// Reads the options values from a config file. Must be called after
+ /// registering all options. This is usually used internally after the
+ /// standard --config option is used, but it may also be called from a
+ /// program.
+ void ReadConfigFile(const std::string &filename);
+
+ /// Number of positional parameters (c.f. argc-1).
+ int NumArgs() const;
+
+ /// Returns one of the positional parameters; 1-based indexing for argc/argv
+ /// compatibility. Will crash if param is not >=1 and <=NumArgs().
+ std::string GetArg(int param) const;
+
+ std::string GetOptArg(int param) const {
+ return (param <= NumArgs() ? GetArg(param) : "");
+ }
+
+ /// The following function will return a possibly quoted and escaped
+ /// version of "str", according to the current shell. Currently
+ /// this is just hardwired to bash. It's useful for debug output.
+ static std::string Escape(const std::string &str);
+
+ private:
+ /// Template to register various variable types,
+ /// used for program-specific parameters
+ template<typename T>
+ void RegisterTmpl(const std::string &name, T *ptr, const std::string &doc);
+
+ // Following functions do just the datatype-specific part of the job
+ /// Register boolean variable
+ void RegisterSpecific(const std::string &name, const std::string &idx,
+ bool *b, const std::string &doc, bool is_standard);
+ /// Register int32 variable
+ void RegisterSpecific(const std::string &name, const std::string &idx,
+ int32 *i, const std::string &doc, bool is_standard);
+ /// Register unsinged int32 variable
+ void RegisterSpecific(const std::string &name, const std::string &idx,
+ uint32 *u,
+ const std::string &doc, bool is_standard);
+ /// Register float variable
+ void RegisterSpecific(const std::string &name, const std::string &idx,
+ float *f, const std::string &doc, bool is_standard);
+ /// Register double variable [useful as we change BaseFloat type].
+ void RegisterSpecific(const std::string &name, const std::string &idx,
+ double *f, const std::string &doc, bool is_standard);
+ /// Register string variable
+ void RegisterSpecific(const std::string &name, const std::string &idx,
+ std::string *s, const std::string &doc,
+ bool is_standard);
+
+ /// Does the actual job for both kinds of parameters
+ /// Does the common part of the job for all datatypes,
+ /// then calls RegisterSpecific
+ template<typename T>
+ void RegisterCommon(const std::string &name,
+ T *ptr, const std::string &doc, bool is_standard);
+
+ /// Set option with name "key" to "value"; will crash if can't do it.
+ /// "has_equal_sign" is used to allow --x for a boolean option x,
+ /// and --y=, for a string option y.
+ bool SetOption(const std::string &key, const std::string &value,
+ bool has_equal_sign);
+
+ bool ToBool(std::string str);
+ int32 ToInt(const std::string &str);
+ uint32 ToUint(const std::string &str);
+ float ToFloat(const std::string &str);
+ double ToDouble(const std::string &str);
+
+ // maps for option variables
+ std::map<std::string, bool*> bool_map_;
+ std::map<std::string, int32*> int_map_;
+ std::map<std::string, uint32*> uint_map_;
+ std::map<std::string, float*> float_map_;
+ std::map<std::string, double*> double_map_;
+ std::map<std::string, std::string*> string_map_;
+
+ /**
+ Structure for options' documentation
+ */
+ struct DocInfo {
+ DocInfo() {}
+ DocInfo(const std::string &name, const std::string &usemsg)
+ : name_(name), use_msg_(usemsg), is_standard_(false) {}
+ DocInfo(const std::string &name, const std::string &usemsg,
+ bool is_standard)
+ : name_(name), use_msg_(usemsg), is_standard_(is_standard) {}
+
+ std::string name_;
+ std::string use_msg_;
+ bool is_standard_;
+ };
+ typedef std::map<std::string, DocInfo> DocMapType;
+ DocMapType doc_map_; ///< map for the documentation
+
+ bool print_args_; ///< variable for the implicit --print-args parameter
+ bool help_; ///< variable for the implicit --help parameter
+ std::string config_; ///< variable for the implicit --config parameter
+ std::vector<std::string> positional_args_;
+ const char *usage_;
+ int argc_;
+ const char *const *argv_;
+
+ /// These members are not normally used. They are only used when the object
+ /// is constructed with a prefix
+ std::string prefix_;
+ OptionsItf *other_parser_;
+ protected:
+ /// SplitLongArg parses an argument of the form --a=b, --a=, or --a,
+ /// and sets "has_equal_sign" to true if an equals-sign was parsed..
+ /// this is needed in order to correctly allow --x for a boolean option
+ /// x, and --y= for a string option y, and to disallow --x= and --y.
+ void SplitLongArg(const std::string &in, std::string *key,
+ std::string *value, bool *has_equal_sign);
+
+ void NormalizeArgName(std::string *str);
+};
+
+/// This template is provided for convenience in reading config classes from
+/// files; this is not the standard way to read configuration options, but may
+/// occasionally be needed. This function assumes the config has a function
+/// "void Register(OptionsItf *opts)" which it can call to register the
+/// ParseOptions object.
+template<class C> void ReadConfigFromFile(const std::string &config_filename,
+ C *c) {
+ std::ostringstream usage_str;
+ usage_str << "Parsing config from "
+ << "from '" << config_filename << "'";
+ ParseOptions po(usage_str.str().c_str());
+ c->Register(&po);
+ po.ReadConfigFile(config_filename);
+}
+
+/// This variant of the template ReadConfigFromFile is for if you need to read
+/// two config classes from the same file.
+template<class C1, class C2> void ReadConfigsFromFile(const std::string &conf,
+ C1 *c1, C2 *c2) {
+ std::ostringstream usage_str;
+ usage_str << "Parsing config from "
+ << "from '" << conf << "'";
+ ParseOptions po(usage_str.str().c_str());
+ c1->Register(&po);
+ c2->Register(&po);
+ po.ReadConfigFile(conf);
+}
+
+
+
+} // namespace kaldi
+
+#endif // KALDI_UTIL_PARSE_OPTIONS_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/simple-io-funcs.cc b/runtime/onnxruntime/third_party/kaldi/util/simple-io-funcs.cc
new file mode 100644
index 000000000..cb732a10a
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/simple-io-funcs.cc
@@ -0,0 +1,81 @@
+// util/simple-io-funcs.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#include "util/simple-io-funcs.h"
+#include "util/text-utils.h"
+
+namespace kaldi {
+
+bool WriteIntegerVectorSimple(const std::string &wxfilename,
+ const std::vector<int32> &list) {
+ kaldi::Output ko;
+ // false, false is: text-mode, no Kaldi header.
+ if (!ko.Open(wxfilename, false, false)) return false;
+ for (size_t i = 0; i < list.size(); i++) ko.Stream() << list[i] << '\n';
+ return ko.Close();
+}
+
+bool ReadIntegerVectorSimple(const std::string &rxfilename,
+ std::vector<int32> *list) {
+ kaldi::Input ki;
+ if (!ki.OpenTextMode(rxfilename)) return false;
+ std::istream &is = ki.Stream();
+ int32 i;
+ list->clear();
+ while ( !(is >> i).fail() )
+ list->push_back(i);
+ is >> std::ws;
+ return is.eof(); // should be eof, or junk at end of file.
+}
+
+bool WriteIntegerVectorVectorSimple(const std::string &wxfilename,
+ const std::vector<std::vector<int32> > &list) {
+ kaldi::Output ko;
+ // false, false is: text-mode, no Kaldi header.
+ if (!ko.Open(wxfilename, false, false)) return false;
+ std::ostream &os = ko.Stream();
+ for (size_t i = 0; i < list.size(); i++) {
+ for (size_t j = 0; j < list[i].size(); j++) {
+ os << list[i][j];
+ if (j+1 < list[i].size()) os << ' ';
+ }
+ os << '\n';
+ }
+ return ko.Close();
+}
+
+bool ReadIntegerVectorVectorSimple(const std::string &rxfilename,
+ std::vector<std::vector<int32> > *list) {
+ kaldi::Input ki;
+ if (!ki.OpenTextMode(rxfilename)) return false;
+ std::istream &is = ki.Stream();
+ list->clear();
+ std::string line;
+ while (std::getline(is, line)) {
+ std::vector<int32> v;
+ if (!SplitStringToIntegers(line, " \t\r", true, &v)) {
+ list->clear();
+ return false;
+ }
+ list->push_back(v);
+ }
+ return is.eof(); // if we're not at EOF, something weird happened.
+}
+
+
+} // end namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/util/simple-io-funcs.h b/runtime/onnxruntime/third_party/kaldi/util/simple-io-funcs.h
new file mode 100644
index 000000000..30b90acb3
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/simple-io-funcs.h
@@ -0,0 +1,63 @@
+// util/simple-io-funcs.h
+
+// Copyright 2009-2011 Microsoft Corporation; Jan Silovsky
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#ifndef KALDI_UTIL_SIMPLE_IO_FUNCS_H_
+#define KALDI_UTIL_SIMPLE_IO_FUNCS_H_
+
+#include <string>
+#include <vector>
+#include "util/kaldi-io.h"
+
+// This header contains some utilities for reading some common, simple text
+// formats:integers in files, one per line, and integers in files, possibly
+// multiple per line. these are not really fully native Kaldi formats; they are
+// mostly for small files that might be generated by scripts, and can be read
+// all at one time. for longer files of this type, we would probably use the
+// Table code.
+
+namespace kaldi {
+
+/// WriteToList attempts to write this list of integers, one per line,
+/// to the given file, in text format.
+/// returns true if succeeded.
+bool WriteIntegerVectorSimple(const std::string &wxfilename,
+ const std::vector<int32> &v);
+
+/// ReadFromList attempts to read this list of integers, one per line,
+/// from the given file, in text format.
+/// returns true if succeeded.
+bool ReadIntegerVectorSimple(const std::string &rxfilename,
+ std::vector<int32> *v);
+
+// This is a file format like:
+// 1 2
+// 3
+//
+// 4 5 6
+// etc.
+bool WriteIntegerVectorVectorSimple(const std::string &wxfilename,
+ const std::vector<std::vector<int32> > &v);
+
+bool ReadIntegerVectorVectorSimple(const std::string &rxfilename,
+ std::vector<std::vector<int32> > *v);
+
+
+} // end namespace kaldi.
+
+
+#endif // KALDI_UTIL_SIMPLE_IO_FUNCS_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/simple-options-test.cc b/runtime/onnxruntime/third_party/kaldi/util/simple-options-test.cc
new file mode 100644
index 000000000..1314cb231
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/simple-options-test.cc
@@ -0,0 +1,86 @@
+// util/simple-options-test.cc
+
+// Copyright 2013 Tanel Alumae, Tallinn University of Technology
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+#include "util/simple-options.h"
+
+namespace kaldi {
+
+
+void UnitTestSimpleOptions() {
+ std::string str="default_for_str";
+ int32 num = 1;
+ uint32 unum = 2;
+ float realnum = 0.1;
+ bool flag = false;
+ bool rval;
+ SimpleOptions so;
+
+ so.Register("num", &num, "Description of num");
+ so.Register("unum", &unum, "Description of unum");
+ so.Register("str", &str, "Description of str");
+ so.Register("flag", &flag, "Description of flag");
+ so.Register("realnum", &realnum, "Description of realnum");
+
+ rval = so.SetOption("num", 42);
+ KALDI_ASSERT(rval);
+ so.SetOption("unum", static_cast<uint32>(43));
+ KALDI_ASSERT(rval);
+ rval = so.SetOption("str", (std::string)"foo");
+ KALDI_ASSERT(rval);
+ rval = so.SetOption("flag", false);
+ KALDI_ASSERT(rval);
+
+ KALDI_ASSERT(num == 42);
+ KALDI_ASSERT(unum == 43);
+ KALDI_ASSERT(str == "foo");
+ KALDI_ASSERT(flag == false);
+
+ rval = so.SetOption("str", "foo2");
+ KALDI_ASSERT(rval);
+ KALDI_ASSERT(str == "foo2");
+
+ // test automatic conversion between int and uint
+ rval = so.SetOption("unum", 44);
+ KALDI_ASSERT(rval);
+ KALDI_ASSERT(unum == 44);
+
+ // test automatic conversion between float and double
+ rval = so.SetOption("realnum", static_cast<float>(0.2));
+ KALDI_ASSERT(rval);
+ KALDI_ASSERT(realnum - 0.2 < 0.000001);
+ rval = so.SetOption("realnum", static_cast<double>(0.3));
+ KALDI_ASSERT(rval);
+ KALDI_ASSERT(realnum - 0.3 < 0.000001);
+
+ SimpleOptions::OptionType type;
+ rval = so.GetOptionType("num", &type);
+ KALDI_ASSERT(rval);
+ KALDI_ASSERT(type == SimpleOptions::kInt32);
+
+ rval = so.GetOptionType("xxxx", &type);
+ KALDI_ASSERT(rval == false);
+}
+
+
+} // end namespace kaldi.
+
+int main() {
+ using namespace kaldi;
+ UnitTestSimpleOptions();
+ return 0;
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/util/simple-options.cc b/runtime/onnxruntime/third_party/kaldi/util/simple-options.cc
new file mode 100644
index 000000000..592500e29
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/simple-options.cc
@@ -0,0 +1,184 @@
+// util/simple-options.cc
+
+// Copyright 2013 Tanel Alumae, Tallinn University of Technology
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "util/simple-options.h"
+
+
+namespace kaldi {
+
+void SimpleOptions::Register(const std::string &name,
+ bool *value,
+ const std::string &doc) {
+ bool_map_[name] = value;
+ option_info_list_.push_back(std::make_pair(name, OptionInfo(doc, kBool)));
+}
+
+void SimpleOptions::Register(const std::string &name,
+ int32 *value,
+ const std::string &doc) {
+ int_map_[name] = value;
+ option_info_list_.push_back(std::make_pair(name, OptionInfo(doc, kInt32)));
+}
+
+void SimpleOptions::Register(const std::string &name,
+ uint32 *value,
+ const std::string &doc) {
+ uint_map_[name] = value;
+ option_info_list_.push_back(std::make_pair(name, OptionInfo(doc, kUint32)));
+}
+
+void SimpleOptions::Register(const std::string &name,
+ float *value,
+ const std::string &doc) {
+ float_map_[name] = value;
+ option_info_list_.push_back(std::make_pair(name, OptionInfo(doc, kFloat)));
+}
+
+void SimpleOptions::Register(const std::string &name,
+ double *value,
+ const std::string &doc) {
+ double_map_[name] = value;
+ option_info_list_.push_back(std::make_pair(name, OptionInfo(doc, kDouble)));
+}
+
+void SimpleOptions::Register(const std::string &name,
+ std::string *value,
+ const std::string &doc) {
+ string_map_[name] = value;
+ option_info_list_.push_back(std::make_pair(name, OptionInfo(doc, kString)));
+}
+
+template<typename T>
+static bool SetOptionImpl(const std::string &key, const T &value,
+ std::map<std::string, T*> &some_map) {
+ if (some_map.end() != some_map.find(key)) {
+ *(some_map[key]) = value;
+ return true;
+ }
+ return false;
+}
+
+bool SimpleOptions::SetOption(const std::string &key, const bool &value) {
+ return SetOptionImpl(key, value, bool_map_);
+}
+
+bool SimpleOptions::SetOption(const std::string &key, const int32 &value) {
+ if (!SetOptionImpl(key, value, int_map_)) {
+ if (!SetOptionImpl(key, static_cast<uint32>(value), uint_map_)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SimpleOptions::SetOption(const std::string &key, const uint32 &value) {
+ if (!SetOptionImpl(key, value, uint_map_)) {
+ if (!SetOptionImpl(key, static_cast<int32>(value), int_map_)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SimpleOptions::SetOption(const std::string &key, const float &value) {
+ if (!SetOptionImpl(key, value, float_map_)) {
+ if (!SetOptionImpl(key, static_cast<double>(value), double_map_)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SimpleOptions::SetOption(const std::string &key, const double &value) {
+ if (!SetOptionImpl(key, value, double_map_)) {
+ if (!SetOptionImpl(key, static_cast<float>(value), float_map_)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SimpleOptions::SetOption(const std::string &key,
+ const std::string &value) {
+ return SetOptionImpl(key, value, string_map_);
+}
+
+bool SimpleOptions::SetOption(const std::string &key, const char *value) {
+ std::string str_value = std::string(value);
+ return SetOptionImpl(key, str_value, string_map_);
+}
+
+
+template<typename T>
+static bool GetOptionImpl(const std::string &key, T *value,
+ std::map<std::string, T*> &some_map) {
+ typename std::map<std::string, T*>::iterator it = some_map.find(key);
+ if (it != some_map.end()) {
+ *value = *(it->second);
+ return true;
+ }
+ return false;
+}
+
+bool SimpleOptions::GetOption(const std::string &key, bool *value) {
+ return GetOptionImpl(key, value, bool_map_);
+}
+
+bool SimpleOptions::GetOption(const std::string &key, int32 *value) {
+ return GetOptionImpl(key, value, int_map_);
+}
+
+bool SimpleOptions::GetOption(const std::string &key, uint32 *value) {
+ return GetOptionImpl(key, value, uint_map_);
+}
+
+bool SimpleOptions::GetOption(const std::string &key, float *value) {
+ return GetOptionImpl(key, value, float_map_);
+}
+
+bool SimpleOptions::GetOption(const std::string &key, double *value) {
+ return GetOptionImpl(key, value, double_map_);
+}
+
+bool SimpleOptions::GetOption(const std::string &key, std::string *value) {
+ return GetOptionImpl(key, value, string_map_);
+}
+
+std::vector<std::pair<std::string, SimpleOptions::OptionInfo> >
+SimpleOptions::GetOptionInfoList() {
+ return option_info_list_;
+}
+
+bool SimpleOptions::GetOptionType(const std::string &key, OptionType *type) {
+ for (std::vector <std::pair<std::string,
+ OptionInfo> >::iterator dx = option_info_list_.begin();
+ dx != option_info_list_.end(); dx++) {
+ std::pair<std::string, SimpleOptions::OptionInfo> info_pair = (*dx);
+ if (info_pair.first == key) {
+ *type = info_pair.second.type;
+ return true;
+ }
+ }
+ return false;
+}
+
+
+
+} // namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/util/simple-options.h b/runtime/onnxruntime/third_party/kaldi/util/simple-options.h
new file mode 100644
index 000000000..eb896f427
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/simple-options.h
@@ -0,0 +1,113 @@
+// util/simple-options.h
+
+// Copyright 2013 Tanel Alumae, Tallinn University of Technology
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_UTIL_SIMPLE_OPTIONS_H_
+#define KALDI_UTIL_SIMPLE_OPTIONS_H_
+
+#include <map>
+#include <string>
+#include <vector>
+
+#include "base/kaldi-common.h"
+#include "itf/options-itf.h"
+
+namespace kaldi {
+
+
+/// The class SimpleOptions is an implementation of OptionsItf that allows
+/// setting and getting option values programmatically, i.e., via getter
+/// and setter methods. It doesn't provide any command line parsing
+/// functionality.
+/// The class ParseOptions should be used for command-line options.
+class SimpleOptions : public OptionsItf {
+ public:
+ SimpleOptions() {
+ }
+
+ virtual ~SimpleOptions() {
+ }
+
+ // Methods from the interface
+ void Register(const std::string &name, bool *ptr, const std::string &doc);
+ void Register(const std::string &name, int32 *ptr, const std::string &doc);
+ void Register(const std::string &name, uint32 *ptr, const std::string &doc);
+ void Register(const std::string &name, float *ptr, const std::string &doc);
+ void Register(const std::string &name, double *ptr, const std::string &doc);
+ void Register(const std::string &name, std::string *ptr,
+ const std::string &doc);
+
+ // set option with the specified key, return true if successful
+ bool SetOption(const std::string &key, const bool &value);
+ bool SetOption(const std::string &key, const int32 &value);
+ bool SetOption(const std::string &key, const uint32 &value);
+ bool SetOption(const std::string &key, const float &value);
+ bool SetOption(const std::string &key, const double &value);
+ bool SetOption(const std::string &key, const std::string &value);
+ bool SetOption(const std::string &key, const char* value);
+
+ // get option with the specified key and put to 'value',
+ // return true if successful
+ bool GetOption(const std::string &key, bool *value);
+ bool GetOption(const std::string &key, int32 *value);
+ bool GetOption(const std::string &key, uint32 *value);
+ bool GetOption(const std::string &key, float *value);
+ bool GetOption(const std::string &key, double *value);
+ bool GetOption(const std::string &key, std::string *value);
+
+ enum OptionType {
+ kBool,
+ kInt32,
+ kUint32,
+ kFloat,
+ kDouble,
+ kString
+ };
+
+ struct OptionInfo {
+ OptionInfo(const std::string &doc, OptionType type) :
+ doc(doc), type(type) {
+ }
+ std::string doc;
+ OptionType type;
+ };
+
+ std::vector<std::pair<std::string, OptionInfo> > GetOptionInfoList();
+
+ /*
+ * Puts the type of the option with name 'key' in the argument 'type'.
+ * Return true if such option is found, false otherwise.
+ */
+ bool GetOptionType(const std::string &key, OptionType *type);
+
+ private:
+
+ std::vector<std::pair<std::string, OptionInfo> > option_info_list_;
+
+ // maps for option variables
+ std::map<std::string, bool*> bool_map_;
+ std::map<std::string, int32*> int_map_;
+ std::map<std::string, uint32*> uint_map_;
+ std::map<std::string, float*> float_map_;
+ std::map<std::string, double*> double_map_;
+ std::map<std::string, std::string*> string_map_;
+};
+
+} // namespace kaldi
+
+#endif // KALDI_UTIL_SIMPLE_OPTIONS_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/stl-utils-test.cc b/runtime/onnxruntime/third_party/kaldi/util/stl-utils-test.cc
new file mode 100644
index 000000000..11781e2f9
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/stl-utils-test.cc
@@ -0,0 +1,275 @@
+// util/stl-utils-test.cc
+
+// Copyright 2009-2012 Microsoft Corporation; Saarland University
+// Johns Hopkins University (Author: Daniel Povey)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/stl-utils.h"
+
+namespace kaldi {
+static void TestIsSorted() {
+ for (int i = 0;i < 100;i++) {
+ std::vector<int> vec, vec2;
+ int len = Rand()%5;
+ for (int i = 0;i < len;i++)
+ vec.push_back(Rand() % 10);
+ vec2 = vec;
+ std::sort(vec2.begin(), vec2.end());
+ KALDI_ASSERT(IsSorted(vec) == (vec == vec2));
+ }
+}
+
+static void TestIsSortedAndUniq() {
+ for (int i = 0;i < 100;i++) {
+ std::vector<int> vec, vec2;
+ int len = Rand()%5;
+ for (int i = 0;i < len;i++)
+ vec.push_back(Rand() % 10);
+
+ if (!IsSortedAndUniq(vec)) {
+ bool ok = false;
+ for (size_t i = 0; i+1 < (size_t)len; i++)
+ if (vec[i] >= vec[i+1]) ok = true; // found out-of-order or dup.
+ KALDI_ASSERT(ok);
+ } else { // is sorted + uniq.
+ for (size_t i = 0; i+1 < (size_t)len; i++)
+ KALDI_ASSERT(vec[i] < vec[i+1]);
+ }
+ }
+}
+
+
+static void TestUniq() {
+ for (int i = 0;i < 100;i++) {
+ std::vector<int> vec;
+
+ int cur = 1; // sorted order.
+ int len = Rand()%5;
+ for (int i = 0;i < len;i++) {
+ cur += 1 + (Rand() % 100);
+ vec.push_back(cur);
+ }
+ std::vector<int> vec2;
+ for (int i = 0;i < len;i++) {
+ int count = 1 + Rand()%5;
+ for (int j = 0;j < count;j++) vec2.push_back(vec[i]);
+ }
+ Uniq(&vec2);
+ KALDI_ASSERT(vec2 == vec);
+ }
+}
+
+
+static void TestSortAndUniq() {
+ for (int i = 0;i < 100;i++) {
+ std::vector<int> vec;
+
+ int len = Rand()%5;
+ for (int i = 0;i < len;i++) {
+ int n = Rand() % 100;
+ bool ok = true;
+ for (size_t j = 0;j < vec.size();j++) if (vec[j] == n) ok = false;
+ if (ok) vec.push_back(n);
+ }
+ // don't sort.
+ std::vector<int> vec2(vec); // make sure all things in "vec" represented
+ // in vec2.
+ int len2 = Rand()%10;
+ if (vec.size() > 0) // add more, randomly.
+ for (int i = 0;i < len2;i++)
+ vec2.push_back(vec[Rand()%vec.size()]);
+ SortAndUniq(&vec2);
+ std::sort(vec.begin(), vec.end());
+ KALDI_ASSERT(vec == vec2);
+ }
+}
+
+void TestCopySetToVector() {
+ for (int p = 0; p < 100; p++) {
+ std::set<int> st;
+ int sz = Rand() % 20;
+ for (int i = 0;i < sz;i++) st.insert(Rand() % 10);
+ std::vector<int> v;
+ CopySetToVector(st, &v);
+ KALDI_ASSERT(st.size() == v.size());
+ for (size_t i = 0;i < v.size();i++) KALDI_ASSERT(st.count(v[i]) != 0);
+ }
+}
+
+
+void TestCopyMapToVector() {
+ for (int p = 0; p < 100; p++) {
+ std::map<int, int> mp;
+ int sz = Rand() % 20;
+ for (int i = 0;i < sz;i++) mp[Rand() % 10] = Rand() % 20;
+ std::vector<std::pair<int, int> > v;
+ CopyMapToVector(mp, &v);
+ KALDI_ASSERT(mp.size() == v.size());
+ for (size_t i = 0;i < v.size();i++)
+ KALDI_ASSERT(mp[v[i].first] == v[i].second);
+ }
+}
+
+
+void TestCopyMapKeysToVector() {
+ for (int p = 0; p < 100; p++) {
+ std::map<int, int> mp;
+ int sz = Rand() % 20;
+ for (int i = 0;i < sz;i++) mp[Rand() % 10] = Rand() % 20;
+ std::vector<int> v;
+ CopyMapKeysToVector(mp, &v);
+ KALDI_ASSERT(mp.size() == v.size());
+ for (size_t i = 0;i < v.size();i++) KALDI_ASSERT(mp.count(v[i]) == 1);
+ }
+}
+
+void TestCopyMapValuesToVector() {
+ for (int p = 0; p < 100; p++) {
+ std::map<int, int> mp;
+ int sz = Rand() % 20;
+ for (int i = 0;i < sz;i++) mp[Rand() % 10] = Rand() % 20;
+ std::vector<int> v;
+ CopyMapValuesToVector(mp, &v);
+ KALDI_ASSERT(mp.size() == v.size());
+ int i = 0;
+ for (std::map<int, int>::iterator iter = mp.begin(); iter != mp.end();
+ iter++) {
+ KALDI_ASSERT(v[i++] == iter->second);
+ }
+ }
+}
+
+void TestCopyMapKeysToSet() {
+ for (int p = 0; p < 100; p++) {
+ std::map<int, int> mp;
+ int sz = Rand() % 20;
+ for (int i = 0;i < sz;i++) mp[Rand() % 10] = Rand() % 20;
+ std::vector<int> v;
+ std::set<int> s;
+ CopyMapKeysToVector(mp, &v);
+ CopyMapKeysToSet(mp, &s);
+ std::set<int> s2;
+ CopyVectorToSet(v, &s2);
+ KALDI_ASSERT(s == s2);
+ }
+}
+
+
+void TestCopyMapValuesToSet() {
+ for (int p = 0; p < 100; p++) {
+ std::map<int, int> mp;
+ int sz = Rand() % 20;
+ for (int i = 0;i < sz;i++) mp[Rand() % 10] = Rand() % 20;
+ std::vector<int> v;
+ std::set<int> s;
+ CopyMapValuesToVector(mp, &v);
+ CopyMapValuesToSet(mp, &s);
+ std::set<int> s2;
+ CopyVectorToSet(v, &s2);
+ KALDI_ASSERT(s == s2);
+ }
+}
+
+
+void TestContainsNullPointers() {
+ for (int p = 0; p < 100; p++) {
+ std::vector<char*> vec;
+ int sz = Rand() % 3;
+ bool is_null = false;
+ for (int i = 0;i < sz;i++) {
+ vec.push_back(reinterpret_cast<char*>(static_cast<intptr_t>(Rand() % 2)));
+ if (vec.back() == NULL)
+ is_null = true;
+ }
+ KALDI_ASSERT(is_null == ContainsNullPointers(vec));
+ }
+}
+
+void TestReverseVector() {
+ for (int p = 0; p < 100; p++) {
+ std::vector<int> vec;
+ int sz = Rand() % 5;
+ for (int i = 0;i < sz;i++)
+ vec.push_back(Rand() % 4);
+ std::vector<int> vec2(vec), vec3(vec);
+ ReverseVector(&vec2);
+ ReverseVector(&vec2);
+ KALDI_ASSERT(vec2 == vec);
+ ReverseVector(&vec3);
+ for (size_t i = 0; i < vec.size(); i++)
+ KALDI_ASSERT(vec[i] == vec3[vec.size()-1-i]);
+ }
+}
+
+void TestMergePairVectorSumming() {
+ for (int p = 0; p < 100; p++) {
+ std::vector<std::pair<int32, int16> > v;
+ std::map<int32, int16> m;
+ int sz = Rand() % 10;
+ for (size_t i = 0; i < sz; i++) {
+ int32 key = Rand() % 10;
+ int16 val = (Rand() % 5) - 2;
+ v.push_back(std::make_pair(key, val));
+ if (m.count(key) == 0) m[key] = val;
+ else
+ m[key] += val;
+ }
+ MergePairVectorSumming(&v);
+ KALDI_ASSERT(IsSorted(v));
+ for (size_t i = 0; i < v.size(); i++) {
+ KALDI_ASSERT(v[i].second == m[v[i].first]);
+ KALDI_ASSERT(v[i].second != 0.0);
+ if (i > 0) KALDI_ASSERT(v[i].first > v[i-1].first);
+ }
+ for (std::map<int32, int16>::const_iterator iter = m.begin();
+ iter != m.end(); ++iter) {
+ if (iter->second != 0) {
+ size_t i;
+ for (i = 0; i < v.size(); i++)
+ if (v[i].first == iter->first) break;
+ KALDI_ASSERT(i != v.size()); // Or we didn't find this
+ // key in v.
+ }
+ }
+ }
+}
+
+} // end namespace kaldi
+
+int main() {
+ using namespace kaldi;
+ TestIsSorted();
+ TestIsSortedAndUniq();
+ TestUniq();
+ TestSortAndUniq();
+ TestCopySetToVector();
+ TestCopyMapToVector();
+ TestCopyMapKeysToVector();
+ TestCopyMapValuesToVector();
+ TestCopyMapKeysToSet();
+ TestCopyMapValuesToSet();
+ TestContainsNullPointers();
+ TestReverseVector();
+ TestMergePairVectorSumming();
+ // CopyVectorToSet implicitly tested by last 2.
+ std::cout << "Test OK\n";
+}
+
+
+
diff --git a/runtime/onnxruntime/third_party/kaldi/util/stl-utils.h b/runtime/onnxruntime/third_party/kaldi/util/stl-utils.h
new file mode 100644
index 000000000..647073a22
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/stl-utils.h
@@ -0,0 +1,317 @@
+// util/stl-utils.h
+
+// Copyright 2009-2011 Microsoft Corporation; Saarland University
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_UTIL_STL_UTILS_H_
+#define KALDI_UTIL_STL_UTILS_H_
+
+#include <unordered_map>
+#include <unordered_set>
+using std::unordered_map;
+using std::unordered_set;
+
+#include <algorithm>
+#include <map>
+#include <set>
+#include <string>
+#include <vector>
+#include "base/kaldi-common.h"
+
+namespace kaldi {
+
+/// Sorts and uniq's (removes duplicates) from a vector.
+template<typename T>
+inline void SortAndUniq(std::vector<T> *vec) {
+ std::sort(vec->begin(), vec->end());
+ vec->erase(std::unique(vec->begin(), vec->end()), vec->end());
+}
+
+
+/// Returns true if the vector is sorted.
+template<typename T>
+inline bool IsSorted(const std::vector<T> &vec) {
+ typename std::vector<T>::const_iterator iter = vec.begin(), end = vec.end();
+ if (iter == end) return true;
+ while (1) {
+ typename std::vector<T>::const_iterator next_iter = iter;
+ ++next_iter;
+ if (next_iter == end) return true; // end of loop and nothing out of order
+ if (*next_iter < *iter) return false;
+ iter = next_iter;
+ }
+}
+
+
+/// Returns true if the vector is sorted and contains each element
+/// only once.
+template<typename T>
+inline bool IsSortedAndUniq(const std::vector<T> &vec) {
+ typename std::vector<T>::const_iterator iter = vec.begin(), end = vec.end();
+ if (iter == end) return true;
+ while (1) {
+ typename std::vector<T>::const_iterator next_iter = iter;
+ ++next_iter;
+ if (next_iter == end) return true; // end of loop and nothing out of order
+ if (*next_iter <= *iter) return false;
+ iter = next_iter;
+ }
+}
+
+
+/// Removes duplicate elements from a sorted list.
+template<typename T>
+inline void Uniq(std::vector<T> *vec) { // must be already sorted.
+ KALDI_PARANOID_ASSERT(IsSorted(*vec));
+ KALDI_ASSERT(vec);
+ vec->erase(std::unique(vec->begin(), vec->end()), vec->end());
+}
+
+/// Copies the elements of a set to a vector.
+template<class T>
+void CopySetToVector(const std::set<T> &s, std::vector<T> *v) {
+ // copies members of s into v, in sorted order from lowest to highest
+ // (because the set was in sorted order).
+ KALDI_ASSERT(v != NULL);
+ v->resize(s.size());
+ typename std::set<T>::const_iterator siter = s.begin(), send = s.end();
+ typename std::vector<T>::iterator viter = v->begin();
+ for (; siter != send; ++siter, ++viter) {
+ *viter = *siter;
+ }
+}
+
+template<class T>
+void CopySetToVector(const unordered_set<T> &s, std::vector<T> *v) {
+ KALDI_ASSERT(v != NULL);
+ v->resize(s.size());
+ typename unordered_set<T>::const_iterator siter = s.begin(), send = s.end();
+ typename std::vector<T>::iterator viter = v->begin();
+ for (; siter != send; ++siter, ++viter) {
+ *viter = *siter;
+ }
+}
+
+
+/// Copies the (key, value) pairs in a map to a vector of pairs.
+template<class A, class B>
+void CopyMapToVector(const std::map<A, B> &m,
+ std::vector<std::pair<A, B> > *v) {
+ KALDI_ASSERT(v != NULL);
+ v->resize(m.size());
+ typename std::map<A, B>::const_iterator miter = m.begin(), mend = m.end();
+ typename std::vector<std::pair<A, B> >::iterator viter = v->begin();
+ for (; miter != mend; ++miter, ++viter) {
+ *viter = std::make_pair(miter->first, miter->second);
+ // do it like this because of const casting.
+ }
+}
+
+/// Copies the keys in a map to a vector.
+template<class A, class B>
+void CopyMapKeysToVector(const std::map<A, B> &m, std::vector<A> *v) {
+ KALDI_ASSERT(v != NULL);
+ v->resize(m.size());
+ typename std::map<A, B>::const_iterator miter = m.begin(), mend = m.end();
+ typename std::vector<A>::iterator viter = v->begin();
+ for (; miter != mend; ++miter, ++viter) {
+ *viter = miter->first;
+ }
+}
+
+/// Copies the values in a map to a vector.
+template<class A, class B>
+void CopyMapValuesToVector(const std::map<A, B> &m, std::vector<B> *v) {
+ KALDI_ASSERT(v != NULL);
+ v->resize(m.size());
+ typename std::map<A, B>::const_iterator miter = m.begin(), mend = m.end();
+ typename std::vector<B>::iterator viter = v->begin();
+ for (; miter != mend; ++miter, ++viter) {
+ *viter = miter->second;
+ }
+}
+
+/// Copies the keys in a map to a set.
+template<class A, class B>
+void CopyMapKeysToSet(const std::map<A, B> &m, std::set<A> *s) {
+ KALDI_ASSERT(s != NULL);
+ s->clear();
+ typename std::map<A, B>::const_iterator miter = m.begin(), mend = m.end();
+ for (; miter != mend; ++miter) {
+ s->insert(s->end(), miter->first);
+ }
+}
+
+/// Copies the values in a map to a set.
+template<class A, class B>
+void CopyMapValuesToSet(const std::map<A, B> &m, std::set<B> *s) {
+ KALDI_ASSERT(s != NULL);
+ s->clear();
+ typename std::map<A, B>::const_iterator miter = m.begin(), mend = m.end();
+ for (; miter != mend; ++miter)
+ s->insert(s->end(), miter->second);
+}
+
+
+/// Copies the contents of a vector to a set.
+template<class A>
+void CopyVectorToSet(const std::vector<A> &v, std::set<A> *s) {
+ KALDI_ASSERT(s != NULL);
+ s->clear();
+ typename std::vector<A>::const_iterator iter = v.begin(), end = v.end();
+ for (; iter != end; ++iter)
+ s->insert(s->end(), *iter);
+ // s->end() is a hint in case v was sorted. will work regardless.
+}
+
+/// Deletes any non-NULL pointers in the vector v, and sets
+/// the corresponding entries of v to NULL
+template<class A>
+void DeletePointers(std::vector<A*> *v) {
+ KALDI_ASSERT(v != NULL);
+ typename std::vector<A*>::iterator iter = v->begin(), end = v->end();
+ for (; iter != end; ++iter) {
+ if (*iter != NULL) {
+ delete *iter;
+ *iter = NULL; // set to NULL for extra safety.
+ }
+ }
+}
+
+/// Returns true if the vector of pointers contains NULL pointers.
+template<class A>
+bool ContainsNullPointers(const std::vector<A*> &v) {
+ typename std::vector<A*>::const_iterator iter = v.begin(), end = v.end();
+ for (; iter != end; ++iter)
+ if (*iter == static_cast<A*> (NULL)) return true;
+ return false;
+}
+
+/// Copies the contents a vector of one type to a vector
+/// of another type.
+template<typename A, typename B>
+void CopyVectorToVector(const std::vector<A> &vec_in, std::vector<B> *vec_out) {
+ KALDI_ASSERT(vec_out != NULL);
+ vec_out->resize(vec_in.size());
+ for (size_t i = 0; i < vec_in.size(); i++)
+ (*vec_out)[i] = static_cast<B> (vec_in[i]);
+}
+
+/// A hashing function-object for vectors.
+template<typename Int>
+struct VectorHasher { // hashing function for vector<Int>.
+ size_t operator()(const std::vector<Int> &x) const noexcept {
+ size_t ans = 0;
+ typename std::vector<Int>::const_iterator iter = x.begin(), end = x.end();
+ for (; iter != end; ++iter) {
+ ans *= kPrime;
+ ans += *iter;
+ }
+ return ans;
+ }
+ VectorHasher() { // Check we're instantiated with an integer type.
+ KALDI_ASSERT_IS_INTEGER_TYPE(Int);
+ }
+ private:
+ static const int kPrime = 7853;
+};
+
+/// A hashing function-object for pairs of ints
+template<typename Int1, typename Int2 = Int1>
+struct PairHasher { // hashing function for pair<int>
+ size_t operator()(const std::pair<Int1, Int2> &x) const noexcept {
+ // 7853 was chosen at random from a list of primes.
+ return x.first + x.second * 7853;
+ }
+ PairHasher() { // Check we're instantiated with an integer type.
+ KALDI_ASSERT_IS_INTEGER_TYPE(Int1);
+ KALDI_ASSERT_IS_INTEGER_TYPE(Int2);
+ }
+};
+
+
+/// A hashing function object for strings.
+struct StringHasher { // hashing function for std::string
+ size_t operator()(const std::string &str) const noexcept {
+ size_t ans = 0, len = str.length();
+ const char *c = str.c_str(), *end = c + len;
+ for (; c != end; c++) {
+ ans *= kPrime;
+ ans += *c;
+ }
+ return ans;
+ }
+ private:
+ static const int kPrime = 7853;
+};
+
+/// Reverses the contents of a vector.
+template<typename T>
+inline void ReverseVector(std::vector<T> *vec) {
+ KALDI_ASSERT(vec != NULL);
+ size_t sz = vec->size();
+ for (size_t i = 0; i < sz/2; i++)
+ std::swap( (*vec)[i], (*vec)[sz-1-i]);
+}
+
+
+/// Comparator object for pairs that compares only the first pair.
+template<class A, class B>
+struct CompareFirstMemberOfPair {
+ inline bool operator() (const std::pair<A, B> &p1,
+ const std::pair<A, B> &p2) {
+ return p1.first < p2.first;
+ }
+};
+
+/// For a vector of pair<I, F> where I is an integer and F a floating-point or
+/// integer type, this function sorts a vector of type vector<pair<I, F> > on
+/// the I value and then merges elements with equal I values, summing these over
+/// the F component and then removing any F component with zero value. This
+/// is for where the vector of pairs represents a map from the integer to float
+/// component, with an "adding" type of semantics for combining the elements.
+template<typename I, typename F>
+inline void MergePairVectorSumming(std::vector<std::pair<I, F> > *vec) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ CompareFirstMemberOfPair<I, F> c;
+ std::sort(vec->begin(), vec->end(), c); // sort on 1st element.
+ typename std::vector<std::pair<I, F> >::iterator out = vec->begin(),
+ in = vec->begin(), end = vec->end();
+ // special case: while there is nothing to be changed, skip over
+ // initial input (avoids unnecessary copying).
+ while (in + 1 < end && in[0].first != in[1].first && in[0].second != 0.0) {
+ in++;
+ out++;
+ }
+ while (in < end) {
+ // We reach this point only at the first element of
+ // each stretch of identical .first elements.
+ *out = *in;
+ ++in;
+ while (in < end && in->first == out->first) {
+ out->second += in->second; // this is the merge operation.
+ ++in;
+ }
+ if (out->second != static_cast<F>(0)) // Don't keep zero elements.
+ out++;
+ }
+ vec->erase(out, end);
+}
+
+} // namespace kaldi
+
+#endif // KALDI_UTIL_STL_UTILS_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/table-types.h b/runtime/onnxruntime/third_party/kaldi/util/table-types.h
new file mode 100644
index 000000000..b6c19de12
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/table-types.h
@@ -0,0 +1,207 @@
+// util/table-types.h
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2020 Mobvoi AI Lab, Beijing, China (author: Fangjun Kuang)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef KALDI_UTIL_TABLE_TYPES_H_
+#define KALDI_UTIL_TABLE_TYPES_H_
+#include "base/kaldi-common.h"
+#include "util/kaldi-table.h"
+#include "util/kaldi-holder.h"
+#include "matrix/matrix-lib.h"
+
+namespace kaldi {
+
+// This header defines typedefs that are specific instantiations of
+// the Table types.
+
+/// \addtogroup table_types
+/// @{
+
+typedef TableWriter<KaldiObjectHolder<MatrixBase<BaseFloat> > >
+ BaseFloatMatrixWriter;
+typedef SequentialTableReader<KaldiObjectHolder<Matrix<BaseFloat> > >
+ SequentialBaseFloatMatrixReader;
+typedef RandomAccessTableReader<KaldiObjectHolder<Matrix<BaseFloat> > >
+ RandomAccessBaseFloatMatrixReader;
+typedef RandomAccessTableReaderMapped<KaldiObjectHolder<Matrix<BaseFloat> > >
+ RandomAccessBaseFloatMatrixReaderMapped;
+
+typedef TableWriter<KaldiObjectHolder<MatrixBase<double> > >
+ DoubleMatrixWriter;
+typedef SequentialTableReader<KaldiObjectHolder<Matrix<double> > >
+ SequentialDoubleMatrixReader;
+typedef RandomAccessTableReader<KaldiObjectHolder<Matrix<double> > >
+ RandomAccessDoubleMatrixReader;
+typedef RandomAccessTableReaderMapped<KaldiObjectHolder<Matrix<double> > >
+ RandomAccessDoubleMatrixReaderMapped;
+
+typedef TableWriter<KaldiObjectHolder<CompressedMatrix> >
+ CompressedMatrixWriter;
+
+typedef TableWriter<KaldiObjectHolder<VectorBase<BaseFloat> > >
+ BaseFloatVectorWriter;
+typedef SequentialTableReader<KaldiObjectHolder<Vector<BaseFloat> > >
+ SequentialBaseFloatVectorReader;
+typedef RandomAccessTableReader<KaldiObjectHolder<Vector<BaseFloat> > >
+ RandomAccessBaseFloatVectorReader;
+typedef RandomAccessTableReaderMapped<KaldiObjectHolder<Vector<BaseFloat> > >
+ RandomAccessBaseFloatVectorReaderMapped;
+
+typedef TableWriter<KaldiObjectHolder<VectorBase<double> > >
+ DoubleVectorWriter;
+typedef SequentialTableReader<KaldiObjectHolder<Vector<double> > >
+ SequentialDoubleVectorReader;
+typedef RandomAccessTableReader<KaldiObjectHolder<Vector<double> > >
+ RandomAccessDoubleVectorReader;
+
+typedef TableWriter<KaldiObjectHolder<NumpyArray<BaseFloat>>>
+ BaseFloatNumpyArrayWriter;
+typedef SequentialTableReader<KaldiObjectHolder<NumpyArray<BaseFloat>>>
+ SequentialBaseFloatNumpyArrayReader;
+typedef RandomAccessTableReader<KaldiObjectHolder<NumpyArray<BaseFloat>>>
+ RandomAccessBaseFloatNumpyArrayReader;
+
+typedef TableWriter<KaldiObjectHolder<NumpyArray<double>>>
+ DoubleNumpyArrayWriter;
+typedef SequentialTableReader<KaldiObjectHolder<NumpyArray<double>>>
+ SequentialDoubleNumpyArrayReader;
+typedef RandomAccessTableReader<KaldiObjectHolder<NumpyArray<double>>>
+ RandomAccessDoubleNumpyArrayReader;
+
+typedef TableWriter<KaldiObjectHolder<CuMatrix<BaseFloat> > >
+ BaseFloatCuMatrixWriter;
+typedef SequentialTableReader<KaldiObjectHolder<CuMatrix<BaseFloat> > >
+ SequentialBaseFloatCuMatrixReader;
+typedef RandomAccessTableReader<KaldiObjectHolder<CuMatrix<BaseFloat> > >
+ RandomAccessBaseFloatCuMatrixReader;
+typedef RandomAccessTableReaderMapped<KaldiObjectHolder<CuMatrix<BaseFloat> > >
+ RandomAccessBaseFloatCuMatrixReaderMapped;
+
+typedef TableWriter<KaldiObjectHolder<CuMatrix<double> > >
+ DoubleCuMatrixWriter;
+typedef SequentialTableReader<KaldiObjectHolder<CuMatrix<double> > >
+ SequentialDoubleCuMatrixReader;
+typedef RandomAccessTableReader<KaldiObjectHolder<CuMatrix<double> > >
+ RandomAccessDoubleCuMatrixReader;
+typedef RandomAccessTableReaderMapped<KaldiObjectHolder<CuMatrix<double> > >
+ RandomAccessDoubleCuMatrixReaderMapped;
+
+typedef TableWriter<KaldiObjectHolder<CuVector<BaseFloat> > >
+ BaseFloatCuVectorWriter;
+typedef SequentialTableReader<KaldiObjectHolder<CuVector<BaseFloat> > >
+ SequentialBaseFloatCuVectorReader;
+typedef RandomAccessTableReader<KaldiObjectHolder<CuVector<BaseFloat> > >
+ RandomAccessBaseFloatCuVectorReader;
+typedef RandomAccessTableReaderMapped<KaldiObjectHolder<CuVector<BaseFloat> > >
+ RandomAccessBaseFloatCuVectorReaderMapped;
+
+typedef TableWriter<KaldiObjectHolder<CuVector<double> > >
+ DoubleCuVectorWriter;
+typedef SequentialTableReader<KaldiObjectHolder<CuVector<double> > >
+ SequentialDoubleCuVectorReader;
+typedef RandomAccessTableReader<KaldiObjectHolder<CuVector<double> > >
+ RandomAccessDoubleCuVectorReader;
+
+
+typedef TableWriter<BasicHolder<int32> > Int32Writer;
+typedef SequentialTableReader<BasicHolder<int32> > SequentialInt32Reader;
+typedef RandomAccessTableReader<BasicHolder<int32> > RandomAccessInt32Reader;
+
+typedef TableWriter<BasicVectorHolder<int32> > Int32VectorWriter;
+typedef SequentialTableReader<BasicVectorHolder<int32> >
+ SequentialInt32VectorReader;
+typedef RandomAccessTableReader<BasicVectorHolder<int32> >
+ RandomAccessInt32VectorReader;
+
+typedef TableWriter<BasicVectorVectorHolder<int32> > Int32VectorVectorWriter;
+typedef SequentialTableReader<BasicVectorVectorHolder<int32> >
+ SequentialInt32VectorVectorReader;
+typedef RandomAccessTableReader<BasicVectorVectorHolder<int32> >
+ RandomAccessInt32VectorVectorReader;
+
+typedef TableWriter<BasicPairVectorHolder<int32> > Int32PairVectorWriter;
+typedef SequentialTableReader<BasicPairVectorHolder<int32> >
+ SequentialInt32PairVectorReader;
+typedef RandomAccessTableReader<BasicPairVectorHolder<int32> >
+ RandomAccessInt32PairVectorReader;
+
+typedef TableWriter<BasicPairVectorHolder<BaseFloat> >
+ BaseFloatPairVectorWriter;
+typedef SequentialTableReader<BasicPairVectorHolder<BaseFloat> >
+ SequentialBaseFloatPairVectorReader;
+typedef RandomAccessTableReader<BasicPairVectorHolder<BaseFloat> >
+ RandomAccessBaseFloatPairVectorReader;
+
+typedef TableWriter<BasicHolder<BaseFloat> > BaseFloatWriter;
+typedef SequentialTableReader<BasicHolder<BaseFloat> >
+ SequentialBaseFloatReader;
+typedef RandomAccessTableReader<BasicHolder<BaseFloat> >
+ RandomAccessBaseFloatReader;
+typedef RandomAccessTableReaderMapped<BasicHolder<BaseFloat> >
+ RandomAccessBaseFloatReaderMapped;
+
+typedef TableWriter<BasicHolder<double> > DoubleWriter;
+typedef SequentialTableReader<BasicHolder<double> > SequentialDoubleReader;
+typedef RandomAccessTableReader<BasicHolder<double> > RandomAccessDoubleReader;
+
+typedef TableWriter<BasicHolder<bool> > BoolWriter;
+typedef SequentialTableReader<BasicHolder<bool> > SequentialBoolReader;
+typedef RandomAccessTableReader<BasicHolder<bool> > RandomAccessBoolReader;
+
+
+
+/// TokenWriter is a writer specialized for std::string where the strings
+/// are nonempty and whitespace-free. T == std::string
+typedef TableWriter<TokenHolder> TokenWriter;
+typedef SequentialTableReader<TokenHolder> SequentialTokenReader;
+typedef RandomAccessTableReader<TokenHolder> RandomAccessTokenReader;
+
+
+/// TokenVectorWriter is a writer specialized for sequences of
+/// std::string where the strings are nonempty and whitespace-free.
+/// T == std::vector<std::string>
+typedef TableWriter<TokenVectorHolder> TokenVectorWriter;
+// Ditto for SequentialTokenVectorReader.
+typedef SequentialTableReader<TokenVectorHolder> SequentialTokenVectorReader;
+typedef RandomAccessTableReader<TokenVectorHolder>
+ RandomAccessTokenVectorReader;
+
+
+typedef TableWriter<KaldiObjectHolder<GeneralMatrix> >
+ GeneralMatrixWriter;
+typedef SequentialTableReader<KaldiObjectHolder<GeneralMatrix> >
+ SequentialGeneralMatrixReader;
+typedef RandomAccessTableReader<KaldiObjectHolder<GeneralMatrix> >
+ RandomAccessGeneralMatrixReader;
+typedef RandomAccessTableReaderMapped<KaldiObjectHolder<GeneralMatrix> >
+ RandomAccessGeneralMatrixReaderMapped;
+
+
+
+/// @}
+
+// Note: for FST reader/writer, see ../fstext/fstext-utils.h
+// [not done yet].
+
+} // end namespace kaldi
+
+
+
+#endif // KALDI_UTIL_TABLE_TYPES_H_
diff --git a/runtime/onnxruntime/third_party/kaldi/util/text-utils-test.cc b/runtime/onnxruntime/third_party/kaldi/util/text-utils-test.cc
new file mode 100644
index 000000000..3b58f4f1d
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/text-utils-test.cc
@@ -0,0 +1,538 @@
+// util/text-utils-test.cc
+
+// Copyright 2009-2011 Microsoft Corporation
+// 2017 Johns Hopkins University (author: Daniel Povey)
+// 2015 Vimal Manohar (Johns Hopkins University)
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+
+#include "base/kaldi-common.h"
+#include "util/text-utils.h"
+
+namespace kaldi {
+
+char GetRandChar() {
+ return static_cast<char>(32 + Rand() % 95); // between ' ' and '~'
+}
+
+const char *ws_delim = " \t\n\r";
+char GetRandDelim() {
+ if (Rand() % 2 == 0)
+ return static_cast<char>(33 + Rand() % 94); // between '!' and '~';
+ else
+ return ws_delim[Rand() % 4];
+}
+
+
+void TestSplitStringToVector() {
+ // srand((unsigned int)time(NULL));
+ // didn't compile on cygwin.
+
+ {
+ std::vector<std::string> str_vec;
+ SplitStringToVector("", " ", false, &str_vec);
+ KALDI_ASSERT(str_vec.size() == 1); // If this fails it may just mean
+ // that someone changed the
+ // semantics of SplitStringToVector in a reasonable way.
+ SplitStringToVector("", " ", true, &str_vec);
+ KALDI_ASSERT(str_vec.empty());
+ }
+ for (int j = 0; j < 100; j++) {
+ std::vector<std::string> str_vec;
+ int sz = Rand() % 73;
+ std::string full;
+ for (int i = 0; i < sz-1; i++) {
+ full.push_back((Rand() % 7 == 0)? GetRandDelim() : GetRandChar());
+ }
+ std::string delim;
+ delim.push_back(GetRandDelim());
+ bool omit_empty_strings = (Rand() %2 == 0)? true : false;
+ SplitStringToVector(full, delim.c_str(), omit_empty_strings, &str_vec);
+ std::string new_full;
+ for (size_t i = 0; i < str_vec.size(); i++) {
+ if (omit_empty_strings) KALDI_ASSERT(str_vec[i] != "");
+ new_full.append(str_vec[i]);
+ if (i < str_vec.size() -1) new_full.append(delim);
+ }
+ std::string new_full2;
+ JoinVectorToString(str_vec, delim.c_str(), omit_empty_strings, &new_full2);
+ if (omit_empty_strings) { // sequences of delimiters cannot be matched
+ size_t start = full.find_first_not_of(delim),
+ end = full.find_last_not_of(delim);
+ if (start == std::string::npos) { // only delimiters
+ KALDI_ASSERT(end == std::string::npos);
+ } else {
+ std::string full_test;
+ char last = '\0';
+ for (size_t i = start; i <= end; i++) {
+ if (full[i] != last || last != *delim.c_str())
+ full_test.push_back(full[i]);
+ last = full[i];
+ }
+ if (!full.empty()) {
+ KALDI_ASSERT(new_full.compare(full_test) == 0);
+ KALDI_ASSERT(new_full2.compare(full_test) == 0);
+ }
+ }
+ } else if (!full.empty()) {
+ KALDI_ASSERT(new_full.compare(full) == 0);
+ KALDI_ASSERT(new_full2.compare(full) == 0);
+ }
+ }
+}
+
+void TestSplitStringToIntegers() {
+ {
+ std::vector<int32> v;
+ KALDI_ASSERT(SplitStringToIntegers("-1:2:4", ":", false, &v) == true
+ && v.size() == 3 && v[0] == -1 && v[1] == 2 && v[2] == 4);
+ KALDI_ASSERT(SplitStringToIntegers("-1:2:4:", ":", false, &v) == false);
+ KALDI_ASSERT(SplitStringToIntegers(":-1::2:4:", ":", true, &v) == true
+ && v.size() == 3 && v[0] == -1 && v[1] == 2 && v[2] == 4);
+ KALDI_ASSERT(SplitStringToIntegers("-1\n2\t4", " \n\t\r", false, &v) == true
+ && v.size() == 3 && v[0] == -1 && v[1] == 2 && v[2] == 4);
+ KALDI_ASSERT(SplitStringToIntegers(" ", " \n\t\r", true, &v) == true
+ && v.size() == 0);
+ KALDI_ASSERT(SplitStringToIntegers("", " \n\t\r", false, &v) == true
+ && v.size() == 0);
+ }
+
+ {
+ std::vector<uint32> v;
+ KALDI_ASSERT(SplitStringToIntegers("-1:2:4", ":", false, &v) == false);
+ // cannot put negative number in uint32.
+ }
+}
+
+
+
+void TestSplitStringToFloats() {
+ {
+ std::vector<float> v;
+ KALDI_ASSERT(SplitStringToFloats("-1:2.5:4", ":", false, &v) == true
+ && v.size() == 3 && v[0] == -1 && v[1] == 2.5 && v[2] == 4);
+ KALDI_ASSERT(SplitStringToFloats("-1:2.5:4:", ":", false, &v) == false);
+ KALDI_ASSERT(SplitStringToFloats(":-1::2:4:", ":", true, &v) == true
+ && v.size() == 3 && v[0] == -1 && v[1] == 2 && v[2] == 4);
+ KALDI_ASSERT(SplitStringToFloats("-1\n2.5\t4", " \n\t\r", false, &v) == true
+ && v.size() == 3 && v[0] == -1 && v[1] == 2.5 && v[2] == 4);
+ KALDI_ASSERT(SplitStringToFloats(" ", " \n\t\r", true, &v) == true
+ && v.size() == 0);
+ KALDI_ASSERT(SplitStringToFloats("", " \n\t\r", false, &v) == true
+ && v.size() == 0);
+ }
+
+ {
+ std::vector<double> v;
+ KALDI_ASSERT(SplitStringToFloats("-1:2:4", ":", false, &v) == true);
+ }
+}
+
+void TestConvertStringToInteger() {
+ int32 i;
+ KALDI_ASSERT(ConvertStringToInteger("12345", &i) && i == 12345);
+ KALDI_ASSERT(ConvertStringToInteger("-12345", &i) && i == -12345);
+ char j;
+ KALDI_ASSERT(!ConvertStringToInteger("-12345", &j)); // too big for char.
+
+ KALDI_ASSERT(ConvertStringToInteger(" -12345 ", &i)); // whitespace accepted
+
+ KALDI_ASSERT(!ConvertStringToInteger("a ", &i)); // non-integers rejected.
+
+ KALDI_ASSERT(ConvertStringToInteger("0", &i) && i == 0);
+
+ uint64 k;
+ KALDI_ASSERT(ConvertStringToInteger("12345", &k) && k == 12345);
+ KALDI_ASSERT(!ConvertStringToInteger("-12345", &k)); // unsigned,
+ // cannot convert.
+}
+
+template<class Real>
+void TestConvertStringToReal() {
+ Real d;
+ KALDI_ASSERT(ConvertStringToReal("1", &d) && d == 1.0);
+ KALDI_ASSERT(ConvertStringToReal("-1", &d) && d == -1.0);
+ KALDI_ASSERT(ConvertStringToReal("-1", &d) && d == -1.0);
+ KALDI_ASSERT(ConvertStringToReal(" -1 ", &d) && d == -1.0);
+ KALDI_ASSERT(!ConvertStringToReal("-1 x", &d));
+ KALDI_ASSERT(!ConvertStringToReal("-1f", &d));
+ KALDI_ASSERT(ConvertStringToReal("12345.2", &d) && fabs(d-12345.2) < 1.0);
+ KALDI_ASSERT(ConvertStringToReal("1.0e+08", &d) && fabs(d-1.0e+08) < 100.0);
+
+ // it also works for inf or nan.
+ KALDI_ASSERT(ConvertStringToReal("inf", &d) && d > 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal(" inf", &d) && d > 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal("inf ", &d) && d > 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal(" inf ", &d) && d > 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal("+inf", &d) && d > 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal("-inf", &d) && d < 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal("Inf", &d) && d > 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal("INF", &d) && d > 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal("InF", &d) && d > 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal("infinity", &d) && d > 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal("-infinity", &d) && d < 0 && d - d != 0);
+ KALDI_ASSERT(!ConvertStringToReal("GARBAGE inf", &d));
+ KALDI_ASSERT(!ConvertStringToReal("GARBAGEinf", &d));
+ KALDI_ASSERT(!ConvertStringToReal("infGARBAGE", &d));
+ KALDI_ASSERT(!ConvertStringToReal("inf_GARBAGE", &d));
+ KALDI_ASSERT(!ConvertStringToReal("inf GARBAGE", &d));
+ KALDI_ASSERT(!ConvertStringToReal("GARBAGE infinity", &d));
+ KALDI_ASSERT(!ConvertStringToReal("GARBAGEinfinity", &d));
+ KALDI_ASSERT(!ConvertStringToReal("infinityGARBAGE", &d));
+ KALDI_ASSERT(!ConvertStringToReal("infinity_GARBAGE", &d));
+ KALDI_ASSERT(!ConvertStringToReal("infinity GARBAGE", &d));
+ KALDI_ASSERT(ConvertStringToReal("1.#INF", &d) && d > 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal("-1.#INF", &d) && d < 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal("-1.#INF ", &d) && d < 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal(" -1.#INF ", &d) && d < 0 && d - d != 0);
+ KALDI_ASSERT(!ConvertStringToReal("GARBAGE 1.#INF", &d));
+ KALDI_ASSERT(!ConvertStringToReal("GARBAGE1.#INF", &d));
+ KALDI_ASSERT(!ConvertStringToReal("2.#INF", &d));
+ KALDI_ASSERT(!ConvertStringToReal("-2.#INF", &d));
+ KALDI_ASSERT(!ConvertStringToReal("1.#INFGARBAGE", &d));
+ KALDI_ASSERT(!ConvertStringToReal("1.#INF_GARBAGE", &d));
+
+ KALDI_ASSERT(ConvertStringToReal("nan", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal("+nan", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal("-nan", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal("Nan", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal("NAN", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal("NaN", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal(" NaN", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal("NaN ", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal(" NaN ", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal("1.#QNAN", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal("-1.#QNAN", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal("1.#QNAN ", &d) && d != d);
+ KALDI_ASSERT(ConvertStringToReal(" 1.#QNAN ", &d) && d != d);
+ KALDI_ASSERT(!ConvertStringToReal("GARBAGE nan", &d));
+ KALDI_ASSERT(!ConvertStringToReal("GARBAGEnan", &d));
+ KALDI_ASSERT(!ConvertStringToReal("nanGARBAGE", &d));
+ KALDI_ASSERT(!ConvertStringToReal("nan_GARBAGE", &d));
+ KALDI_ASSERT(!ConvertStringToReal("nan GARBAGE", &d));
+ KALDI_ASSERT(!ConvertStringToReal("GARBAGE 1.#QNAN", &d));
+ KALDI_ASSERT(!ConvertStringToReal("GARBAGE1.#QNAN", &d));
+ KALDI_ASSERT(!ConvertStringToReal("2.#QNAN", &d));
+ KALDI_ASSERT(!ConvertStringToReal("-2.#QNAN", &d));
+ KALDI_ASSERT(!ConvertStringToReal("-1.#QNAN_GARBAGE", &d));
+ KALDI_ASSERT(!ConvertStringToReal("-1.#QNANGARBAGE", &d));
+}
+
+template<class Real>
+void TestNan() {
+ Real d;
+ KALDI_ASSERT(ConvertStringToReal(std::to_string(sqrt(-1)), &d) && d != d);
+}
+
+template<class Real>
+void TestInf() {
+ Real d;
+ KALDI_ASSERT(ConvertStringToReal(std::to_string(exp(10000)), &d) &&
+ d > 0 && d - d != 0);
+ KALDI_ASSERT(ConvertStringToReal(std::to_string(-exp(10000)), &d) &&
+ d < 0 && d - d != 0);
+}
+
+
+std::string TrimTmp(std::string s) {
+ Trim(&s);
+ return s;
+}
+
+void TestTrim() {
+ KALDI_ASSERT(TrimTmp(" a ") == "a");
+ KALDI_ASSERT(TrimTmp(" a b c") == "a b c");
+ KALDI_ASSERT(TrimTmp("") == "");
+ KALDI_ASSERT(TrimTmp("X\n") == "X");
+ KALDI_ASSERT(TrimTmp("X\n\t") == "X");
+ KALDI_ASSERT(TrimTmp("\n\tX") == "X");
+} // end namespace kaldi
+
+
+void TestSplitStringOnFirstSpace() {
+ std::string a, b;
+ SplitStringOnFirstSpace("a b", &a, &b);
+ KALDI_ASSERT(a == "a" && b == "b");
+ SplitStringOnFirstSpace("aa bb", &a, &b);
+ KALDI_ASSERT(a == "aa" && b == "bb");
+ SplitStringOnFirstSpace("aa", &a, &b);
+ KALDI_ASSERT(a == "aa" && b == "");
+ SplitStringOnFirstSpace(" aa \n\t ", &a, &b);
+ KALDI_ASSERT(a == "aa" && b == "");
+ SplitStringOnFirstSpace(" \n\t ", &a, &b);
+ KALDI_ASSERT(a == "" && b == "");
+ SplitStringOnFirstSpace(" aa bb \n\t ", &a, &b);
+ KALDI_ASSERT(a == "aa" && b == "bb");
+ SplitStringOnFirstSpace(" aa bb cc ", &a, &b);
+ KALDI_ASSERT(a == "aa" && b == "bb cc");
+ SplitStringOnFirstSpace(" aa bb cc ", &a, &b);
+ KALDI_ASSERT(a == "aa" && b == "bb cc");
+ SplitStringOnFirstSpace(" aa bb cc", &a, &b);
+ KALDI_ASSERT(a == "aa" && b == "bb cc");
+}
+
+void TestIsToken() {
+ KALDI_ASSERT(IsToken("a"));
+ KALDI_ASSERT(IsToken("ab"));
+ KALDI_ASSERT(!IsToken("ab "));
+ KALDI_ASSERT(!IsToken(" ab"));
+ KALDI_ASSERT(!IsToken("a b"));
+ KALDI_ASSERT(IsToken("\231")); // typical non-ASCII printable character,
+ // something with an accent.
+ KALDI_ASSERT(!IsToken("\377")); // character 255, which is a form of space.
+ KALDI_ASSERT(IsToken("a-b,c,d=ef"));
+ KALDI_ASSERT(!IsToken("a\nb"));
+ KALDI_ASSERT(!IsToken("a\tb"));
+ KALDI_ASSERT(!IsToken("ab\t"));
+ KALDI_ASSERT(!IsToken(""));
+}
+
+void TestIsLine() {
+ KALDI_ASSERT(IsLine("a"));
+ KALDI_ASSERT(IsLine("a b"));
+ KALDI_ASSERT(!IsLine("a\nb"));
+ KALDI_ASSERT(!IsLine("a b "));
+ KALDI_ASSERT(!IsLine(" a b"));
+}
+
+
+void TestStringsApproxEqual() {
+ // we must test the test.
+ KALDI_ASSERT(!StringsApproxEqual("a", "b"));
+ KALDI_ASSERT(!StringsApproxEqual("1", "2"));
+ KALDI_ASSERT(StringsApproxEqual("1.234", "1.235", 2));
+ KALDI_ASSERT(!StringsApproxEqual("1.234", "1.235", 3));
+ KALDI_ASSERT(StringsApproxEqual("x 1.234 y", "x 1.2345 y", 3));
+ KALDI_ASSERT(!StringsApproxEqual("x 1.234 y", "x 1.2345 y", 4));
+ KALDI_ASSERT(StringsApproxEqual("x 1.234 y 6.41", "x 1.235 y 6.49", 1));
+ KALDI_ASSERT(!StringsApproxEqual("x 1.234 y 6.41", "x 1.235 y 6.49", 2));
+ KALDI_ASSERT(StringsApproxEqual("x 1.234 y 6.41", "x 1.235 y 6.411", 2));
+ KALDI_ASSERT(StringsApproxEqual("x 1.0 y", "x 1.0001 y", 3));
+ KALDI_ASSERT(!StringsApproxEqual("x 1.0 y", "x 1.0001 y", 4));
+}
+
+void UnitTestConfigLineParse() {
+ std::string str;
+ {
+ ConfigLine cfl;
+ str = "a-b xx=yyy foo=bar baz=123 ba=1:2";
+ bool status = cfl.ParseLine(str);
+ KALDI_ASSERT(status && cfl.FirstToken() == "a-b");
+
+ KALDI_ASSERT(cfl.HasUnusedValues());
+ std::string str_value;
+ KALDI_ASSERT(cfl.GetValue("xx", &str_value));
+ KALDI_ASSERT(str_value == "yyy");
+ KALDI_ASSERT(cfl.HasUnusedValues());
+ KALDI_ASSERT(cfl.GetValue("foo", &str_value));
+ KALDI_ASSERT(str_value == "bar");
+ KALDI_ASSERT(cfl.HasUnusedValues());
+ KALDI_ASSERT(!cfl.GetValue("xy", &str_value));
+ KALDI_ASSERT(cfl.GetValue("baz", &str_value));
+ KALDI_ASSERT(str_value == "123");
+
+ std::vector<int32> int_values;
+ KALDI_ASSERT(!cfl.GetValue("xx", &int_values));
+ KALDI_ASSERT(cfl.GetValue("baz", &int_values));
+ KALDI_ASSERT(cfl.HasUnusedValues());
+ KALDI_ASSERT(int_values.size() == 1 && int_values[0] == 123);
+ KALDI_ASSERT(cfl.GetValue("ba", &int_values));
+ KALDI_ASSERT(int_values.size() == 2 && int_values[0] == 1 && int_values[1] == 2);
+ KALDI_ASSERT(!cfl.HasUnusedValues());
+ }
+
+ {
+ ConfigLine cfl;
+ str = "a-b baz=x y z pp = qq ab =cd ac= bd";
+ KALDI_ASSERT(!cfl.ParseLine(str));
+ }
+ {
+ ConfigLine cfl;
+ str = "a-b baz=x y z pp = qq ab=cd ac=bd";
+ KALDI_ASSERT(!cfl.ParseLine(str));
+ }
+ {
+ ConfigLine cfl;
+ str = "foo-bar";
+ KALDI_ASSERT(cfl.ParseLine(str));
+ }
+ {
+ ConfigLine cfl;
+ str = "foo-bar a=b c d f=g";
+ std::string value;
+ KALDI_ASSERT(cfl.ParseLine(str) && cfl.FirstToken() == "foo-bar" &&
+ cfl.GetValue("a", &value) && value == "b c d" &&
+ cfl.GetValue("f", &value) && value == "g" &&
+ !cfl.HasUnusedValues());
+ }
+ {
+ ConfigLine cfl;
+ str = "zzz a=b baz";
+ KALDI_ASSERT(cfl.ParseLine(str) && cfl.FirstToken() == "zzz" &&
+ cfl.UnusedValues() == "a=b baz");
+ }
+ {
+ ConfigLine cfl;
+ str = "xxx a=b baz ";
+ KALDI_ASSERT(cfl.ParseLine(str) && cfl.UnusedValues() == "a=b baz");
+ }
+ {
+ ConfigLine cfl;
+ str = "xxx a=b =c";
+ KALDI_ASSERT(!cfl.ParseLine(str));
+ }
+ {
+ ConfigLine cfl;
+ str = "xxx baz='x y z' pp=qq ab=cd ac=bd";
+ KALDI_ASSERT(cfl.ParseLine(str) && cfl.FirstToken() == "xxx");
+ std::string str_value;
+ KALDI_ASSERT(cfl.GetValue("baz", &str_value));
+ KALDI_ASSERT(str_value == "x y z");
+ KALDI_ASSERT(cfl.GetValue("pp", &str_value));
+ KALDI_ASSERT(str_value == "qq");
+ KALDI_ASSERT(cfl.UnusedValues() == "ab=cd ac=bd");
+ KALDI_ASSERT(cfl.GetValue("ab", &str_value));
+ KALDI_ASSERT(str_value == "cd");
+ KALDI_ASSERT(cfl.UnusedValues() == "ac=bd");
+ KALDI_ASSERT(cfl.HasUnusedValues());
+ KALDI_ASSERT(cfl.GetValue("ac", &str_value));
+ KALDI_ASSERT(str_value == "bd");
+ KALDI_ASSERT(!cfl.HasUnusedValues());
+ }
+
+ {
+ ConfigLine cfl;
+ str = "x baz= pp = qq flag=t ";
+ KALDI_ASSERT(!cfl.ParseLine(str));
+ }
+ {
+ ConfigLine cfl;
+ str = " x baz= pp=qq flag=t ";
+ KALDI_ASSERT(cfl.ParseLine(str) && cfl.FirstToken() == "x");
+
+ std::string str_value;
+ KALDI_ASSERT(cfl.GetValue("baz", &str_value));
+ KALDI_ASSERT(str_value == "");
+ KALDI_ASSERT(cfl.GetValue("pp", &str_value));
+ KALDI_ASSERT(str_value == "qq");
+ KALDI_ASSERT(cfl.HasUnusedValues());
+ KALDI_ASSERT(cfl.GetValue("flag", &str_value));
+ KALDI_ASSERT(str_value == "t");
+ KALDI_ASSERT(!cfl.HasUnusedValues());
+
+ bool bool_value = false;
+ KALDI_ASSERT(cfl.GetValue("flag", &bool_value));
+ KALDI_ASSERT(bool_value);
+ }
+
+ {
+ ConfigLine cfl;
+ str = "xx _baz=a -pp=qq";
+ KALDI_ASSERT(!cfl.ParseLine(str));
+ }
+ {
+ ConfigLine cfl;
+ str = "xx 0baz=a pp=qq";
+ KALDI_ASSERT(!cfl.ParseLine(str));
+ }
+ {
+ ConfigLine cfl;
+ str = "xx -baz=a pp=qq";
+ KALDI_ASSERT(!cfl.ParseLine(str));
+ }
+ {
+ ConfigLine cfl;
+ str = "xx _baz'=a pp=qq";
+ KALDI_ASSERT(!cfl.ParseLine(str));
+ }
+ {
+ ConfigLine cfl;
+ str = " baz=g";
+ KALDI_ASSERT(cfl.ParseLine(str) && cfl.FirstToken() == "");
+ bool flag;
+ KALDI_ASSERT(!cfl.GetValue("baz", &flag));
+ }
+ {
+ ConfigLine cfl;
+ str = "xx _baz1=a pp=qq";
+ KALDI_ASSERT(cfl.ParseLine(str));
+
+ std::string str_value;
+ KALDI_ASSERT(cfl.GetValue("_baz1", &str_value));
+ }
+}
+
+void UnitTestReadConfig() {
+ std::string str = "a-b alpha=aa beta=\"b b\"# String test\n"
+ "a-b beta2='b c' beta3=bd # \n"
+ "a-b gamma=1:2:3:4 # Int Vector test\n"
+ " a-b de1ta=f # Bool + Integer in key Comment test delta=t \n"
+ "a-b _epsilon=-1 # Int Vector test _epsilon=1 \n"
+ "a-b zet-_a=0.15 theta=1.1# Float, -, _ test\n"
+ "a-b quoted='a b c' # quoted string\n"
+ "a-b quoted2=\"d e 'a b=c' f\" # string quoted with double quotes";
+
+ std::istringstream is(str);
+ std::vector<std::string> lines;
+ ReadConfigLines(is, &lines);
+ KALDI_ASSERT(lines.size() == 8);
+
+ ConfigLine cfl;
+ for (size_t i = 0; i < lines.size(); i++) {
+ KALDI_ASSERT(cfl.ParseLine(lines[i]) && cfl.FirstToken() == "a-b");
+ if (i == 1) {
+ KALDI_ASSERT(cfl.GetValue("beta2", &str) && str == "b c");
+ }
+ if (i == 4) {
+ KALDI_ASSERT(cfl.GetValue("_epsilon", &str) && str == "-1");
+ }
+ if (i == 5) {
+ BaseFloat float_val = 0;
+ KALDI_ASSERT(cfl.GetValue("zet-_a", &float_val) && ApproxEqual(float_val, 0.15));
+ }
+ if (i == 6) {
+ KALDI_ASSERT(cfl.GetValue("quoted", &str) && str == "a b c");
+ }
+ if (i == 7) {
+ KALDI_ASSERT(cfl.GetValue("quoted2", &str) && str == "d e 'a b=c' f");
+ }
+ }
+}
+
+} // end namespace kaldi
+
+int main() {
+ using namespace kaldi;
+ TestSplitStringToVector();
+ TestSplitStringToIntegers();
+ TestSplitStringToFloats();
+ TestConvertStringToInteger();
+ TestConvertStringToReal<float>();
+ TestConvertStringToReal<double>();
+ TestTrim();
+ TestSplitStringOnFirstSpace();
+ TestIsToken();
+ TestIsLine();
+ TestStringsApproxEqual();
+ TestNan<float>();
+ TestNan<double>();
+ TestInf<float>();
+ TestInf<double>();
+ UnitTestConfigLineParse();
+ UnitTestReadConfig();
+ std::cout << "Test OK\n";
+}
diff --git a/runtime/onnxruntime/third_party/kaldi/util/text-utils.cc b/runtime/onnxruntime/third_party/kaldi/util/text-utils.cc
new file mode 100644
index 000000000..85006e9b5
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/text-utils.cc
@@ -0,0 +1,591 @@
+// util/text-utils.cc
+
+// Copyright 2009-2011 Saarland University; Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+
+// http://www.apache.org/licenses/LICENSE-2.0
+
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#include "util/text-utils.h"
+#include <limits>
+#include <map>
+#include <algorithm>
+#include "base/kaldi-common.h"
+
+namespace kaldi {
+
+
+template<class F>
+bool SplitStringToFloats(const std::string &full,
+ const char *delim,
+ bool omit_empty_strings, // typically false
+ std::vector<F> *out) {
+ KALDI_ASSERT(out != NULL);
+ if (*(full.c_str()) == '\0') {
+ out->clear();
+ return true;
+ }
+ std::vector<std::string> split;
+ SplitStringToVector(full, delim, omit_empty_strings, &split);
+ out->resize(split.size());
+ for (size_t i = 0; i < split.size(); i++) {
+ F f = 0;
+ if (!ConvertStringToReal(split[i], &f))
+ return false;
+ (*out)[i] = f;
+ }
+ return true;
+}
+
+// Instantiate the template above for float and double.
+template
+bool SplitStringToFloats(const std::string &full,
+ const char *delim,
+ bool omit_empty_strings,
+ std::vector<float> *out);
+template
+bool SplitStringToFloats(const std::string &full,
+ const char *delim,
+ bool omit_empty_strings,
+ std::vector<double> *out);
+
+void SplitStringToVector(const std::string &full, const char *delim,
+ bool omit_empty_strings,
+ std::vector<std::string> *out) {
+ size_t start = 0, found = 0, end = full.size();
+ out->clear();
+ while (found != std::string::npos) {
+ found = full.find_first_of(delim, start);
+ // start != end condition is for when the delimiter is at the end
+ if (!omit_empty_strings || (found != start && start != end))
+ out->push_back(full.substr(start, found - start));
+ start = found + 1;
+ }
+}
+
+void JoinVectorToString(const std::vector<std::string> &vec_in,
+ const char *delim, bool omit_empty_strings,
+ std::string *str_out) {
+ std::string tmp_str;
+ for (size_t i = 0; i < vec_in.size(); i++) {
+ if (!omit_empty_strings || !vec_in[i].empty()) {
+ tmp_str.append(vec_in[i]);
+ if (i < vec_in.size() - 1)
+ if (!omit_empty_strings || !vec_in[i+1].empty())
+ tmp_str.append(delim);
+ }
+ }
+ str_out->swap(tmp_str);
+}
+
+void Trim(std::string *str) {
+ const char *white_chars = " \t\n\r\f\v";
+
+ std::string::size_type pos = str->find_last_not_of(white_chars);
+ if (pos != std::string::npos) {
+ str->erase(pos + 1);
+ pos = str->find_first_not_of(white_chars);
+ if (pos != std::string::npos) str->erase(0, pos);
+ } else {
+ str->erase(str->begin(), str->end());
+ }
+}
+
+bool IsToken(const std::string &token) {
+ size_t l = token.length();
+ if (l == 0) return false;
+ for (size_t i = 0; i < l; i++) {
+ unsigned char c = token[i];
+ if ((!isprint(c) || isspace(c)) && (isascii(c) || c == (unsigned char)255))
+ return false;
+ // The "&& (isascii(c) || c == 255)" was added so that we won't reject
+ // non-ASCII characters such as French characters with accents [except for
+ // 255 which is "nbsp", a form of space].
+ }
+ return true;
+}
+
+
+void SplitStringOnFirstSpace(const std::string &str,
+ std::string *first,
+ std::string *rest) {
+ const char *white_chars = " \t\n\r\f\v";
+ typedef std::string::size_type I;
+ const I npos = std::string::npos;
+ I first_nonwhite = str.find_first_not_of(white_chars);
+ if (first_nonwhite == npos) {
+ first->clear();
+ rest->clear();
+ return;
+ }
+ // next_white is first whitespace after first nonwhitespace.
+ I next_white = str.find_first_of(white_chars, first_nonwhite);
+
+ if (next_white == npos) { // no more whitespace...
+ *first = std::string(str, first_nonwhite);
+ rest->clear();
+ return;
+ }
+ I next_nonwhite = str.find_first_not_of(white_chars, next_white);
+ if (next_nonwhite == npos) {
+ *first = std::string(str, first_nonwhite, next_white-first_nonwhite);
+ rest->clear();
+ return;
+ }
+
+ I last_nonwhite = str.find_last_not_of(white_chars);
+ KALDI_ASSERT(last_nonwhite != npos); // or coding error.
+
+ *first = std::string(str, first_nonwhite, next_white-first_nonwhite);
+ *rest = std::string(str, next_nonwhite, last_nonwhite+1-next_nonwhite);
+}
+
+bool IsLine(const std::string &line) {
+ if (line.find('\n') != std::string::npos) return false;
+ if (line.empty()) return true;
+ if (isspace(*(line.begin()))) return false;
+ if (isspace(*(line.rbegin()))) return false;
+ std::string::const_iterator iter = line.begin(), end = line.end();
+ for (; iter != end; iter++)
+ if (!isprint(*iter)) return false;
+ return true;
+}
+
+template <class T>
+class NumberIstream{
+ public:
+ explicit NumberIstream(std::istream &i) : in_(i) {}
+
+ NumberIstream & operator >> (T &x) {
+ if (!in_.good()) return *this;
+ in_ >> x;
+ if (!in_.fail() && RemainderIsOnlySpaces()) return *this;
+ return ParseOnFail(&x);
+ }
+
+ private:
+ std::istream &in_;
+
+ bool RemainderIsOnlySpaces() {
+ if (in_.tellg() != std::istream::pos_type(-1)) {
+ std::string rem;
+ in_ >> rem;
+
+ if (rem.find_first_not_of(' ') != std::string::npos) {
+ // there is not only spaces
+ return false;
+ }
+ }
+
+ in_.clear();
+ return true;
+ }
+
+ NumberIstream & ParseOnFail(T *x) {
+ std::string str;
+ in_.clear();
+ in_.seekg(0);
+ // If the stream is broken even before trying
+ // to read from it or if there are many tokens,
+ // it's pointless to try.
+ if (!(in_ >> str) || !RemainderIsOnlySpaces()) {
+ in_.setstate(std::ios_base::failbit);
+ return *this;
+ }
+
+ std::map<std::string, T> inf_nan_map;
+ // we'll keep just uppercase values.
+ inf_nan_map["INF"] = std::numeric_limits<T>::infinity();
+ inf_nan_map["+INF"] = std::numeric_limits<T>::infinity();
+ inf_nan_map["-INF"] = - std::numeric_limits<T>::infinity();
+ inf_nan_map["INFINITY"] = std::numeric_limits<T>::infinity();
+ inf_nan_map["+INFINITY"] = std::numeric_limits<T>::infinity();
+ inf_nan_map["-INFINITY"] = - std::numeric_limits<T>::infinity();
+ inf_nan_map["NAN"] = std::numeric_limits<T>::quiet_NaN();
+ inf_nan_map["+NAN"] = std::numeric_limits<T>::quiet_NaN();
+ inf_nan_map["-NAN"] = - std::numeric_limits<T>::quiet_NaN();
+ // MSVC
+ inf_nan_map["1.#INF"] = std::numeric_limits<T>::infinity();
+ inf_nan_map["-1.#INF"] = - std::numeric_limits<T>::infinity();
+ inf_nan_map["1.#QNAN"] = std::numeric_limits<T>::quiet_NaN();
+ inf_nan_map["-1.#QNAN"] = - std::numeric_limits<T>::quiet_NaN();
+
+ std::transform(str.begin(), str.end(), str.begin(), ::toupper);
+
+ if (inf_nan_map.find(str) != inf_nan_map.end()) {
+ *x = inf_nan_map[str];
+ } else {
+ in_.setstate(std::ios_base::failbit);
+ }
+
+ return *this;
+ }
+};
+
+
+template <typename T>
+bool ConvertStringToReal(const std::string &str,
+ T *out) {
+ std::istringstream iss(str);
+
+ NumberIstream<T> i(iss);
+
+ i >> *out;
+
+ if (iss.fail()) {
+ // Number conversion failed.
+ return false;
+ }
+
+ return true;
+}
+
+template
+bool ConvertStringToReal(const std::string &str,
+ float *out);
+template
+bool ConvertStringToReal(const std::string &str,
+ double *out);
+
+
+
+/*
+ This function is a helper function of StringsApproxEqual. It should be
+ thought of as a recursive function-- it was designed that way-- but rather
+ than actually recursing (which would cause problems with stack overflow), we
+ just set the args and return to the start.
+
+ The 'decimal_places_tolerance' argument is just passed in from outside,
+ see the documentation for StringsApproxEqual in text-utils.h to see an
+ explanation. The argument 'places_into_number' provides some information
+ about the strings 'a' and 'b' that precedes the current pointers.
+ For purposes of this comment, let's define the 'decimal' of a number
+ as the part that comes after the decimal point, e.g. in '99.123',
+ '123' would be the decimal. If 'places_into_number' is -1, it means
+ we're not currently inside some place like that (i.e. it's not the
+ case that we're pointing to the '1' or the '2' or the '3').
+ If it's 0, then we'd be pointing to the first place after the decimal,
+ '1' in this case. Note if one of the numbers is shorter than the
+ other, like '99.123' versus '99.1234' and 'a' points to the first '3'
+ while 'b' points to the second '4', 'places_into_number' referes to the
+ shorter of the two, i.e. it would be 2 in this example.
+
+
+ */
+bool StringsApproxEqualInternal(const char *a, const char *b,
+ int32 decimal_places_tolerance,
+ int32 places_into_number) {
+start:
+ char ca = *a, cb = *b;
+ if (ca == cb) {
+ if (ca == '\0') {
+ return true;
+ } else {
+ if (places_into_number >= 0) {
+ if (isdigit(ca)) {
+ places_into_number++;
+ } else {
+ places_into_number = -1;
+ }
+ } else {
+ if (ca == '.') {
+ places_into_number = 0;
+ }
+ }
+ a++;
+ b++;
+ goto start;
+ }
+ } else {
+ if (places_into_number >= decimal_places_tolerance &&
+ (isdigit(ca) || isdigit(cb))) {
+ // we're potentially willing to accept this difference between the
+ // strings.
+ if (isdigit(ca)) a++;
+ if (isdigit(cb)) b++;
+ // we'll have advanced at least one of the two strings.
+ goto start;
+ } else if (places_into_number >= 0 &&
+ ((ca == '0' && !isdigit(cb)) || (cb == '0' && !isdigit(ca)))) {
+ // this clause is designed to ensure that, for example,
+ // "0.1" would count the same as "0.100001".
+ if (ca == '0') a++;
+ else b++;
+ places_into_number++;
+ goto start;
+ } else {
+ return false;
+ }
+ }
+
+}
+
+
+bool StringsApproxEqual(const std::string &a,
+ const std::string &b,
+ int32 decimal_places_tolerance) {
+ return StringsApproxEqualInternal(a.c_str(), b.c_str(),
+ decimal_places_tolerance, -1);
+}
+
+
+bool ConfigLine::ParseLine(const std::string &line) {
+ data_.clear();
+ whole_line_ = line;
+ if (line.size() == 0) return false; // Empty line
+ size_t pos = 0, size = line.size();
+ while (isspace(line[pos]) && pos < size) pos++;
+ if (pos == size)
+ return false; // whitespace-only line
+ size_t first_token_start_pos = pos;
+ // first get first_token_.
+ while (!isspace(line[pos]) && pos < size) {
+ if (line[pos] == '=') {
+ // If the first block of non-whitespace looks like "foo-bar=...",
+ // then we ignore it: there is no initial token, and FirstToken()
+ // is empty.
+ pos = first_token_start_pos;
+ break;
+ }
+ pos++;
+ }
+ first_token_ = std::string(line, first_token_start_pos, pos - first_token_start_pos);
+ // first_token_ is expected to be either empty or something like
+ // "component-node", which actually is a slightly more restrictive set of
+ // strings than IsValidName() checks for this is a convenient way to check it.
+ if (!first_token_.empty() && !IsValidName(first_token_))
+ return false;
+
+ while (pos < size) {
+ if (isspace(line[pos])) {
+ pos++;
+ continue;
+ }
+
+ // OK, at this point we know that we are pointing at nonspace.
+ size_t next_equals_sign = line.find_first_of("=", pos);
+ if (next_equals_sign == pos || next_equals_sign == std::string::npos) {
+ // we're looking for something like 'key=value'. If there is no equals sign,
+ // or it's not preceded by something, it's a parsing failure.
+ return false;
+ }
+ std::string key(line, pos, next_equals_sign - pos);
+ if (!IsValidName(key)) return false;
+
+ // handle any quotes. we support key='blah blah' or key="foo bar".
+ // no escaping is supported.
+ if (line[next_equals_sign+1] == '\'' || line[next_equals_sign+1] == '"') {
+ char my_quote = line[next_equals_sign+1];
+ size_t next_quote = line.find_first_of(my_quote, next_equals_sign + 2);
+ if (next_quote == std::string::npos) { // no matching quote was found.
+ KALDI_WARN << "No matching quote for " << my_quote << " in config line '"
+ << line << "'";
+ return false;
+ } else {
+ std::string value(line, next_equals_sign + 2,
+ next_quote - next_equals_sign - 2);
+ data_.insert(std::make_pair(key, std::make_pair(value, false)));
+ pos = next_quote + 1;
+ continue;
+ }
+ } else {
+ // we want to be able to parse something like "... input=Offset(a, -1) foo=bar":
+ // in general, config values with spaces in them, even without quoting.
+
+ size_t next_next_equals_sign = line.find_first_of("=", next_equals_sign + 1),
+ terminating_space = size;
+
+ if (next_next_equals_sign != std::string::npos) { // found a later equals sign.
+ size_t preceding_space = line.find_last_of(" \t", next_next_equals_sign);
+ if (preceding_space != std::string::npos &&
+ preceding_space > next_equals_sign)
+ terminating_space = preceding_space;
+ }
+ while (isspace(line[terminating_space - 1]) && terminating_space > 0)
+ terminating_space--;
+
+ std::string value(line, next_equals_sign + 1,
+ terminating_space - (next_equals_sign + 1));
+ data_.insert(std::make_pair(key, std::make_pair(value, false)));
+ pos = terminating_space;
+ }
+ }
+ return true;
+}
+
+bool ConfigLine::GetValue(const std::string &key, std::string *value) {
+ KALDI_ASSERT(value != NULL);
+ std::map<std::string, std::pair<std::string, bool> >::iterator it = data_.begin();
+ for (; it != data_.end(); ++it) {
+ if (it->first == key) {
+ *value = (it->second).first;
+ (it->second).second = true;
+ return true;
+ }
+ }
+ return false;
+}
+
+bool ConfigLine::GetValue(const std::string &key, BaseFloat *value) {
+ KALDI_ASSERT(value != NULL);
+ std::map<std::string, std::pair<std::string, bool> >::iterator it = data_.begin();
+ for (; it != data_.end(); ++it) {
+ if (it->first == key) {
+ if (!ConvertStringToReal((it->second).first, value))
+ return false;
+ (it->second).second = true;
+ return true;
+ }
+ }
+ return false;
+}
+
+bool ConfigLine::GetValue(const std::string &key, int32 *value) {
+ KALDI_ASSERT(value != NULL);
+ std::map<std::string, std::pair<std::string, bool> >::iterator it = data_.begin();
+ for (; it != data_.end(); ++it) {
+ if (it->first == key) {
+ if (!ConvertStringToInteger((it->second).first, value))
+ return false;
+ (it->second).second = true;
+ return true;
+ }
+ }
+ return false;
+}
+
+bool ConfigLine::GetValue(const std::string &key, std::vector<int32> *value) {
+ KALDI_ASSERT(value != NULL);
+ value->clear();
+ std::map<std::string, std::pair<std::string, bool> >::iterator it = data_.begin();
+ for (; it != data_.end(); ++it) {
+ if (it->first == key) {
+ if (!SplitStringToIntegers((it->second).first, ":,", true, value)) {
+ // KALDI_WARN << "Bad option " << (it->second).first;
+ return false;
+ }
+ (it->second).second = true;
+ return true;
+ }
+ }
+ return false;
+}
+
+bool ConfigLine::GetValue(const std::string &key, bool *value) {
+ KALDI_ASSERT(value != NULL);
+ std::map<std::string, std::pair<std::string, bool> >::iterator it = data_.begin();
+ for (; it != data_.end(); ++it) {
+ if (it->first == key) {
+ if ((it->second).first.size() == 0) return false;
+ switch (((it->second).first)[0]) {
+ case 'F':
+ case 'f':
+ *value = false;
+ break;
+ case 'T':
+ case 't':
+ *value = true;
+ break;
+ default:
+ return false;
+ }
+ (it->second).second = true;
+ return true;
+ }
+ }
+ return false;
+}
+
+bool ConfigLine::HasUnusedValues() const {
+ std::map<std::string, std::pair<std::string, bool> >::const_iterator it = data_.begin();
+ for (; it != data_.end(); ++it) {
+ if (!(it->second).second) return true;
+ }
+ return false;
+}
+
+std::string ConfigLine::UnusedValues() const {
+ std::string unused_str;
+ std::map<std::string, std::pair<std::string, bool> >::const_iterator it = data_.begin();
+ for (; it != data_.end(); ++it) {
+ if (!(it->second).second) {
+ if (unused_str == "")
+ unused_str = it->first + "=" + (it->second).first;
+ else
+ unused_str += " " + it->first + "=" + (it->second).first;
+ }
+ }
+ return unused_str;
+}
+
+//// This is like ExpectToken but for two tokens, and it
+//// will either accept token1 and then token2, or just token2.
+//// This is useful in Read functions where the first token
+//// may already have been consumed.
+//void ExpectOneOrTwoTokens(std::istream &is, bool binary,
+// const std::string &token1,
+// const std::string &token2) {
+// KALDI_ASSERT(token1 != token2);
+// std::string temp;
+// ReadToken(is, binary, &temp);
+// if (temp == token1) {
+// ExpectToken(is, binary, token2);
+// } else {
+// if (temp != token2) {
+// KALDI_ERR << "Expecting token " << token1 << " or " << token2
+// << " but got " << temp;
+// }
+// }
+//}
+
+
+bool IsValidName(const std::string &name) {
+ if (name.size() == 0) return false;
+ for (size_t i = 0; i < name.size(); i++) {
+ if (i == 0 && !isalpha(name[i]) && name[i] != '_')
+ return false;
+ if (!isalnum(name[i]) && name[i] != '_' && name[i] != '-' && name[i] != '.')
+ return false;
+ }
+ return true;
+}
+
+void ReadConfigLines(std::istream &is,
+ std::vector<std::string> *lines) {
+ KALDI_ASSERT(lines != NULL);
+ std::string line;
+ while (std::getline(is, line)) {
+ if (line.size() == 0) continue;
+ size_t start = line.find_first_not_of(" \t");
+ size_t end = line.find_first_of('#');
+ if (start == std::string::npos || start == end) continue;
+ end = line.find_last_not_of(" \t", end - 1);
+ KALDI_ASSERT(end >= start);
+ lines->push_back(line.substr(start, end - start + 1));
+ }
+}
+
+void ParseConfigLines(const std::vector<std::string> &lines,
+ std::vector<ConfigLine> *config_lines) {
+ config_lines->resize(lines.size());
+ for (size_t i = 0; i < lines.size(); i++) {
+ bool ret = (*config_lines)[i].ParseLine(lines[i]);
+ if (!ret) {
+ KALDI_ERR << "Error parsing config line: " << lines[i];
+ }
+ }
+}
+
+
+} // end namespace kaldi
diff --git a/runtime/onnxruntime/third_party/kaldi/util/text-utils.h b/runtime/onnxruntime/third_party/kaldi/util/text-utils.h
new file mode 100644
index 000000000..02f4bf483
--- /dev/null
+++ b/runtime/onnxruntime/third_party/kaldi/util/text-utils.h
@@ -0,0 +1,281 @@
+// util/text-utils.h
+
+// Copyright 2009-2011 Saarland University; Microsoft Corporation
+
+// See ../../COPYING for clarification regarding multiple authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+// MERCHANTABLITY OR NON-INFRINGEMENT.
+// See the Apache 2 License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef KALDI_UTIL_TEXT_UTILS_H_
+#define KALDI_UTIL_TEXT_UTILS_H_
+
+#include <errno.h>
+#include <string>
+#include <algorithm>
+#include <map>
+#include <set>
+#include <vector>
+#include <limits>
+#include "base/kaldi-common.h"
+
+
+namespace kaldi {
+
+/// Split a string using any of the single character delimiters.
+/// If omit_empty_strings == true, the output will contain any
+/// nonempty strings after splitting on any of the
+/// characters in the delimiter. If omit_empty_strings == false,
+/// the output will contain n+1 strings if there are n characters
+/// in the set "delim" within the input string. In this case
+/// the empty string is split to a single empty string.
+void SplitStringToVector(const std::string &full, const char *delim,
+ bool omit_empty_strings,
+ std::vector<std::string> *out);
+
+/// Joins the elements of a vector of strings into a single string using
+/// "delim" as the delimiter. If omit_empty_strings == true, any empty strings
+/// in the vector are skipped. A vector of empty strings results in an empty
+/// string on the output.
+void JoinVectorToString(const std::vector<std::string> &vec_in,
+ const char *delim, bool omit_empty_strings,
+ std::string *str_out);
+
+/**
+ \brief Split a string (e.g. 1:2:3) into a vector of integers.
+
+ \param [in] delim String containing a list of characters, any of which
+ is allowed as a delimiter.
+ \param [in] omit_empty_strings If true, empty strings between delimiters are
+ allowed and will not produce an output integer; if false,
+ instances of characters in 'delim' that are consecutive or
+ at the start or end of the string would be an error.
+ You'll normally want this to be true if 'delim' consists
+ of spaces, and false otherwise.
+ \param [out] out The output list of integers.
+*/
+template<class I>
+bool SplitStringToIntegers(const std::string &full,
+ const char *delim,
+ bool omit_empty_strings, // typically false [but
+ // should probably be true
+ // if "delim" is spaces].
+ std::vector<I> *out) {
+ KALDI_ASSERT(out != NULL);
+ KALDI_ASSERT_IS_INTEGER_TYPE(I);
+ if (*(full.c_str()) == '\0') {
+ out->clear();
+ return true;
+ }
+ std::vector<std::string> split;
+ SplitStringToVector(full, delim, omit_empty_strings, &split);
+ out->resize(split.size());
+ for (size_t i = 0; i < split.size(); i++) {
+ const char *this_str = split[i].c_str();
+ char *end = NULL;
+ int64 j = 0;
+ j = KALDI_STRTOLL(this_str, &end);
+ if (end == this_str || *end != '\0') {
+ out->clear();
+ return false;
+ } else {
+ I jI = static_cast<I>(j);
+ if (static_cast<int64>(jI) != j) {
+ // output type cannot fit this integer.
+ out->clear();
+ return false;
+ }
+ (*out)[i] = jI;
+ }
+ }
+ return true;
+}
+
+// This is defined for F = float and double.
+template<class F>
+bool SplitStringToFloats(const std::string &full,
+ const char *delim,
+ bool omit_empty_strings, // typically false
+ std::vector<F> *out);
+
+
+/// Converts a string into an integer via strtoll and returns false if there was
+/// any kind of problem (i.e. the string was not an integer or contained extra
+/// non-whitespace junk, or the integer was too large to fit into the type it is
+/// being converted into). Only sets *out if everything was OK and it returns
+/// true.
+template<class Int>
+bool ConvertStringToInteger(const std::string &str,
+ Int *out) {
+ KALDI_ASSERT_IS_INTEGER_TYPE(Int);
+ const char *this_str = str.c_str();
+ char *end = NULL;
+ errno = 0;
+ int64 i = KALDI_STRTOLL(this_str, &end);
+ if (end != this_str)
+ while (isspace(*end)) end++;
+ if (end == this_str || *end != '\0' || errno != 0)
+ return false;
+ Int iInt = static_cast<Int>(i);
+ if (static_cast<int64>(iInt) != i ||
+ (i < 0 && !std::numeric_limits<Int>::is_signed)) {
+ return false;
+ }
+ *out = iInt;
+ return true;
+}
+
+
+/// ConvertStringToReal converts a string into either float or double
+/// and returns false if there was any kind of problem (i.e. the string
+/// was not a floating point number or contained extra non-whitespace junk).
+/// Be careful- this function will successfully read inf's or nan's.
+template <typename T>
+bool ConvertStringToReal(const std::string &str,
+ T *out);
+
+/// Removes the beginning and trailing whitespaces from a string
+void Trim(std::string *str);
+
+
+/// Removes leading and trailing white space from the string, then splits on the
+/// first section of whitespace found (if present), putting the part before the
+/// whitespace in "first" and the rest in "rest". If there is no such space,
+/// everything that remains after removing leading and trailing whitespace goes
+/// in "first".
+void SplitStringOnFirstSpace(const std::string &line,
+ std::string *first,
+ std::string *rest);
+
+
+/// Returns true if "token" is nonempty, and all characters are
+/// printable and whitespace-free.
+bool IsToken(const std::string &token);
+
+
+/// Returns true if "line" is free of \n characters and unprintable
+/// characters, and does not contain leading or trailing whitespace.
+bool IsLine(const std::string &line);
+
+
+
+/**
+ This function returns true when two text strings are approximately equal, and
+ false when they are not. The definition of 'equal' is normal string
+ equality, except that two substrings like "0.31134" and "0.311341" would be
+ considered equal. 'decimal_places_tolerance' controls how many digits after
+ the '.' have to match up.
+ E.g. StringsApproxEqual("hello 0.23 there", "hello 0.24 there", 2) would
+ return false because there is a difference in the 2nd decimal, but with
+ an argument of 1 it would return true.
+ */
+bool StringsApproxEqual(const std::string &a,
+ const std::string &b,
+ int32 decimal_places_check = 2);
+
+/**
+ This class is responsible for parsing input like
+ hi-there xx=yyy a=b c empty= f-oo=Append(bar, sss) ba_z=123 bing='a b c' baz="a b c d='a b' e"
+ and giving you access to the fields, in this case
+
+ FirstToken() == "hi-there", and key->value pairs:
+
+ xx->yyy, a->"b c", empty->"", f-oo->"Append(bar, sss)", ba_z->"123",
+ bing->"a b c", baz->"a b c d='a b' e"
+
+ The first token is optional, if the line started with a key-value pair then
+ FirstValue() will be empty.
+
+ Note: it can parse value fields with space inside them only if they are free of the '='
+ character. If values are going to contain the '=' character, you need to quote them
+ with either single or double quotes.
+
+ Key values may contain -_a-zA-Z0-9, but must begin with a-zA-Z_.
+ */
+class ConfigLine {
+ public:
+ // Tries to parse the line as a config-file line. Returns false
+ // if it could not for some reason, e.g. parsing failure. In most cases
+ // prints no warnings; the user should do this. Does not expect comments.
+ bool ParseLine(const std::string &line);
+
+ // the GetValue functions are overloaded for various types. They return true
+ // if the key exists with value that can be converted to that type, and false
+ // otherwise. They also mark the key-value pair as having been read. It is
+ // not an error to read values twice.
+ bool GetValue(const std::string &key, std::string *value);
+ bool GetValue(const std::string &key, BaseFloat *value);
+ bool GetValue(const std::string &key, int32 *value);
+ // Values may be separated by ":" or by ",".
+ bool GetValue(const std::string &key, std::vector<int32> *value);
+ bool GetValue(const std::string &key, bool *value);
+
+ bool HasUnusedValues() const;
+ /// returns e.g. foo=bar xxx=yyy if foo and xxx were not consumed by one
+ /// of the GetValue() functions.
+ std::string UnusedValues() const;
+
+ const std::string &FirstToken() const { return first_token_; }
+
+ const std::string WholeLine() { return whole_line_; }
+ // use default assignment operator and copy constructor.
+ private:
+ std::string whole_line_;
+ // the first token of the line, e.g. if line is
+ // foo-bar baz=bing
+ // then first_token_ would be "foo-bar".
+ std::string first_token_;
+
+ // data_ maps from key to (value, is-this-value-consumed?).
+ std::map<std::string, std::pair<std::string, bool> > data_;
+
+};
+
+/// This function is like ExpectToken but for two tokens, and it will either
+/// accept token1 and then token2, or just token2. This is useful in Read
+/// functions where the first token may already have been consumed.
+void ExpectOneOrTwoTokens(std::istream &is, bool binary,
+ const std::string &token1,
+ const std::string &token2);
+
+
+/**
+ This function reads in a config file and *appends* its contents to a vector of
+ lines; it is responsible for removing comments (anything after '#') and
+ stripping out any lines that contain only whitespace after comment removal.
+ */
+void ReadConfigLines(std::istream &is,
+ std::vector<std::string> *lines);
+
+
+/**
+ This function converts config-lines from a simple sequence of strings
+ as output by ReadConfigLines(), into a sequence of first-tokens and
+ name-value pairs. The general format is:
+ "command-type bar=baz xx=yyy"
+ etc., although there are subtleties as to what exactly is allowed, see
+ documentation for class ConfigLine for details.
+ This function will die if there was a parsing failure.
+ */
+void ParseConfigLines(const std::vector<std::string> &lines,
+ std::vector<ConfigLine> *config_lines);
+
+
+/// Returns true if 'name' would be a valid name for a component or node in a
+/// nnet3Nnet. This is a nonempty string beginning with A-Za-z_, and containing only
+/// '-', '_', '.', A-Z, a-z, or 0-9.
+bool IsValidName(const std::string &name);
+
+} // namespace kaldi
+
+#endif // KALDI_UTIL_TEXT_UTILS_H_
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/.editorconfig b/runtime/onnxruntime/third_party/openfst/.editorconfig
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/.editorconfig
rename to runtime/onnxruntime/third_party/openfst/.editorconfig
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/.gitignore b/runtime/onnxruntime/third_party/openfst/.gitignore
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/.gitignore
rename to runtime/onnxruntime/third_party/openfst/.gitignore
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/BUILD.bazel b/runtime/onnxruntime/third_party/openfst/BUILD.bazel
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/BUILD.bazel
rename to runtime/onnxruntime/third_party/openfst/BUILD.bazel
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/CMakeLists.txt
similarity index 94%
rename from funasr/runtime/onnxruntime/third_party/openfst/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/CMakeLists.txt
index f6dac7424..2dd9df567 100644
--- a/funasr/runtime/onnxruntime/third_party/openfst/CMakeLists.txt
+++ b/runtime/onnxruntime/third_party/openfst/CMakeLists.txt
@@ -48,8 +48,8 @@ option(HAVE_PYTHON "Build python" OFF)
option(HAVE_SPECIAL "Build special" ON)
set(WITH_GFLAGS OFF CACHE BOOL "whether build glog with gflags" FORCE)
- set(HAVE_BIN OFF CACHE BOOL "Build the fst binaries" FORCE)
- set(HAVE_SCRIPT OFF CACHE BOOL "Build the fstscript" FORCE)
+ set(HAVE_BIN ON CACHE BOOL "Build the fst binaries" FORCE)
+ set(HAVE_SCRIPT ON CACHE BOOL "Build the fstscript" FORCE)
set(HAVE_COMPACT OFF CACHE BOOL "Build compact" FORCE)
set(HAVE_CONST OFF CACHE BOOL "Build const" FORCE)
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/Makefile.am b/runtime/onnxruntime/third_party/openfst/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/Makefile.in b/runtime/onnxruntime/third_party/openfst/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/README.md b/runtime/onnxruntime/third_party/openfst/README.md
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/README.md
rename to runtime/onnxruntime/third_party/openfst/README.md
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/_import_release.sh b/runtime/onnxruntime/third_party/openfst/_import_release.sh
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/_import_release.sh
rename to runtime/onnxruntime/third_party/openfst/_import_release.sh
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/_package_release.cmd b/runtime/onnxruntime/third_party/openfst/_package_release.cmd
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/_package_release.cmd
rename to runtime/onnxruntime/third_party/openfst/_package_release.cmd
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/aclocal.m4 b/runtime/onnxruntime/third_party/openfst/aclocal.m4
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/aclocal.m4
rename to runtime/onnxruntime/third_party/openfst/aclocal.m4
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/config.guess b/runtime/onnxruntime/third_party/openfst/config.guess
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/config.guess
rename to runtime/onnxruntime/third_party/openfst/config.guess
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/config.h.in b/runtime/onnxruntime/third_party/openfst/config.h.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/config.h.in
rename to runtime/onnxruntime/third_party/openfst/config.h.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/config.sub b/runtime/onnxruntime/third_party/openfst/config.sub
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/config.sub
rename to runtime/onnxruntime/third_party/openfst/config.sub
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/configure.ac b/runtime/onnxruntime/third_party/openfst/configure.ac
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/configure.ac
rename to runtime/onnxruntime/third_party/openfst/configure.ac
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/ltmain.sh b/runtime/onnxruntime/third_party/openfst/ltmain.sh
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/ltmain.sh
rename to runtime/onnxruntime/third_party/openfst/ltmain.sh
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/m4/ac_python_devel.m4 b/runtime/onnxruntime/third_party/openfst/m4/ac_python_devel.m4
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/m4/ac_python_devel.m4
rename to runtime/onnxruntime/third_party/openfst/m4/ac_python_devel.m4
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/m4/libtool.m4 b/runtime/onnxruntime/third_party/openfst/m4/libtool.m4
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/m4/libtool.m4
rename to runtime/onnxruntime/third_party/openfst/m4/libtool.m4
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/m4/ltoptions.m4 b/runtime/onnxruntime/third_party/openfst/m4/ltoptions.m4
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/m4/ltoptions.m4
rename to runtime/onnxruntime/third_party/openfst/m4/ltoptions.m4
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/m4/ltsugar.m4 b/runtime/onnxruntime/third_party/openfst/m4/ltsugar.m4
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/m4/ltsugar.m4
rename to runtime/onnxruntime/third_party/openfst/m4/ltsugar.m4
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/m4/ltversion.m4 b/runtime/onnxruntime/third_party/openfst/m4/ltversion.m4
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/m4/ltversion.m4
rename to runtime/onnxruntime/third_party/openfst/m4/ltversion.m4
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/m4/lt~obsolete.m4 b/runtime/onnxruntime/third_party/openfst/m4/lt~obsolete.m4
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/m4/lt~obsolete.m4
rename to runtime/onnxruntime/third_party/openfst/m4/lt~obsolete.m4
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/openfst.sln b/runtime/onnxruntime/third_party/openfst/openfst.sln
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/openfst.sln
rename to runtime/onnxruntime/third_party/openfst/openfst.sln
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/bin/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/bin/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/bin/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/bin/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/bin/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/bin/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/bin.vcxproj b/runtime/onnxruntime/third_party/openfst/src/bin/bin.vcxproj
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/bin.vcxproj
rename to runtime/onnxruntime/third_party/openfst/src/bin/bin.vcxproj
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstarcsort-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstarcsort-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstarcsort-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstarcsort-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstarcsort.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstarcsort.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstarcsort.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstarcsort.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstclosure-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstclosure-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstclosure-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstclosure-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstclosure.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstclosure.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstclosure.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstclosure.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstcompile-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstcompile-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstcompile-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstcompile-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstcompile.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstcompile.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstcompile.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstcompile.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstcompose-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstcompose-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstcompose-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstcompose-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstcompose.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstcompose.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstcompose.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstcompose.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconcat-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstconcat-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconcat-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstconcat-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconcat.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstconcat.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconcat.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstconcat.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconnect-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstconnect-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconnect-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstconnect-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconnect.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstconnect.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconnect.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstconnect.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconvert-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstconvert-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconvert-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstconvert-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconvert.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstconvert.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstconvert.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstconvert.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdeterminize-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstdeterminize-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdeterminize-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstdeterminize-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdeterminize.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstdeterminize.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdeterminize.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstdeterminize.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdifference-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstdifference-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdifference-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstdifference-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdifference.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstdifference.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdifference.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstdifference.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdisambiguate-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstdisambiguate-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdisambiguate-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstdisambiguate-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdisambiguate.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstdisambiguate.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdisambiguate.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstdisambiguate.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdraw-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstdraw-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdraw-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstdraw-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdraw.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstdraw.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstdraw.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstdraw.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstencode-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstencode-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstencode-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstencode-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstencode.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstencode.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstencode.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstencode.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstepsnormalize-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstepsnormalize-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstepsnormalize-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstepsnormalize-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstepsnormalize.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstepsnormalize.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstepsnormalize.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstepsnormalize.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstequal-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstequal-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstequal-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstequal-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstequal.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstequal.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstequal.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstequal.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstequivalent-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstequivalent-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstequivalent-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstequivalent-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstequivalent.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstequivalent.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstequivalent.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstequivalent.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstinfo-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstinfo-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstinfo-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstinfo-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstinfo.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstinfo.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstinfo.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstinfo.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstintersect-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstintersect-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstintersect-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstintersect-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstintersect.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstintersect.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstintersect.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstintersect.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstinvert-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstinvert-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstinvert-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstinvert-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstinvert.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstinvert.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstinvert.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstinvert.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstisomorphic-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstisomorphic-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstisomorphic-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstisomorphic-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstisomorphic.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstisomorphic.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstisomorphic.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstisomorphic.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstmap-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstmap-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstmap-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstmap-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstmap.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstmap.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstmap.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstmap.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstminimize-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstminimize-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstminimize-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstminimize-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstminimize.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstminimize.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstminimize.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstminimize.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstprint-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstprint-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstprint-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstprint-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstprint.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstprint.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstprint.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstprint.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstproject-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstproject-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstproject-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstproject-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstproject.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstproject.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstproject.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstproject.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstprune-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstprune-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstprune-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstprune-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstprune.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstprune.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstprune.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstprune.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstpush-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstpush-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstpush-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstpush-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstpush.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstpush.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstpush.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstpush.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrandgen-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstrandgen-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrandgen-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstrandgen-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrandgen.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstrandgen.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrandgen.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstrandgen.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrelabel-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstrelabel-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrelabel-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstrelabel-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrelabel.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstrelabel.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrelabel.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstrelabel.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreplace-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstreplace-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreplace-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstreplace-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreplace.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstreplace.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreplace.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstreplace.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreverse-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstreverse-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreverse-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstreverse-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreverse.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstreverse.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreverse.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstreverse.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreweight-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstreweight-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreweight-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstreweight-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreweight.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstreweight.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstreweight.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstreweight.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrmepsilon-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstrmepsilon-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrmepsilon-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstrmepsilon-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrmepsilon.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstrmepsilon.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstrmepsilon.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstrmepsilon.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestdistance-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestdistance-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestdistance-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstshortestdistance-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestdistance.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestdistance.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestdistance.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstshortestdistance.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestpath-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestpath-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestpath-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstshortestpath-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestpath.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestpath.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstshortestpath.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstshortestpath.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstsymbols-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstsymbols-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstsymbols-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstsymbols-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstsymbols.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstsymbols.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstsymbols.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstsymbols.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstsynchronize-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstsynchronize-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstsynchronize-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstsynchronize-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstsynchronize.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstsynchronize.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstsynchronize.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstsynchronize.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fsttopsort-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fsttopsort-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fsttopsort-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fsttopsort-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fsttopsort.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fsttopsort.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fsttopsort.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fsttopsort.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstunion-main.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstunion-main.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstunion-main.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstunion-main.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstunion.cc b/runtime/onnxruntime/third_party/openfst/src/bin/fstunion.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/bin/fstunion.cc
rename to runtime/onnxruntime/third_party/openfst/src/bin/fstunion.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/extensions/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/extensions/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_acceptor-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_acceptor-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_acceptor-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_acceptor-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_string-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_string-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_string-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_string-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_unweighted-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_unweighted-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_unweighted-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_unweighted-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_unweighted_acceptor-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_unweighted_acceptor-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_unweighted_acceptor-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_unweighted_acceptor-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_weighted_string-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_weighted_string-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_weighted_string-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact16_weighted_string-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_acceptor-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_acceptor-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_acceptor-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_acceptor-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_string-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_string-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_string-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_string-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_unweighted-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_unweighted-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_unweighted-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_unweighted-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_unweighted_acceptor-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_unweighted_acceptor-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_unweighted_acceptor-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_unweighted_acceptor-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_weighted_string-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_weighted_string-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_weighted_string-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact64_weighted_string-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_acceptor-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_acceptor-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_acceptor-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_acceptor-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_string-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_string-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_string-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_string-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_unweighted-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_unweighted-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_unweighted-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_unweighted-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_unweighted_acceptor-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_unweighted_acceptor-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_unweighted_acceptor-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_unweighted_acceptor-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_weighted_string-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_weighted_string-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_weighted_string-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compact/compact8_weighted_string-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/extensions/compress/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compress/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/compress/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compress/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/compress/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compress/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/compress-script.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compress/compress-script.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/compress-script.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compress/compress-script.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/fstcompress.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compress/fstcompress.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/fstcompress.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compress/fstcompress.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/fstrandmod.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/compress/fstrandmod.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/compress/fstrandmod.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/compress/fstrandmod.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/extensions/const/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/extensions/const/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/const/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/const/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/const/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/const/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/const16-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/const/const16-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/const16-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/const/const16-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/const64-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/const/const64-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/const64-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/const/const64-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/const8-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/const/const8-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/const/const8-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/const/const8-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/extensions/far/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/far/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/far/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/far-class.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/far-class.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/far-class.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/far-class.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farcompilestrings.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/farcompilestrings.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farcompilestrings.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/farcompilestrings.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farcreate.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/farcreate.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farcreate.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/farcreate.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farequal.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/farequal.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farequal.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/farequal.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farextract.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/farextract.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farextract.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/farextract.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farinfo.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/farinfo.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farinfo.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/farinfo.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farisomorphic.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/farisomorphic.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farisomorphic.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/farisomorphic.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farprintstrings.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/farprintstrings.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farprintstrings.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/farprintstrings.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farscript.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/farscript.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/farscript.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/farscript.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/getters.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/getters.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/getters.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/getters.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/script-impl.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/script-impl.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/script-impl.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/script-impl.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/stlist.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/stlist.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/stlist.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/stlist.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/strings.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/strings.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/strings.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/strings.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/sttable.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/far/sttable.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/far/sttable.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/far/sttable.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/extensions/linear/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/extensions/linear/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/linear/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/linear/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/linear/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/linear/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/fstlinear.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/linear/fstlinear.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/fstlinear.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/linear/fstlinear.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/fstloglinearapply.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/linear/fstloglinearapply.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/fstloglinearapply.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/linear/fstloglinearapply.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/linear-classifier-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/linear/linear-classifier-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/linear-classifier-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/linear/linear-classifier-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/linear-tagger-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/linear/linear-tagger-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/linear-tagger-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/linear/linear-tagger-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/linearscript.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/linear/linearscript.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/linear/linearscript.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/linear/linearscript.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/arc_lookahead-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/arc_lookahead-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/arc_lookahead-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/arc_lookahead-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/ilabel_lookahead-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/ilabel_lookahead-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/ilabel_lookahead-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/ilabel_lookahead-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/olabel_lookahead-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/olabel_lookahead-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/olabel_lookahead-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/lookahead/olabel_lookahead-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtcompose.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtcompose.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtcompose.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtcompose.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtexpand.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtexpand.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtexpand.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtexpand.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtinfo.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtinfo.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtinfo.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtinfo.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtreverse.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtreverse.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtreverse.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtreverse.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtscript.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtscript.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtscript.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/mpdt/mpdtscript.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/extensions/ngram/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/ngram/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/ngram/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/bitmap-index.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/bitmap-index.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/bitmap-index.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/ngram/bitmap-index.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/ngram-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/ngram-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/ngram-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/ngram/ngram-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/nthbit.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/nthbit.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/ngram/nthbit.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/ngram/nthbit.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/extensions/pdt/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/pdt/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/pdt/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/getters.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/getters.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/getters.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/pdt/getters.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtcompose.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtcompose.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtcompose.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtcompose.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtexpand.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtexpand.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtexpand.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtexpand.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtinfo.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtinfo.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtinfo.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtinfo.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtreplace.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtreplace.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtreplace.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtreplace.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtreverse.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtreverse.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtreverse.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtreverse.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtscript.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtscript.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtscript.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtscript.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtshortestpath.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtshortestpath.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtshortestpath.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/pdt/pdtshortestpath.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/python/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/python/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/python/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/python/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/basictypes.pxd b/runtime/onnxruntime/third_party/openfst/src/extensions/python/basictypes.pxd
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/basictypes.pxd
rename to runtime/onnxruntime/third_party/openfst/src/extensions/python/basictypes.pxd
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/fst.pxd b/runtime/onnxruntime/third_party/openfst/src/extensions/python/fst.pxd
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/fst.pxd
rename to runtime/onnxruntime/third_party/openfst/src/extensions/python/fst.pxd
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/ios.pxd b/runtime/onnxruntime/third_party/openfst/src/extensions/python/ios.pxd
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/ios.pxd
rename to runtime/onnxruntime/third_party/openfst/src/extensions/python/ios.pxd
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/memory.pxd b/runtime/onnxruntime/third_party/openfst/src/extensions/python/memory.pxd
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/memory.pxd
rename to runtime/onnxruntime/third_party/openfst/src/extensions/python/memory.pxd
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.pxd b/runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.pxd
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.pxd
rename to runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.pxd
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.pyx b/runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.pyx
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.pyx
rename to runtime/onnxruntime/third_party/openfst/src/extensions/python/pywrapfst.pyx
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/extensions/special/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/extensions/special/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/extensions/special/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/extensions/special/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/extensions/special/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/extensions/special/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/fstspecial.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/special/fstspecial.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/fstspecial.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/special/fstspecial.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/phi-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/special/phi-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/phi-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/special/phi-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/rho-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/special/rho-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/rho-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/special/rho-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/sigma-fst.cc b/runtime/onnxruntime/third_party/openfst/src/extensions/special/sigma-fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/extensions/special/sigma-fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/extensions/special/sigma-fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/include/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/include/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/include/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/include/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/accumulator.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/accumulator.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/accumulator.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/accumulator.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/add-on.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/add-on.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/add-on.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/add-on.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/arc-arena.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/arc-arena.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/arc-arena.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/arc-arena.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/arc-map.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/arc-map.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/arc-map.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/arc-map.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/arc.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/arc.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/arc.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/arc.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/arcfilter.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/arcfilter.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/arcfilter.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/arcfilter.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/arcsort.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/arcsort.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/arcsort.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/arcsort.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/bi-table.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/bi-table.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/bi-table.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/bi-table.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/cache.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/cache.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/cache.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/cache.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/closure.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/closure.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/closure.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/closure.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/compact-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/compact-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/compact-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/compact-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/compat.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/compat.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/compat.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/compat.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/complement.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/complement.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/complement.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/complement.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/compose-filter.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/compose-filter.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/compose-filter.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/compose-filter.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/compose.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/compose.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/compose.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/compose.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/concat.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/concat.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/concat.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/concat.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/config.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/config.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/config.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/config.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/config.h.in b/runtime/onnxruntime/third_party/openfst/src/include/fst/config.h.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/config.h.in
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/config.h.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/connect.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/connect.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/connect.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/connect.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/const-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/const-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/const-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/const-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/determinize.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/determinize.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/determinize.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/determinize.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/dfs-visit.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/dfs-visit.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/dfs-visit.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/dfs-visit.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/difference.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/difference.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/difference.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/difference.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/disambiguate.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/disambiguate.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/disambiguate.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/disambiguate.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/edit-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/edit-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/edit-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/edit-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/encode.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/encode.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/encode.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/encode.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/epsnormalize.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/epsnormalize.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/epsnormalize.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/epsnormalize.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/equal.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/equal.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/equal.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/equal.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/equivalent.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/equivalent.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/equivalent.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/equivalent.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/expanded-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/expanded-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/expanded-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/expanded-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/expectation-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/expectation-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/expectation-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/expectation-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/compress-script.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/compress-script.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/compress-script.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/compress-script.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/compress.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/compress.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/compress.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/compress.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/elias.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/elias.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/elias.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/elias.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/gzfile.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/gzfile.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/gzfile.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/gzfile.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/randmod.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/randmod.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/randmod.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/compress/randmod.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/compile-strings.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/compile-strings.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/compile-strings.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/compile-strings.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/create.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/create.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/create.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/create.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/equal.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/equal.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/equal.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/equal.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/extract.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/extract.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/extract.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/extract.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/far-class.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/far-class.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/far-class.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/far-class.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/far.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/far.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/far.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/far.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/farlib.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/farlib.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/farlib.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/farlib.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/farscript.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/farscript.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/farscript.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/farscript.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/getters.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/getters.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/getters.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/getters.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/info.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/info.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/info.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/info.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/isomorphic.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/isomorphic.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/isomorphic.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/isomorphic.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/print-strings.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/print-strings.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/print-strings.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/print-strings.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/script-impl.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/script-impl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/script-impl.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/script-impl.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/stlist.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/stlist.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/stlist.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/stlist.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/sttable.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/sttable.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/sttable.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/far/sttable.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst-data-builder.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst-data-builder.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst-data-builder.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst-data-builder.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst-data.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst-data.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst-data.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst-data.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linear-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linearscript.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linearscript.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linearscript.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/linearscript.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/loglinear-apply.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/loglinear-apply.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/loglinear-apply.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/loglinear-apply.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/trie.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/trie.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/trie.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/linear/trie.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/compose.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/compose.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/compose.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/compose.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/expand.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/expand.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/expand.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/expand.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/info.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/info.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/info.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/info.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdt.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdt.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdt.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdt.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdtlib.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdtlib.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdtlib.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdtlib.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdtscript.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdtscript.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdtscript.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/mpdtscript.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/read_write_utils.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/read_write_utils.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/read_write_utils.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/read_write_utils.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/reverse.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/reverse.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/reverse.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/mpdt/reverse.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/bitmap-index.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/bitmap-index.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/bitmap-index.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/bitmap-index.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/ngram-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/ngram-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/ngram-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/ngram-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/nthbit.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/nthbit.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/nthbit.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/ngram/nthbit.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/collection.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/collection.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/collection.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/collection.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/compose.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/compose.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/compose.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/compose.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/expand.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/expand.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/expand.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/expand.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/getters.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/getters.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/getters.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/getters.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/info.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/info.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/info.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/info.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/paren.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/paren.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/paren.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/paren.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdt.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdt.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdt.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdt.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdtlib.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdtlib.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdtlib.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdtlib.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdtscript.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdtscript.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdtscript.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/pdtscript.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/replace.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/replace.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/replace.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/replace.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/reverse.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/reverse.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/reverse.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/reverse.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/shortest-path.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/shortest-path.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/shortest-path.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/pdt/shortest-path.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/phi-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/phi-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/phi-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/phi-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/rho-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/rho-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/rho-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/rho-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/sigma-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/sigma-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/sigma-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/extensions/special/sigma-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/factor-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/factor-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/factor-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/factor-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/filter-state.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/filter-state.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/filter-state.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/filter-state.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/flags.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/flags.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/flags.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/flags.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/float-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/float-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/float-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/float-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/fst-decl.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/fst-decl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/fst-decl.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/fst-decl.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/fstlib.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/fstlib.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/fstlib.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/fstlib.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/generic-register.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/generic-register.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/generic-register.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/generic-register.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/heap.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/heap.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/heap.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/heap.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/icu.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/icu.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/icu.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/icu.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/intersect.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/intersect.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/intersect.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/intersect.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/interval-set.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/interval-set.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/interval-set.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/interval-set.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/invert.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/invert.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/invert.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/invert.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/isomorphic.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/isomorphic.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/isomorphic.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/isomorphic.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/label-reachable.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/label-reachable.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/label-reachable.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/label-reachable.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/lexicographic-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/lexicographic-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/lexicographic-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/lexicographic-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/lock.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/lock.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/lock.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/lock.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/log.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/log.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/log.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/log.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/lookahead-filter.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/lookahead-filter.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/lookahead-filter.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/lookahead-filter.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/lookahead-matcher.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/lookahead-matcher.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/lookahead-matcher.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/lookahead-matcher.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/map.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/map.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/map.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/map.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/mapped-file.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/mapped-file.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/mapped-file.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/mapped-file.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/matcher-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/matcher-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/matcher-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/matcher-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/matcher.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/matcher.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/matcher.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/matcher.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/memory.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/memory.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/memory.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/memory.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/minimize.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/minimize.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/minimize.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/minimize.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/mutable-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/mutable-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/mutable-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/mutable-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/pair-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/pair-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/pair-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/pair-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/partition.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/partition.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/partition.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/partition.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/power-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/power-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/power-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/power-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/product-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/product-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/product-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/product-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/project.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/project.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/project.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/project.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/properties.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/properties.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/properties.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/properties.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/prune.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/prune.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/prune.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/prune.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/push.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/push.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/push.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/push.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/queue.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/queue.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/queue.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/queue.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/randequivalent.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/randequivalent.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/randequivalent.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/randequivalent.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/randgen.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/randgen.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/randgen.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/randgen.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/rational.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/rational.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/rational.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/rational.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/register.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/register.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/register.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/register.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/relabel.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/relabel.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/relabel.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/relabel.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/replace-util.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/replace-util.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/replace-util.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/replace-util.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/replace.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/replace.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/replace.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/replace.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/reverse.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/reverse.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/reverse.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/reverse.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/reweight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/reweight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/reweight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/reweight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/rmepsilon.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/rmepsilon.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/rmepsilon.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/rmepsilon.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/rmfinalepsilon.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/rmfinalepsilon.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/rmfinalepsilon.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/rmfinalepsilon.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arc-class.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arc-class.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arc-class.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/arc-class.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arciterator-class.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arciterator-class.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arciterator-class.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/arciterator-class.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arcsort.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arcsort.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arcsort.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/arcsort.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arg-packs.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arg-packs.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/arg-packs.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/arg-packs.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/closure.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/closure.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/closure.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/closure.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/compile-impl.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/compile-impl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/compile-impl.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/compile-impl.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/compile.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/compile.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/compile.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/compile.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/compose.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/compose.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/compose.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/compose.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/concat.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/concat.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/concat.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/concat.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/connect.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/connect.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/connect.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/connect.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/convert.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/convert.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/convert.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/convert.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/decode.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/decode.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/decode.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/decode.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/determinize.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/determinize.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/determinize.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/determinize.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/difference.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/difference.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/difference.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/difference.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/disambiguate.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/disambiguate.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/disambiguate.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/disambiguate.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/draw-impl.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/draw-impl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/draw-impl.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/draw-impl.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/draw.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/draw.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/draw.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/draw.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/encode.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/encode.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/encode.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/encode.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/encodemapper-class.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/encodemapper-class.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/encodemapper-class.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/encodemapper-class.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/epsnormalize.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/epsnormalize.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/epsnormalize.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/epsnormalize.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/equal.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/equal.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/equal.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/equal.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/equivalent.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/equivalent.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/equivalent.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/equivalent.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/fst-class.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/fst-class.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/fst-class.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/fst-class.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/fstscript-decl.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/fstscript-decl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/fstscript-decl.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/fstscript-decl.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/fstscript.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/fstscript.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/fstscript.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/fstscript.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/getters.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/getters.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/getters.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/getters.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/info-impl.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/info-impl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/info-impl.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/info-impl.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/info.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/info.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/info.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/info.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/intersect.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/intersect.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/intersect.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/intersect.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/invert.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/invert.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/invert.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/invert.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/isomorphic.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/isomorphic.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/isomorphic.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/isomorphic.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/map.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/map.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/map.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/map.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/minimize.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/minimize.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/minimize.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/minimize.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/print-impl.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/print-impl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/print-impl.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/print-impl.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/print.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/print.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/print.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/print.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/project.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/project.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/project.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/project.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/prune.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/prune.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/prune.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/prune.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/push.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/push.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/push.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/push.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/randequivalent.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/randequivalent.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/randequivalent.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/randequivalent.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/randgen.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/randgen.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/randgen.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/randgen.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/register.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/register.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/register.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/register.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/relabel.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/relabel.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/relabel.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/relabel.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/replace.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/replace.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/replace.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/replace.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/reverse.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/reverse.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/reverse.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/reverse.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/reweight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/reweight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/reweight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/reweight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/rmepsilon.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/rmepsilon.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/rmepsilon.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/rmepsilon.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/script-impl.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/script-impl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/script-impl.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/script-impl.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/shortest-distance.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/shortest-distance.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/shortest-distance.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/shortest-distance.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/shortest-path.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/shortest-path.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/shortest-path.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/shortest-path.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/stateiterator-class.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/stateiterator-class.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/stateiterator-class.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/stateiterator-class.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/synchronize.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/synchronize.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/synchronize.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/synchronize.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/text-io.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/text-io.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/text-io.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/text-io.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/topsort.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/topsort.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/topsort.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/topsort.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/union.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/union.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/union.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/union.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/verify.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/verify.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/verify.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/verify.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/weight-class.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/script/weight-class.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/script/weight-class.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/script/weight-class.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/set-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/set-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/set-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/set-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/shortest-distance.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/shortest-distance.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/shortest-distance.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/shortest-distance.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/shortest-path.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/shortest-path.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/shortest-path.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/shortest-path.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/signed-log-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/signed-log-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/signed-log-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/signed-log-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/sparse-power-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/sparse-power-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/sparse-power-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/sparse-power-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/sparse-tuple-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/sparse-tuple-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/sparse-tuple-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/sparse-tuple-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/state-map.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/state-map.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/state-map.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/state-map.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/state-reachable.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/state-reachable.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/state-reachable.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/state-reachable.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/state-table.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/state-table.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/state-table.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/state-table.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/statesort.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/statesort.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/statesort.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/statesort.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/string-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/string-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/string-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/string-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/string.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/string.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/string.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/string.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/symbol-table-ops.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/symbol-table-ops.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/symbol-table-ops.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/symbol-table-ops.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/symbol-table.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/symbol-table.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/symbol-table.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/symbol-table.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/synchronize.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/synchronize.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/synchronize.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/synchronize.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/test-properties.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/test-properties.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/test-properties.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/test-properties.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/test/algo_test.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/test/algo_test.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/test/algo_test.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/test/algo_test.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/test/fst_test.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/test/fst_test.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/test/fst_test.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/test/fst_test.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/test/rand-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/test/rand-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/test/rand-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/test/rand-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/test/weight-tester.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/test/weight-tester.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/test/weight-tester.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/test/weight-tester.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/topsort.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/topsort.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/topsort.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/topsort.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/tuple-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/tuple-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/tuple-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/tuple-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/types.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/types.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/types.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/types.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/union-find.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/union-find.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/union-find.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/union-find.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/union-weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/union-weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/union-weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/union-weight.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/union.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/union.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/union.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/union.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/util.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/util.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/util.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/util.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/vector-fst.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/vector-fst.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/vector-fst.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/vector-fst.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/verify.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/verify.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/verify.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/verify.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/visit.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/visit.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/visit.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/visit.h
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/weight.h b/runtime/onnxruntime/third_party/openfst/src/include/fst/weight.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/include/fst/weight.h
rename to runtime/onnxruntime/third_party/openfst/src/include/fst/weight.h
diff --git a/runtime/onnxruntime/third_party/openfst/src/lib/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/lib/CMakeLists.txt
new file mode 100644
index 000000000..9960ce955
--- /dev/null
+++ b/runtime/onnxruntime/third_party/openfst/src/lib/CMakeLists.txt
@@ -0,0 +1,34 @@
+FILE(GLOB HEADER_FILES ../include/fst/*.h)
+
+
+add_library(fst
+ compat.cc
+ flags.cc
+ fst-types.cc
+ fst.cc
+ mapped-file.cc
+ properties.cc
+ symbol-table.cc
+ symbol-table-ops.cc
+ util.cc
+ weight.cc
+ ${HEADER_FILES}
+)
+set_target_properties(fst PROPERTIES
+ SOVERSION "${SOVERSION}"
+)
+
+include_directories(${CMAKE_SOURCE_DIR}/build/third_party/glog)
+include_directories(${CMAKE_SOURCE_DIR}/third_party/glog/src)
+link_directories(${CMAKE_SOURCE_DIR}/build/third_party/glog)
+
+include_directories(${CMAKE_SOURCE_DIR}/third_party/gflags/src/include)
+link_directories(${CMAKE_SOURCE_DIR}/build/third_party/gflags)
+
+target_link_libraries(fst PUBLIC glog gflags)
+add_dependencies(fst glog gflags)
+
+install(TARGETS fst
+ LIBRARY DESTINATION lib
+ ARCHIVE DESTINATION lib
+ RUNTIME DESTINATION lib)
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/lib/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/lib/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/lib/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/lib/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/compat.cc b/runtime/onnxruntime/third_party/openfst/src/lib/compat.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/compat.cc
rename to runtime/onnxruntime/third_party/openfst/src/lib/compat.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/flags.cc b/runtime/onnxruntime/third_party/openfst/src/lib/flags.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/flags.cc
rename to runtime/onnxruntime/third_party/openfst/src/lib/flags.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/fst-types.cc b/runtime/onnxruntime/third_party/openfst/src/lib/fst-types.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/fst-types.cc
rename to runtime/onnxruntime/third_party/openfst/src/lib/fst-types.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/fst.cc b/runtime/onnxruntime/third_party/openfst/src/lib/fst.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/fst.cc
rename to runtime/onnxruntime/third_party/openfst/src/lib/fst.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/libfst.vcxproj b/runtime/onnxruntime/third_party/openfst/src/lib/libfst.vcxproj
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/libfst.vcxproj
rename to runtime/onnxruntime/third_party/openfst/src/lib/libfst.vcxproj
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/libfst.vcxproj.filters b/runtime/onnxruntime/third_party/openfst/src/lib/libfst.vcxproj.filters
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/libfst.vcxproj.filters
rename to runtime/onnxruntime/third_party/openfst/src/lib/libfst.vcxproj.filters
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/mapped-file.cc b/runtime/onnxruntime/third_party/openfst/src/lib/mapped-file.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/mapped-file.cc
rename to runtime/onnxruntime/third_party/openfst/src/lib/mapped-file.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/properties.cc b/runtime/onnxruntime/third_party/openfst/src/lib/properties.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/properties.cc
rename to runtime/onnxruntime/third_party/openfst/src/lib/properties.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/symbol-table-ops.cc b/runtime/onnxruntime/third_party/openfst/src/lib/symbol-table-ops.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/symbol-table-ops.cc
rename to runtime/onnxruntime/third_party/openfst/src/lib/symbol-table-ops.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/symbol-table.cc b/runtime/onnxruntime/third_party/openfst/src/lib/symbol-table.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/symbol-table.cc
rename to runtime/onnxruntime/third_party/openfst/src/lib/symbol-table.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/util.cc b/runtime/onnxruntime/third_party/openfst/src/lib/util.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/util.cc
rename to runtime/onnxruntime/third_party/openfst/src/lib/util.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/lib/weight.cc b/runtime/onnxruntime/third_party/openfst/src/lib/weight.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/lib/weight.cc
rename to runtime/onnxruntime/third_party/openfst/src/lib/weight.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/openfst-multibin.targets b/runtime/onnxruntime/third_party/openfst/src/openfst-multibin.targets
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/openfst-multibin.targets
rename to runtime/onnxruntime/third_party/openfst/src/openfst-multibin.targets
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/openfst.props b/runtime/onnxruntime/third_party/openfst/src/openfst.props
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/openfst.props
rename to runtime/onnxruntime/third_party/openfst/src/openfst.props
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/openfst.targets b/runtime/onnxruntime/third_party/openfst/src/openfst.targets
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/openfst.targets
rename to runtime/onnxruntime/third_party/openfst/src/openfst.targets
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/openfst.user.props b/runtime/onnxruntime/third_party/openfst/src/openfst.user.props
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/openfst.user.props
rename to runtime/onnxruntime/third_party/openfst/src/openfst.user.props
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/script/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/script/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/script/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/script/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/script/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/script/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/arciterator-class.cc b/runtime/onnxruntime/third_party/openfst/src/script/arciterator-class.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/arciterator-class.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/arciterator-class.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/arcsort.cc b/runtime/onnxruntime/third_party/openfst/src/script/arcsort.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/arcsort.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/arcsort.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/closure.cc b/runtime/onnxruntime/third_party/openfst/src/script/closure.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/closure.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/closure.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/compile.cc b/runtime/onnxruntime/third_party/openfst/src/script/compile.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/compile.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/compile.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/compose.cc b/runtime/onnxruntime/third_party/openfst/src/script/compose.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/compose.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/compose.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/concat.cc b/runtime/onnxruntime/third_party/openfst/src/script/concat.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/concat.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/concat.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/connect.cc b/runtime/onnxruntime/third_party/openfst/src/script/connect.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/connect.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/connect.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/convert.cc b/runtime/onnxruntime/third_party/openfst/src/script/convert.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/convert.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/convert.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/decode.cc b/runtime/onnxruntime/third_party/openfst/src/script/decode.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/decode.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/decode.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/determinize.cc b/runtime/onnxruntime/third_party/openfst/src/script/determinize.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/determinize.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/determinize.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/difference.cc b/runtime/onnxruntime/third_party/openfst/src/script/difference.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/difference.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/difference.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/disambiguate.cc b/runtime/onnxruntime/third_party/openfst/src/script/disambiguate.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/disambiguate.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/disambiguate.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/draw.cc b/runtime/onnxruntime/third_party/openfst/src/script/draw.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/draw.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/draw.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/encode.cc b/runtime/onnxruntime/third_party/openfst/src/script/encode.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/encode.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/encode.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/encodemapper-class.cc b/runtime/onnxruntime/third_party/openfst/src/script/encodemapper-class.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/encodemapper-class.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/encodemapper-class.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/epsnormalize.cc b/runtime/onnxruntime/third_party/openfst/src/script/epsnormalize.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/epsnormalize.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/epsnormalize.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/equal.cc b/runtime/onnxruntime/third_party/openfst/src/script/equal.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/equal.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/equal.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/equivalent.cc b/runtime/onnxruntime/third_party/openfst/src/script/equivalent.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/equivalent.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/equivalent.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/fst-class.cc b/runtime/onnxruntime/third_party/openfst/src/script/fst-class.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/fst-class.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/fst-class.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/getters.cc b/runtime/onnxruntime/third_party/openfst/src/script/getters.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/getters.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/getters.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/info-impl.cc b/runtime/onnxruntime/third_party/openfst/src/script/info-impl.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/info-impl.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/info-impl.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/info.cc b/runtime/onnxruntime/third_party/openfst/src/script/info.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/info.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/info.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/intersect.cc b/runtime/onnxruntime/third_party/openfst/src/script/intersect.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/intersect.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/intersect.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/invert.cc b/runtime/onnxruntime/third_party/openfst/src/script/invert.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/invert.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/invert.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/isomorphic.cc b/runtime/onnxruntime/third_party/openfst/src/script/isomorphic.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/isomorphic.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/isomorphic.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/libfstscript.vcxproj b/runtime/onnxruntime/third_party/openfst/src/script/libfstscript.vcxproj
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/libfstscript.vcxproj
rename to runtime/onnxruntime/third_party/openfst/src/script/libfstscript.vcxproj
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/libfstscript.vcxproj.filters b/runtime/onnxruntime/third_party/openfst/src/script/libfstscript.vcxproj.filters
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/libfstscript.vcxproj.filters
rename to runtime/onnxruntime/third_party/openfst/src/script/libfstscript.vcxproj.filters
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/map.cc b/runtime/onnxruntime/third_party/openfst/src/script/map.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/map.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/map.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/minimize.cc b/runtime/onnxruntime/third_party/openfst/src/script/minimize.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/minimize.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/minimize.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/print.cc b/runtime/onnxruntime/third_party/openfst/src/script/print.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/print.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/print.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/project.cc b/runtime/onnxruntime/third_party/openfst/src/script/project.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/project.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/project.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/prune.cc b/runtime/onnxruntime/third_party/openfst/src/script/prune.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/prune.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/prune.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/push.cc b/runtime/onnxruntime/third_party/openfst/src/script/push.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/push.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/push.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/randequivalent.cc b/runtime/onnxruntime/third_party/openfst/src/script/randequivalent.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/randequivalent.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/randequivalent.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/randgen.cc b/runtime/onnxruntime/third_party/openfst/src/script/randgen.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/randgen.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/randgen.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/relabel.cc b/runtime/onnxruntime/third_party/openfst/src/script/relabel.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/relabel.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/relabel.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/replace.cc b/runtime/onnxruntime/third_party/openfst/src/script/replace.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/replace.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/replace.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/reverse.cc b/runtime/onnxruntime/third_party/openfst/src/script/reverse.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/reverse.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/reverse.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/reweight.cc b/runtime/onnxruntime/third_party/openfst/src/script/reweight.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/reweight.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/reweight.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/rmepsilon.cc b/runtime/onnxruntime/third_party/openfst/src/script/rmepsilon.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/rmepsilon.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/rmepsilon.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/shortest-distance.cc b/runtime/onnxruntime/third_party/openfst/src/script/shortest-distance.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/shortest-distance.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/shortest-distance.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/shortest-path.cc b/runtime/onnxruntime/third_party/openfst/src/script/shortest-path.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/shortest-path.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/shortest-path.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/stateiterator-class.cc b/runtime/onnxruntime/third_party/openfst/src/script/stateiterator-class.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/stateiterator-class.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/stateiterator-class.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/synchronize.cc b/runtime/onnxruntime/third_party/openfst/src/script/synchronize.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/synchronize.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/synchronize.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/text-io.cc b/runtime/onnxruntime/third_party/openfst/src/script/text-io.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/text-io.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/text-io.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/topsort.cc b/runtime/onnxruntime/third_party/openfst/src/script/topsort.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/topsort.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/topsort.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/union.cc b/runtime/onnxruntime/third_party/openfst/src/script/union.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/union.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/union.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/verify.cc b/runtime/onnxruntime/third_party/openfst/src/script/verify.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/verify.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/verify.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/script/weight-class.cc b/runtime/onnxruntime/third_party/openfst/src/script/weight-class.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/script/weight-class.cc
rename to runtime/onnxruntime/third_party/openfst/src/script/weight-class.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/test/CMakeLists.txt b/runtime/onnxruntime/third_party/openfst/src/test/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/test/CMakeLists.txt
rename to runtime/onnxruntime/third_party/openfst/src/test/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/test/Makefile.am b/runtime/onnxruntime/third_party/openfst/src/test/Makefile.am
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/test/Makefile.am
rename to runtime/onnxruntime/third_party/openfst/src/test/Makefile.am
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/test/Makefile.in b/runtime/onnxruntime/third_party/openfst/src/test/Makefile.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/test/Makefile.in
rename to runtime/onnxruntime/third_party/openfst/src/test/Makefile.in
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/test/algo_test.cc b/runtime/onnxruntime/third_party/openfst/src/test/algo_test.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/test/algo_test.cc
rename to runtime/onnxruntime/third_party/openfst/src/test/algo_test.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/test/fst_test.cc b/runtime/onnxruntime/third_party/openfst/src/test/fst_test.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/test/fst_test.cc
rename to runtime/onnxruntime/third_party/openfst/src/test/fst_test.cc
diff --git a/funasr/runtime/onnxruntime/third_party/openfst/src/test/weight_test.cc b/runtime/onnxruntime/third_party/openfst/src/test/weight_test.cc
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/openfst/src/test/weight_test.cc
rename to runtime/onnxruntime/third_party/openfst/src/test/weight_test.cc
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/CMakeLists.txt b/runtime/onnxruntime/third_party/yaml-cpp/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/CMakeLists.txt
rename to runtime/onnxruntime/third_party/yaml-cpp/CMakeLists.txt
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/anchor.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/anchor.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/anchor.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/anchor.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/binary.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/binary.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/binary.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/binary.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/contrib/anchordict.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/contrib/anchordict.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/contrib/anchordict.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/contrib/anchordict.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/contrib/graphbuilder.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/contrib/graphbuilder.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/contrib/graphbuilder.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/contrib/graphbuilder.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/dll.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/dll.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/dll.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/dll.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitfromevents.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitfromevents.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitfromevents.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitfromevents.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitter.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitter.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitter.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitter.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitterdef.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitterdef.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitterdef.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitterdef.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emittermanip.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emittermanip.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emittermanip.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emittermanip.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitterstyle.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitterstyle.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitterstyle.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/emitterstyle.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/eventhandler.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/eventhandler.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/eventhandler.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/eventhandler.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/exceptions.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/exceptions.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/exceptions.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/exceptions.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/mark.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/mark.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/mark.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/mark.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/convert.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/convert.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/convert.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/convert.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/bool_type.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/bool_type.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/bool_type.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/bool_type.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/impl.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/impl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/impl.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/impl.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/iterator.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/iterator.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/iterator.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/iterator.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/iterator_fwd.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/iterator_fwd.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/iterator_fwd.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/iterator_fwd.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/memory.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/memory.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/memory.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/memory.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_data.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_data.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_data.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_data.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_iterator.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_iterator.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_iterator.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_iterator.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_ref.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_ref.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_ref.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/detail/node_ref.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/emit.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/emit.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/emit.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/emit.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/impl.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/impl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/impl.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/impl.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/iterator.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/iterator.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/iterator.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/iterator.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/node.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/node.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/node.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/node.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/parse.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/parse.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/parse.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/parse.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/ptr.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/ptr.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/ptr.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/ptr.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/type.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/type.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/type.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/node/type.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/noncopyable.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/noncopyable.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/noncopyable.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/noncopyable.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/null.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/null.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/null.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/null.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/ostream_wrapper.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/ostream_wrapper.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/ostream_wrapper.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/ostream_wrapper.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/parser.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/parser.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/parser.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/parser.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/stlemitter.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/stlemitter.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/stlemitter.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/stlemitter.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/traits.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/traits.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/traits.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/traits.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/yaml.h b/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/yaml.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/yaml.h
rename to runtime/onnxruntime/third_party/yaml-cpp/include/yaml-cpp/yaml.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/install.txt b/runtime/onnxruntime/third_party/yaml-cpp/install.txt
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/install.txt
rename to runtime/onnxruntime/third_party/yaml-cpp/install.txt
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/binary.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/binary.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/binary.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/binary.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/collectionstack.h b/runtime/onnxruntime/third_party/yaml-cpp/src/collectionstack.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/collectionstack.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/collectionstack.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilder.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilder.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilder.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilder.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilderadapter.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilderadapter.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilderadapter.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilderadapter.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilderadapter.h b/runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilderadapter.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilderadapter.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/contrib/graphbuilderadapter.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/convert.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/convert.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/convert.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/convert.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/directives.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/directives.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/directives.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/directives.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/directives.h b/runtime/onnxruntime/third_party/yaml-cpp/src/directives.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/directives.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/directives.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emit.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/emit.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emit.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/emit.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitfromevents.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/emitfromevents.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitfromevents.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/emitfromevents.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitter.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/emitter.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitter.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/emitter.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitterstate.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/emitterstate.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitterstate.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/emitterstate.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitterstate.h b/runtime/onnxruntime/third_party/yaml-cpp/src/emitterstate.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitterstate.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/emitterstate.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitterutils.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/emitterutils.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitterutils.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/emitterutils.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitterutils.h b/runtime/onnxruntime/third_party/yaml-cpp/src/emitterutils.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/emitterutils.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/emitterutils.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/exceptions.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/exceptions.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/exceptions.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/exceptions.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/exp.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/exp.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/exp.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/exp.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/exp.h b/runtime/onnxruntime/third_party/yaml-cpp/src/exp.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/exp.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/exp.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/indentation.h b/runtime/onnxruntime/third_party/yaml-cpp/src/indentation.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/indentation.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/indentation.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/memory.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/memory.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/memory.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/memory.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/node.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/node.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/node.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/node.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/node_data.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/node_data.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/node_data.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/node_data.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/nodebuilder.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/nodebuilder.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/nodebuilder.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/nodebuilder.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/nodebuilder.h b/runtime/onnxruntime/third_party/yaml-cpp/src/nodebuilder.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/nodebuilder.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/nodebuilder.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/nodeevents.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/nodeevents.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/nodeevents.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/nodeevents.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/nodeevents.h b/runtime/onnxruntime/third_party/yaml-cpp/src/nodeevents.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/nodeevents.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/nodeevents.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/null.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/null.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/null.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/null.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/ostream_wrapper.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/ostream_wrapper.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/ostream_wrapper.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/ostream_wrapper.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/parse.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/parse.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/parse.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/parse.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/parser.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/parser.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/parser.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/parser.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/ptr_vector.h b/runtime/onnxruntime/third_party/yaml-cpp/src/ptr_vector.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/ptr_vector.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/ptr_vector.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/regex_yaml.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/regex_yaml.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/regex_yaml.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/regex_yaml.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/regex_yaml.h b/runtime/onnxruntime/third_party/yaml-cpp/src/regex_yaml.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/regex_yaml.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/regex_yaml.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/regeximpl.h b/runtime/onnxruntime/third_party/yaml-cpp/src/regeximpl.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/regeximpl.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/regeximpl.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scanner.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/scanner.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scanner.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/scanner.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scanner.h b/runtime/onnxruntime/third_party/yaml-cpp/src/scanner.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scanner.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/scanner.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scanscalar.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/scanscalar.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scanscalar.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/scanscalar.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scanscalar.h b/runtime/onnxruntime/third_party/yaml-cpp/src/scanscalar.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scanscalar.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/scanscalar.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scantag.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/scantag.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scantag.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/scantag.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scantag.h b/runtime/onnxruntime/third_party/yaml-cpp/src/scantag.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scantag.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/scantag.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scantoken.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/scantoken.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/scantoken.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/scantoken.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/setting.h b/runtime/onnxruntime/third_party/yaml-cpp/src/setting.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/setting.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/setting.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/simplekey.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/simplekey.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/simplekey.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/simplekey.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/singledocparser.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/singledocparser.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/singledocparser.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/singledocparser.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/singledocparser.h b/runtime/onnxruntime/third_party/yaml-cpp/src/singledocparser.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/singledocparser.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/singledocparser.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/stream.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/stream.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/stream.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/stream.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/stream.h b/runtime/onnxruntime/third_party/yaml-cpp/src/stream.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/stream.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/stream.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/streamcharsource.h b/runtime/onnxruntime/third_party/yaml-cpp/src/streamcharsource.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/streamcharsource.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/streamcharsource.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/stringsource.h b/runtime/onnxruntime/third_party/yaml-cpp/src/stringsource.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/stringsource.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/stringsource.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/tag.cpp b/runtime/onnxruntime/third_party/yaml-cpp/src/tag.cpp
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/tag.cpp
rename to runtime/onnxruntime/third_party/yaml-cpp/src/tag.cpp
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/tag.h b/runtime/onnxruntime/third_party/yaml-cpp/src/tag.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/tag.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/tag.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/src/token.h b/runtime/onnxruntime/third_party/yaml-cpp/src/token.h
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/src/token.h
rename to runtime/onnxruntime/third_party/yaml-cpp/src/token.h
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp-config-version.cmake.in b/runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp-config-version.cmake.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp-config-version.cmake.in
rename to runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp-config-version.cmake.in
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp-config.cmake.in b/runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp-config.cmake.in
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp-config.cmake.in
rename to runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp-config.cmake.in
diff --git a/funasr/runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp.pc.cmake b/runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp.pc.cmake
similarity index 100%
rename from funasr/runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp.pc.cmake
rename to runtime/onnxruntime/third_party/yaml-cpp/yaml-cpp.pc.cmake
diff --git a/funasr/runtime/python/libtorch/funasr_torch/utils/__init__.py b/runtime/python/__init__.py
similarity index 100%
rename from funasr/runtime/python/libtorch/funasr_torch/utils/__init__.py
rename to runtime/python/__init__.py
diff --git a/funasr/runtime/python/grpc/Readme.md b/runtime/python/grpc/Readme.md
similarity index 100%
rename from funasr/runtime/python/grpc/Readme.md
rename to runtime/python/grpc/Readme.md
diff --git a/funasr/runtime/python/grpc/grpc_main_client.py b/runtime/python/grpc/grpc_main_client.py
similarity index 100%
rename from funasr/runtime/python/grpc/grpc_main_client.py
rename to runtime/python/grpc/grpc_main_client.py
diff --git a/funasr/runtime/python/grpc/proto/Readme.md b/runtime/python/grpc/proto/Readme.md
similarity index 100%
rename from funasr/runtime/python/grpc/proto/Readme.md
rename to runtime/python/grpc/proto/Readme.md
diff --git a/funasr/runtime/python/grpc/proto/paraformer.proto b/runtime/python/grpc/proto/paraformer.proto
similarity index 100%
rename from funasr/runtime/python/grpc/proto/paraformer.proto
rename to runtime/python/grpc/proto/paraformer.proto
diff --git a/funasr/runtime/python/grpc/proto/workflow.png b/runtime/python/grpc/proto/workflow.png
similarity index 100%
rename from funasr/runtime/python/grpc/proto/workflow.png
rename to runtime/python/grpc/proto/workflow.png
diff --git a/funasr/runtime/python/grpc/requirements.txt b/runtime/python/grpc/requirements.txt
similarity index 100%
rename from funasr/runtime/python/grpc/requirements.txt
rename to runtime/python/grpc/requirements.txt
diff --git a/funasr/runtime/python/http/README.md b/runtime/python/http/README.md
similarity index 100%
rename from funasr/runtime/python/http/README.md
rename to runtime/python/http/README.md
diff --git a/funasr/runtime/python/http/asr_nginx.conf b/runtime/python/http/asr_nginx.conf
similarity index 100%
rename from funasr/runtime/python/http/asr_nginx.conf
rename to runtime/python/http/asr_nginx.conf
diff --git a/funasr/runtime/python/http/client.py b/runtime/python/http/client.py
similarity index 100%
rename from funasr/runtime/python/http/client.py
rename to runtime/python/http/client.py
diff --git a/funasr/runtime/python/http/requirements.txt b/runtime/python/http/requirements.txt
similarity index 100%
rename from funasr/runtime/python/http/requirements.txt
rename to runtime/python/http/requirements.txt
diff --git a/funasr/runtime/python/http/server.py b/runtime/python/http/server.py
similarity index 100%
rename from funasr/runtime/python/http/server.py
rename to runtime/python/http/server.py
diff --git a/funasr/runtime/python/http/start_server.sh b/runtime/python/http/start_server.sh
similarity index 100%
rename from funasr/runtime/python/http/start_server.sh
rename to runtime/python/http/start_server.sh
diff --git a/funasr/runtime/python/libtorch/README.md b/runtime/python/libtorch/README.md
similarity index 100%
rename from funasr/runtime/python/libtorch/README.md
rename to runtime/python/libtorch/README.md
diff --git a/funasr/runtime/python/onnxruntime/__init__.py b/runtime/python/libtorch/__init__.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/__init__.py
rename to runtime/python/libtorch/__init__.py
diff --git a/funasr/runtime/python/libtorch/demo.py b/runtime/python/libtorch/demo.py
similarity index 100%
rename from funasr/runtime/python/libtorch/demo.py
rename to runtime/python/libtorch/demo.py
diff --git a/funasr/runtime/python/libtorch/funasr_torch/__init__.py b/runtime/python/libtorch/funasr_torch/__init__.py
similarity index 100%
rename from funasr/runtime/python/libtorch/funasr_torch/__init__.py
rename to runtime/python/libtorch/funasr_torch/__init__.py
diff --git a/funasr/runtime/python/libtorch/funasr_torch/paraformer_bin.py b/runtime/python/libtorch/funasr_torch/paraformer_bin.py
similarity index 100%
rename from funasr/runtime/python/libtorch/funasr_torch/paraformer_bin.py
rename to runtime/python/libtorch/funasr_torch/paraformer_bin.py
diff --git a/funasr/runtime/python/onnxruntime/funasr_onnx/utils/__init__.py b/runtime/python/libtorch/funasr_torch/utils/__init__.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/funasr_onnx/utils/__init__.py
rename to runtime/python/libtorch/funasr_torch/utils/__init__.py
diff --git a/funasr/runtime/python/libtorch/funasr_torch/utils/compute_wer.py b/runtime/python/libtorch/funasr_torch/utils/compute_wer.py
similarity index 100%
rename from funasr/runtime/python/libtorch/funasr_torch/utils/compute_wer.py
rename to runtime/python/libtorch/funasr_torch/utils/compute_wer.py
diff --git a/funasr/runtime/python/libtorch/funasr_torch/utils/frontend.py b/runtime/python/libtorch/funasr_torch/utils/frontend.py
similarity index 100%
rename from funasr/runtime/python/libtorch/funasr_torch/utils/frontend.py
rename to runtime/python/libtorch/funasr_torch/utils/frontend.py
diff --git a/funasr/runtime/python/libtorch/funasr_torch/utils/postprocess_utils.py b/runtime/python/libtorch/funasr_torch/utils/postprocess_utils.py
similarity index 100%
rename from funasr/runtime/python/libtorch/funasr_torch/utils/postprocess_utils.py
rename to runtime/python/libtorch/funasr_torch/utils/postprocess_utils.py
diff --git a/funasr/runtime/python/libtorch/funasr_torch/utils/timestamp_utils.py b/runtime/python/libtorch/funasr_torch/utils/timestamp_utils.py
similarity index 100%
rename from funasr/runtime/python/libtorch/funasr_torch/utils/timestamp_utils.py
rename to runtime/python/libtorch/funasr_torch/utils/timestamp_utils.py
diff --git a/funasr/runtime/python/libtorch/funasr_torch/utils/utils.py b/runtime/python/libtorch/funasr_torch/utils/utils.py
similarity index 100%
rename from funasr/runtime/python/libtorch/funasr_torch/utils/utils.py
rename to runtime/python/libtorch/funasr_torch/utils/utils.py
diff --git a/funasr/runtime/python/libtorch/setup.py b/runtime/python/libtorch/setup.py
similarity index 100%
rename from funasr/runtime/python/libtorch/setup.py
rename to runtime/python/libtorch/setup.py
diff --git a/funasr/runtime/python/onnxruntime/README.md b/runtime/python/onnxruntime/README.md
similarity index 100%
rename from funasr/runtime/python/onnxruntime/README.md
rename to runtime/python/onnxruntime/README.md
diff --git a/funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/encoder/1/.gitkeep b/runtime/python/onnxruntime/__init__.py
similarity index 100%
rename from funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/encoder/1/.gitkeep
rename to runtime/python/onnxruntime/__init__.py
diff --git a/funasr/runtime/python/onnxruntime/demo_contextual_paraformer.py b/runtime/python/onnxruntime/demo_contextual_paraformer.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/demo_contextual_paraformer.py
rename to runtime/python/onnxruntime/demo_contextual_paraformer.py
diff --git a/funasr/runtime/python/onnxruntime/demo_paraformer_offline.py b/runtime/python/onnxruntime/demo_paraformer_offline.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/demo_paraformer_offline.py
rename to runtime/python/onnxruntime/demo_paraformer_offline.py
diff --git a/funasr/runtime/python/onnxruntime/demo_paraformer_online.py b/runtime/python/onnxruntime/demo_paraformer_online.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/demo_paraformer_online.py
rename to runtime/python/onnxruntime/demo_paraformer_online.py
diff --git a/funasr/runtime/python/onnxruntime/demo_punc_offline.py b/runtime/python/onnxruntime/demo_punc_offline.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/demo_punc_offline.py
rename to runtime/python/onnxruntime/demo_punc_offline.py
diff --git a/funasr/runtime/python/onnxruntime/demo_punc_online.py b/runtime/python/onnxruntime/demo_punc_online.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/demo_punc_online.py
rename to runtime/python/onnxruntime/demo_punc_online.py
diff --git a/funasr/runtime/python/onnxruntime/demo_vad_offline.py b/runtime/python/onnxruntime/demo_vad_offline.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/demo_vad_offline.py
rename to runtime/python/onnxruntime/demo_vad_offline.py
diff --git a/funasr/runtime/python/onnxruntime/demo_vad_online.py b/runtime/python/onnxruntime/demo_vad_online.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/demo_vad_online.py
rename to runtime/python/onnxruntime/demo_vad_online.py
diff --git a/funasr/runtime/python/onnxruntime/funasr_onnx/__init__.py b/runtime/python/onnxruntime/funasr_onnx/__init__.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/funasr_onnx/__init__.py
rename to runtime/python/onnxruntime/funasr_onnx/__init__.py
diff --git a/funasr/runtime/python/onnxruntime/funasr_onnx/paraformer_bin.py b/runtime/python/onnxruntime/funasr_onnx/paraformer_bin.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/funasr_onnx/paraformer_bin.py
rename to runtime/python/onnxruntime/funasr_onnx/paraformer_bin.py
diff --git a/funasr/runtime/python/onnxruntime/funasr_onnx/paraformer_online_bin.py b/runtime/python/onnxruntime/funasr_onnx/paraformer_online_bin.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/funasr_onnx/paraformer_online_bin.py
rename to runtime/python/onnxruntime/funasr_onnx/paraformer_online_bin.py
diff --git a/funasr/runtime/python/onnxruntime/funasr_onnx/punc_bin.py b/runtime/python/onnxruntime/funasr_onnx/punc_bin.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/funasr_onnx/punc_bin.py
rename to runtime/python/onnxruntime/funasr_onnx/punc_bin.py
diff --git a/funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/infer_pipeline/1/.gitkeep b/runtime/python/onnxruntime/funasr_onnx/utils/__init__.py
similarity index 100%
rename from funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/infer_pipeline/1/.gitkeep
rename to runtime/python/onnxruntime/funasr_onnx/utils/__init__.py
diff --git a/funasr/runtime/python/onnxruntime/funasr_onnx/utils/e2e_vad.py b/runtime/python/onnxruntime/funasr_onnx/utils/e2e_vad.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/funasr_onnx/utils/e2e_vad.py
rename to runtime/python/onnxruntime/funasr_onnx/utils/e2e_vad.py
diff --git a/funasr/runtime/python/onnxruntime/funasr_onnx/utils/frontend.py b/runtime/python/onnxruntime/funasr_onnx/utils/frontend.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/funasr_onnx/utils/frontend.py
rename to runtime/python/onnxruntime/funasr_onnx/utils/frontend.py
diff --git a/funasr/runtime/python/onnxruntime/funasr_onnx/utils/postprocess_utils.py b/runtime/python/onnxruntime/funasr_onnx/utils/postprocess_utils.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/funasr_onnx/utils/postprocess_utils.py
rename to runtime/python/onnxruntime/funasr_onnx/utils/postprocess_utils.py
diff --git a/funasr/runtime/python/onnxruntime/funasr_onnx/utils/timestamp_utils.py b/runtime/python/onnxruntime/funasr_onnx/utils/timestamp_utils.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/funasr_onnx/utils/timestamp_utils.py
rename to runtime/python/onnxruntime/funasr_onnx/utils/timestamp_utils.py
diff --git a/funasr/runtime/python/onnxruntime/funasr_onnx/utils/utils.py b/runtime/python/onnxruntime/funasr_onnx/utils/utils.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/funasr_onnx/utils/utils.py
rename to runtime/python/onnxruntime/funasr_onnx/utils/utils.py
diff --git a/funasr/runtime/python/onnxruntime/funasr_onnx/vad_bin.py b/runtime/python/onnxruntime/funasr_onnx/vad_bin.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/funasr_onnx/vad_bin.py
rename to runtime/python/onnxruntime/funasr_onnx/vad_bin.py
diff --git a/funasr/runtime/python/onnxruntime/setup.py b/runtime/python/onnxruntime/setup.py
similarity index 100%
rename from funasr/runtime/python/onnxruntime/setup.py
rename to runtime/python/onnxruntime/setup.py
diff --git a/funasr/runtime/python/utils/compute_wer.py b/runtime/python/utils/compute_wer.py
similarity index 100%
rename from funasr/runtime/python/utils/compute_wer.py
rename to runtime/python/utils/compute_wer.py
diff --git a/funasr/runtime/python/utils/proce_text.py b/runtime/python/utils/proce_text.py
similarity index 100%
rename from funasr/runtime/python/utils/proce_text.py
rename to runtime/python/utils/proce_text.py
diff --git a/funasr/runtime/python/utils/requirements.txt b/runtime/python/utils/requirements.txt
similarity index 100%
rename from funasr/runtime/python/utils/requirements.txt
rename to runtime/python/utils/requirements.txt
diff --git a/funasr/runtime/python/utils/split_scp.pl b/runtime/python/utils/split_scp.pl
similarity index 100%
rename from funasr/runtime/python/utils/split_scp.pl
rename to runtime/python/utils/split_scp.pl
diff --git a/funasr/runtime/python/utils/test_cer.py b/runtime/python/utils/test_cer.py
similarity index 100%
rename from funasr/runtime/python/utils/test_cer.py
rename to runtime/python/utils/test_cer.py
diff --git a/funasr/runtime/python/utils/test_cer.sh b/runtime/python/utils/test_cer.sh
similarity index 100%
rename from funasr/runtime/python/utils/test_cer.sh
rename to runtime/python/utils/test_cer.sh
diff --git a/funasr/runtime/python/utils/test_rtf.py b/runtime/python/utils/test_rtf.py
similarity index 100%
rename from funasr/runtime/python/utils/test_rtf.py
rename to runtime/python/utils/test_rtf.py
diff --git a/funasr/runtime/python/utils/test_rtf.sh b/runtime/python/utils/test_rtf.sh
similarity index 100%
rename from funasr/runtime/python/utils/test_rtf.sh
rename to runtime/python/utils/test_rtf.sh
diff --git a/funasr/runtime/python/utils/test_rtf_gpu.py b/runtime/python/utils/test_rtf_gpu.py
similarity index 100%
rename from funasr/runtime/python/utils/test_rtf_gpu.py
rename to runtime/python/utils/test_rtf_gpu.py
diff --git a/funasr/runtime/python/websocket/README.md b/runtime/python/websocket/README.md
similarity index 100%
rename from funasr/runtime/python/websocket/README.md
rename to runtime/python/websocket/README.md
diff --git a/funasr/runtime/python/websocket/funasr_client_api.py b/runtime/python/websocket/funasr_client_api.py
similarity index 100%
rename from funasr/runtime/python/websocket/funasr_client_api.py
rename to runtime/python/websocket/funasr_client_api.py
diff --git a/funasr/runtime/python/websocket/funasr_wss_client.py b/runtime/python/websocket/funasr_wss_client.py
similarity index 100%
rename from funasr/runtime/python/websocket/funasr_wss_client.py
rename to runtime/python/websocket/funasr_wss_client.py
diff --git a/funasr/runtime/python/websocket/funasr_wss_server.py b/runtime/python/websocket/funasr_wss_server.py
similarity index 100%
rename from funasr/runtime/python/websocket/funasr_wss_server.py
rename to runtime/python/websocket/funasr_wss_server.py
diff --git a/funasr/runtime/python/websocket/requirements_client.txt b/runtime/python/websocket/requirements_client.txt
similarity index 100%
rename from funasr/runtime/python/websocket/requirements_client.txt
rename to runtime/python/websocket/requirements_client.txt
diff --git a/funasr/runtime/python/websocket/requirements_server.txt b/runtime/python/websocket/requirements_server.txt
similarity index 100%
rename from funasr/runtime/python/websocket/requirements_server.txt
rename to runtime/python/websocket/requirements_server.txt
diff --git a/funasr/runtime/python/websocket/ssl_key b/runtime/python/websocket/ssl_key
similarity index 100%
rename from funasr/runtime/python/websocket/ssl_key
rename to runtime/python/websocket/ssl_key
diff --git a/funasr/runtime/readme.md b/runtime/readme.md
similarity index 69%
rename from funasr/runtime/readme.md
rename to runtime/readme.md
index b93d3a8da..4489bb497 100644
--- a/funasr/runtime/readme.md
+++ b/runtime/readme.md
@@ -16,6 +16,10 @@ Currently, the FunASR runtime-SDK supports the deployment of file transcription
To meet the needs of different users, we have prepared different tutorials with text and images for both novice and advanced developers.
+### Whats-new
+- 2023/11/08: Adaptation to runtime structure changes (FunASR/funasr/runtime -> FunASR/runtime), docker image version funasr-runtime-sdk-en-cpu-0.1.1 ().
+- 2023/10/16: English File Transcription Service 1.0 released, docker image version funasr-runtime-sdk-en-cpu-0.1.0 (e0de03eb0163), refer to the detailed documentation([here](https://mp.weixin.qq.com/s/DZZUTj-6xwFfi-96ml--4A))
+
### Technical Principles
The technical principles and documentation behind FunASR explain the underlying technology, recognition accuracy, computational efficiency, and core advantages of the framework, including convenience, high precision, high efficiency, and support for long audio chains. For detailed information, please refer to the documentation available by [docs](https://mp.weixin.qq.com/s/DZZUTj-6xwFfi-96ml--4A).
@@ -28,17 +32,18 @@ The documentation mainly targets novice users who have no need for modifications
The documentation mainly targets advanced developers who require modifications and customization of the service. It supports downloading model deployments from modelscope and also supports deploying models that users have fine-tuned. For detailed information, please refer to the documentation available by [docs](./docs/SDK_advanced_guide_offline_en.md)
-### latest version & image ID
-| image version | image ID | INFO |
-|------------------------------|-----|------|
-| funasr-runtime-sdk-en-cpu-0.1.0 | e0de03eb0163 | |
-
## The real-time transcription service, Mandarin (CPU)
The FunASR real-time speech-to-text service software package not only performs real-time speech-to-text conversion, but also allows high-precision transcription text correction at the end of each sentence and outputs text with punctuation, supporting high-concurrency multiple requests.
In order to meet the needs of different users for different scenarios, different tutorials are prepared:
+### Whats-new
+- 2023/11/08: Real-time Transcription Service 1.4 released, supporting server-side loading of hotwords (updated hotword communication protocol), adaptation to runtime structure changes (FunASR/funasr/runtime -> FunASR/runtime), docker image version funasr-runtime-sdk-online-cpu-0.1.4().
+- 2023/09/19: Real-time Transcription Service 1.2 released, supporting hotwords, timestamps, and ITN model in 2pass mode, docker image version funasr-runtime-sdk-online-cpu-0.1.2 (7222c5319bcf).
+- 2023/08/11: Real-time Transcription Service 1.1 released, addressing some known bugs (including server crashes), docker image version funasr-runtime-sdk-online-cpu-0.1.1 (bdbdd0b27dee).
+- 2023/08/07: Real-time Transcription Service 1.0 released, docker image version funasr-runtime-sdk-online-cpu-0.1.0(bdbdd0b27dee), refer to the detailed documentation([here](https://mp.weixin.qq.com/s/8He081-FM-9IEI4D-lxZ9w))
+
### Convenient Deployment Tutorial
This is suitable for scenarios where there is no need to modify the service deployment SDK and the deployed model comes from ModelScope or is finetuned by the user. For detailed tutorials, please refer to [docs](./docs/SDK_tutorial_online.md)
@@ -52,11 +57,6 @@ This is suitable for scenarios where there is a need to modify the service deplo
The document introduces the technology principles behind the service, recognition accuracy, computing efficiency, and core advantages: convenience, high precision, high efficiency, and long audio chain. For detailed documentation, please refer to [docs](https://mp.weixin.qq.com/s/8He081-FM-9IEI4D-lxZ9w).
-### latest version & image ID
-
-| image version | image ID | INFO |
-|-------------------------------------|-----|------|
-| funasr-runtime-sdk-online-cpu-0.1.3 | 0adef7779589 | |
## File Transcription Service, Mandarin (CPU)
@@ -64,6 +64,12 @@ Currently, the FunASR runtime-SDK supports the deployment of file transcription
To meet the needs of different users, we have prepared different tutorials with text and images for both novice and advanced developers.
+### Whats-new
+2023/11/08: File Transcription Service 3.0 released, supporting punctuation large model, Ngram model, fst hotwords (updated hotword communication protocol), server-side loading of hotwords, adaptation to runtime structure changes (FunASR/funasr/runtime -> FunASR/runtime), docker image version funasr-runtime-sdk-cpu-0.3.0 (), refer to the detailed documentation ([here]())
+2023/09/19: File Transcription Service 2.2 released, supporting ITN model, docker image version funasr-runtime-sdk-cpu-0.2.2 (2c5286be13e9).
+2023/08/22: File Transcription Service 2.0 released, integrated ffmpeg to support various audio and video inputs, supporting hotword model and timestamp model, docker image version funasr-runtime-sdk-cpu-0.2.0 (1ad3d19e0707), refer to the detailed documentation ([here](https://mp.weixin.qq.com/s/oJHe0MKDqTeuIFH-F7GHMg))
+2023/07/03: File Transcription Service 1.0 released, docker image version funasr-runtime-sdk-cpu-0.1.0 (1ad3d19e0707), refer to the detailed documentation ([here](https://mp.weixin.qq.com/s/DHQwbgdBWcda0w_L60iUww))
+
### Technical Principles
The technical principles and documentation behind FunASR explain the underlying technology, recognition accuracy, computational efficiency, and core advantages of the framework, including convenience, high precision, high efficiency, and support for long audio chains. For detailed information, please refer to the documentation available by [docs](https://mp.weixin.qq.com/s/DHQwbgdBWcda0w_L60iUww).
@@ -76,7 +82,3 @@ The documentation mainly targets novice users who have no need for modifications
The documentation mainly targets advanced developers who require modifications and customization of the service. It supports downloading model deployments from modelscope and also supports deploying models that users have fine-tuned. For detailed information, please refer to the documentation available by [docs](./docs/SDK_advanced_guide_offline.md)
-### latest version & image ID
-| image version | image ID | INFO |
-|------------------------------|-----|------|
-| funasr-runtime-sdk-cpu-0.2.2 | 2c5286be13e9 | |
diff --git a/funasr/runtime/readme_cn.md b/runtime/readme_cn.md
similarity index 62%
rename from funasr/runtime/readme_cn.md
rename to runtime/readme_cn.md
index 2c69c62d5..e31ea3f69 100644
--- a/funasr/runtime/readme_cn.md
+++ b/runtime/readme_cn.md
@@ -16,11 +16,14 @@ SDK 支持以下几种服务部署:
英文离线文件转写服务部署(CPU版本),拥有完整的语音识别链路,可以将几十个小时的长音频与视频识别成带标点的文字,而且支持上百路请求同时进行转写。
为了支持不同用户的需求,针对不同场景,准备了不同的图文教程:
+### 最新动态
+- 2023/11/08: 英文离线文件转写服务 1.1 发布,runtime结构变化适配(FunASR/funasr/runtime->FunASR/runtime),dokcer镜像版本funasr-runtime-sdk-en-cpu-0.1.1 ()
+- 2023/10/16: 英文离线文件转写服务 1.0 发布,dokcer镜像版本funasr-runtime-sdk-en-cpu-0.1.0 (e0de03eb0163),详细文档参考([点击此处](https://mp.weixin.qq.com/s/DZZUTj-6xwFfi-96ml--4A))
+
### 便捷部署教程
适用场景为,对服务部署SDK无修改需求,部署模型来自于ModelScope,或者用户finetune,详细教程参考([点击此处](./docs/SDK_tutorial_en_zh.md))
-
### 开发指南
适用场景为,对服务部署SDK有修改需求,部署模型来自于ModelScope,或者用户finetune,详细文档参考([点击此处](./docs/SDK_advanced_guide_offline_en_zh.md))
@@ -29,17 +32,17 @@ SDK 支持以下几种服务部署:
文档介绍了背后技术原理,识别准确率,计算效率等,以及核心优势介绍:便捷、高精度、高效率、长音频链路,详细文档参考([点击此处](https://mp.weixin.qq.com/s/DZZUTj-6xwFfi-96ml--4A))
-### 最新版本及image ID
-| image version | image ID | INFO |
-|------------------------------|-----|------|
-| funasr-runtime-sdk-en-cpu-0.1.0 | e0de03eb0163 | |
-
## 中文实时语音听写服务(CPU版本)
-
FunASR实时语音听写服务软件包,既可以实时地进行语音转文字,而且能够在说话句尾用高精度的转写文字修正输出,输出文字带有标点,支持高并发多路请求。
为了支持不同用户的需求,针对不同场景,准备了不同的图文教程:
+### 最新动态
+- 2023/11/08: 中文实时语音听写服务 1.4 发布,支持服务端加载热词(更新热词通信协议)、runtime结构变化适配(FunASR/funasr/runtime->FunASR/runtime),dokcer镜像版本funasr-runtime-sdk-online-cpu-0.1.4 ()
+- 2023/09/19: 中文实时语音听写服务 1.2 发布,2pass模式支持热词、时间戳、ITN模型,dokcer镜像版本funasr-runtime-sdk-online-cpu-0.1.2 (7222c5319bcf)
+- 2023/08/11: 中文实时语音听写服务 1.1 发布,修复了部分已知的bug(包括server崩溃等),dokcer镜像版本funasr-runtime-sdk-online-cpu-0.1.1 (bdbdd0b27dee)
+- 2023/08/07: 中文实时语音听写服务 1.0 发布,dokcer镜像版本funasr-runtime-sdk-online-cpu-0.1.0 (bdbdd0b27dee),详细文档参考([点击此处](https://mp.weixin.qq.com/s/8He081-FM-9IEI4D-lxZ9w))
+
### 便捷部署教程
适用场景为,对服务部署SDK无修改需求,部署模型来自于ModelScope,或者用户finetune,详细教程参考([点击此处](./docs/SDK_tutorial_online_zh.md))
@@ -53,23 +56,22 @@ FunASR实时语音听写服务软件包,既可以实时地进行语音转文
文档介绍了背后技术原理,识别准确率,计算效率等,以及核心优势介绍:便捷、高精度、高效率、长音频链路,详细文档参考([点击此处](https://mp.weixin.qq.com/s/8He081-FM-9IEI4D-lxZ9w))
-### 最新版本及image ID
-
-| image version | image ID | INFO |
-|-------------------------------------|-----|------|
-| funasr-runtime-sdk-online-cpu-0.1.3 | 0adef7779589 | |
-
## 中文离线文件转写服务(CPU版本)
中文语音离线文件服务部署(CPU版本),拥有完整的语音识别链路,可以将几十个小时的长音频与视频识别成带标点的文字,而且支持上百路请求同时进行转写。
为了支持不同用户的需求,针对不同场景,准备了不同的图文教程:
+### 最新动态
+- 2023/11/08: 中文离线文件转写服务 3.0 发布,支持标点大模型、支持Ngram模型、支持fst热词(更新热词通信协议)、支持服务端加载热词、runtime结构变化适配(FunASR/funasr/runtime->FunASR/runtime),dokcer镜像版本funasr-runtime-sdk-cpu-0.3.0 (),详细文档参考([点击此处]())
+- 2023/09/19: 中文离线文件转写服务 2.2 发布,支持ITN模型,dokcer镜像版本funasr-runtime-sdk-cpu-0.2.2 (2c5286be13e9)
+- 2023/08/22: 中文离线文件转写服务 2.0 发布,集成ffmpeg支持多种音视频输入、支持热词模型、支持时间戳模型,dokcer镜像版本funasr-runtime-sdk-cpu-0.2.0 (1ad3d19e0707),详细文档参考([点击此处](https://mp.weixin.qq.com/s/oJHe0MKDqTeuIFH-F7GHMg))
+- 2023/07/03: 中文离线文件转写服务 1.0 发布,dokcer镜像版本funasr-runtime-sdk-cpu-0.1.0 (1ad3d19e0707),详细文档参考([点击此处](https://mp.weixin.qq.com/s/DHQwbgdBWcda0w_L60iUww))
+
### 便捷部署教程
适用场景为,对服务部署SDK无修改需求,部署模型来自于ModelScope,或者用户finetune,详细教程参考([点击此处](./docs/SDK_tutorial_zh.md))
-
### 开发指南
适用场景为,对服务部署SDK有修改需求,部署模型来自于ModelScope,或者用户finetune,详细文档参考([点击此处](./docs/SDK_advanced_guide_offline_zh.md))
@@ -78,7 +80,3 @@ FunASR实时语音听写服务软件包,既可以实时地进行语音转文
文档介绍了背后技术原理,识别准确率,计算效率等,以及核心优势介绍:便捷、高精度、高效率、长音频链路,详细文档参考([点击此处](https://mp.weixin.qq.com/s/DHQwbgdBWcda0w_L60iUww))
-### 最新版本及image ID
-| image version | image ID | INFO |
-|------------------------------|-----|------|
-| funasr-runtime-sdk-cpu-0.2.2 | 2c5286be13e9 | |
diff --git a/funasr/runtime/run_server.sh b/runtime/run_server.sh
similarity index 56%
rename from funasr/runtime/run_server.sh
rename to runtime/run_server.sh
index 65ad4a5dd..8f6ccbf4b 100644
--- a/funasr/runtime/run_server.sh
+++ b/runtime/run_server.sh
@@ -4,6 +4,7 @@ model_dir="damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-onnx"
vad_dir="damo/speech_fsmn_vad_zh-cn-16k-common-onnx"
punc_dir="damo/punc_ct-transformer_zh-cn-common-vocab272727-onnx"
itn_dir="thuduj12/fst_itn_zh"
+lm_dir=""
decoder_thread_num=32
io_thread_num=8
port=10095
@@ -11,33 +12,35 @@ certfile="../../../ssl_key/server.crt"
keyfile="../../../ssl_key/server.key"
hotword="../../hotwords.txt"
-. ../../egs/aishell/transformer/utils/parse_options.sh || exit 1;
+. ../egs/aishell/transformer/utils/parse_options.sh || exit 1;
-cd /workspace/FunASR/funasr/runtime/websocket/build/bin
+cd /workspace/FunASR/runtime/websocket/build/bin
if [ -z "$certfile" ] || [ "$certfile" -eq 0 ]; then
./funasr-wss-server \
- --download-model-dir ${download_model_dir} \
- --model-dir ${model_dir} \
- --vad-dir ${vad_dir} \
- --punc-dir ${punc_dir} \
- --itn-dir ${itn_dir} \
+ --download-model-dir "${download_model_dir}" \
+ --model-dir "${model_dir}" \
+ --vad-dir "${vad_dir}" \
+ --punc-dir "${punc_dir}" \
+ --itn-dir "${itn_dir}" \
+ --lm-dir "${lm_dir}" \
--decoder-thread-num ${decoder_thread_num} \
--io-thread-num ${io_thread_num} \
--port ${port} \
--certfile "" \
--keyfile "" \
- --hotword ${hotword}
+ --hotword "${hotword}"
else
./funasr-wss-server \
- --download-model-dir ${download_model_dir} \
- --model-dir ${model_dir} \
- --vad-dir ${vad_dir} \
- --punc-dir ${punc_dir} \
- --itn-dir ${itn_dir} \
+ --download-model-dir "${download_model_dir}" \
+ --model-dir "${model_dir}" \
+ --vad-dir "${vad_dir}" \
+ --punc-dir "${punc_dir}" \
+ --itn-dir "${itn_dir}" \
+ --lm-dir "${lm_dir}" \
--decoder-thread-num ${decoder_thread_num} \
--io-thread-num ${io_thread_num} \
--port ${port} \
- --certfile ${certfile} \
- --keyfile ${keyfile} \
- --hotword ${hotword}
+ --certfile "${certfile}" \
+ --keyfile "${keyfile}" \
+ --hotword "${hotword}"
fi
diff --git a/funasr/runtime/run_server_2pass.sh b/runtime/run_server_2pass.sh
similarity index 58%
rename from funasr/runtime/run_server_2pass.sh
rename to runtime/run_server_2pass.sh
index e9d9f6166..c8e218799 100644
--- a/funasr/runtime/run_server_2pass.sh
+++ b/runtime/run_server_2pass.sh
@@ -12,35 +12,35 @@ certfile="../../../ssl_key/server.crt"
keyfile="../../../ssl_key/server.key"
hotword="../../hotwords.txt"
-. ../../egs/aishell/transformer/utils/parse_options.sh || exit 1;
+. ../egs/aishell/transformer/utils/parse_options.sh || exit 1;
-cd /workspace/FunASR/funasr/runtime/websocket/build/bin
+cd /workspace/FunASR/runtime/websocket/build/bin
if [ -z "$certfile" ] || [ "$certfile" -eq 0 ]; then
./funasr-wss-server-2pass \
- --download-model-dir ${download_model_dir} \
- --model-dir ${model_dir} \
- --online-model-dir ${online_model_dir} \
- --vad-dir ${vad_dir} \
- --punc-dir ${punc_dir} \
- --itn-dir ${itn_dir} \
+ --download-model-dir "${download_model_dir}" \
+ --model-dir "${model_dir}" \
+ --online-model-dir "${online_model_dir}" \
+ --vad-dir "${vad_dir}" \
+ --punc-dir "${punc_dir}" \
+ --itn-dir "${itn_dir}" \
--decoder-thread-num ${decoder_thread_num} \
--io-thread-num ${io_thread_num} \
--port ${port} \
--certfile "" \
--keyfile "" \
- --hotword ${hotword}
+ --hotword "${hotword}"
else
./funasr-wss-server-2pass \
- --download-model-dir ${download_model_dir} \
- --model-dir ${model_dir} \
- --online-model-dir ${online_model_dir} \
- --vad-dir ${vad_dir} \
- --punc-dir ${punc_dir} \
- --itn-dir ${itn_dir} \
+ --download-model-dir "${download_model_dir}" \
+ --model-dir "${model_dir}" \
+ --online-model-dir "${online_model_dir}" \
+ --vad-dir "${vad_dir}" \
+ --punc-dir "${punc_dir}" \
+ --itn-dir "${itn_dir}" \
--decoder-thread-num ${decoder_thread_num} \
--io-thread-num ${io_thread_num} \
--port ${port} \
- --certfile ${certfile} \
- --keyfile ${keyfile} \
- --hotword ${hotword}
+ --certfile "${certfile}" \
+ --keyfile "${keyfile}" \
+ --hotword "${hotword}"
fi
diff --git a/funasr/runtime/ssl_key/readme.md b/runtime/ssl_key/readme.md
similarity index 100%
rename from funasr/runtime/ssl_key/readme.md
rename to runtime/ssl_key/readme.md
diff --git a/funasr/runtime/ssl_key/readme_cn.md b/runtime/ssl_key/readme_cn.md
similarity index 100%
rename from funasr/runtime/ssl_key/readme_cn.md
rename to runtime/ssl_key/readme_cn.md
diff --git a/funasr/runtime/ssl_key/server.crt b/runtime/ssl_key/server.crt
similarity index 100%
rename from funasr/runtime/ssl_key/server.crt
rename to runtime/ssl_key/server.crt
diff --git a/funasr/runtime/ssl_key/server.key b/runtime/ssl_key/server.key
similarity index 100%
rename from funasr/runtime/ssl_key/server.key
rename to runtime/ssl_key/server.key
diff --git a/runtime/tools/fst/add_lex_disambig.pl b/runtime/tools/fst/add_lex_disambig.pl
new file mode 100755
index 000000000..803e7f632
--- /dev/null
+++ b/runtime/tools/fst/add_lex_disambig.pl
@@ -0,0 +1,118 @@
+#!/usr/bin/perl
+# Copyright 2010-2011 Microsoft Corporation
+# 2013 Johns Hopkins University (author: Daniel Povey)
+
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+# WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+# MERCHANTABLITY OR NON-INFRINGEMENT.
+# See the Apache 2 License for the specific language governing permissions and
+# limitations under the License.
+
+
+# Adds disambiguation symbols to a lexicon.
+# Outputs still in the normal lexicon format.
+# Disambig syms are numbered #1, #2, #3, etc. (#0
+# reserved for symbol in grammar).
+# Outputs the number of disambig syms to the standard output.
+# With the --pron-probs option, expects the second field
+# of each lexicon line to be a pron-prob.
+
+$pron_probs = 0;
+
+if ($ARGV[0] eq "--pron-probs") {
+ $pron_probs = 1;
+ shift @ARGV;
+}
+
+if(@ARGV != 2) {
+ die "Usage: add_lex_disambig.pl [--pron-probs] lexicon.txt lexicon_disambig.txt "
+}
+
+
+$lexfn = shift @ARGV;
+$lexoutfn = shift @ARGV;
+
+open(L, "<$lexfn") || die "Error opening lexicon $lexfn";
+
+# (1) Read in the lexicon.
+@L = ( );
+while(<L>) {
+ @A = split(" ", $_);
+ push @L, join(" ", @A);
+}
+
+# (2) Work out the count of each phone-sequence in the
+# lexicon.
+
+foreach $l (@L) {
+ @A = split(" ", $l);
+ shift @A; # Remove word.
+ if ($pron_probs) {
+ $p = shift @A;
+ if (!($p > 0.0 && $p <= 1.0)) { die "Bad lexicon line $l (expecting pron-prob as second field)"; }
+ }
+ $count{join(" ",@A)}++;
+}
+
+# (3) For each left sub-sequence of each phone-sequence, note down
+# that exists (for identifying prefixes of longer strings).
+
+foreach $l (@L) {
+ @A = split(" ", $l);
+ shift @A; # Remove word.
+ if ($pron_probs) { shift @A; } # remove pron-prob.
+ while(@A > 0) {
+ pop @A; # Remove last phone
+ $issubseq{join(" ",@A)} = 1;
+ }
+}
+
+# (4) For each entry in the lexicon:
+# if the phone sequence is unique and is not a
+# prefix of another word, no diambig symbol.
+# Else output #1, or #2, #3, ... if the same phone-seq
+# has already been assigned a disambig symbol.
+
+
+open(O, ">$lexoutfn") || die "Opening lexicon file $lexoutfn for writing.\n";
+
+$max_disambig = 0;
+foreach $l (@L) {
+ @A = split(" ", $l);
+ $word = shift @A;
+ if ($pron_probs) { $pron_prob = shift @A; }
+ $phnseq = join(" ",@A);
+ if(!defined $issubseq{$phnseq}
+ && $count{$phnseq} == 1) {
+ ; # Do nothing.
+ } else {
+ if($phnseq eq "") { # need disambig symbols for the empty string
+ # that are not use anywhere else.
+ $max_disambig++;
+ $reserved{$max_disambig} = 1;
+ $phnseq = "#$max_disambig";
+ } else {
+ $curnumber = $disambig_of{$phnseq};
+ if(!defined{$curnumber}) { $curnumber = 0; }
+ $curnumber++; # now 1 or 2, ...
+ while(defined $reserved{$curnumber} ) { $curnumber++; } # skip over reserved symbols
+ if($curnumber > $max_disambig) {
+ $max_disambig = $curnumber;
+ }
+ $disambig_of{$phnseq} = $curnumber;
+ $phnseq = $phnseq . " #" . $curnumber;
+ }
+ }
+ if ($pron_probs) { print O "$word\t$pron_prob\t$phnseq\n"; }
+ else { print O "$word\t$phnseq\n"; }
+}
+
+print $max_disambig . "\n";
+
diff --git a/runtime/tools/fst/collect_resource_file.sh b/runtime/tools/fst/collect_resource_file.sh
new file mode 100755
index 000000000..cb533bb6e
--- /dev/null
+++ b/runtime/tools/fst/collect_resource_file.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+
+# Collect TLG.fst
+lm_dir=$1
+tgt_dir=$2
+
+tlg=${lm_dir}/lang/TLG.fst
+
+[ ! -f $tlg ] && echo No TLG file $tlg && exit 1;
+
+rm -rf $tgt_dir
+mkdir -p $tgt_dir
+cp -r $tlg ${tgt_dir}/TLG.fst
+
+# Generate configuration file
+wd_file=${lm_dir}/lang/words.txt
+cfg_file=${tgt_dir}/config.yaml
+
+[ ! -f $wd_file ] && echo No words list $wd_file && exit 1;
+
+cat $wd_file | awk '{print $1}' | awk '
+ BEGIN {
+ print "token_list:";
+ }
+ {
+ printf("- \"%s\"\n", $1);
+ }
+ END {
+ }' > $cfg_file || exit 1;
+
diff --git a/runtime/tools/fst/compile_dict_token.sh b/runtime/tools/fst/compile_dict_token.sh
new file mode 100755
index 000000000..6a654220c
--- /dev/null
+++ b/runtime/tools/fst/compile_dict_token.sh
@@ -0,0 +1,84 @@
+#!/bin/bash
+# Copyright 2015 Yajie Miao (Carnegie Mellon University)
+
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+# WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+# MERCHANTABLITY OR NON-INFRINGEMENT.
+# See the Apache 2 License for the specific language governing permissions and
+# limitations under the License.
+
+# This script compiles the lexicon and CTC tokens into FSTs. FST compiling slightly differs between the
+# phoneme and character-based lexicons.
+
+. fst/parse_options.sh
+
+if [ $# -ne 3 ]; then
+ echo "usage: utils/compile_dict_token.sh <dict-src-dir> <tmp-dir> <lang-dir>"
+ echo "e.g.: utils/compile_dict_token.sh data/local/dict_phn data/local/lang_phn_tmp data/lang_phn"
+ echo "<dict-src-dir> should contain the following files:"
+ echo "lexicon.out units.txt"
+ echo "options: "
+ exit 1;
+fi
+
+srcdir=$1
+tmpdir=$2
+dir=$3
+mkdir -p $tmpdir $dir
+
+[ -f path.sh ] && . ./path.sh
+
+cp $srcdir/units.txt $dir
+
+# Add probabilities to lexicon entries. There is in fact no point of doing this here since all the entries have 1.0.
+# But utils/make_lexicon_fst.pl requires a probabilistic version, so we just leave it as it is.
+perl -ape 's/(\S+\s+)(.+)/${1}1.0\t$2/;' < $srcdir/lexicon.out > $tmpdir/lexiconp.txt || exit 1;
+
+# Add disambiguation symbols to the lexicon. This is necessary for determinizing the composition of L.fst and G.fst.
+# Without these symbols, determinization will fail.
+ndisambig=`fst/add_lex_disambig.pl $tmpdir/lexiconp.txt $tmpdir/lexiconp_disambig.txt`
+ndisambig=$[$ndisambig+1];
+
+( for n in `seq 0 $ndisambig`; do echo '#'$n; done ) > $tmpdir/disambig.list
+
+# Get the full list of CTC tokens used in FST. These tokens include <eps>, the blank <blk>, the actual labels (e.g.,
+# phonemes), and the disambiguation symbols.
+cat $srcdir/units.txt | awk '{print $1}' > $tmpdir/units.list
+(echo '<eps>') | cat - $tmpdir/units.list $tmpdir/disambig.list | awk '{print $1 " " (NR-1)}' > $dir/tokens.txt
+
+# Compile the tokens into FST
+fst/ctc_token_fst.py $dir/tokens.txt | fstcompile --isymbols=$dir/tokens.txt --osymbols=$dir/tokens.txt \
+ --keep_isymbols=false --keep_osymbols=false | fstarcsort --sort_type=olabel > $dir/T.fst || exit 1;
+
+# Encode the words with indices. Will be used in lexicon and language model FST compiling.
+cat $tmpdir/lexiconp.txt | awk '{print $1}' | sort | uniq | awk '
+ BEGIN {
+ print "<eps> 0";
+ }
+ {
+ printf("%s %d\n", $1, NR);
+ }
+ END {
+ printf("#0 %d\n", NR+1);
+ printf("<s> %d\n", NR+2);
+ printf("</s> %d\n", NR+3);
+ }' > $dir/words.txt || exit 1;
+
+# Now compile the lexicon FST. Depending on the size of your lexicon, it may take some time.
+token_disambig_symbol=`grep \#0 $dir/tokens.txt | awk '{print $2}'`
+word_disambig_symbol=`grep \#0 $dir/words.txt | awk '{print $2}'`
+
+fst/make_lexicon_fst.pl --pron-probs $tmpdir/lexiconp_disambig.txt 0 "sil" '#'$ndisambig | \
+ fstcompile --isymbols=$dir/tokens.txt --osymbols=$dir/words.txt \
+ --keep_isymbols=false --keep_osymbols=false | \
+ fstaddselfloops "echo $token_disambig_symbol |" "echo $word_disambig_symbol |" | \
+ fstarcsort --sort_type=olabel > $dir/L.fst || exit 1;
+
+echo "Dict and token FSTs compiling succeeded"
diff --git a/runtime/tools/fst/ctc_token_fst.py b/runtime/tools/fst/ctc_token_fst.py
new file mode 100755
index 000000000..e4cdabd4b
--- /dev/null
+++ b/runtime/tools/fst/ctc_token_fst.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python
+
+# Apache 2.0
+
+import sys
+
+with open(sys.argv[1], 'r') as fread:
+ print('0 0 <blank> <eps>')
+ nodeX = 1
+ for entry in fread.readlines():
+ entry = entry.replace('\n', '').strip()
+ fields = entry.split(' ')
+ phone = fields[0]
+ if phone == '<eps>' or phone == '<blank>':
+ continue
+ if '#' in phone:
+ print(str(0) + ' ' + str(0) + ' ' + '<eps>' + ' ' + phone)
+ else:
+ print(str(0) + ' ' + str(nodeX) + ' ' + phone + ' ' + phone)
+ print(str(nodeX) + ' ' + str(nodeX) + ' ' + phone + ' <eps>')
+ print(str(nodeX) + ' ' + str(0) + ' ' + '<eps> <eps>')
+ nodeX += 1
+ print('0')
+
diff --git a/runtime/tools/fst/eps2disambig.pl b/runtime/tools/fst/eps2disambig.pl
new file mode 100755
index 000000000..fecbdc833
--- /dev/null
+++ b/runtime/tools/fst/eps2disambig.pl
@@ -0,0 +1,23 @@
+#!/usr/bin/perl
+# Copyright 2010-2011 Microsoft Corporation
+
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+# WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+# MERCHANTABLITY OR NON-INFRINGEMENT.
+# See the Apache 2 License for the specific language governing permissions and
+# limitations under the License.
+
+# This script replaces epsilon with #0 on the input side only, of the G.fst
+# acceptor.
+
+while(<>){
+ s:^(\d+\s+\d+\s+)\<eps\>(\s+):$1#0$2:;
+ print;
+}
diff --git a/runtime/tools/fst/generate_lexicon.py b/runtime/tools/fst/generate_lexicon.py
new file mode 100755
index 000000000..a5a47ec6e
--- /dev/null
+++ b/runtime/tools/fst/generate_lexicon.py
@@ -0,0 +1,35 @@
+#!/usr/bin/env python3
+# encoding: utf-8
+
+import sys
+
+# sys.argv[1]: lm dict
+# sys.argv[2]: lexicon file
+# sys.argv[3]: lexicon file for corpus.dict
+
+lex_dict = {}
+with open(sys.argv[2], 'r', encoding='utf8') as fin:
+ for line in fin:
+ words = line.strip().split('\t')
+ if len(words) != 2:
+ continue
+ lex_dict[words[0]] = words[1]
+
+with open(sys.argv[1], 'r', encoding='utf8') as fin, \
+ open(sys.argv[3], 'w', encoding='utf8') as fout:
+ for line in fin:
+ word = line.strip()
+ if word == '<s>' or word == '</s>':
+ continue
+ word_lex = ""
+ if word in lex_dict:
+ word_lex = lex_dict[word]
+ else:
+ for i in range(len(word)):
+ if word[i] in lex_dict:
+ word_lex += " " + lex_dict[word[i]]
+ else:
+ word_lex += " <unk>"
+
+ fout.write('{}\t{}\n'.format(word, word_lex.strip()))
+
diff --git a/runtime/tools/fst/make_decode_graph.sh b/runtime/tools/fst/make_decode_graph.sh
new file mode 100755
index 000000000..c89268eac
--- /dev/null
+++ b/runtime/tools/fst/make_decode_graph.sh
@@ -0,0 +1,34 @@
+#!/bin/bash
+#
+
+if [ -f path.sh ]; then . path.sh; fi
+
+lm_dir=$1
+tgt_lang=$2
+
+arpa_lm=${lm_dir}/lm.arpa
+[ ! -f $arpa_lm ] && echo No such file $arpa_lm && exit 1;
+
+# Compose the language model to FST
+cat "$arpa_lm" | \
+ grep -v '<s> <s>' | \
+ grep -v '</s> <s>' | \
+ grep -v '</s> </s>' | \
+ grep -v -i '<unk>' | \
+ arpa2fst --read-symbol-table=$tgt_lang/words.txt --keep-symbols=true - | fstprint | \
+ fst/eps2disambig.pl | fst/s2eps.pl | fstcompile --isymbols=$tgt_lang/words.txt \
+ --osymbols=$tgt_lang/words.txt --keep_isymbols=false --keep_osymbols=false | \
+ fstrmepsilon | fstarcsort --sort_type=ilabel > $tgt_lang/G.fst
+
+
+echo "Checking how stochastic G is (the first of these numbers should be small):"
+fstisstochastic $tgt_lang/G.fst
+
+# Compose the token, lexicon and language-model FST into the final decoding graph
+fsttablecompose $tgt_lang/L.fst $tgt_lang/G.fst | fstdeterminizestar --use-log=true | \
+ fstminimizeencoded | fstarcsort --sort_type=ilabel > $tgt_lang/LG.fst || exit 1;
+fsttablecompose $tgt_lang/T.fst $tgt_lang/LG.fst > $tgt_lang/TLG.fst || exit 1;
+
+echo "Composing decoding graph TLG.fst succeeded"
+rm -r $tgt_lang/LG.fst # We don't need to keep this intermediate FST
+
diff --git a/runtime/tools/fst/make_lexicon_fst.pl b/runtime/tools/fst/make_lexicon_fst.pl
new file mode 100755
index 000000000..ee2c585cf
--- /dev/null
+++ b/runtime/tools/fst/make_lexicon_fst.pl
@@ -0,0 +1,148 @@
+#!/usr/bin/perl -w
+# Copyright 2010-2011 Microsoft Corporation
+# 2013 Johns Hopkins University (author: Daniel Povey)
+
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+# WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+# MERCHANTABLITY OR NON-INFRINGEMENT.
+# See the Apache 2 License for the specific language governing permissions and
+# limitations under the License.
+
+
+# makes lexicon FST, in text form, from lexicon (pronunciation probabilities optional).
+
+$pron_probs = 0;
+
+if ($ARGV[0] eq "--pron-probs") {
+ $pron_probs = 1;
+ shift @ARGV;
+}
+
+if (@ARGV != 1 && @ARGV != 3 && @ARGV != 4) {
+ print STDERR
+ "Usage: make_lexicon_fst.pl [--pron-probs] lexicon.txt [silprob silphone [sil_disambig_sym]] >lexiconfst.txt
+Creates a lexicon FST that transduces phones to words, and may allow optional silence.
+Note: ordinarily, each line of lexicon.txt is: word phone1 phone2 ... phoneN; if the --pron-probs option is
+used, each line is: word pronunciation-probability phone1 phone2 ... phoneN. The probability 'prob' will
+typically be between zero and one, and note that it's generally helpful to normalize so the largest one
+for each word is 1.0, but this is your responsibility. The silence disambiguation symbol, e.g. something
+like #5, is used only when creating a lexicon with disambiguation symbols, e.g. L_disambig.fst, and was
+introduced to fix a particular case of non-determinism of decoding graphs.\n";
+ exit(1);
+}
+
+$lexfn = shift @ARGV;
+if (@ARGV == 0) {
+ $silprob = 0.0;
+} elsif (@ARGV == 2) {
+ ($silprob,$silphone) = @ARGV;
+} else {
+ ($silprob,$silphone,$sildisambig) = @ARGV;
+}
+if ($silprob != 0.0) {
+ $silprob < 1.0 || die "Sil prob cannot be >= 1.0";
+ $silcost = -log($silprob);
+ $nosilcost = -log(1.0 - $silprob);
+}
+
+
+open(L, "<$lexfn") || die "Error opening lexicon $lexfn";
+
+
+if ( $silprob == 0.0 ) { # No optional silences: just have one (loop+final) state which is numbered zero.
+ $loopstate = 0;
+ $nextstate = 1; # next unallocated state.
+ while (<L>) {
+ @A = split(" ", $_);
+ @A == 0 && die "Empty lexicon line.";
+ $w = shift @A;
+ if (! $pron_probs) {
+ $pron_cost = 0.0;
+ } else {
+ $pron_prob = shift @A;
+ if (! defined $pron_prob || !($pron_prob > 0.0 && $pron_prob <= 1.0)) {
+ die "Bad pronunciation probability in line $_";
+ }
+ $pron_cost = -log($pron_prob);
+ }
+ if ($pron_cost != 0.0) { $pron_cost_string = "\t$pron_cost"; } else { $pron_cost_string = ""; }
+
+ $s = $loopstate;
+ $word_or_eps = $w;
+ while (@A > 0) {
+ $p = shift @A;
+ if (@A > 0) {
+ $ns = $nextstate++;
+ } else {
+ $ns = $loopstate;
+ }
+ print "$s\t$ns\t$p\t$word_or_eps$pron_cost_string\n";
+ $word_or_eps = "<eps>";
+ $pron_cost_string = ""; # so we only print it on the first arc of the word.
+ $s = $ns;
+ }
+ }
+ print "$loopstate\t0\n"; # final-cost.
+} else { # have silence probs.
+ $startstate = 0;
+ $loopstate = 1;
+ $silstate = 2; # state from where we go to loopstate after emitting silence.
+ print "$startstate\t$loopstate\t<eps>\t<eps>\t$nosilcost\n"; # no silence.
+ if (!defined $sildisambig) {
+ print "$startstate\t$loopstate\t$silphone\t<eps>\t$silcost\n"; # silence.
+ print "$silstate\t$loopstate\t$silphone\t<eps>\n"; # no cost.
+ $nextstate = 3;
+ } else {
+ $disambigstate = 3;
+ $nextstate = 4;
+ print "$startstate\t$disambigstate\t$silphone\t<eps>\t$silcost\n"; # silence.
+ print "$silstate\t$disambigstate\t$silphone\t<eps>\n"; # no cost.
+ print "$disambigstate\t$loopstate\t$sildisambig\t<eps>\n"; # silence disambiguation symbol.
+ }
+ while (<L>) {
+ @A = split(" ", $_);
+ $w = shift @A;
+ if (! $pron_probs) {
+ $pron_cost = 0.0;
+ } else {
+ $pron_prob = shift @A;
+ if (! defined $pron_prob || !($pron_prob > 0.0 && $pron_prob <= 1.0)) {
+ die "Bad pronunciation probability in line $_";
+ }
+ $pron_cost = -log($pron_prob);
+ }
+ if ($pron_cost != 0.0) { $pron_cost_string = "\t$pron_cost"; } else { $pron_cost_string = ""; }
+ $s = $loopstate;
+ $word_or_eps = $w;
+ while (@A > 0) {
+ $p = shift @A;
+ if (@A > 0) {
+ $ns = $nextstate++;
+ print "$s\t$ns\t$p\t$word_or_eps$pron_cost_string\n";
+ $word_or_eps = "<eps>";
+ $pron_cost_string = ""; $pron_cost = 0.0; # so we only print it the 1st time.
+ $s = $ns;
+ } else {
+ if (!defined($silphone) || $p ne $silphone) {
+ # This is non-deterministic but relatively compact,
+ # and avoids epsilons.
+ $local_nosilcost = $nosilcost + $pron_cost;
+ $local_silcost = $silcost + $pron_cost;
+ print "$s\t$loopstate\t$p\t$word_or_eps\t$local_nosilcost\n";
+ print "$s\t$silstate\t$p\t$word_or_eps\t$local_silcost\n";
+ } else {
+ # no point putting opt-sil after silence word.
+ print "$s\t$loopstate\t$p\t$word_or_eps$pron_cost_string\n";
+ }
+ }
+ }
+ }
+ print "$loopstate\t0\n"; # final-cost.
+}
diff --git a/runtime/tools/fst/parse_options.sh b/runtime/tools/fst/parse_options.sh
new file mode 100755
index 000000000..fdc8a3628
--- /dev/null
+++ b/runtime/tools/fst/parse_options.sh
@@ -0,0 +1,97 @@
+#!/bin/bash
+
+# Copyright 2012 Johns Hopkins University (Author: Daniel Povey);
+# Arnab Ghoshal, Karel Vesely
+
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+# WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+# MERCHANTABLITY OR NON-INFRINGEMENT.
+# See the Apache 2 License for the specific language governing permissions and
+# limitations under the License.
+
+
+# Parse command-line options.
+# To be sourced by another script (as in ". parse_options.sh").
+# Option format is: --option-name arg
+# and shell variable "option_name" gets set to value "arg."
+# The exception is --help, which takes no arguments, but prints the
+# $help_message variable (if defined).
+
+
+###
+### The --config file options have lower priority to command line
+### options, so we need to import them first...
+###
+
+# Now import all the configs specified by command-line, in left-to-right order
+for ((argpos=1; argpos<$#; argpos++)); do
+ if [ "${!argpos}" == "--config" ]; then
+ argpos_plus1=$((argpos+1))
+ config=${!argpos_plus1}
+ [ ! -r $config ] && echo "$0: missing config '$config'" && exit 1
+ . $config # source the config file.
+ fi
+done
+
+
+###
+### No we process the command line options
+###
+while true; do
+ [ -z "${1:-}" ] && break; # break if there are no arguments
+ case "$1" in
+ # If the enclosing script is called with --help option, print the help
+ # message and exit. Scripts should put help messages in $help_message
+ --help|-h) if [ -z "$help_message" ]; then echo "No help found." 1>&2;
+ else printf "$help_message\n" 1>&2 ; fi;
+ exit 0 ;;
+ --*=*) echo "$0: options to scripts must be of the form --name value, got '$1'"
+ exit 1 ;;
+ # If the first command-line argument begins with "--" (e.g. --foo-bar),
+ # then work out the variable name as $name, which will equal "foo_bar".
+ --*) name=`echo "$1" | sed s/^--// | sed s/-/_/g`;
+ # Next we test whether the variable in question is undefned-- if so it's
+ # an invalid option and we die. Note: $0 evaluates to the name of the
+ # enclosing script.
+ # The test [ -z ${foo_bar+xxx} ] will return true if the variable foo_bar
+ # is undefined. We then have to wrap this test inside "eval" because
+ # foo_bar is itself inside a variable ($name).
+ eval '[ -z "${'$name'+xxx}" ]' && echo "$0: invalid option $1" 1>&2 && exit 1;
+
+ oldval="`eval echo \\$$name`";
+ # Work out whether we seem to be expecting a Boolean argument.
+ if [ "$oldval" == "true" ] || [ "$oldval" == "false" ]; then
+ was_bool=true;
+ else
+ was_bool=false;
+ fi
+
+ # Set the variable to the right value-- the escaped quotes make it work if
+ # the option had spaces, like --cmd "queue.pl -sync y"
+ eval $name=\"$2\";
+
+ # Check that Boolean-valued arguments are really Boolean.
+ if $was_bool && [[ "$2" != "true" && "$2" != "false" ]]; then
+ echo "$0: expected \"true\" or \"false\": $1 $2" 1>&2
+ exit 1;
+ fi
+ shift 2;
+ ;;
+ *) break;
+ esac
+done
+
+
+# Check for an empty argument to the --cmd option, which can easily occur as a
+# result of scripting errors.
+[ ! -z "${cmd+xxx}" ] && [ -z "$cmd" ] && echo "$0: empty argument to --cmd option" 1>&2 && exit 1;
+
+
+true; # so this script returns exit code 0.
diff --git a/runtime/tools/fst/s2eps.pl b/runtime/tools/fst/s2eps.pl
new file mode 100755
index 000000000..de993db67
--- /dev/null
+++ b/runtime/tools/fst/s2eps.pl
@@ -0,0 +1,27 @@
+#!/usr/bin/perl
+# Copyright 2010-2011 Microsoft Corporation
+
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
+# WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
+# MERCHANTABLITY OR NON-INFRINGEMENT.
+# See the Apache 2 License for the specific language governing permissions and
+# limitations under the License.
+
+# This script replaces <s> and </s> with <eps> (on both input and output sides),
+# for the G.fst acceptor.
+
+while(<>){
+ @A = split(" ", $_);
+ if ( @A >= 4 ) {
+ if ($A[2] eq "<s>" || $A[2] eq "</s>") { $A[2] = "<eps>"; }
+ if ($A[3] eq "<s>" || $A[3] eq "</s>") { $A[3] = "<eps>"; }
+ }
+ print join("\t", @A) . "\n";
+}
diff --git a/runtime/tools/fst/train_lms.sh b/runtime/tools/fst/train_lms.sh
new file mode 100755
index 000000000..1fdb0ef62
--- /dev/null
+++ b/runtime/tools/fst/train_lms.sh
@@ -0,0 +1,25 @@
+#!/bin/bash
+
+## Make sure that srilm is installed
+
+dir=lm
+mkdir -p $dir
+[ -f path.sh ] && . ./path.sh
+
+# Prepare data, the format of the text should be:
+# BAC009S0002W0122 而 对 楼市 成交 抑制 作用 最 大 的 限 购
+# BAC009S0002W0123 也 成为 地方 政府 的 眼中 钉
+corpus=lm/text
+
+# generate lm dict
+cat $corpus | awk '{for(n=2;n<=NF;n++) print tolower($n); }' | \
+ cat - <(echo "<unk>";echo "<s>"; echo "</s>") | \
+ sort | uniq -c | sort -nr | awk '{print $2}' > $dir/corpus.dict || exit 1;
+
+# train ngram
+cat $corpus | awk '{for(n=2;n<=NF;n++){ printf tolower($n); if(n<NF) printf " "; else print ""; }}' > $dir/train
+
+ngram-count -text $dir/train -order 4 -limit-vocab -vocab $dir/corpus.dict -unk \
+ -kndiscount -interpolate -gt1min 1 -gt2min 1 -gt3min 2 -gt4min 2 -lm $dir/lm.arpa
+
+
diff --git a/runtime/tools/path.sh b/runtime/tools/path.sh
new file mode 100644
index 000000000..87f8220c5
--- /dev/null
+++ b/runtime/tools/path.sh
@@ -0,0 +1,3 @@
+export FUNASR_RUNTIME_ROOT=`pwd`/../
+export PATH=$FUNASR_RUNTIME_ROOT/onnxruntime/build/bin:$PWD:$PATH
+export LC_ALL=C
diff --git a/runtime/tools/train_compile_ngram.sh b/runtime/tools/train_compile_ngram.sh
new file mode 100644
index 000000000..6b2989d3b
--- /dev/null
+++ b/runtime/tools/train_compile_ngram.sh
@@ -0,0 +1,21 @@
+chmod +x fst/*
+[ -f path.sh ] && . ./path.sh
+
+# download train corpus and lexicon
+wget https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/requirements/lm.tar.gz
+tar -zxvf lm.tar.gz
+
+# train lm, make sure that srilm is installed
+bash fst/train_lms.sh
+
+# generate lexicon
+python3 fst/generate_lexicon.py lm/corpus.dict lm/lexicon.txt lm/lexicon.out
+
+# Compile the lexicon and token FSTs
+fst/compile_dict_token.sh lm lm/tmp lm/lang
+
+# Compile the language-model FST and the final decoding graph TLG.fst
+fst/make_decode_graph.sh lm lm/lang || exit 1;
+
+# Collect resource files required for decoding
+fst/collect_resource_file.sh lm lm/resource
diff --git a/funasr/runtime/triton_gpu/Dockerfile/Dockerfile.server b/runtime/triton_gpu/Dockerfile/Dockerfile.server
similarity index 100%
rename from funasr/runtime/triton_gpu/Dockerfile/Dockerfile.server
rename to runtime/triton_gpu/Dockerfile/Dockerfile.server
diff --git a/funasr/runtime/triton_gpu/README.md b/runtime/triton_gpu/README.md
similarity index 100%
rename from funasr/runtime/triton_gpu/README.md
rename to runtime/triton_gpu/README.md
diff --git a/funasr/runtime/triton_gpu/client/aishell_test.txt b/runtime/triton_gpu/client/aishell_test.txt
similarity index 100%
rename from funasr/runtime/triton_gpu/client/aishell_test.txt
rename to runtime/triton_gpu/client/aishell_test.txt
diff --git a/funasr/runtime/triton_gpu/client/client.py b/runtime/triton_gpu/client/client.py
similarity index 100%
rename from funasr/runtime/triton_gpu/client/client.py
rename to runtime/triton_gpu/client/client.py
diff --git a/funasr/runtime/triton_gpu/client/decode_manifest_triton.py b/runtime/triton_gpu/client/decode_manifest_triton.py
similarity index 100%
rename from funasr/runtime/triton_gpu/client/decode_manifest_triton.py
rename to runtime/triton_gpu/client/decode_manifest_triton.py
diff --git a/funasr/runtime/triton_gpu/client/decode_manifest_triton_wo_cuts.py b/runtime/triton_gpu/client/decode_manifest_triton_wo_cuts.py
similarity index 100%
rename from funasr/runtime/triton_gpu/client/decode_manifest_triton_wo_cuts.py
rename to runtime/triton_gpu/client/decode_manifest_triton_wo_cuts.py
diff --git a/funasr/runtime/triton_gpu/client/speech_client.py b/runtime/triton_gpu/client/speech_client.py
similarity index 100%
rename from funasr/runtime/triton_gpu/client/speech_client.py
rename to runtime/triton_gpu/client/speech_client.py
diff --git a/funasr/runtime/triton_gpu/client/test_wavs/long.wav b/runtime/triton_gpu/client/test_wavs/long.wav
similarity index 100%
rename from funasr/runtime/triton_gpu/client/test_wavs/long.wav
rename to runtime/triton_gpu/client/test_wavs/long.wav
diff --git a/funasr/runtime/triton_gpu/client/test_wavs/mid.wav b/runtime/triton_gpu/client/test_wavs/mid.wav
similarity index 100%
rename from funasr/runtime/triton_gpu/client/test_wavs/mid.wav
rename to runtime/triton_gpu/client/test_wavs/mid.wav
diff --git a/funasr/runtime/triton_gpu/client/utils.py b/runtime/triton_gpu/client/utils.py
similarity index 100%
rename from funasr/runtime/triton_gpu/client/utils.py
rename to runtime/triton_gpu/client/utils.py
diff --git a/runtime/triton_gpu/model_repo_paraformer_large_offline/encoder/1/.gitkeep b/runtime/triton_gpu/model_repo_paraformer_large_offline/encoder/1/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/encoder/config.pbtxt b/runtime/triton_gpu/model_repo_paraformer_large_offline/encoder/config.pbtxt
similarity index 100%
rename from funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/encoder/config.pbtxt
rename to runtime/triton_gpu/model_repo_paraformer_large_offline/encoder/config.pbtxt
diff --git a/funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/feature_extractor/1/model.py b/runtime/triton_gpu/model_repo_paraformer_large_offline/feature_extractor/1/model.py
similarity index 100%
rename from funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/feature_extractor/1/model.py
rename to runtime/triton_gpu/model_repo_paraformer_large_offline/feature_extractor/1/model.py
diff --git a/funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/feature_extractor/config.pbtxt b/runtime/triton_gpu/model_repo_paraformer_large_offline/feature_extractor/config.pbtxt
similarity index 100%
rename from funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/feature_extractor/config.pbtxt
rename to runtime/triton_gpu/model_repo_paraformer_large_offline/feature_extractor/config.pbtxt
diff --git a/runtime/triton_gpu/model_repo_paraformer_large_offline/infer_pipeline/1/.gitkeep b/runtime/triton_gpu/model_repo_paraformer_large_offline/infer_pipeline/1/.gitkeep
new file mode 100644
index 000000000..e69de29bb
diff --git a/funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/infer_pipeline/config.pbtxt b/runtime/triton_gpu/model_repo_paraformer_large_offline/infer_pipeline/config.pbtxt
similarity index 100%
rename from funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/infer_pipeline/config.pbtxt
rename to runtime/triton_gpu/model_repo_paraformer_large_offline/infer_pipeline/config.pbtxt
diff --git a/funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/scoring/1/model.py b/runtime/triton_gpu/model_repo_paraformer_large_offline/scoring/1/model.py
similarity index 100%
rename from funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/scoring/1/model.py
rename to runtime/triton_gpu/model_repo_paraformer_large_offline/scoring/1/model.py
diff --git a/funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/scoring/config.pbtxt b/runtime/triton_gpu/model_repo_paraformer_large_offline/scoring/config.pbtxt
similarity index 100%
rename from funasr/runtime/triton_gpu/model_repo_paraformer_large_offline/scoring/config.pbtxt
rename to runtime/triton_gpu/model_repo_paraformer_large_offline/scoring/config.pbtxt
diff --git a/funasr/runtime/websocket/CMakeLists.txt b/runtime/websocket/CMakeLists.txt
similarity index 94%
rename from funasr/runtime/websocket/CMakeLists.txt
rename to runtime/websocket/CMakeLists.txt
index 56c425518..5f14bf4b0 100644
--- a/funasr/runtime/websocket/CMakeLists.txt
+++ b/runtime/websocket/CMakeLists.txt
@@ -109,14 +109,18 @@ endif()
include_directories(${PROJECT_SOURCE_DIR}/../onnxruntime/include/)
+include_directories(${PROJECT_SOURCE_DIR}/../onnxruntime/src)
include_directories(${PROJECT_SOURCE_DIR}/../onnxruntime/third_party/yaml-cpp/include/)
include_directories(${PROJECT_SOURCE_DIR}/../onnxruntime/third_party/kaldi-native-fbank)
include_directories(${PROJECT_SOURCE_DIR}/../onnxruntime/third_party/jieba/include)
include_directories(${PROJECT_SOURCE_DIR}/../onnxruntime/third_party/jieba/include/limonp/include)
+include_directories(${PROJECT_SOURCE_DIR}/../onnxruntime/third_party)
+include_directories(${PROJECT_SOURCE_DIR}/../onnxruntime/third_party/kaldi)
add_subdirectory(${PROJECT_SOURCE_DIR}/../onnxruntime/third_party/yaml-cpp yaml-cpp)
add_subdirectory(${PROJECT_SOURCE_DIR}/../onnxruntime/third_party/kaldi-native-fbank/kaldi-native-fbank/csrc csrc)
add_subdirectory(${PROJECT_SOURCE_DIR}/../onnxruntime/src src)
+add_subdirectory(${PROJECT_SOURCE_DIR}/../onnxruntime/third_party/kaldi kaldi)
# install openssl first apt-get install libssl-dev
find_package(OpenSSL REQUIRED)
diff --git a/funasr/runtime/websocket/bin/CMakeLists.txt b/runtime/websocket/bin/CMakeLists.txt
similarity index 100%
rename from funasr/runtime/websocket/bin/CMakeLists.txt
rename to runtime/websocket/bin/CMakeLists.txt
diff --git a/funasr/runtime/websocket/bin/funasr-wss-client-2pass.cpp b/runtime/websocket/bin/funasr-wss-client-2pass.cpp
similarity index 90%
rename from funasr/runtime/websocket/bin/funasr-wss-client-2pass.cpp
rename to runtime/websocket/bin/funasr-wss-client-2pass.cpp
index c1250283c..e2cce28ce 100644
--- a/funasr/runtime/websocket/bin/funasr-wss-client-2pass.cpp
+++ b/runtime/websocket/bin/funasr-wss-client-2pass.cpp
@@ -27,7 +27,7 @@
#include <websocketpp/client.hpp>
#include <websocketpp/common/thread.hpp>
#include <websocketpp/config/asio_client.hpp>
-
+#include "util.h"
#include "audio.h"
#include "nlohmann/json.hpp"
#include "tclap/CmdLine.h"
@@ -45,15 +45,6 @@ void WaitABit() {
}
std::atomic<int> wav_index(0);
-bool IsTargetFile(const std::string& filename, const std::string target) {
- std::size_t pos = filename.find_last_of(".");
- if (pos == std::string::npos) {
- return false;
- }
- std::string extension = filename.substr(pos + 1);
- return (extension == target);
-}
-
typedef websocketpp::config::asio_client::message_type::ptr message_ptr;
typedef websocketpp::lib::shared_ptr<websocketpp::lib::asio::ssl::context>
context_ptr;
@@ -132,8 +123,8 @@ class WebsocketClient {
// This method will block until the connection is complete
void run(const std::string& uri, const std::vector<string>& wav_list,
const std::vector<string>& wav_ids, std::string asr_mode,
- std::vector<int> chunk_size, bool is_record=false, std::string hotwords="",
- int use_itn=1) {
+ std::vector<int> chunk_size, const std::unordered_map<std::string, int>& hws_map,
+ bool is_record=false, int use_itn=1) {
// Create a new connection to the given URI
websocketpp::lib::error_code ec;
typename websocketpp::client<T>::connection_ptr con =
@@ -155,9 +146,9 @@ class WebsocketClient {
websocketpp::lib::thread asio_thread(&websocketpp::client<T>::run,
&m_client);
if(is_record){
- send_rec_data(asr_mode, chunk_size, hotwords, use_itn);
+ send_rec_data(asr_mode, chunk_size, hws_map, use_itn);
}else{
- send_wav_data(wav_list[0], wav_ids[0], asr_mode, chunk_size, hotwords, use_itn);
+ send_wav_data(wav_list[0], wav_ids[0], asr_mode, chunk_size, hws_map, use_itn);
}
WaitABit();
@@ -193,17 +184,18 @@ class WebsocketClient {
}
// send wav to server
void send_wav_data(string wav_path, string wav_id, std::string asr_mode,
- std::vector<int> chunk_vector, string hotwords, int use_itn) {
+ std::vector<int> chunk_vector, const std::unordered_map<std::string, int>& hws_map,
+ int use_itn) {
uint64_t count = 0;
std::stringstream val;
funasr::Audio audio(1);
int32_t sampling_rate = 16000;
std::string wav_format = "pcm";
- if (IsTargetFile(wav_path.c_str(), "wav")) {
+ if (funasr::IsTargetFile(wav_path.c_str(), "wav")) {
int32_t sampling_rate = -1;
if (!audio.LoadWav(wav_path.c_str(), &sampling_rate)) return;
- } else if (IsTargetFile(wav_path.c_str(), "pcm")) {
+ } else if (funasr::IsTargetFile(wav_path.c_str(), "pcm")) {
if (!audio.LoadPcmwav(wav_path.c_str(), &sampling_rate)) return;
} else {
wav_format = "others";
@@ -251,8 +243,15 @@ class WebsocketClient {
if(use_itn == 0){
jsonbegin["itn"] = false;
}
- LOG(INFO) << "hotwords: "<< hotwords;
- jsonbegin["hotwords"] = hotwords;
+ if(!hws_map.empty()){
+ LOG(INFO) << "hotwords: ";
+ for (const auto& pair : hws_map) {
+ LOG(INFO) << pair.first << " : " << pair.second;
+ }
+ nlohmann::json json_map(hws_map);
+ std::string json_map_str = json_map.dump();
+ jsonbegin["hotwords"] = json_map_str;
+ }
m_client.send(m_hdl, jsonbegin.dump(), websocketpp::frame::opcode::text,
ec);
@@ -335,7 +334,7 @@ class WebsocketClient {
}
void send_rec_data(std::string asr_mode, std::vector<int> chunk_vector,
- string hotwords, int use_itn) {
+ const std::unordered_map<std::string, int>& hws_map, int use_itn) {
// first message
bool wait = false;
while (1) {
@@ -375,8 +374,15 @@ class WebsocketClient {
if(use_itn == 0){
jsonbegin["itn"] = false;
}
- LOG(INFO) << "hotwords: "<< hotwords;
- jsonbegin["hotwords"] = hotwords;
+ if(!hws_map.empty()){
+ LOG(INFO) << "hotwords: ";
+ for (const auto& pair : hws_map) {
+ LOG(INFO) << pair.first << " : " << pair.second;
+ }
+ nlohmann::json json_map(hws_map);
+ std::string json_map_str = json_map.dump();
+ jsonbegin["hotwords"] = json_map_str;
+ }
m_client.send(m_hdl, jsonbegin.dump(), websocketpp::frame::opcode::text,
ec);
// mic
@@ -499,7 +505,8 @@ int main(int argc, char* argv[]) {
"", "use-itn",
"use-itn is 1 means use itn, 0 means not use itn", false, 1,
"int");
- TCLAP::ValueArg<std::string> hotword_("", HOTWORD, "*.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)", false, "", "string");
+ TCLAP::ValueArg<std::string> hotword_("", HOTWORD,
+ "the hotword file, one hotword perline, Format: Hotword Weight (could be: 阿里巴巴 20)", false, "", "string");
cmd.add(server_ip_);
cmd.add(port_);
@@ -543,24 +550,12 @@ int main(int argc, char* argv[]) {
uri = "ws://" + server_ip + ":" + port;
}
- // read hotwords
- std::string hotword = hotword_.getValue();
- std::string hotwords_="";
-
- if(IsTargetFile(hotword, "txt")){
- ifstream in(hotword);
- if (!in.is_open()) {
- LOG(ERROR) << "Failed to open file: " << hotword;
- return 0;
- }
- string line;
- while(getline(in, line))
- {
- hotwords_ +=line+HOTWORD_SEP;
- }
- in.close();
- }else{
- hotwords_ = hotword;
+ // hotwords
+ std::string hotword_path = hotword_.getValue();
+ unordered_map<string, int> hws_map;
+ if(!hotword_path.empty()){
+ LOG(INFO) << "hotword path: " << hotword_path;
+ funasr::ExtractHws(hotword_path, hws_map);
}
if(is_record == 1){
@@ -572,11 +567,11 @@ int main(int argc, char* argv[]) {
c.m_client.set_tls_init_handler(bind(&OnTlsInit, ::_1));
- c.run(uri, tmp_wav_list, tmp_wav_ids, asr_mode, chunk_size, true, hotwords_, use_itn);
+ c.run(uri, tmp_wav_list, tmp_wav_ids, asr_mode, chunk_size, hws_map, true, use_itn);
} else {
WebsocketClient<websocketpp::config::asio_client> c(is_ssl);
- c.run(uri, tmp_wav_list, tmp_wav_ids, asr_mode, chunk_size, true, hotwords_, use_itn);
+ c.run(uri, tmp_wav_list, tmp_wav_ids, asr_mode, chunk_size, hws_map, true, use_itn);
}
}else{
@@ -584,7 +579,7 @@ int main(int argc, char* argv[]) {
std::vector<string> wav_list;
std::vector<string> wav_ids;
string default_id = "wav_default_id";
- if (IsTargetFile(wav_path, "scp")) {
+ if (funasr::IsTargetFile(wav_path, "scp")) {
ifstream in(wav_path);
if (!in.is_open()) {
printf("Failed to open scp file");
@@ -617,17 +612,17 @@ int main(int argc, char* argv[]) {
tmp_wav_ids.emplace_back(wav_ids[wav_i + i]);
client_threads.emplace_back(
- [uri, tmp_wav_list, tmp_wav_ids, asr_mode, chunk_size, is_ssl, hotwords_, use_itn]() {
+ [uri, tmp_wav_list, tmp_wav_ids, asr_mode, chunk_size, is_ssl, hws_map, use_itn]() {
if (is_ssl == 1) {
WebsocketClient<websocketpp::config::asio_tls_client> c(is_ssl);
c.m_client.set_tls_init_handler(bind(&OnTlsInit, ::_1));
- c.run(uri, tmp_wav_list, tmp_wav_ids, asr_mode, chunk_size, false, hotwords_, use_itn);
+ c.run(uri, tmp_wav_list, tmp_wav_ids, asr_mode, chunk_size, hws_map, false, use_itn);
} else {
WebsocketClient<websocketpp::config::asio_client> c(is_ssl);
- c.run(uri, tmp_wav_list, tmp_wav_ids, asr_mode, chunk_size, false, hotwords_, use_itn);
+ c.run(uri, tmp_wav_list, tmp_wav_ids, asr_mode, chunk_size, hws_map, false, use_itn);
}
});
}
diff --git a/funasr/runtime/websocket/bin/funasr-wss-client.cpp b/runtime/websocket/bin/funasr-wss-client.cpp
similarity index 90%
rename from funasr/runtime/websocket/bin/funasr-wss-client.cpp
rename to runtime/websocket/bin/funasr-wss-client.cpp
index 39a3e67a4..ad68c63d4 100644
--- a/funasr/runtime/websocket/bin/funasr-wss-client.cpp
+++ b/runtime/websocket/bin/funasr-wss-client.cpp
@@ -22,7 +22,7 @@
#include <atomic>
#include <thread>
#include <glog/logging.h>
-
+#include "util.h"
#include "audio.h"
#include "nlohmann/json.hpp"
#include "tclap/CmdLine.h"
@@ -39,15 +39,6 @@ void WaitABit() {
}
std::atomic<int> wav_index(0);
-bool IsTargetFile(const std::string& filename, const std::string target) {
- std::size_t pos = filename.find_last_of(".");
- if (pos == std::string::npos) {
- return false;
- }
- std::string extension = filename.substr(pos + 1);
- return (extension == target);
-}
-
typedef websocketpp::config::asio_client::message_type::ptr message_ptr;
typedef websocketpp::lib::shared_ptr<websocketpp::lib::asio::ssl::context> context_ptr;
using websocketpp::lib::bind;
@@ -123,7 +114,7 @@ class WebsocketClient {
// This method will block until the connection is complete
void run(const std::string& uri, const std::vector<string>& wav_list, const std::vector<string>& wav_ids,
- std::string hotwords, int use_itn=1) {
+ const std::unordered_map<std::string, int>& hws_map, int use_itn=1) {
// Create a new connection to the given URI
websocketpp::lib::error_code ec;
typename websocketpp::client<T>::connection_ptr con =
@@ -151,7 +142,7 @@ class WebsocketClient {
break;
}
total_send += 1;
- send_wav_data(wav_list[i], wav_ids[i], hotwords, send_hotword, use_itn);
+ send_wav_data(wav_list[i], wav_ids[i], hws_map, send_hotword, use_itn);
if(send_hotword){
send_hotword = false;
}
@@ -189,18 +180,20 @@ class WebsocketClient {
m_done = true;
}
// send wav to server
- void send_wav_data(string wav_path, string wav_id, string hotwords, bool send_hotword, bool use_itn) {
+ void send_wav_data(string wav_path, string wav_id,
+ const std::unordered_map<std::string, int>& hws_map,
+ bool send_hotword, bool use_itn) {
uint64_t count = 0;
std::stringstream val;
funasr::Audio audio(1);
int32_t sampling_rate = 16000;
std::string wav_format = "pcm";
- if(IsTargetFile(wav_path.c_str(), "wav")){
+ if(funasr::IsTargetFile(wav_path.c_str(), "wav")){
int32_t sampling_rate = -1;
if(!audio.LoadWav(wav_path.c_str(), &sampling_rate))
return ;
- }else if(IsTargetFile(wav_path.c_str(), "pcm")){
+ }else if(funasr::IsTargetFile(wav_path.c_str(), "pcm")){
if (!audio.LoadPcmwav(wav_path.c_str(), &sampling_rate))
return ;
}else{
@@ -250,8 +243,15 @@ class WebsocketClient {
}
jsonbegin["is_speaking"] = true;
if(send_hotword){
- LOG(INFO) << "hotwords: "<< hotwords;
- jsonbegin["hotwords"] = hotwords;
+ if(!hws_map.empty()){
+ LOG(INFO) << "hotwords: ";
+ for (const auto& pair : hws_map) {
+ LOG(INFO) << pair.first << " : " << pair.second;
+ }
+ nlohmann::json json_map(hws_map);
+ std::string json_map_str = json_map.dump();
+ jsonbegin["hotwords"] = json_map_str;
+ }
}
m_client.send(m_hdl, jsonbegin.dump(), websocketpp::frame::opcode::text,
ec);
@@ -360,7 +360,8 @@ int main(int argc, char* argv[]) {
TCLAP::ValueArg<int> use_itn_(
"", "use-itn",
"use-itn is 1 means use itn, 0 means not use itn", false, 1, "int");
- TCLAP::ValueArg<std::string> hotword_("", HOTWORD, "*.txt(one hotword perline) or hotwords seperate by space (could be: 阿里巴巴 达摩院)", false, "", "string");
+ TCLAP::ValueArg<std::string> hotword_("", HOTWORD,
+ "the hotword file, one hotword perline, Format: Hotword Weight (could be: 阿里巴巴 20)", false, "", "string");
cmd.add(server_ip_);
cmd.add(port_);
@@ -386,31 +387,19 @@ int main(int argc, char* argv[]) {
uri = "ws://" + server_ip + ":" + port;
}
- // read hotwords
- std::string hotword = hotword_.getValue();
- std::string hotwords_="";
-
- if(IsTargetFile(hotword, "txt")){
- ifstream in(hotword);
- if (!in.is_open()) {
- LOG(ERROR) << "Failed to open file: " << hotword;
- return 0;
- }
- string line;
- while(getline(in, line))
- {
- hotwords_ +=line+HOTWORD_SEP;
- }
- in.close();
- }else{
- hotwords_ = hotword;
+ // hotwords
+ std::string hotword_path = hotword_.getValue();
+ unordered_map<string, int> hws_map;
+ if(!hotword_path.empty()){
+ LOG(INFO) << "hotword path: " << hotword_path;
+ funasr::ExtractHws(hotword_path, hws_map);
}
// read wav_path
std::vector<string> wav_list;
std::vector<string> wav_ids;
string default_id = "wav_default_id";
- if(IsTargetFile(wav_path, "scp")){
+ if(funasr::IsTargetFile(wav_path, "scp")){
ifstream in(wav_path);
if (!in.is_open()) {
printf("Failed to open scp file");
@@ -432,17 +421,17 @@ int main(int argc, char* argv[]) {
}
for (size_t i = 0; i < threads_num; i++) {
- client_threads.emplace_back([uri, wav_list, wav_ids, is_ssl, hotwords_, use_itn]() {
+ client_threads.emplace_back([uri, wav_list, wav_ids, is_ssl, hws_map, use_itn]() {
if (is_ssl == 1) {
WebsocketClient<websocketpp::config::asio_tls_client> c(is_ssl);
c.m_client.set_tls_init_handler(bind(&OnTlsInit, ::_1));
- c.run(uri, wav_list, wav_ids, hotwords_, use_itn);
+ c.run(uri, wav_list, wav_ids, hws_map, use_itn);
} else {
WebsocketClient<websocketpp::config::asio_client> c(is_ssl);
- c.run(uri, wav_list, wav_ids, hotwords_, use_itn);
+ c.run(uri, wav_list, wav_ids, hws_map, use_itn);
}
});
}
diff --git a/funasr/runtime/websocket/bin/funasr-wss-server-2pass.cpp b/runtime/websocket/bin/funasr-wss-server-2pass.cpp
similarity index 95%
rename from funasr/runtime/websocket/bin/funasr-wss-server-2pass.cpp
rename to runtime/websocket/bin/funasr-wss-server-2pass.cpp
index 1c879578c..83bcaebda 100644
--- a/funasr/runtime/websocket/bin/funasr-wss-server-2pass.cpp
+++ b/runtime/websocket/bin/funasr-wss-server-2pass.cpp
@@ -13,9 +13,12 @@
// <string>] --model-dir <string> [--] [--version] [-h]
#include <unistd.h>
#include "websocket-server-2pass.h"
-
#include <fstream>
-std::string hotwords = "";
+#include "util.h"
+
+// hotwords
+std::unordered_map<std::string, int> hws_map_;
+int fst_inc_wts_=20;
using namespace std;
void GetValue(TCLAP::ValueArg<std::string>& value_arg, string key,
@@ -23,6 +26,7 @@ void GetValue(TCLAP::ValueArg<std::string>& value_arg, string key,
model_path.insert({key, value_arg.getValue()});
LOG(INFO) << key << " : " << value_arg.getValue();
}
+
int main(int argc, char* argv[]) {
try {
google::InitGoogleLogging(argv[0]);
@@ -112,14 +116,14 @@ int main(int argc, char* argv[]) {
"connection",
false, "../../../ssl_key/server.key", "string");
- TCLAP::ValueArg<std::string> hotwordsfile(
- "", "hotword",
- "default: ../../hotwords.txt, path of hotwordsfile"
- "connection",
- false, "../../hotwords.txt", "string");
+ TCLAP::ValueArg<std::string> hotword("", HOTWORD,
+ "the hotword file, one hotword perline, Format: Hotword Weight (could be: 阿里巴巴 20)",
+ false, "/workspace/resources/hotwords.txt", "string");
+ TCLAP::ValueArg<std::int32_t> fst_inc_wts("", FST_INC_WTS,
+ "the fst hotwords incremental bias", false, 20, "int32_t");
// add file
- cmd.add(hotwordsfile);
+ cmd.add(hotword);
cmd.add(certfile);
cmd.add(keyfile);
@@ -155,6 +159,7 @@ int main(int argc, char* argv[]) {
GetValue(punc_dir, PUNC_DIR, model_path);
GetValue(punc_quant, PUNC_QUANT, model_path);
GetValue(itn_dir, ITN_DIR, model_path);
+ GetValue(hotword, HOTWORD, model_path);
GetValue(offline_model_revision, "offline-model-revision", model_path);
GetValue(online_model_revision, "online-model-revision", model_path);
@@ -429,20 +434,12 @@ int main(int argc, char* argv[]) {
std::string s_certfile = certfile.getValue();
std::string s_keyfile = keyfile.getValue();
- std::string s_hotwordsfile = hotwordsfile.getValue();
- std::string line;
- std::ifstream file(s_hotwordsfile);
- LOG(INFO) << "hotwordsfile path: " << s_hotwordsfile;
-
- if (file.is_open()) {
- while (getline(file, line)) {
- hotwords += line+HOTWORD_SEP;
- }
- LOG(INFO) << "hotwords: " << hotwords;
- file.close();
- } else {
- LOG(ERROR) << "Unable to open hotwords file: " << s_hotwordsfile;
- }
+ // hotword file
+ std::string hotword_path;
+ hotword_path = model_path.at(HOTWORD);
+ fst_inc_wts_ = fst_inc_wts.getValue();
+ LOG(INFO) << "hotword path: " << hotword_path;
+ funasr::ExtractHws(hotword_path, hws_map_);
bool is_ssl = false;
if (!s_certfile.empty()) {
@@ -487,6 +484,9 @@ int main(int argc, char* argv[]) {
websocket_srv.initAsr(model_path, s_model_thread_num); // init asr model
}
+ LOG(INFO) << "decoder-thread-num: " << s_decoder_thread_num;
+ LOG(INFO) << "io-thread-num: " << s_io_thread_num;
+ LOG(INFO) << "model-thread-num: " << s_model_thread_num;
LOG(INFO) << "asr model init finished. listen on port:" << s_port;
// Start the ASIO network io_service run loop
diff --git a/funasr/runtime/websocket/bin/funasr-wss-server.cpp b/runtime/websocket/bin/funasr-wss-server.cpp
similarity index 72%
rename from funasr/runtime/websocket/bin/funasr-wss-server.cpp
rename to runtime/websocket/bin/funasr-wss-server.cpp
index b571dbef2..c285fd3b1 100644
--- a/funasr/runtime/websocket/bin/funasr-wss-server.cpp
+++ b/runtime/websocket/bin/funasr-wss-server.cpp
@@ -12,9 +12,13 @@
// <string>] --model-dir <string> [--] [--version] [-h]
#include "websocket-server.h"
#include <unistd.h>
-
#include <fstream>
-std::string hotwords = "";
+#include "util.h"
+
+// hotwords
+std::unordered_map<std::string, int> hws_map_;
+int fst_inc_wts_=20;
+float global_beam_, lattice_beam_, am_scale_;
using namespace std;
void GetValue(TCLAP::ValueArg<std::string>& value_arg, string key,
@@ -22,6 +26,7 @@ void GetValue(TCLAP::ValueArg<std::string>& value_arg, string key,
model_path.insert({key, value_arg.getValue()});
LOG(INFO) << key << " : " << value_arg.getValue();
}
+
int main(int argc, char* argv[]) {
try {
@@ -89,27 +94,38 @@ int main(int argc, char* argv[]) {
TCLAP::ValueArg<int> decoder_thread_num(
"", "decoder-thread-num", "decoder thread num", false, 8, "int");
TCLAP::ValueArg<int> model_thread_num("", "model-thread-num",
- "model thread num", false, 4, "int");
+ "model thread num", false, 1, "int");
TCLAP::ValueArg<std::string> certfile("", "certfile",
- "default: ../../../ssl_key/server.crt, path of certficate for WSS connection. if it is empty, it will be in WS mode.",
+ "default: ../../../ssl_key/server.crt, path of certficate for WSS connection. if it is empty, it will be in WS mode.",
false, "../../../ssl_key/server.crt", "string");
TCLAP::ValueArg<std::string> keyfile("", "keyfile",
"default: ../../../ssl_key/server.key, path of keyfile for WSS connection",
false, "../../../ssl_key/server.key", "string");
- TCLAP::ValueArg<std::string> hotwordsfile(
- "", "hotword",
- "default: ../../hotwords.txt, path of hotwordsfile"
- "connection",
- false, "../../hotwords.txt", "string");
+ TCLAP::ValueArg<float> global_beam("", GLOB_BEAM, "the decoding beam for beam searching ", false, 3.0, "float");
+ TCLAP::ValueArg<float> lattice_beam("", LAT_BEAM, "the lattice generation beam for beam searching ", false, 3.0, "float");
+ TCLAP::ValueArg<float> am_scale("", AM_SCALE, "the acoustic scale for beam searching ", false, 10.0, "float");
+
+ TCLAP::ValueArg<std::string> lm_dir("", LM_DIR,
+ "the LM model path, which contains compiled models: TLG.fst, config.yaml ", false, "", "string");
+ TCLAP::ValueArg<std::string> lm_revision(
+ "", "lm-revision", "LM model revision", false, "v1.0.1", "string");
+ TCLAP::ValueArg<std::string> hotword("", HOTWORD,
+ "the hotword file, one hotword perline, Format: Hotword Weight (could be: 阿里巴巴 20)",
+ false, "/workspace/resources/hotwords.txt", "string");
+ TCLAP::ValueArg<std::int32_t> fst_inc_wts("", FST_INC_WTS,
+ "the fst hotwords incremental bias", false, 20, "int32_t");
// add file
- cmd.add(hotwordsfile);
+ cmd.add(hotword);
+ cmd.add(fst_inc_wts);
+ cmd.add(global_beam);
+ cmd.add(lattice_beam);
+ cmd.add(am_scale);
cmd.add(certfile);
cmd.add(keyfile);
-
cmd.add(download_model_dir);
cmd.add(model_dir);
cmd.add(model_revision);
@@ -122,6 +138,8 @@ int main(int argc, char* argv[]) {
cmd.add(punc_quant);
cmd.add(itn_dir);
cmd.add(itn_revision);
+ cmd.add(lm_dir);
+ cmd.add(lm_revision);
cmd.add(listen_ip);
cmd.add(port);
@@ -138,11 +156,18 @@ int main(int argc, char* argv[]) {
GetValue(punc_dir, PUNC_DIR, model_path);
GetValue(punc_quant, PUNC_QUANT, model_path);
GetValue(itn_dir, ITN_DIR, model_path);
+ GetValue(lm_dir, LM_DIR, model_path);
+ GetValue(hotword, HOTWORD, model_path);
GetValue(model_revision, "model-revision", model_path);
GetValue(vad_revision, "vad-revision", model_path);
GetValue(punc_revision, "punc-revision", model_path);
GetValue(itn_revision, "itn-revision", model_path);
+ GetValue(lm_revision, "lm-revision", model_path);
+
+ global_beam_ = global_beam.getValue();
+ lattice_beam_ = lattice_beam.getValue();
+ am_scale_ = am_scale.getValue();
// Download model form Modelscope
try{
@@ -155,6 +180,7 @@ int main(int argc, char* argv[]) {
std::string s_punc_path = model_path[PUNC_DIR];
std::string s_punc_quant = model_path[PUNC_QUANT];
std::string s_itn_path = model_path[ITN_DIR];
+ std::string s_lm_path = model_path[LM_DIR];
std::string python_cmd = "python -m funasr.utils.runtime_sdk_download_tool --type onnx --quantize True ";
@@ -218,6 +244,7 @@ int main(int argc, char* argv[]) {
if (found != std::string::npos) {
model_path["model-revision"]="v1.0.0";
s_itn_path="";
+ s_lm_path="";
}
// modelscope
@@ -246,6 +273,91 @@ int main(int argc, char* argv[]) {
LOG(INFO) << "ASR model is not set, use default.";
}
+ if (!s_itn_path.empty()) {
+ std::string python_cmd_itn;
+ std::string down_itn_path;
+ std::string down_itn_model;
+
+ if (access(s_itn_path.c_str(), F_OK) == 0) {
+ // local
+ python_cmd_itn = python_cmd + " --model-name " + s_itn_path +
+ " --export-dir ./ " + " --model_revision " +
+ model_path["itn-revision"] + " --export False ";
+ down_itn_path = s_itn_path;
+ } else {
+ // modelscope
+ LOG(INFO) << "Download model: " << s_itn_path
+ << " from modelscope : ";
+ python_cmd_itn = python_cmd + " --model-name " +
+ s_itn_path +
+ " --export-dir " + s_download_model_dir +
+ " --model_revision " + model_path["itn-revision"]
+ + " --export False ";
+ down_itn_path =
+ s_download_model_dir +
+ "/" + s_itn_path;
+ }
+
+ int ret = system(python_cmd_itn.c_str());
+ if (ret != 0) {
+ LOG(INFO) << "Failed to download model from modelscope. If you set local itn model path, you can ignore the errors.";
+ }
+ down_itn_model = down_itn_path + "/zh_itn_tagger.fst";
+
+ if (access(down_itn_model.c_str(), F_OK) != 0) {
+ LOG(ERROR) << down_itn_model << " do not exists.";
+ exit(-1);
+ } else {
+ model_path[ITN_DIR] = down_itn_path;
+ LOG(INFO) << "Set " << ITN_DIR << " : " << model_path[ITN_DIR];
+ }
+ } else {
+ LOG(INFO) << "ITN model is not set, not executed.";
+ }
+
+ if (!s_lm_path.empty() && s_lm_path != "NONE" && s_lm_path != "none") {
+ std::string python_cmd_lm;
+ std::string down_lm_path;
+ std::string down_lm_model;
+
+ if (access(s_lm_path.c_str(), F_OK) == 0) {
+ // local
+ python_cmd_lm = python_cmd + " --model-name " + s_lm_path +
+ " --export-dir ./ " + " --model_revision " +
+ model_path["lm-revision"] + " --export False ";
+ down_lm_path = s_lm_path;
+ } else {
+ // modelscope
+ LOG(INFO) << "Download model: " << s_lm_path
+ << " from modelscope : ";
+ python_cmd_lm = python_cmd + " --model-name " +
+ s_lm_path +
+ " --export-dir " + s_download_model_dir +
+ " --model_revision " + model_path["lm-revision"]
+ + " --export False ";
+ down_lm_path =
+ s_download_model_dir +
+ "/" + s_lm_path;
+ }
+
+ int ret = system(python_cmd_lm.c_str());
+ if (ret != 0) {
+ LOG(INFO) << "Failed to download model from modelscope. If you set local lm model path, you can ignore the errors.";
+ }
+ down_lm_model = down_lm_path + "/TLG.fst";
+
+ if (access(down_lm_model.c_str(), F_OK) != 0) {
+ LOG(ERROR) << down_lm_model << " do not exists.";
+ exit(-1);
+ } else {
+ model_path[LM_DIR] = down_lm_path;
+ LOG(INFO) << "Set " << LM_DIR << " : " << model_path[LM_DIR];
+ }
+ } else {
+ LOG(INFO) << "LM model is not set, not executed.";
+ model_path[LM_DIR] = "";
+ }
+
if(punc_dir.isSet() && !s_punc_path.empty()){
std::string python_cmd_punc;
std::string down_punc_path;
@@ -282,48 +394,6 @@ int main(int argc, char* argv[]) {
LOG(INFO) << "PUNC model is not set, use default.";
}
- if (!s_itn_path.empty()) {
- std::string python_cmd_itn;
- std::string down_itn_path;
- std::string down_itn_model;
-
- if (access(s_itn_path.c_str(), F_OK) == 0) {
- // local
- python_cmd_itn = python_cmd + " --model-name " + s_itn_path +
- " --export-dir ./ " + " --model_revision " +
- model_path["itn-revision"] + " --export False ";
- down_itn_path = s_itn_path;
- } else {
- // modelscope
- LOG(INFO) << "Download model: " << s_itn_path
- << " from modelscope : ";
- python_cmd_itn = python_cmd + " --model-name " +
- s_itn_path +
- " --export-dir " + s_download_model_dir +
- " --model_revision " + model_path["itn-revision"]
- + " --export False ";
- down_itn_path =
- s_download_model_dir +
- "/" + s_itn_path;
- }
-
- int ret = system(python_cmd_itn.c_str());
- if (ret != 0) {
- LOG(INFO) << "Failed to download model from modelscope. If you set local itn model path, you can ignore the errors.";
- }
- down_itn_model = down_itn_path + "/zh_itn_tagger.fst";
-
- if (access(down_itn_model.c_str(), F_OK) != 0) {
- LOG(ERROR) << down_itn_model << " do not exists.";
- exit(-1);
- } else {
- model_path[ITN_DIR] = down_itn_path;
- LOG(INFO) << "Set " << ITN_DIR << " : " << model_path[ITN_DIR];
- }
- } else {
- LOG(INFO) << "ITN model is not set, not executed.";
- }
-
} catch (std::exception const& e) {
LOG(ERROR) << "Error: " << e.what();
}
@@ -342,21 +412,13 @@ int main(int argc, char* argv[]) {
std::string s_certfile = certfile.getValue();
std::string s_keyfile = keyfile.getValue();
-
- std::string s_hotwordsfile = hotwordsfile.getValue();
- std::string line;
- std::ifstream file(s_hotwordsfile);
- LOG(INFO) << "hotwordsfile path: " << s_hotwordsfile;
-
- if (file.is_open()) {
- while (getline(file, line)) {
- hotwords += line+HOTWORD_SEP;
- }
- LOG(INFO) << "hotwords: " << hotwords;
- file.close();
- } else {
- LOG(ERROR) << "Unable to open hotwords file: " << s_hotwordsfile;
- }
+
+ // hotword file
+ std::string hotword_path;
+ hotword_path = model_path.at(HOTWORD);
+ fst_inc_wts_ = fst_inc_wts.getValue();
+ LOG(INFO) << "hotword path: " << hotword_path;
+ funasr::ExtractHws(hotword_path, hws_map_);
bool is_ssl = false;
if (!s_certfile.empty()) {
@@ -401,6 +463,9 @@ int main(int argc, char* argv[]) {
websocket_srv.initAsr(model_path, s_model_thread_num); // init asr model
}
+ LOG(INFO) << "decoder-thread-num: " << s_decoder_thread_num;
+ LOG(INFO) << "io-thread-num: " << s_io_thread_num;
+ LOG(INFO) << "model-thread-num: " << s_model_thread_num;
LOG(INFO) << "asr model init finished. listen on port:" << s_port;
// Start the ASIO network io_service run loop
diff --git a/funasr/runtime/websocket/bin/microphone.cpp b/runtime/websocket/bin/microphone.cpp
similarity index 100%
rename from funasr/runtime/websocket/bin/microphone.cpp
rename to runtime/websocket/bin/microphone.cpp
diff --git a/funasr/runtime/websocket/bin/microphone.h b/runtime/websocket/bin/microphone.h
similarity index 100%
rename from funasr/runtime/websocket/bin/microphone.h
rename to runtime/websocket/bin/microphone.h
diff --git a/funasr/runtime/websocket/bin/websocket-server-2pass.cpp b/runtime/websocket/bin/websocket-server-2pass.cpp
similarity index 90%
rename from funasr/runtime/websocket/bin/websocket-server-2pass.cpp
rename to runtime/websocket/bin/websocket-server-2pass.cpp
index a6374710d..b0d322c24 100644
--- a/funasr/runtime/websocket/bin/websocket-server-2pass.cpp
+++ b/runtime/websocket/bin/websocket-server-2pass.cpp
@@ -16,7 +16,8 @@
#include <utility>
#include <vector>
-extern std::string hotwords;
+extern std::unordered_map<std::string, int> hws_map_;
+extern int fst_inc_wts_;
context_ptr WebSocketServer::on_tls_init(tls_mode mode,
websocketpp::connection_hdl hdl,
@@ -374,33 +375,56 @@ void WebSocketServer::on_message(websocketpp::connection_hdl hdl,
if (jsonresult.contains("wav_format")) {
msg_data->msg["wav_format"] = jsonresult["wav_format"];
}
+
+ // hotwords: fst/nn
if(msg_data->hotwords_embedding == NULL){
+ std::unordered_map<std::string, int> merged_hws_map;
+ std::string nn_hotwords = "";
+
if (jsonresult["hotwords"] != nullptr) {
- msg_data->msg["hotwords"] = jsonresult["hotwords"];
- if (!msg_data->msg["hotwords"].empty()) {
- std::string hw = msg_data->msg["hotwords"];
- hw = hw + " " + hotwords;
- LOG(INFO) << "hotwords: " << hw;
- std::vector<std::vector<float>> new_hotwords_embedding = CompileHotwordEmbedding(tpass_handle, hw, ASR_TWO_PASS);
- msg_data->hotwords_embedding =
- std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
- }
- } else {
- if (hotwords.empty()) {
- std::string hw = "";
- LOG(INFO)<<"hotwords: " << hw;
- std::vector<std::vector<float>> new_hotwords_embedding= CompileHotwordEmbedding(tpass_handle, hw, ASR_TWO_PASS);
- msg_data->hotwords_embedding =
- std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
- }else {
- std::string hw = hotwords;
- LOG(INFO) << "hotwords: " << hw;
- std::vector<std::vector<float>> new_hotwords_embedding= CompileHotwordEmbedding(tpass_handle, hw, ASR_TWO_PASS);
- msg_data->hotwords_embedding =
- std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
+ std::string json_string = jsonresult["hotwords"];
+ if (!json_string.empty()){
+ nlohmann::json json_fst_hws;
+ try{
+ json_fst_hws = nlohmann::json::parse(json_string);
+ } catch (std::exception const &e)
+ {
+ LOG(ERROR)<<e.what();
+ break;
+ }
+
+ if(json_fst_hws.type() == nlohmann::json::value_t::object){
+ // fst
+ try{
+ std::unordered_map<std::string, int> client_hws_map = json_fst_hws;
+ merged_hws_map.insert(client_hws_map.begin(), client_hws_map.end());
+ } catch (const std::exception& e) {
+ LOG(INFO) << e.what();
+ }
+ }else{
+ // nn
+ std::string client_nn_hws = jsonresult["hotwords"];
+ nn_hotwords += " " + client_nn_hws;
+ LOG(INFO) << "nn hotwords: " << client_nn_hws;
+ }
}
}
+ merged_hws_map.insert(hws_map_.begin(), hws_map_.end());
+
+ // fst
+ LOG(INFO) << "hotwords: ";
+ for (const auto& pair : merged_hws_map) {
+ nn_hotwords += " " + pair.first;
+ LOG(INFO) << pair.first << " : " << pair.second;
+ }
+ // FunWfstDecoderLoadHwsRes(msg_data->decoder_handle, fst_inc_wts_, merged_hws_map);
+
+ // nn
+ std::vector<std::vector<float>> new_hotwords_embedding = CompileHotwordEmbedding(tpass_handle, nn_hotwords, ASR_TWO_PASS);
+ msg_data->hotwords_embedding =
+ std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
}
+
if (jsonresult.contains("audio_fs")) {
msg_data->msg["audio_fs"] = jsonresult["audio_fs"];
}
@@ -476,8 +500,7 @@ void WebSocketServer::on_message(websocketpp::connection_hdl hdl,
try{
// post to decode
-
- std::vector<std::vector<float>> hotwords_embedding_(*(msg_data->hotwords_embedding));
+ std::vector<std::vector<float>> hotwords_embedding_(*(msg_data->hotwords_embedding));
msg_data->strand_->post(
std::bind(&WebSocketServer::do_decoder, this,
std::move(subvector), std::move(hdl),
@@ -495,7 +518,7 @@ void WebSocketServer::on_message(websocketpp::connection_hdl hdl,
}
catch (std::exception const &e)
{
- LOG(ERROR)<<e.what();
+ LOG(ERROR)<<e.what();
}
}
} else {
diff --git a/funasr/runtime/websocket/bin/websocket-server-2pass.h b/runtime/websocket/bin/websocket-server-2pass.h
similarity index 99%
rename from funasr/runtime/websocket/bin/websocket-server-2pass.h
rename to runtime/websocket/bin/websocket-server-2pass.h
index 26962ede5..3e78a3438 100644
--- a/funasr/runtime/websocket/bin/websocket-server-2pass.h
+++ b/runtime/websocket/bin/websocket-server-2pass.h
@@ -21,6 +21,7 @@
#include <utility>
#define ASIO_STANDALONE 1 // not boost
#include <glog/logging.h>
+#include "util/text-utils.h"
#include <fstream>
#include <functional>
diff --git a/funasr/runtime/websocket/bin/websocket-server.cpp b/runtime/websocket/bin/websocket-server.cpp
similarity index 78%
rename from funasr/runtime/websocket/bin/websocket-server.cpp
rename to runtime/websocket/bin/websocket-server.cpp
index 134f5fadc..eeeafb72e 100644
--- a/funasr/runtime/websocket/bin/websocket-server.cpp
+++ b/runtime/websocket/bin/websocket-server.cpp
@@ -16,7 +16,9 @@
#include <utility>
#include <vector>
-extern std::string hotwords;
+extern std::unordered_map<std::string, int> hws_map_;
+extern int fst_inc_wts_;
+extern float global_beam_, lattice_beam_, am_scale_;
context_ptr WebSocketServer::on_tls_init(tls_mode mode,
websocketpp::connection_hdl hdl,
@@ -58,12 +60,14 @@ context_ptr WebSocketServer::on_tls_init(tls_mode mode,
// feed buffer to asr engine for decoder
void WebSocketServer::do_decoder(const std::vector<char>& buffer,
websocketpp::connection_hdl& hdl,
+ nlohmann::json& msg,
websocketpp::lib::mutex& thread_lock,
std::vector<std::vector<float>> &hotwords_embedding,
std::string wav_name,
bool itn,
int audio_fs,
- std::string wav_format) {
+ std::string wav_format,
+ FUNASR_DEC_HANDLE& decoder_handle) {
scoped_lock guard(thread_lock);
try {
int num_samples = buffer.size(); // the size of the buf
@@ -73,8 +77,8 @@ void WebSocketServer::do_decoder(const std::vector<char>& buffer,
std::string stamp_res;
try{
FUNASR_RESULT Result = FunOfflineInferBuffer(
- asr_hanlde, buffer.data(), buffer.size(), RASR_NONE, NULL,
- hotwords_embedding, audio_fs, wav_format, itn);
+ asr_handle, buffer.data(), buffer.size(), RASR_NONE, NULL,
+ hotwords_embedding, audio_fs, wav_format, itn, decoder_handle);
asr_result = ((FUNASR_RECOG_RESULT*)Result)->msg; // get decode result
stamp_res = ((FUNASR_RECOG_RESULT*)Result)->stamp;
@@ -126,6 +130,7 @@ void WebSocketServer::do_decoder(const std::vector<char>& buffer,
} catch (std::exception const& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
+ msg["access_num"]=(int)msg["access_num"]-1;
}
void WebSocketServer::on_open(websocketpp::connection_hdl hdl) {
@@ -140,6 +145,10 @@ void WebSocketServer::on_open(websocketpp::connection_hdl hdl) {
data_msg->msg["wav_name"] = "wav-default-id";
data_msg->msg["itn"] = true;
data_msg->msg["audio_fs"] = 16000;
+ data_msg->msg["access_num"] = 0; // the number of access for this object, when it is 0, we can free it saftly
+ FUNASR_DEC_HANDLE decoder_handle =
+ FunASRWfstDecoderInit(asr_handle, ASR_OFFLINE, global_beam_, lattice_beam_, am_scale_);
+ data_msg->decoder_handle = decoder_handle;
data_map.emplace(hdl, data_msg);
LOG(INFO) << "on_open, active connections: " << data_map.size();
}
@@ -173,7 +182,10 @@ void remove_hdl(
return;
}
unique_lock guard_decoder(*(data_msg->thread_lock));
- if (data_msg->msg["is_eof"]==true) {
+ if (data_msg->msg["access_num"]==0 && data_msg->msg["is_eof"]==true) {
+ FunWfstDecoderUnloadHwsRes(data_msg->decoder_handle);
+ FunASRWfstDecoderUninit(data_msg->decoder_handle);
+ data_msg->decoder_handle = nullptr;
data_map.erase(hdl);
LOG(INFO) << "remove one connection";
}
@@ -271,32 +283,54 @@ void WebSocketServer::on_message(websocketpp::connection_hdl hdl,
if (jsonresult["wav_format"] != nullptr) {
msg_data->msg["wav_format"] = jsonresult["wav_format"];
}
+
+ // hotwords: fst/nn
if(msg_data->hotwords_embedding == NULL){
+ std::unordered_map<std::string, int> merged_hws_map;
+ std::string nn_hotwords = "";
+
if (jsonresult["hotwords"] != nullptr) {
- msg_data->msg["hotwords"] = jsonresult["hotwords"];
- if (!msg_data->msg["hotwords"].empty()) {
- std::string hw = msg_data->msg["hotwords"];
- hw = hw + " " + hotwords;
- LOG(INFO) << "hotwords: " << hw;
- std::vector<std::vector<float>> new_hotwords_embedding = CompileHotwordEmbedding(asr_hanlde, hw);
- msg_data->hotwords_embedding =
- std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
- }
- } else {
- if (hotwords.empty()) {
- std::string hw = "";
- LOG(INFO)<<"hotwords: " << hw;
- std::vector<std::vector<float>> new_hotwords_embedding= CompileHotwordEmbedding(asr_hanlde, hw);
- msg_data->hotwords_embedding =
- std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
- }else {
- std::string hw = hotwords;
- LOG(INFO) << "hotwords: " << hw;
- std::vector<std::vector<float>> new_hotwords_embedding= CompileHotwordEmbedding(asr_hanlde, hw);
- msg_data->hotwords_embedding =
- std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
+ std::string json_string = jsonresult["hotwords"];
+ if (!json_string.empty()){
+ nlohmann::json json_fst_hws;
+ try{
+ json_fst_hws = nlohmann::json::parse(json_string);
+ } catch (std::exception const &e)
+ {
+ LOG(ERROR)<<e.what();
+ break;
+ }
+
+ if(json_fst_hws.type() == nlohmann::json::value_t::object){
+ // fst
+ try{
+ std::unordered_map<std::string, int> client_hws_map = json_fst_hws;
+ merged_hws_map.insert(client_hws_map.begin(), client_hws_map.end());
+ } catch (const std::exception& e) {
+ LOG(INFO) << e.what();
+ }
+ }else{
+ // nn
+ std::string client_nn_hws = jsonresult["hotwords"];
+ nn_hotwords += " " + client_nn_hws;
+ LOG(INFO) << "nn hotwords: " << client_nn_hws;
+ }
}
}
+ merged_hws_map.insert(hws_map_.begin(), hws_map_.end());
+
+ // fst
+ LOG(INFO) << "hotwords: ";
+ for (const auto& pair : merged_hws_map) {
+ nn_hotwords += " " + pair.first;
+ LOG(INFO) << pair.first << " : " << pair.second;
+ }
+ FunWfstDecoderLoadHwsRes(msg_data->decoder_handle, fst_inc_wts_, merged_hws_map);
+
+ // nn
+ std::vector<std::vector<float>> new_hotwords_embedding= CompileHotwordEmbedding(asr_handle, nn_hotwords);
+ msg_data->hotwords_embedding =
+ std::make_shared<std::vector<std::vector<float>>>(new_hotwords_embedding);
}
if (jsonresult.contains("audio_fs")) {
msg_data->msg["audio_fs"] = jsonresult["audio_fs"];
@@ -313,12 +347,15 @@ void WebSocketServer::on_message(websocketpp::connection_hdl hdl,
std::bind(&WebSocketServer::do_decoder, this,
std::move(*(sample_data_p.get())),
std::move(hdl),
+ std::ref(msg_data->msg),
std::ref(*thread_lock_p),
std::move(hotwords_embedding_),
msg_data->msg["wav_name"],
msg_data->msg["itn"],
msg_data->msg["audio_fs"],
- msg_data->msg["wav_format"]));
+ msg_data->msg["wav_format"],
+ std::ref(msg_data->decoder_handle)));
+ msg_data->msg["access_num"]=(int)(msg_data->msg["access_num"])+1;
}
break;
}
@@ -347,7 +384,7 @@ void WebSocketServer::initAsr(std::map<std::string, std::string>& model_path,
try {
// init model with api
- asr_hanlde = FunOfflineInit(model_path, thread_num);
+ asr_handle = FunOfflineInit(model_path, thread_num);
LOG(INFO) << "model successfully inited";
LOG(INFO) << "initAsr run check_and_clean_connection";
diff --git a/funasr/runtime/websocket/bin/websocket-server.h b/runtime/websocket/bin/websocket-server.h
similarity index 91%
rename from funasr/runtime/websocket/bin/websocket-server.h
rename to runtime/websocket/bin/websocket-server.h
index 3fc435a8b..d51107165 100644
--- a/funasr/runtime/websocket/bin/websocket-server.h
+++ b/runtime/websocket/bin/websocket-server.h
@@ -19,8 +19,10 @@
#include <string>
#include <thread>
#include <utility>
+#include <unordered_map>
#define ASIO_STANDALONE 1 // not boost
#include <glog/logging.h>
+#include "util/text-utils.h"
#include <fstream>
#include <functional>
@@ -57,6 +59,7 @@ typedef struct {
std::shared_ptr<std::vector<char>> samples;
std::shared_ptr<std::vector<std::vector<float>>> hotwords_embedding=NULL;
std::shared_ptr<websocketpp::lib::mutex> thread_lock; // lock for each connection
+ FUNASR_DEC_HANDLE decoder_handle=NULL;
} FUNASR_MESSAGE;
// See https://wiki.mozilla.org/Security/Server_Side_TLS for more details about
@@ -70,7 +73,7 @@ class WebSocketServer {
: io_decoder_(io_decoder),
is_ssl(is_ssl),
server_(server),
- wss_server_(wss_server) {
+ wss_server_(wss_server){
if (is_ssl) {
std::cout << "certfile path is " << s_certfile << std::endl;
wss_server->set_tls_init_handler(
@@ -111,10 +114,14 @@ class WebSocketServer {
}
void do_decoder(const std::vector<char>& buffer,
websocketpp::connection_hdl& hdl,
+ nlohmann::json& msg,
websocketpp::lib::mutex& thread_lock,
std::vector<std::vector<float>> &hotwords_embedding,
- std::string wav_name, bool itn,
- int audio_fs,std::string wav_format);
+ std::string wav_name,
+ bool itn,
+ int audio_fs,
+ std::string wav_format,
+ FUNASR_DEC_HANDLE& decoder_handle);
void initAsr(std::map<std::string, std::string>& model_path, int thread_num);
void on_message(websocketpp::connection_hdl hdl, message_ptr msg);
@@ -127,7 +134,7 @@ class WebSocketServer {
void check_and_clean_connection();
asio::io_context& io_decoder_; // threads for asr decoder
// std::ofstream fout;
- FUNASR_HANDLE asr_hanlde; // asr engine handle
+ FUNASR_HANDLE asr_handle; // asr engine handle
bool isonline = false; // online or offline engine, now only support offline
bool is_ssl = true;
server* server_; // websocket server
@@ -142,4 +149,5 @@ class WebSocketServer {
websocketpp::lib::mutex m_lock; // mutex for sample_map
};
+// std::unordered_map<std::string, int>& hws_map, int fst_inc_wts, std::string& nn_hotwords
#endif // WEBSOCKET_SERVER_H_
diff --git a/runtime/websocket/hotwords.txt b/runtime/websocket/hotwords.txt
new file mode 100644
index 000000000..f092a4a91
--- /dev/null
+++ b/runtime/websocket/hotwords.txt
@@ -0,0 +1,2 @@
+阿里巴巴 20
+通义实验室 30
diff --git a/funasr/runtime/websocket/readme.md b/runtime/websocket/readme.md
similarity index 94%
rename from funasr/runtime/websocket/readme.md
rename to runtime/websocket/readme.md
index f057caaef..11c110a5d 100644
--- a/funasr/runtime/websocket/readme.md
+++ b/runtime/websocket/readme.md
@@ -29,7 +29,7 @@ apt-get install libssl-dev #ubuntu
### Build runtime
```shell
-git clone https://github.com/alibaba-damo-academy/FunASR.git && cd FunASR/funasr/runtime/websocket
+git clone https://github.com/alibaba-damo-academy/FunASR.git && cd FunASR/runtime/websocket
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=release .. -DONNXRUNTIME_DIR=/path/to/onnxruntime-linux-x64-1.14.0 -DFFMPEG_DIR=/path/to/ffmpeg-N-111383-g20b8688092-linux64-gpl-shared
make -j 4
diff --git a/funasr/runtime/websocket/readme_zh.md b/runtime/websocket/readme_zh.md
similarity index 94%
rename from funasr/runtime/websocket/readme_zh.md
rename to runtime/websocket/readme_zh.md
index 8629eee03..a94007962 100644
--- a/funasr/runtime/websocket/readme_zh.md
+++ b/runtime/websocket/readme_zh.md
@@ -30,7 +30,7 @@ apt-get install libssl-dev #ubuntu
### 编译 runtime
```shell
-git clone https://github.com/alibaba-damo-academy/FunASR.git && cd FunASR/funasr/runtime/websocket
+git clone https://github.com/alibaba-damo-academy/FunASR.git && cd FunASR/runtime/websocket
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=release .. -DONNXRUNTIME_DIR=/path/to/onnxruntime-linux-x64-1.14.0 -DFFMPEG_DIR=/path/to/ffmpeg-N-111383-g20b8688092-linux64-gpl-shared
make -j 4
diff --git a/funasr/runtime/websocket/requirements_install.md b/runtime/websocket/requirements_install.md
similarity index 100%
rename from funasr/runtime/websocket/requirements_install.md
rename to runtime/websocket/requirements_install.md