paraformer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. /**
  2. * Copyright FunASR (https://github.com/alibaba-damo-academy/FunASR). All Rights Reserved.
  3. * MIT License (https://opensource.org/licenses/MIT)
  4. */
  5. #include "precomp.h"
  6. #include "paraformer.h"
  7. #include "encode_converter.h"
  8. #include <cstddef>
  9. using namespace std;
  10. namespace funasr {
  11. Paraformer::Paraformer()
  12. :use_hotword(false),
  13. env_(ORT_LOGGING_LEVEL_ERROR, "paraformer"),session_options_{},
  14. hw_env_(ORT_LOGGING_LEVEL_ERROR, "paraformer_hw"),hw_session_options{} {
  15. }
  16. // offline
  17. void Paraformer::InitAsr(const std::string &am_model, const std::string &am_cmvn, const std::string &am_config, int thread_num){
  18. // knf options
  19. fbank_opts_.frame_opts.dither = 0;
  20. fbank_opts_.mel_opts.num_bins = n_mels;
  21. fbank_opts_.frame_opts.samp_freq = MODEL_SAMPLE_RATE;
  22. fbank_opts_.frame_opts.window_type = window_type;
  23. fbank_opts_.frame_opts.frame_shift_ms = frame_shift;
  24. fbank_opts_.frame_opts.frame_length_ms = frame_length;
  25. fbank_opts_.energy_floor = 0;
  26. fbank_opts_.mel_opts.debug_mel = false;
  27. // fbank_ = std::make_unique<knf::OnlineFbank>(fbank_opts);
  28. // session_options_.SetInterOpNumThreads(1);
  29. session_options_.SetIntraOpNumThreads(thread_num);
  30. session_options_.SetGraphOptimizationLevel(ORT_ENABLE_ALL);
  31. // DisableCpuMemArena can improve performance
  32. session_options_.DisableCpuMemArena();
  33. try {
  34. m_session_ = std::make_unique<Ort::Session>(env_, ORTSTRING(am_model).c_str(), session_options_);
  35. LOG(INFO) << "Successfully load model from " << am_model;
  36. } catch (std::exception const &e) {
  37. LOG(ERROR) << "Error when load am onnx model: " << e.what();
  38. exit(-1);
  39. }
  40. string strName;
  41. GetInputName(m_session_.get(), strName);
  42. m_strInputNames.push_back(strName.c_str());
  43. GetInputName(m_session_.get(), strName,1);
  44. m_strInputNames.push_back(strName);
  45. if (use_hotword) {
  46. GetInputName(m_session_.get(), strName, 2);
  47. m_strInputNames.push_back(strName);
  48. }
  49. size_t numOutputNodes = m_session_->GetOutputCount();
  50. for(int index=0; index<numOutputNodes; index++){
  51. GetOutputName(m_session_.get(), strName, index);
  52. m_strOutputNames.push_back(strName);
  53. }
  54. for (auto& item : m_strInputNames)
  55. m_szInputNames.push_back(item.c_str());
  56. for (auto& item : m_strOutputNames)
  57. m_szOutputNames.push_back(item.c_str());
  58. vocab = new Vocab(am_config.c_str());
  59. LoadConfigFromYaml(am_config.c_str());
  60. phone_set_ = new PhoneSet(am_config.c_str());
  61. LoadCmvn(am_cmvn.c_str());
  62. }
  63. // online
  64. void Paraformer::InitAsr(const std::string &en_model, const std::string &de_model, const std::string &am_cmvn, const std::string &am_config, int thread_num){
  65. LoadOnlineConfigFromYaml(am_config.c_str());
  66. // knf options
  67. fbank_opts_.frame_opts.dither = 0;
  68. fbank_opts_.mel_opts.num_bins = n_mels;
  69. fbank_opts_.frame_opts.samp_freq = MODEL_SAMPLE_RATE;
  70. fbank_opts_.frame_opts.window_type = window_type;
  71. fbank_opts_.frame_opts.frame_shift_ms = frame_shift;
  72. fbank_opts_.frame_opts.frame_length_ms = frame_length;
  73. fbank_opts_.energy_floor = 0;
  74. fbank_opts_.mel_opts.debug_mel = false;
  75. // session_options_.SetInterOpNumThreads(1);
  76. session_options_.SetIntraOpNumThreads(thread_num);
  77. session_options_.SetGraphOptimizationLevel(ORT_ENABLE_ALL);
  78. // DisableCpuMemArena can improve performance
  79. session_options_.DisableCpuMemArena();
  80. try {
  81. encoder_session_ = std::make_unique<Ort::Session>(env_, ORTSTRING(en_model).c_str(), session_options_);
  82. LOG(INFO) << "Successfully load model from " << en_model;
  83. } catch (std::exception const &e) {
  84. LOG(ERROR) << "Error when load am encoder model: " << e.what();
  85. exit(-1);
  86. }
  87. try {
  88. decoder_session_ = std::make_unique<Ort::Session>(env_, ORTSTRING(de_model).c_str(), session_options_);
  89. LOG(INFO) << "Successfully load model from " << de_model;
  90. } catch (std::exception const &e) {
  91. LOG(ERROR) << "Error when load am decoder model: " << e.what();
  92. exit(-1);
  93. }
  94. // encoder
  95. string strName;
  96. GetInputName(encoder_session_.get(), strName);
  97. en_strInputNames.push_back(strName.c_str());
  98. GetInputName(encoder_session_.get(), strName,1);
  99. en_strInputNames.push_back(strName);
  100. GetOutputName(encoder_session_.get(), strName);
  101. en_strOutputNames.push_back(strName);
  102. GetOutputName(encoder_session_.get(), strName,1);
  103. en_strOutputNames.push_back(strName);
  104. GetOutputName(encoder_session_.get(), strName,2);
  105. en_strOutputNames.push_back(strName);
  106. for (auto& item : en_strInputNames)
  107. en_szInputNames_.push_back(item.c_str());
  108. for (auto& item : en_strOutputNames)
  109. en_szOutputNames_.push_back(item.c_str());
  110. // decoder
  111. int de_input_len = 4 + fsmn_layers;
  112. int de_out_len = 2 + fsmn_layers;
  113. for(int i=0;i<de_input_len; i++){
  114. GetInputName(decoder_session_.get(), strName, i);
  115. de_strInputNames.push_back(strName.c_str());
  116. }
  117. for(int i=0;i<de_out_len; i++){
  118. GetOutputName(decoder_session_.get(), strName,i);
  119. de_strOutputNames.push_back(strName);
  120. }
  121. for (auto& item : de_strInputNames)
  122. de_szInputNames_.push_back(item.c_str());
  123. for (auto& item : de_strOutputNames)
  124. de_szOutputNames_.push_back(item.c_str());
  125. vocab = new Vocab(am_config.c_str());
  126. phone_set_ = new PhoneSet(am_config.c_str());
  127. LoadCmvn(am_cmvn.c_str());
  128. }
  129. // 2pass
  130. void Paraformer::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){
  131. // online
  132. InitAsr(en_model, de_model, am_cmvn, am_config, thread_num);
  133. // offline
  134. try {
  135. m_session_ = std::make_unique<Ort::Session>(env_, ORTSTRING(am_model).c_str(), session_options_);
  136. LOG(INFO) << "Successfully load model from " << am_model;
  137. } catch (std::exception const &e) {
  138. LOG(ERROR) << "Error when load am onnx model: " << e.what();
  139. exit(-1);
  140. }
  141. string strName;
  142. GetInputName(m_session_.get(), strName);
  143. m_strInputNames.push_back(strName.c_str());
  144. GetInputName(m_session_.get(), strName,1);
  145. m_strInputNames.push_back(strName);
  146. if (use_hotword) {
  147. GetInputName(m_session_.get(), strName, 2);
  148. m_strInputNames.push_back(strName);
  149. }
  150. // support time stamp
  151. size_t numOutputNodes = m_session_->GetOutputCount();
  152. for(int index=0; index<numOutputNodes; index++){
  153. GetOutputName(m_session_.get(), strName, index);
  154. m_strOutputNames.push_back(strName);
  155. }
  156. for (auto& item : m_strInputNames)
  157. m_szInputNames.push_back(item.c_str());
  158. for (auto& item : m_strOutputNames)
  159. m_szOutputNames.push_back(item.c_str());
  160. }
  161. void Paraformer::InitLm(const std::string &lm_file,
  162. const std::string &lm_cfg_file) {
  163. try {
  164. lm_ = std::shared_ptr<fst::Fst<fst::StdArc>>(
  165. fst::Fst<fst::StdArc>::Read(lm_file));
  166. if (lm_){
  167. if (vocab) { delete vocab; }
  168. vocab = new Vocab(lm_cfg_file.c_str());
  169. LOG(INFO) << "Successfully load lm file " << lm_file;
  170. }else{
  171. LOG(ERROR) << "Failed to load lm file " << lm_file;
  172. }
  173. } catch (std::exception const &e) {
  174. LOG(ERROR) << "Error when load lm file: " << e.what();
  175. exit(0);
  176. }
  177. }
  178. void Paraformer::LoadConfigFromYaml(const char* filename){
  179. YAML::Node config;
  180. try{
  181. config = YAML::LoadFile(filename);
  182. }catch(exception const &e){
  183. LOG(ERROR) << "Error loading file, yaml file error or not exist.";
  184. exit(-1);
  185. }
  186. try{
  187. YAML::Node lang_conf = config["lang"];
  188. if (lang_conf.IsDefined()){
  189. language = lang_conf.as<string>();
  190. }
  191. }catch(exception const &e){
  192. LOG(ERROR) << "Error when load argument from vad config YAML.";
  193. exit(-1);
  194. }
  195. }
  196. void Paraformer::LoadOnlineConfigFromYaml(const char* filename){
  197. YAML::Node config;
  198. try{
  199. config = YAML::LoadFile(filename);
  200. }catch(exception const &e){
  201. LOG(ERROR) << "Error loading file, yaml file error or not exist.";
  202. exit(-1);
  203. }
  204. try{
  205. YAML::Node frontend_conf = config["frontend_conf"];
  206. YAML::Node encoder_conf = config["encoder_conf"];
  207. YAML::Node decoder_conf = config["decoder_conf"];
  208. YAML::Node predictor_conf = config["predictor_conf"];
  209. this->window_type = frontend_conf["window"].as<string>();
  210. this->n_mels = frontend_conf["n_mels"].as<int>();
  211. this->frame_length = frontend_conf["frame_length"].as<int>();
  212. this->frame_shift = frontend_conf["frame_shift"].as<int>();
  213. this->lfr_m = frontend_conf["lfr_m"].as<int>();
  214. this->lfr_n = frontend_conf["lfr_n"].as<int>();
  215. this->encoder_size = encoder_conf["output_size"].as<int>();
  216. this->fsmn_dims = encoder_conf["output_size"].as<int>();
  217. this->fsmn_layers = decoder_conf["num_blocks"].as<int>();
  218. this->fsmn_lorder = decoder_conf["kernel_size"].as<int>()-1;
  219. this->cif_threshold = predictor_conf["threshold"].as<double>();
  220. this->tail_alphas = predictor_conf["tail_threshold"].as<double>();
  221. }catch(exception const &e){
  222. LOG(ERROR) << "Error when load argument from vad config YAML.";
  223. exit(-1);
  224. }
  225. }
  226. void Paraformer::InitHwCompiler(const std::string &hw_model, int thread_num) {
  227. hw_session_options.SetIntraOpNumThreads(thread_num);
  228. hw_session_options.SetGraphOptimizationLevel(ORT_ENABLE_ALL);
  229. // DisableCpuMemArena can improve performance
  230. hw_session_options.DisableCpuMemArena();
  231. try {
  232. hw_m_session = std::make_unique<Ort::Session>(hw_env_, ORTSTRING(hw_model).c_str(), hw_session_options);
  233. LOG(INFO) << "Successfully load model from " << hw_model;
  234. } catch (std::exception const &e) {
  235. LOG(ERROR) << "Error when load hw compiler onnx model: " << e.what();
  236. exit(-1);
  237. }
  238. string strName;
  239. GetInputName(hw_m_session.get(), strName);
  240. hw_m_strInputNames.push_back(strName.c_str());
  241. //GetInputName(hw_m_session.get(), strName,1);
  242. //hw_m_strInputNames.push_back(strName);
  243. GetOutputName(hw_m_session.get(), strName);
  244. hw_m_strOutputNames.push_back(strName);
  245. for (auto& item : hw_m_strInputNames)
  246. hw_m_szInputNames.push_back(item.c_str());
  247. for (auto& item : hw_m_strOutputNames)
  248. hw_m_szOutputNames.push_back(item.c_str());
  249. // if init hotword compiler is called, this is a hotword paraformer model
  250. use_hotword = true;
  251. }
  252. void Paraformer::InitSegDict(const std::string &seg_dict_model) {
  253. seg_dict = new SegDict(seg_dict_model.c_str());
  254. }
  255. Paraformer::~Paraformer()
  256. {
  257. if(vocab){
  258. delete vocab;
  259. }
  260. if(seg_dict){
  261. delete seg_dict;
  262. }
  263. if(phone_set_){
  264. delete phone_set_;
  265. }
  266. }
  267. void Paraformer::StartUtterance()
  268. {
  269. }
  270. void Paraformer::EndUtterance()
  271. {
  272. }
  273. void Paraformer::Reset()
  274. {
  275. }
  276. void Paraformer::FbankKaldi(float sample_rate, const float* waves, int len, std::vector<std::vector<float>> &asr_feats) {
  277. knf::OnlineFbank fbank_(fbank_opts_);
  278. std::vector<float> buf(len);
  279. for (int32_t i = 0; i != len; ++i) {
  280. buf[i] = waves[i] * 32768;
  281. }
  282. fbank_.AcceptWaveform(sample_rate, buf.data(), buf.size());
  283. int32_t frames = fbank_.NumFramesReady();
  284. for (int32_t i = 0; i != frames; ++i) {
  285. const float *frame = fbank_.GetFrame(i);
  286. std::vector<float> frame_vector(frame, frame + fbank_opts_.mel_opts.num_bins);
  287. asr_feats.emplace_back(frame_vector);
  288. }
  289. }
  290. void Paraformer::LoadCmvn(const char *filename)
  291. {
  292. ifstream cmvn_stream(filename);
  293. if (!cmvn_stream.is_open()) {
  294. LOG(ERROR) << "Failed to open file: " << filename;
  295. exit(-1);
  296. }
  297. string line;
  298. while (getline(cmvn_stream, line)) {
  299. istringstream iss(line);
  300. vector<string> line_item{istream_iterator<string>{iss}, istream_iterator<string>{}};
  301. if (line_item[0] == "<AddShift>") {
  302. getline(cmvn_stream, line);
  303. istringstream means_lines_stream(line);
  304. vector<string> means_lines{istream_iterator<string>{means_lines_stream}, istream_iterator<string>{}};
  305. if (means_lines[0] == "<LearnRateCoef>") {
  306. for (int j = 3; j < means_lines.size() - 1; j++) {
  307. means_list_.push_back(stof(means_lines[j]));
  308. }
  309. continue;
  310. }
  311. }
  312. else if (line_item[0] == "<Rescale>") {
  313. getline(cmvn_stream, line);
  314. istringstream vars_lines_stream(line);
  315. vector<string> vars_lines{istream_iterator<string>{vars_lines_stream}, istream_iterator<string>{}};
  316. if (vars_lines[0] == "<LearnRateCoef>") {
  317. for (int j = 3; j < vars_lines.size() - 1; j++) {
  318. vars_list_.push_back(stof(vars_lines[j])*scale);
  319. }
  320. continue;
  321. }
  322. }
  323. }
  324. }
  325. string Paraformer::GreedySearch(float * in, int n_len, int64_t token_nums, bool is_stamp, std::vector<float> us_alphas, std::vector<float> us_cif_peak)
  326. {
  327. vector<int> hyps;
  328. int Tmax = n_len;
  329. for (int i = 0; i < Tmax; i++) {
  330. int max_idx;
  331. float max_val;
  332. FindMax(in + i * token_nums, token_nums, max_val, max_idx);
  333. hyps.push_back(max_idx);
  334. }
  335. if(!is_stamp){
  336. return vocab->Vector2StringV2(hyps, language);
  337. }else{
  338. std::vector<string> char_list;
  339. std::vector<std::vector<float>> timestamp_list;
  340. std::string res_str;
  341. vocab->Vector2String(hyps, char_list);
  342. std::vector<string> raw_char(char_list);
  343. TimestampOnnx(us_alphas, us_cif_peak, char_list, res_str, timestamp_list);
  344. return PostProcess(raw_char, timestamp_list);
  345. }
  346. }
  347. string Paraformer::BeamSearch(WfstDecoder* &wfst_decoder, float *in, int len, int64_t token_nums)
  348. {
  349. return wfst_decoder->Search(in, len, token_nums);
  350. }
  351. string Paraformer::FinalizeDecode(WfstDecoder* &wfst_decoder,
  352. bool is_stamp, std::vector<float> us_alphas, std::vector<float> us_cif_peak)
  353. {
  354. return wfst_decoder->FinalizeDecode(is_stamp, us_alphas, us_cif_peak);
  355. }
  356. void Paraformer::LfrCmvn(std::vector<std::vector<float>> &asr_feats) {
  357. std::vector<std::vector<float>> out_feats;
  358. int T = asr_feats.size();
  359. int T_lrf = ceil(1.0 * T / lfr_n);
  360. // Pad frames at start(copy first frame)
  361. for (int i = 0; i < (lfr_m - 1) / 2; i++) {
  362. asr_feats.insert(asr_feats.begin(), asr_feats[0]);
  363. }
  364. // Merge lfr_m frames as one,lfr_n frames per window
  365. T = T + (lfr_m - 1) / 2;
  366. std::vector<float> p;
  367. for (int i = 0; i < T_lrf; i++) {
  368. if (lfr_m <= T - i * lfr_n) {
  369. for (int j = 0; j < lfr_m; j++) {
  370. p.insert(p.end(), asr_feats[i * lfr_n + j].begin(), asr_feats[i * lfr_n + j].end());
  371. }
  372. out_feats.emplace_back(p);
  373. p.clear();
  374. } else {
  375. // Fill to lfr_m frames at last window if less than lfr_m frames (copy last frame)
  376. int num_padding = lfr_m - (T - i * lfr_n);
  377. for (int j = 0; j < (asr_feats.size() - i * lfr_n); j++) {
  378. p.insert(p.end(), asr_feats[i * lfr_n + j].begin(), asr_feats[i * lfr_n + j].end());
  379. }
  380. for (int j = 0; j < num_padding; j++) {
  381. p.insert(p.end(), asr_feats[asr_feats.size() - 1].begin(), asr_feats[asr_feats.size() - 1].end());
  382. }
  383. out_feats.emplace_back(p);
  384. p.clear();
  385. }
  386. }
  387. // Apply cmvn
  388. for (auto &out_feat: out_feats) {
  389. for (int j = 0; j < means_list_.size(); j++) {
  390. out_feat[j] = (out_feat[j] + means_list_[j]) * vars_list_[j];
  391. }
  392. }
  393. asr_feats = out_feats;
  394. }
  395. string Paraformer::Forward(float* din, int len, bool input_finished, const std::vector<std::vector<float>> &hw_emb, void* decoder_handle)
  396. {
  397. WfstDecoder* wfst_decoder = (WfstDecoder*)decoder_handle;
  398. int32_t in_feat_dim = fbank_opts_.mel_opts.num_bins;
  399. std::vector<std::vector<float>> asr_feats;
  400. FbankKaldi(MODEL_SAMPLE_RATE, din, len, asr_feats);
  401. if(asr_feats.size() == 0){
  402. return "";
  403. }
  404. LfrCmvn(asr_feats);
  405. int32_t feat_dim = lfr_m*in_feat_dim;
  406. int32_t num_frames = asr_feats.size();
  407. std::vector<float> wav_feats;
  408. for (const auto &frame_feat: asr_feats) {
  409. wav_feats.insert(wav_feats.end(), frame_feat.begin(), frame_feat.end());
  410. }
  411. #ifdef _WIN_X86
  412. Ort::MemoryInfo m_memoryInfo = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  413. #else
  414. Ort::MemoryInfo m_memoryInfo = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
  415. #endif
  416. const int64_t input_shape_[3] = {1, num_frames, feat_dim};
  417. Ort::Value onnx_feats = Ort::Value::CreateTensor<float>(m_memoryInfo,
  418. wav_feats.data(),
  419. wav_feats.size(),
  420. input_shape_,
  421. 3);
  422. const int64_t paraformer_length_shape[1] = {1};
  423. std::vector<int32_t> paraformer_length;
  424. paraformer_length.emplace_back(num_frames);
  425. Ort::Value onnx_feats_len = Ort::Value::CreateTensor<int32_t>(
  426. m_memoryInfo, paraformer_length.data(), paraformer_length.size(), paraformer_length_shape, 1);
  427. std::vector<Ort::Value> input_onnx;
  428. input_onnx.emplace_back(std::move(onnx_feats));
  429. input_onnx.emplace_back(std::move(onnx_feats_len));
  430. std::vector<float> embedding;
  431. try{
  432. if (use_hotword) {
  433. if(hw_emb.size()<=0){
  434. LOG(ERROR) << "hw_emb is null";
  435. return "";
  436. }
  437. //PrintMat(hw_emb, "input_clas_emb");
  438. const int64_t hotword_shape[3] = {1, static_cast<int64_t>(hw_emb.size()), static_cast<int64_t>(hw_emb[0].size())};
  439. embedding.reserve(hw_emb.size() * hw_emb[0].size());
  440. for (auto item : hw_emb) {
  441. embedding.insert(embedding.end(), item.begin(), item.end());
  442. }
  443. //LOG(INFO) << "hotword shape " << hotword_shape[0] << " " << hotword_shape[1] << " " << hotword_shape[2] << " size " << embedding.size();
  444. Ort::Value onnx_hw_emb = Ort::Value::CreateTensor<float>(
  445. m_memoryInfo, embedding.data(), embedding.size(), hotword_shape, 3);
  446. input_onnx.emplace_back(std::move(onnx_hw_emb));
  447. }
  448. }catch (std::exception const &e)
  449. {
  450. LOG(ERROR)<<e.what();
  451. return "";
  452. }
  453. string result="";
  454. try {
  455. auto outputTensor = m_session_->Run(Ort::RunOptions{nullptr}, m_szInputNames.data(), input_onnx.data(), input_onnx.size(), m_szOutputNames.data(), m_szOutputNames.size());
  456. std::vector<int64_t> outputShape = outputTensor[0].GetTensorTypeAndShapeInfo().GetShape();
  457. //LOG(INFO) << "paraformer out shape " << outputShape[0] << " " << outputShape[1] << " " << outputShape[2];
  458. int64_t outputCount = std::accumulate(outputShape.begin(), outputShape.end(), 1, std::multiplies<int64_t>());
  459. float* floatData = outputTensor[0].GetTensorMutableData<float>();
  460. auto encoder_out_lens = outputTensor[1].GetTensorMutableData<int64_t>();
  461. // timestamp
  462. if(outputTensor.size() == 4){
  463. std::vector<int64_t> us_alphas_shape = outputTensor[2].GetTensorTypeAndShapeInfo().GetShape();
  464. float* us_alphas_data = outputTensor[2].GetTensorMutableData<float>();
  465. std::vector<float> us_alphas(us_alphas_shape[1]);
  466. for (int i = 0; i < us_alphas_shape[1]; i++) {
  467. us_alphas[i] = us_alphas_data[i];
  468. }
  469. std::vector<int64_t> us_peaks_shape = outputTensor[3].GetTensorTypeAndShapeInfo().GetShape();
  470. float* us_peaks_data = outputTensor[3].GetTensorMutableData<float>();
  471. std::vector<float> us_peaks(us_peaks_shape[1]);
  472. for (int i = 0; i < us_peaks_shape[1]; i++) {
  473. us_peaks[i] = us_peaks_data[i];
  474. }
  475. if (lm_ == nullptr) {
  476. result = GreedySearch(floatData, *encoder_out_lens, outputShape[2], true, us_alphas, us_peaks);
  477. } else {
  478. result = BeamSearch(wfst_decoder, floatData, *encoder_out_lens, outputShape[2]);
  479. if (input_finished) {
  480. result = FinalizeDecode(wfst_decoder, true, us_alphas, us_peaks);
  481. }
  482. }
  483. }else{
  484. if (lm_ == nullptr) {
  485. result = GreedySearch(floatData, *encoder_out_lens, outputShape[2]);
  486. } else {
  487. result = BeamSearch(wfst_decoder, floatData, *encoder_out_lens, outputShape[2]);
  488. if (input_finished) {
  489. result = FinalizeDecode(wfst_decoder);
  490. }
  491. }
  492. }
  493. }
  494. catch (std::exception const &e)
  495. {
  496. LOG(ERROR)<<e.what();
  497. }
  498. return result;
  499. }
  500. std::vector<std::vector<float>> Paraformer::CompileHotwordEmbedding(std::string &hotwords) {
  501. int embedding_dim = encoder_size;
  502. std::vector<std::vector<float>> hw_emb;
  503. if (!use_hotword) {
  504. std::vector<float> vec(embedding_dim, 0);
  505. hw_emb.push_back(vec);
  506. return hw_emb;
  507. }
  508. int max_hotword_len = 10;
  509. std::vector<int32_t> hotword_matrix;
  510. std::vector<int32_t> lengths;
  511. int hotword_size = 1;
  512. int real_hw_size = 0;
  513. if (!hotwords.empty()) {
  514. std::vector<std::string> hotword_array = split(hotwords, ' ');
  515. hotword_size = hotword_array.size() + 1;
  516. hotword_matrix.reserve(hotword_size * max_hotword_len);
  517. for (auto hotword : hotword_array) {
  518. std::vector<std::string> chars;
  519. if (EncodeConverter::IsAllChineseCharactor((const U8CHAR_T*)hotword.c_str(), hotword.size())) {
  520. KeepChineseCharacterAndSplit(hotword, chars);
  521. } else {
  522. // for english
  523. std::vector<std::string> words = split(hotword, ' ');
  524. for (auto word : words) {
  525. std::vector<string> tokens = seg_dict->GetTokensByWord(word);
  526. chars.insert(chars.end(), tokens.begin(), tokens.end());
  527. }
  528. }
  529. if(chars.size()==0){
  530. continue;
  531. }
  532. std::vector<int32_t> hw_vector(max_hotword_len, 0);
  533. int vector_len = std::min(max_hotword_len, (int)chars.size());
  534. int chs_oov = false;
  535. for (int i=0; i<vector_len; i++) {
  536. hw_vector[i] = phone_set_->String2Id(chars[i]);
  537. if(hw_vector[i] == -1){
  538. chs_oov = true;
  539. break;
  540. }
  541. }
  542. if(chs_oov){
  543. LOG(INFO) << "OOV: " << hotword;
  544. continue;
  545. }
  546. LOG(INFO) << hotword;
  547. lengths.push_back(vector_len);
  548. real_hw_size += 1;
  549. hotword_matrix.insert(hotword_matrix.end(), hw_vector.begin(), hw_vector.end());
  550. }
  551. hotword_size = real_hw_size + 1;
  552. }
  553. std::vector<int32_t> blank_vec(max_hotword_len, 0);
  554. blank_vec[0] = 1;
  555. hotword_matrix.insert(hotword_matrix.end(), blank_vec.begin(), blank_vec.end());
  556. lengths.push_back(1);
  557. #ifdef _WIN_X86
  558. Ort::MemoryInfo m_memoryInfo = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
  559. #else
  560. Ort::MemoryInfo m_memoryInfo = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
  561. #endif
  562. const int64_t input_shape_[2] = {hotword_size, max_hotword_len};
  563. Ort::Value onnx_hotword = Ort::Value::CreateTensor<int32_t>(m_memoryInfo,
  564. (int32_t*)hotword_matrix.data(),
  565. hotword_size * max_hotword_len,
  566. input_shape_,
  567. 2);
  568. LOG(INFO) << "clas shape " << hotword_size << " " << max_hotword_len << std::endl;
  569. std::vector<Ort::Value> input_onnx;
  570. input_onnx.emplace_back(std::move(onnx_hotword));
  571. std::vector<std::vector<float>> result;
  572. try {
  573. auto outputTensor = hw_m_session->Run(Ort::RunOptions{nullptr}, hw_m_szInputNames.data(), input_onnx.data(), input_onnx.size(), hw_m_szOutputNames.data(), hw_m_szOutputNames.size());
  574. std::vector<int64_t> outputShape = outputTensor[0].GetTensorTypeAndShapeInfo().GetShape();
  575. int64_t outputCount = std::accumulate(outputShape.begin(), outputShape.end(), 1, std::multiplies<int64_t>());
  576. float* floatData = outputTensor[0].GetTensorMutableData<float>(); // shape [max_hotword_len, hotword_size, dim]
  577. // get embedding by real hotword length
  578. assert(outputShape[0] == max_hotword_len);
  579. assert(outputShape[1] == hotword_size);
  580. embedding_dim = outputShape[2];
  581. for (int j = 0; j < hotword_size; j++)
  582. {
  583. int start_pos = hotword_size * (lengths[j] - 1) * embedding_dim + j * embedding_dim;
  584. std::vector<float> embedding;
  585. embedding.insert(embedding.begin(), floatData + start_pos, floatData + start_pos + embedding_dim);
  586. result.push_back(embedding);
  587. }
  588. }
  589. catch (std::exception const &e)
  590. {
  591. LOG(ERROR)<<e.what();
  592. }
  593. //PrintMat(result, "clas_embedding_output");
  594. return result;
  595. }
  596. Vocab* Paraformer::GetVocab()
  597. {
  598. return vocab;
  599. }
  600. PhoneSet* Paraformer::GetPhoneSet()
  601. {
  602. return phone_set_;
  603. }
  604. string Paraformer::Rescoring()
  605. {
  606. LOG(ERROR)<<"Not Imp!!!!!!";
  607. return "";
  608. }
  609. } // namespace funasr