lattice-incremental-decoder.cc 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  1. // decoder/lattice-incremental-decoder.cc
  2. // Copyright 2019 Zhehuai Chen, Daniel Povey
  3. // See ../../COPYING for clarification regarding multiple authors
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  12. // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  13. // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  14. // MERCHANTABLITY OR NON-INFRINGEMENT.
  15. // See the Apache 2 License for the specific language governing permissions and
  16. // limitations under the License.
  17. #include "decoder/lattice-incremental-decoder.h"
  18. #include "lat/lattice-functions.h"
  19. #include "base/timer.h"
  20. namespace kaldi {
  21. // instantiate this class once for each thing you have to decode.
  22. template <typename FST, typename Token>
  23. LatticeIncrementalDecoderTpl<FST, Token>::LatticeIncrementalDecoderTpl(
  24. const FST &fst, const TransitionInformation &trans_model,
  25. const LatticeIncrementalDecoderConfig &config)
  26. : fst_(&fst),
  27. delete_fst_(false),
  28. num_toks_(0),
  29. config_(config),
  30. determinizer_(trans_model, config) {
  31. config.Check();
  32. toks_.SetSize(1000); // just so on the first frame we do something reasonable.
  33. }
  34. template <typename FST, typename Token>
  35. LatticeIncrementalDecoderTpl<FST, Token>::LatticeIncrementalDecoderTpl(
  36. const LatticeIncrementalDecoderConfig &config, FST *fst,
  37. const TransitionInformation &trans_model)
  38. : fst_(fst),
  39. delete_fst_(true),
  40. num_toks_(0),
  41. config_(config),
  42. determinizer_(trans_model, config) {
  43. config.Check();
  44. toks_.SetSize(1000); // just so on the first frame we do something reasonable.
  45. }
  46. template <typename FST, typename Token>
  47. LatticeIncrementalDecoderTpl<FST, Token>::~LatticeIncrementalDecoderTpl() {
  48. DeleteElems(toks_.Clear());
  49. ClearActiveTokens();
  50. if (delete_fst_) delete fst_;
  51. }
  52. template <typename FST, typename Token>
  53. void LatticeIncrementalDecoderTpl<FST, Token>::InitDecoding() {
  54. // clean up from last time:
  55. DeleteElems(toks_.Clear());
  56. cost_offsets_.clear();
  57. ClearActiveTokens();
  58. warned_ = false;
  59. num_toks_ = 0;
  60. decoding_finalized_ = false;
  61. final_costs_.clear();
  62. StateId start_state = fst_->Start();
  63. KALDI_ASSERT(start_state != fst::kNoStateId);
  64. active_toks_.resize(1);
  65. Token *start_tok = new Token(0.0, 0.0, NULL, NULL, NULL);
  66. active_toks_[0].toks = start_tok;
  67. toks_.Insert(start_state, start_tok);
  68. num_toks_++;
  69. determinizer_.Init();
  70. num_frames_in_lattice_ = 0;
  71. token2label_map_.clear();
  72. next_token_label_ = LatticeIncrementalDeterminizer::kTokenLabelOffset;
  73. ProcessNonemitting(config_.beam);
  74. }
  75. template <typename FST, typename Token>
  76. void LatticeIncrementalDecoderTpl<FST, Token>::UpdateLatticeDeterminization() {
  77. if (NumFramesDecoded() - num_frames_in_lattice_ <
  78. config_.determinize_max_delay)
  79. return;
  80. /* Make sure the token-pruning is active. Note: PruneActiveTokens() has
  81. internal logic that prevents it from doing unnecessary work if you
  82. call it and then immediately call it again. */
  83. PruneActiveTokens(config_.lattice_beam * config_.prune_scale);
  84. int32 first = num_frames_in_lattice_ + config_.determinize_min_chunk_size,
  85. last = NumFramesDecoded(),
  86. fewest_tokens = std::numeric_limits<int32>::max(),
  87. best_frame = -1;
  88. for (int32 t = last; t >= first; t--) {
  89. /* Make sure PruneActiveTokens() has computed num_toks for all these
  90. frames... */
  91. KALDI_ASSERT(active_toks_[t].num_toks != -1);
  92. if (active_toks_[t].num_toks < fewest_tokens) {
  93. // <= because we want the latest one in case of ties.
  94. fewest_tokens = active_toks_[t].num_toks;
  95. best_frame = t;
  96. }
  97. }
  98. /* Skip this update if we have too many tokens, determinization will take too long,
  99. postpone it to the next update */
  100. if (fewest_tokens > config_.determinize_max_active)
  101. return;
  102. /* OK, determinize the chunk that spans from num_frames_in_lattice_ to
  103. best_frame. */
  104. bool use_final_probs = false;
  105. GetLattice(best_frame, use_final_probs);
  106. return;
  107. }
  108. // Returns true if any kind of traceback is available (not necessarily from
  109. // a final state). It should only very rarely return false; this indicates
  110. // an unusual search error.
  111. template <typename FST, typename Token>
  112. bool LatticeIncrementalDecoderTpl<FST, Token>::Decode(DecodableInterface *decodable) {
  113. InitDecoding();
  114. // We use 1-based indexing for frames in this decoder (if you view it in
  115. // terms of features), but note that the decodable object uses zero-based
  116. // numbering, which we have to correct for when we call it.
  117. while (!decodable->IsLastFrame(NumFramesDecoded() - 1)) {
  118. if (NumFramesDecoded() % config_.prune_interval == 0) {
  119. PruneActiveTokens(config_.lattice_beam * config_.prune_scale);
  120. }
  121. UpdateLatticeDeterminization();
  122. BaseFloat cost_cutoff = ProcessEmitting(decodable);
  123. ProcessNonemitting(cost_cutoff);
  124. }
  125. Timer timer;
  126. FinalizeDecoding();
  127. bool use_final_probs = true;
  128. GetLattice(NumFramesDecoded(), use_final_probs);
  129. KALDI_VLOG(2) << "Delay time during and after FinalizeDecoding()"
  130. << "(secs): " << timer.Elapsed();
  131. // Returns true if we have any kind of traceback available (not necessarily
  132. // to the end state; query ReachedFinal() for that).
  133. return !active_toks_.empty() && active_toks_.back().toks != NULL;
  134. }
  135. template <typename FST, typename Token>
  136. void LatticeIncrementalDecoderTpl<FST, Token>::PossiblyResizeHash(size_t num_toks) {
  137. size_t new_sz =
  138. static_cast<size_t>(static_cast<BaseFloat>(num_toks) * config_.hash_ratio);
  139. if (new_sz > toks_.Size()) {
  140. toks_.SetSize(new_sz);
  141. }
  142. }
  143. /*
  144. A note on the definition of extra_cost.
  145. extra_cost is used in pruning tokens, to save memory.
  146. extra_cost can be thought of as a beta (backward) cost assuming
  147. we had set the betas on currently-active tokens to all be the negative
  148. of the alphas for those tokens. (So all currently active tokens would
  149. be on (tied) best paths).
  150. Define the 'forward cost' of a token as zero for any token on the frame
  151. we're currently decoding; and for other frames, as the shortest-path cost
  152. between that token and a token on the frame we're currently decoding.
  153. (by "currently decoding" I mean the most recently processed frame).
  154. Then define the extra_cost of a token (always >= 0) as the forward-cost of
  155. the token minus the smallest forward-cost of any token on the same frame.
  156. We can use the extra_cost to accurately prune away tokens that we know will
  157. never appear in the lattice. If the extra_cost is greater than the desired
  158. lattice beam, the token would provably never appear in the lattice, so we can
  159. prune away the token.
  160. The advantage of storing the extra_cost rather than the forward-cost, is that
  161. it is less costly to keep the extra_cost up-to-date when we process new frames.
  162. When we process a new frame, *all* the previous frames' forward-costs would change;
  163. but in general the extra_cost will change only for a finite number of frames.
  164. (Actually we don't update all the extra_costs every time we update a frame; we
  165. only do it every 'config_.prune_interval' frames).
  166. */
  167. // FindOrAddToken either locates a token in hash of toks_,
  168. // or if necessary inserts a new, empty token (i.e. with no forward links)
  169. // for the current frame. [note: it's inserted if necessary into hash toks_
  170. // and also into the singly linked list of tokens active on this frame
  171. // (whose head is at active_toks_[frame]).
  172. template <typename FST, typename Token>
  173. inline Token *LatticeIncrementalDecoderTpl<FST, Token>::FindOrAddToken(
  174. StateId state, int32 frame_plus_one, BaseFloat tot_cost, Token *backpointer,
  175. bool *changed) {
  176. // Returns the Token pointer. Sets "changed" (if non-NULL) to true
  177. // if the token was newly created or the cost changed.
  178. KALDI_ASSERT(frame_plus_one < active_toks_.size());
  179. Token *&toks = active_toks_[frame_plus_one].toks;
  180. Elem *e_found = toks_.Find(state);
  181. if (e_found == NULL) { // no such token presently.
  182. const BaseFloat extra_cost = 0.0;
  183. // tokens on the currently final frame have zero extra_cost
  184. // as any of them could end up
  185. // on the winning path.
  186. Token *new_tok = new Token(tot_cost, extra_cost, NULL, toks, backpointer);
  187. // NULL: no forward links yet
  188. toks = new_tok;
  189. num_toks_++;
  190. toks_.Insert(state, new_tok);
  191. if (changed) *changed = true;
  192. return new_tok;
  193. } else {
  194. Token *tok = e_found->val; // There is an existing Token for this state.
  195. if (tok->tot_cost > tot_cost) { // replace old token
  196. tok->tot_cost = tot_cost;
  197. // SetBackpointer() just does tok->backpointer = backpointer in
  198. // the case where Token == BackpointerToken, else nothing.
  199. tok->SetBackpointer(backpointer);
  200. // we don't allocate a new token, the old stays linked in active_toks_
  201. // we only replace the tot_cost
  202. // in the current frame, there are no forward links (and no extra_cost)
  203. // only in ProcessNonemitting we have to delete forward links
  204. // in case we visit a state for the second time
  205. // those forward links, that lead to this replaced token before:
  206. // they remain and will hopefully be pruned later (PruneForwardLinks...)
  207. if (changed) *changed = true;
  208. } else {
  209. if (changed) *changed = false;
  210. }
  211. return tok;
  212. }
  213. }
  214. // prunes outgoing links for all tokens in active_toks_[frame]
  215. // it's called by PruneActiveTokens
  216. // all links, that have link_extra_cost > lattice_beam are pruned
  217. template <typename FST, typename Token>
  218. void LatticeIncrementalDecoderTpl<FST, Token>::PruneForwardLinks(
  219. int32 frame_plus_one, bool *extra_costs_changed, bool *links_pruned,
  220. BaseFloat delta) {
  221. // delta is the amount by which the extra_costs must change
  222. // If delta is larger, we'll tend to go back less far
  223. // toward the beginning of the file.
  224. // extra_costs_changed is set to true if extra_cost was changed for any token
  225. // links_pruned is set to true if any link in any token was pruned
  226. *extra_costs_changed = false;
  227. *links_pruned = false;
  228. KALDI_ASSERT(frame_plus_one >= 0 && frame_plus_one < active_toks_.size());
  229. if (active_toks_[frame_plus_one].toks == NULL) { // empty list; should not happen.
  230. if (!warned_) {
  231. KALDI_WARN << "No tokens alive [doing pruning].. warning first "
  232. "time only for each utterance\n";
  233. warned_ = true;
  234. }
  235. }
  236. // We have to iterate until there is no more change, because the links
  237. // are not guaranteed to be in topological order.
  238. bool changed = true; // difference new minus old extra cost >= delta ?
  239. while (changed) {
  240. changed = false;
  241. for (Token *tok = active_toks_[frame_plus_one].toks; tok != NULL;
  242. tok = tok->next) {
  243. ForwardLinkT *link, *prev_link = NULL;
  244. // will recompute tok_extra_cost for tok.
  245. BaseFloat tok_extra_cost = std::numeric_limits<BaseFloat>::infinity();
  246. // tok_extra_cost is the best (min) of link_extra_cost of outgoing links
  247. for (link = tok->links; link != NULL;) {
  248. // See if we need to excise this link...
  249. Token *next_tok = link->next_tok;
  250. BaseFloat link_extra_cost =
  251. next_tok->extra_cost +
  252. ((tok->tot_cost + link->acoustic_cost + link->graph_cost) -
  253. next_tok->tot_cost); // difference in brackets is >= 0
  254. // link_exta_cost is the difference in score between the best paths
  255. // through link source state and through link destination state
  256. KALDI_ASSERT(link_extra_cost == link_extra_cost); // check for NaN
  257. if (link_extra_cost > config_.lattice_beam) { // excise link
  258. ForwardLinkT *next_link = link->next;
  259. if (prev_link != NULL)
  260. prev_link->next = next_link;
  261. else
  262. tok->links = next_link;
  263. delete link;
  264. link = next_link; // advance link but leave prev_link the same.
  265. *links_pruned = true;
  266. } else { // keep the link and update the tok_extra_cost if needed.
  267. if (link_extra_cost < 0.0) { // this is just a precaution.
  268. if (link_extra_cost < -0.01)
  269. KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
  270. link_extra_cost = 0.0;
  271. }
  272. if (link_extra_cost < tok_extra_cost) tok_extra_cost = link_extra_cost;
  273. prev_link = link; // move to next link
  274. link = link->next;
  275. }
  276. } // for all outgoing links
  277. if (fabs(tok_extra_cost - tok->extra_cost) > delta)
  278. changed = true; // difference new minus old is bigger than delta
  279. tok->extra_cost = tok_extra_cost;
  280. // will be +infinity or <= lattice_beam_.
  281. // infinity indicates, that no forward link survived pruning
  282. } // for all Token on active_toks_[frame]
  283. if (changed) *extra_costs_changed = true;
  284. // Note: it's theoretically possible that aggressive compiler
  285. // optimizations could cause an infinite loop here for small delta and
  286. // high-dynamic-range scores.
  287. } // while changed
  288. }
  289. // PruneForwardLinksFinal is a version of PruneForwardLinks that we call
  290. // on the final frame. If there are final tokens active, it uses
  291. // the final-probs for pruning, otherwise it treats all tokens as final.
  292. template <typename FST, typename Token>
  293. void LatticeIncrementalDecoderTpl<FST, Token>::PruneForwardLinksFinal() {
  294. KALDI_ASSERT(!active_toks_.empty());
  295. int32 frame_plus_one = active_toks_.size() - 1;
  296. if (active_toks_[frame_plus_one].toks == NULL) // empty list; should not happen.
  297. KALDI_WARN << "No tokens alive at end of file";
  298. typedef typename unordered_map<Token *, BaseFloat>::const_iterator IterType;
  299. ComputeFinalCosts(&final_costs_, &final_relative_cost_, &final_best_cost_);
  300. decoding_finalized_ = true;
  301. // We call DeleteElems() as a nicety, not because it's really necessary;
  302. // otherwise there would be a time, after calling PruneTokensForFrame() on the
  303. // final frame, when toks_.GetList() or toks_.Clear() would contain pointers
  304. // to nonexistent tokens.
  305. DeleteElems(toks_.Clear());
  306. // Now go through tokens on this frame, pruning forward links... may have to
  307. // iterate a few times until there is no more change, because the list is not
  308. // in topological order. This is a modified version of the code in
  309. // PruneForwardLinks, but here we also take account of the final-probs.
  310. bool changed = true;
  311. BaseFloat delta = 1.0e-05;
  312. while (changed) {
  313. changed = false;
  314. for (Token *tok = active_toks_[frame_plus_one].toks; tok != NULL;
  315. tok = tok->next) {
  316. ForwardLinkT *link, *prev_link = NULL;
  317. // will recompute tok_extra_cost. It has a term in it that corresponds
  318. // to the "final-prob", so instead of initializing tok_extra_cost to infinity
  319. // below we set it to the difference between the (score+final_prob) of this
  320. // token,
  321. // and the best such (score+final_prob).
  322. BaseFloat final_cost;
  323. if (final_costs_.empty()) {
  324. final_cost = 0.0;
  325. } else {
  326. IterType iter = final_costs_.find(tok);
  327. if (iter != final_costs_.end())
  328. final_cost = iter->second;
  329. else
  330. final_cost = std::numeric_limits<BaseFloat>::infinity();
  331. }
  332. BaseFloat tok_extra_cost = tok->tot_cost + final_cost - final_best_cost_;
  333. // tok_extra_cost will be a "min" over either directly being final, or
  334. // being indirectly final through other links, and the loop below may
  335. // decrease its value:
  336. for (link = tok->links; link != NULL;) {
  337. // See if we need to excise this link...
  338. Token *next_tok = link->next_tok;
  339. BaseFloat link_extra_cost =
  340. next_tok->extra_cost +
  341. ((tok->tot_cost + link->acoustic_cost + link->graph_cost) -
  342. next_tok->tot_cost);
  343. if (link_extra_cost > config_.lattice_beam) { // excise link
  344. ForwardLinkT *next_link = link->next;
  345. if (prev_link != NULL)
  346. prev_link->next = next_link;
  347. else
  348. tok->links = next_link;
  349. delete link;
  350. link = next_link; // advance link but leave prev_link the same.
  351. } else { // keep the link and update the tok_extra_cost if needed.
  352. if (link_extra_cost < 0.0) { // this is just a precaution.
  353. if (link_extra_cost < -0.01)
  354. KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
  355. link_extra_cost = 0.0;
  356. }
  357. if (link_extra_cost < tok_extra_cost) tok_extra_cost = link_extra_cost;
  358. prev_link = link;
  359. link = link->next;
  360. }
  361. }
  362. // prune away tokens worse than lattice_beam above best path. This step
  363. // was not necessary in the non-final case because then, this case
  364. // showed up as having no forward links. Here, the tok_extra_cost has
  365. // an extra component relating to the final-prob.
  366. if (tok_extra_cost > config_.lattice_beam)
  367. tok_extra_cost = std::numeric_limits<BaseFloat>::infinity();
  368. // to be pruned in PruneTokensForFrame
  369. if (!ApproxEqual(tok->extra_cost, tok_extra_cost, delta)) changed = true;
  370. tok->extra_cost = tok_extra_cost; // will be +infinity or <= lattice_beam_.
  371. }
  372. } // while changed
  373. }
  374. template <typename FST, typename Token>
  375. BaseFloat LatticeIncrementalDecoderTpl<FST, Token>::FinalRelativeCost() const {
  376. BaseFloat relative_cost;
  377. ComputeFinalCosts(NULL, &relative_cost, NULL);
  378. return relative_cost;
  379. }
  380. // Prune away any tokens on this frame that have no forward links.
  381. // [we don't do this in PruneForwardLinks because it would give us
  382. // a problem with dangling pointers].
  383. // It's called by PruneActiveTokens if any forward links have been pruned
  384. template <typename FST, typename Token>
  385. void LatticeIncrementalDecoderTpl<FST, Token>::PruneTokensForFrame(
  386. int32 frame_plus_one) {
  387. KALDI_ASSERT(frame_plus_one >= 0 && frame_plus_one < active_toks_.size());
  388. Token *&toks = active_toks_[frame_plus_one].toks;
  389. if (toks == NULL) KALDI_WARN << "No tokens alive [doing pruning]";
  390. Token *tok, *next_tok, *prev_tok = NULL;
  391. int32 num_toks = 0;
  392. for (tok = toks; tok != NULL; tok = next_tok, num_toks++) {
  393. next_tok = tok->next;
  394. if (tok->extra_cost == std::numeric_limits<BaseFloat>::infinity()) {
  395. // token is unreachable from end of graph; (no forward links survived)
  396. // excise tok from list and delete tok.
  397. if (prev_tok != NULL)
  398. prev_tok->next = tok->next;
  399. else
  400. toks = tok->next;
  401. delete tok;
  402. num_toks_--;
  403. } else { // fetch next Token
  404. prev_tok = tok;
  405. }
  406. }
  407. active_toks_[frame_plus_one].num_toks = num_toks;
  408. }
  409. // Go backwards through still-alive tokens, pruning them, starting not from
  410. // the current frame (where we want to keep all tokens) but from the frame before
  411. // that. We go backwards through the frames and stop when we reach a point
  412. // where the delta-costs are not changing (and the delta controls when we consider
  413. // a cost to have "not changed").
  414. template <typename FST, typename Token>
  415. void LatticeIncrementalDecoderTpl<FST, Token>::PruneActiveTokens(BaseFloat delta) {
  416. int32 cur_frame_plus_one = NumFramesDecoded();
  417. int32 num_toks_begin = num_toks_;
  418. if (active_toks_[cur_frame_plus_one].num_toks == -1){
  419. // The current frame's tokens don't get pruned so they don't get counted
  420. // (the count is needed by the incremental determinization code).
  421. // Fix this.
  422. int this_frame_num_toks = 0;
  423. for (Token *t = active_toks_[cur_frame_plus_one].toks; t != NULL; t = t->next)
  424. this_frame_num_toks++;
  425. active_toks_[cur_frame_plus_one].num_toks = this_frame_num_toks;
  426. }
  427. // The index "f" below represents a "frame plus one", i.e. you'd have to subtract
  428. // one to get the corresponding index for the decodable object.
  429. for (int32 f = cur_frame_plus_one - 1; f >= 0; f--) {
  430. // Reason why we need to prune forward links in this situation:
  431. // (1) we have never pruned them (new TokenList)
  432. // (2) we have not yet pruned the forward links to the next f,
  433. // after any of those tokens have changed their extra_cost.
  434. if (active_toks_[f].must_prune_forward_links) {
  435. bool extra_costs_changed = false, links_pruned = false;
  436. PruneForwardLinks(f, &extra_costs_changed, &links_pruned, delta);
  437. if (extra_costs_changed && f > 0) // any token has changed extra_cost
  438. active_toks_[f - 1].must_prune_forward_links = true;
  439. if (links_pruned) // any link was pruned
  440. active_toks_[f].must_prune_tokens = true;
  441. active_toks_[f].must_prune_forward_links = false; // job done
  442. }
  443. if (f + 1 < cur_frame_plus_one && // except for last f (no forward links)
  444. active_toks_[f + 1].must_prune_tokens) {
  445. PruneTokensForFrame(f + 1);
  446. active_toks_[f + 1].must_prune_tokens = false;
  447. }
  448. }
  449. KALDI_VLOG(4) << "pruned tokens from " << num_toks_begin
  450. << " to " << num_toks_;
  451. }
  452. template <typename FST, typename Token>
  453. void LatticeIncrementalDecoderTpl<FST, Token>::ComputeFinalCosts(
  454. unordered_map<Token *, BaseFloat> *final_costs, BaseFloat *final_relative_cost,
  455. BaseFloat *final_best_cost) const {
  456. if (decoding_finalized_) {
  457. // If we finalized decoding, the list toks_ will no longer exist, so return
  458. // something we already computed.
  459. if (final_costs) *final_costs = final_costs_;
  460. if (final_relative_cost) *final_relative_cost = final_relative_cost_;
  461. if (final_best_cost) *final_best_cost = final_best_cost_;
  462. return;
  463. }
  464. if (final_costs != NULL) final_costs->clear();
  465. const Elem *final_toks = toks_.GetList();
  466. BaseFloat infinity = std::numeric_limits<BaseFloat>::infinity();
  467. BaseFloat best_cost = infinity, best_cost_with_final = infinity;
  468. while (final_toks != NULL) {
  469. StateId state = final_toks->key;
  470. Token *tok = final_toks->val;
  471. const Elem *next = final_toks->tail;
  472. BaseFloat final_cost = fst_->Final(state).Value();
  473. BaseFloat cost = tok->tot_cost, cost_with_final = cost + final_cost;
  474. best_cost = std::min(cost, best_cost);
  475. best_cost_with_final = std::min(cost_with_final, best_cost_with_final);
  476. if (final_costs != NULL && final_cost != infinity)
  477. (*final_costs)[tok] = final_cost;
  478. final_toks = next;
  479. }
  480. if (final_relative_cost != NULL) {
  481. if (best_cost == infinity && best_cost_with_final == infinity) {
  482. // Likely this will only happen if there are no tokens surviving.
  483. // This seems the least bad way to handle it.
  484. *final_relative_cost = infinity;
  485. } else {
  486. *final_relative_cost = best_cost_with_final - best_cost;
  487. }
  488. }
  489. if (final_best_cost != NULL) {
  490. if (best_cost_with_final != infinity) { // final-state exists.
  491. *final_best_cost = best_cost_with_final;
  492. } else { // no final-state exists.
  493. *final_best_cost = best_cost;
  494. }
  495. }
  496. }
  497. template <typename FST, typename Token>
  498. void LatticeIncrementalDecoderTpl<FST, Token>::AdvanceDecoding(
  499. DecodableInterface *decodable, int32 max_num_frames) {
  500. if (std::is_same<FST, fst::Fst<fst::StdArc> >::value) {
  501. // if the type 'FST' is the FST base-class, then see if the FST type of fst_
  502. // is actually VectorFst or ConstFst. If so, call the AdvanceDecoding()
  503. // function after casting *this to the more specific type.
  504. if (fst_->Type() == "const") {
  505. LatticeIncrementalDecoderTpl<fst::ConstFst<fst::StdArc>, Token> *this_cast =
  506. reinterpret_cast<
  507. LatticeIncrementalDecoderTpl<fst::ConstFst<fst::StdArc>, Token> *>(
  508. this);
  509. this_cast->AdvanceDecoding(decodable, max_num_frames);
  510. return;
  511. } else if (fst_->Type() == "vector") {
  512. LatticeIncrementalDecoderTpl<fst::VectorFst<fst::StdArc>, Token> *this_cast =
  513. reinterpret_cast<
  514. LatticeIncrementalDecoderTpl<fst::VectorFst<fst::StdArc>, Token> *>(
  515. this);
  516. this_cast->AdvanceDecoding(decodable, max_num_frames);
  517. return;
  518. }
  519. }
  520. KALDI_ASSERT(!active_toks_.empty() && !decoding_finalized_ &&
  521. "You must call InitDecoding() before AdvanceDecoding");
  522. int32 num_frames_ready = decodable->NumFramesReady();
  523. // num_frames_ready must be >= num_frames_decoded, or else
  524. // the number of frames ready must have decreased (which doesn't
  525. // make sense) or the decodable object changed between calls
  526. // (which isn't allowed).
  527. KALDI_ASSERT(num_frames_ready >= NumFramesDecoded());
  528. int32 target_frames_decoded = num_frames_ready;
  529. if (max_num_frames >= 0)
  530. target_frames_decoded =
  531. std::min(target_frames_decoded, NumFramesDecoded() + max_num_frames);
  532. while (NumFramesDecoded() < target_frames_decoded) {
  533. if (NumFramesDecoded() % config_.prune_interval == 0) {
  534. PruneActiveTokens(config_.lattice_beam * config_.prune_scale);
  535. }
  536. BaseFloat cost_cutoff = ProcessEmitting(decodable);
  537. ProcessNonemitting(cost_cutoff);
  538. }
  539. UpdateLatticeDeterminization();
  540. }
  541. // FinalizeDecoding() is a version of PruneActiveTokens that we call
  542. // (optionally) on the final frame. Takes into account the final-prob of
  543. // tokens. This function used to be called PruneActiveTokensFinal().
  544. template <typename FST, typename Token>
  545. void LatticeIncrementalDecoderTpl<FST, Token>::FinalizeDecoding() {
  546. int32 final_frame_plus_one = NumFramesDecoded();
  547. int32 num_toks_begin = num_toks_;
  548. // PruneForwardLinksFinal() prunes the final frame (with final-probs), and
  549. // sets decoding_finalized_.
  550. PruneForwardLinksFinal();
  551. for (int32 f = final_frame_plus_one - 1; f >= 0; f--) {
  552. bool b1, b2; // values not used.
  553. BaseFloat dontcare = 0.0; // delta of zero means we must always update
  554. PruneForwardLinks(f, &b1, &b2, dontcare);
  555. PruneTokensForFrame(f + 1);
  556. }
  557. PruneTokensForFrame(0);
  558. KALDI_VLOG(4) << "pruned tokens from " << num_toks_begin << " to " << num_toks_;
  559. }
  560. /// Gets the weight cutoff. Also counts the active tokens.
  561. template <typename FST, typename Token>
  562. BaseFloat LatticeIncrementalDecoderTpl<FST, Token>::GetCutoff(
  563. Elem *list_head, size_t *tok_count, BaseFloat *adaptive_beam, Elem **best_elem) {
  564. BaseFloat best_weight = std::numeric_limits<BaseFloat>::infinity();
  565. // positive == high cost == bad.
  566. size_t count = 0;
  567. if (config_.max_active == std::numeric_limits<int32>::max() &&
  568. config_.min_active == 0) {
  569. for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
  570. BaseFloat w = static_cast<BaseFloat>(e->val->tot_cost);
  571. if (w < best_weight) {
  572. best_weight = w;
  573. if (best_elem) *best_elem = e;
  574. }
  575. }
  576. if (tok_count != NULL) *tok_count = count;
  577. if (adaptive_beam != NULL) *adaptive_beam = config_.beam;
  578. return best_weight + config_.beam;
  579. } else {
  580. tmp_array_.clear();
  581. for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
  582. BaseFloat w = e->val->tot_cost;
  583. tmp_array_.push_back(w);
  584. if (w < best_weight) {
  585. best_weight = w;
  586. if (best_elem) *best_elem = e;
  587. }
  588. }
  589. if (tok_count != NULL) *tok_count = count;
  590. BaseFloat beam_cutoff = best_weight + config_.beam,
  591. min_active_cutoff = std::numeric_limits<BaseFloat>::infinity(),
  592. max_active_cutoff = std::numeric_limits<BaseFloat>::infinity();
  593. KALDI_VLOG(6) << "Number of tokens active on frame " << NumFramesDecoded()
  594. << " is " << tmp_array_.size();
  595. if (tmp_array_.size() > static_cast<size_t>(config_.max_active)) {
  596. std::nth_element(tmp_array_.begin(), tmp_array_.begin() + config_.max_active,
  597. tmp_array_.end());
  598. max_active_cutoff = tmp_array_[config_.max_active];
  599. }
  600. if (max_active_cutoff < beam_cutoff) { // max_active is tighter than beam.
  601. if (adaptive_beam)
  602. *adaptive_beam = max_active_cutoff - best_weight + config_.beam_delta;
  603. return max_active_cutoff;
  604. }
  605. if (tmp_array_.size() > static_cast<size_t>(config_.min_active)) {
  606. if (config_.min_active == 0)
  607. min_active_cutoff = best_weight;
  608. else {
  609. std::nth_element(tmp_array_.begin(), tmp_array_.begin() + config_.min_active,
  610. tmp_array_.size() > static_cast<size_t>(config_.max_active)
  611. ? tmp_array_.begin() + config_.max_active
  612. : tmp_array_.end());
  613. min_active_cutoff = tmp_array_[config_.min_active];
  614. }
  615. }
  616. if (min_active_cutoff > beam_cutoff) { // min_active is looser than beam.
  617. if (adaptive_beam)
  618. *adaptive_beam = min_active_cutoff - best_weight + config_.beam_delta;
  619. return min_active_cutoff;
  620. } else {
  621. *adaptive_beam = config_.beam;
  622. return beam_cutoff;
  623. }
  624. }
  625. }
  626. template <typename FST, typename Token>
  627. BaseFloat LatticeIncrementalDecoderTpl<FST, Token>::ProcessEmitting(
  628. DecodableInterface *decodable) {
  629. KALDI_ASSERT(active_toks_.size() > 0);
  630. int32 frame = active_toks_.size() - 1; // frame is the frame-index
  631. // (zero-based) used to get likelihoods
  632. // from the decodable object.
  633. active_toks_.resize(active_toks_.size() + 1);
  634. Elem *final_toks = toks_.Clear(); // analogous to swapping prev_toks_ / cur_toks_
  635. // in simple-decoder.h. Removes the Elems from
  636. // being indexed in the hash in toks_.
  637. Elem *best_elem = NULL;
  638. BaseFloat adaptive_beam;
  639. size_t tok_cnt;
  640. BaseFloat cur_cutoff = GetCutoff(final_toks, &tok_cnt, &adaptive_beam, &best_elem);
  641. KALDI_VLOG(6) << "Adaptive beam on frame " << NumFramesDecoded() << " is "
  642. << adaptive_beam;
  643. PossiblyResizeHash(tok_cnt); // This makes sure the hash is always big enough.
  644. BaseFloat next_cutoff = std::numeric_limits<BaseFloat>::infinity();
  645. // pruning "online" before having seen all tokens
  646. BaseFloat cost_offset = 0.0; // Used to keep probabilities in a good
  647. // dynamic range.
  648. // First process the best token to get a hopefully
  649. // reasonably tight bound on the next cutoff. The only
  650. // products of the next block are "next_cutoff" and "cost_offset".
  651. if (best_elem) {
  652. StateId state = best_elem->key;
  653. Token *tok = best_elem->val;
  654. cost_offset = -tok->tot_cost;
  655. for (fst::ArcIterator<FST> aiter(*fst_, state); !aiter.Done(); aiter.Next()) {
  656. const Arc &arc = aiter.Value();
  657. if (arc.ilabel != 0) { // propagate..
  658. BaseFloat new_weight = arc.weight.Value() + cost_offset -
  659. decodable->LogLikelihood(frame, arc.ilabel) +
  660. tok->tot_cost;
  661. if (new_weight + adaptive_beam < next_cutoff)
  662. next_cutoff = new_weight + adaptive_beam;
  663. }
  664. }
  665. }
  666. // Store the offset on the acoustic likelihoods that we're applying.
  667. // Could just do cost_offsets_.push_back(cost_offset), but we
  668. // do it this way as it's more robust to future code changes.
  669. cost_offsets_.resize(frame + 1, 0.0);
  670. cost_offsets_[frame] = cost_offset;
  671. // the tokens are now owned here, in final_toks, and the hash is empty.
  672. // 'owned' is a complex thing here; the point is we need to call DeleteElem
  673. // on each elem 'e' to let toks_ know we're done with them.
  674. for (Elem *e = final_toks, *e_tail; e != NULL; e = e_tail) {
  675. // loop this way because we delete "e" as we go.
  676. StateId state = e->key;
  677. Token *tok = e->val;
  678. if (tok->tot_cost <= cur_cutoff) {
  679. for (fst::ArcIterator<FST> aiter(*fst_, state); !aiter.Done(); aiter.Next()) {
  680. const Arc &arc = aiter.Value();
  681. if (arc.ilabel != 0) { // propagate..
  682. BaseFloat ac_cost =
  683. cost_offset - decodable->LogLikelihood(frame, arc.ilabel),
  684. graph_cost = arc.weight.Value(), cur_cost = tok->tot_cost,
  685. tot_cost = cur_cost + ac_cost + graph_cost;
  686. if (tot_cost >= next_cutoff)
  687. continue;
  688. else if (tot_cost + adaptive_beam < next_cutoff)
  689. next_cutoff = tot_cost + adaptive_beam; // prune by best current token
  690. // Note: the frame indexes into active_toks_ are one-based,
  691. // hence the + 1.
  692. Token *next_tok =
  693. FindOrAddToken(arc.nextstate, frame + 1, tot_cost, tok, NULL);
  694. // NULL: no change indicator needed
  695. // Add ForwardLink from tok to next_tok (put on head of list tok->links)
  696. tok->links = new ForwardLinkT(next_tok, arc.ilabel, arc.olabel, graph_cost,
  697. ac_cost, tok->links);
  698. }
  699. } // for all arcs
  700. }
  701. e_tail = e->tail;
  702. toks_.Delete(e); // delete Elem
  703. }
  704. return next_cutoff;
  705. }
  706. // static inline
  707. template <typename FST, typename Token>
  708. void LatticeIncrementalDecoderTpl<FST, Token>::DeleteForwardLinks(Token *tok) {
  709. ForwardLinkT *l = tok->links, *m;
  710. while (l != NULL) {
  711. m = l->next;
  712. delete l;
  713. l = m;
  714. }
  715. tok->links = NULL;
  716. }
  717. template <typename FST, typename Token>
  718. void LatticeIncrementalDecoderTpl<FST, Token>::ProcessNonemitting(BaseFloat cutoff) {
  719. KALDI_ASSERT(!active_toks_.empty());
  720. int32 frame = static_cast<int32>(active_toks_.size()) - 2;
  721. // Note: "frame" is the time-index we just processed, or -1 if
  722. // we are processing the nonemitting transitions before the
  723. // first frame (called from InitDecoding()).
  724. // Processes nonemitting arcs for one frame. Propagates within toks_.
  725. // Note-- this queue structure is is not very optimal as
  726. // it may cause us to process states unnecessarily (e.g. more than once),
  727. // but in the baseline code, turning this vector into a set to fix this
  728. // problem did not improve overall speed.
  729. KALDI_ASSERT(queue_.empty());
  730. if (toks_.GetList() == NULL) {
  731. if (!warned_) {
  732. KALDI_WARN << "Error, no surviving tokens: frame is " << frame;
  733. warned_ = true;
  734. }
  735. }
  736. for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail) {
  737. StateId state = e->key;
  738. if (fst_->NumInputEpsilons(state) != 0) queue_.push_back(state);
  739. }
  740. while (!queue_.empty()) {
  741. StateId state = queue_.back();
  742. queue_.pop_back();
  743. Token *tok =
  744. toks_.Find(state)
  745. ->val; // would segfault if state not in toks_ but this can't happen.
  746. BaseFloat cur_cost = tok->tot_cost;
  747. if (cur_cost >= cutoff) // Don't bother processing successors.
  748. continue;
  749. // If "tok" has any existing forward links, delete them,
  750. // because we're about to regenerate them. This is a kind
  751. // of non-optimality (remember, this is the simple decoder),
  752. // but since most states are emitting it's not a huge issue.
  753. DeleteForwardLinks(tok); // necessary when re-visiting
  754. tok->links = NULL;
  755. for (fst::ArcIterator<FST> aiter(*fst_, state); !aiter.Done(); aiter.Next()) {
  756. const Arc &arc = aiter.Value();
  757. if (arc.ilabel == 0) { // propagate nonemitting only...
  758. BaseFloat graph_cost = arc.weight.Value(), tot_cost = cur_cost + graph_cost;
  759. if (tot_cost < cutoff) {
  760. bool changed;
  761. Token *new_tok =
  762. FindOrAddToken(arc.nextstate, frame + 1, tot_cost, tok, &changed);
  763. tok->links =
  764. new ForwardLinkT(new_tok, 0, arc.olabel, graph_cost, 0, tok->links);
  765. // "changed" tells us whether the new token has a different
  766. // cost from before, or is new [if so, add into queue].
  767. if (changed && fst_->NumInputEpsilons(arc.nextstate) != 0)
  768. queue_.push_back(arc.nextstate);
  769. }
  770. }
  771. } // for all arcs
  772. } // while queue not empty
  773. }
  774. template <typename FST, typename Token>
  775. void LatticeIncrementalDecoderTpl<FST, Token>::DeleteElems(Elem *list) {
  776. for (Elem *e = list, *e_tail; e != NULL; e = e_tail) {
  777. e_tail = e->tail;
  778. toks_.Delete(e);
  779. }
  780. }
  781. template <typename FST, typename Token>
  782. void LatticeIncrementalDecoderTpl<
  783. FST, Token>::ClearActiveTokens() { // a cleanup routine, at utt end/begin
  784. for (size_t i = 0; i < active_toks_.size(); i++) {
  785. // Delete all tokens alive on this frame, and any forward
  786. // links they may have.
  787. for (Token *tok = active_toks_[i].toks; tok != NULL;) {
  788. DeleteForwardLinks(tok);
  789. Token *next_tok = tok->next;
  790. delete tok;
  791. num_toks_--;
  792. tok = next_tok;
  793. }
  794. }
  795. active_toks_.clear();
  796. KALDI_ASSERT(num_toks_ == 0);
  797. }
  798. template <typename FST, typename Token>
  799. const CompactLattice& LatticeIncrementalDecoderTpl<FST, Token>::GetLattice(
  800. int32 num_frames_to_include,
  801. bool use_final_probs) {
  802. KALDI_ASSERT(num_frames_to_include >= num_frames_in_lattice_ &&
  803. num_frames_to_include <= NumFramesDecoded());
  804. if (num_frames_in_lattice_ > 0 &&
  805. determinizer_.GetLattice().NumStates() == 0) {
  806. /* Something went wrong, lattice is empty and will continue to be empty.
  807. User-level code should detect and deal with this.
  808. */
  809. num_frames_in_lattice_ = num_frames_to_include;
  810. return determinizer_.GetLattice();
  811. }
  812. if (decoding_finalized_ && !use_final_probs) {
  813. // This is not supported
  814. KALDI_ERR << "You cannot get the lattice without final-probs after "
  815. "calling FinalizeDecoding().";
  816. }
  817. if (use_final_probs && num_frames_to_include != NumFramesDecoded()) {
  818. /* This is because we only remember the relation between HCLG states and
  819. Tokens for the current frame; the Token does not have a `state` field. */
  820. KALDI_ERR << "use-final-probs may no be true if you are not "
  821. "getting a lattice for all frames decoded so far.";
  822. }
  823. if (num_frames_to_include > num_frames_in_lattice_) {
  824. /* Make sure the token-pruning is up to date. If we just pruned the tokens,
  825. this will do very little work. */
  826. PruneActiveTokens(config_.lattice_beam * config_.prune_scale);
  827. if (determinizer_.GetLattice().NumStates() == 0 ||
  828. determinizer_.GetLattice().Final(0) != CompactLatticeWeight::Zero()) {
  829. num_frames_in_lattice_ = 0;
  830. determinizer_.Init();
  831. }
  832. Lattice chunk_lat;
  833. unordered_map<Label, LatticeArc::StateId> token_label2state;
  834. if (num_frames_in_lattice_ != 0) {
  835. determinizer_.InitializeRawLatticeChunk(&chunk_lat,
  836. &token_label2state);
  837. }
  838. // tok_map will map from Token* to state-id in chunk_lat.
  839. // The cur and prev versions alternate on different frames.
  840. unordered_map<Token*, StateId> &tok2state_map(temp_token_map_);
  841. tok2state_map.clear();
  842. unordered_map<Token*, Label> &next_token2label_map(token2label_map_temp_);
  843. next_token2label_map.clear();
  844. { // Deal with the last frame in the chunk, the one numbered `num_frames_to_include`.
  845. // (Yes, this is backwards). We allocate token labels, and set tokens as
  846. // final, but don't add any transitions. This may leave some states
  847. // disconnected (e.g. due to chains of nonemitting arcs), but it's OK; we'll
  848. // fix it when we generate the next chunk of lattice.
  849. int32 frame = num_frames_to_include;
  850. // Allocate state-ids for all tokens on this frame.
  851. for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
  852. /* If we included the final-costs at this stage, they will cause
  853. non-final states to be pruned out from the end of the lattice. */
  854. BaseFloat final_cost;
  855. { // This block computes final_cost
  856. if (decoding_finalized_) {
  857. if (final_costs_.empty()) {
  858. final_cost = 0.0; /* No final-state survived, so treat all as final
  859. * with probability One(). */
  860. } else {
  861. auto iter = final_costs_.find(tok);
  862. if (iter == final_costs_.end())
  863. final_cost = std::numeric_limits<BaseFloat>::infinity();
  864. else
  865. final_cost = iter->second;
  866. }
  867. } else {
  868. /* this is a `fake` final-cost used to guide pruning. It's as if we
  869. set the betas (backward-probs) on the final frame to the
  870. negatives of the corresponding alphas, so all tokens on the last
  871. frae will be on a best path.. the extra_cost for each token
  872. always corresponds to its alpha+beta on this assumption. We want
  873. the final_cost here to correspond to the beta (backward-prob), so
  874. we get that by final_cost = extra_cost - tot_cost.
  875. [The tot_cost is the forward/alpha cost.]
  876. */
  877. final_cost = tok->extra_cost - tok->tot_cost;
  878. }
  879. }
  880. StateId state = chunk_lat.AddState();
  881. tok2state_map[tok] = state;
  882. if (final_cost < std::numeric_limits<BaseFloat>::infinity()) {
  883. next_token2label_map[tok] = AllocateNewTokenLabel();
  884. StateId token_final_state = chunk_lat.AddState();
  885. LatticeArc::Label ilabel = 0,
  886. olabel = (next_token2label_map[tok] = AllocateNewTokenLabel());
  887. chunk_lat.AddArc(state,
  888. LatticeArc(ilabel, olabel,
  889. LatticeWeight::One(),
  890. token_final_state));
  891. chunk_lat.SetFinal(token_final_state, LatticeWeight(final_cost, 0.0));
  892. }
  893. }
  894. }
  895. // Go in reverse order over the remaining frames so we can create arcs as we
  896. // go, and their destination-states will already be in the map.
  897. for (int32 frame = num_frames_to_include;
  898. frame >= num_frames_in_lattice_; frame--) {
  899. // The conditional below is needed for the last frame of the utterance.
  900. BaseFloat cost_offset = (frame < cost_offsets_.size() ?
  901. cost_offsets_[frame] : 0.0);
  902. // For the first frame of the chunk, we need to make sure the states are
  903. // the ones created by InitializeRawLatticeChunk() (where not pruned away).
  904. if (frame == num_frames_in_lattice_ && num_frames_in_lattice_ != 0) {
  905. for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
  906. auto iter = token2label_map_.find(tok);
  907. KALDI_ASSERT(iter != token2label_map_.end());
  908. Label token_label = iter->second;
  909. auto iter2 = token_label2state.find(token_label);
  910. if (iter2 != token_label2state.end()) {
  911. StateId state = iter2->second;
  912. tok2state_map[tok] = state;
  913. } else {
  914. // Some states may have been pruned out, but we should still allocate
  915. // them. They might have been part of chains of nonemitting arcs
  916. // where the state became disconnected because the last chunk didn't
  917. // include arcs starting at this frame.
  918. StateId state = chunk_lat.AddState();
  919. tok2state_map[tok] = state;
  920. }
  921. }
  922. } else if (frame != num_frames_to_include) { // We already created states
  923. // for the last frame.
  924. for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
  925. StateId state = chunk_lat.AddState();
  926. tok2state_map[tok] = state;
  927. }
  928. }
  929. for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
  930. auto iter = tok2state_map.find(tok);
  931. KALDI_ASSERT(iter != tok2state_map.end());
  932. StateId cur_state = iter->second;
  933. for (ForwardLinkT *l = tok->links; l != NULL; l = l->next) {
  934. auto next_iter = tok2state_map.find(l->next_tok);
  935. if (next_iter == tok2state_map.end()) {
  936. // Emitting arcs from the last frame we're including -- ignore
  937. // these.
  938. KALDI_ASSERT(frame == num_frames_to_include);
  939. continue;
  940. }
  941. StateId next_state = next_iter->second;
  942. BaseFloat this_offset = (l->ilabel != 0 ? cost_offset : 0);
  943. LatticeArc arc(l->ilabel, l->olabel,
  944. LatticeWeight(l->graph_cost, l->acoustic_cost - this_offset),
  945. next_state);
  946. // Note: the epsilons get redundantly included at the end and beginning
  947. // of successive chunks. These will get removed in the determinization.
  948. chunk_lat.AddArc(cur_state, arc);
  949. }
  950. }
  951. }
  952. if (num_frames_in_lattice_ == 0) {
  953. // This block locates the start token. NOTE: we use the fact that in the
  954. // linked list of tokens, things are added at the head, so the start state
  955. // must be at the tail. If this data structure is changed in future, we
  956. // might need to explicitly store the start token as a class member.
  957. Token *tok = active_toks_[0].toks;
  958. if (tok == NULL) {
  959. KALDI_WARN << "No tokens exist on start frame";
  960. return determinizer_.GetLattice(); // will be empty.
  961. }
  962. while (tok->next != NULL)
  963. tok = tok->next;
  964. Token *start_token = tok;
  965. auto iter = tok2state_map.find(start_token);
  966. KALDI_ASSERT(iter != tok2state_map.end());
  967. StateId start_state = iter->second;
  968. chunk_lat.SetStart(start_state);
  969. }
  970. token2label_map_.swap(next_token2label_map);
  971. // bool finished_before_beam =
  972. determinizer_.AcceptRawLatticeChunk(&chunk_lat);
  973. // We are ignoring the return status, which say whether it finished before the beam.
  974. num_frames_in_lattice_ = num_frames_to_include;
  975. if (determinizer_.GetLattice().NumStates() == 0)
  976. return determinizer_.GetLattice(); // Something went wrong, lattice is empty.
  977. }
  978. unordered_map<Token*, BaseFloat> token2final_cost;
  979. unordered_map<Label, BaseFloat> token_label2final_cost;
  980. if (use_final_probs) {
  981. ComputeFinalCosts(&token2final_cost, NULL, NULL);
  982. for (const auto &p: token2final_cost) {
  983. Token *tok = p.first;
  984. BaseFloat cost = p.second;
  985. auto iter = token2label_map_.find(tok);
  986. if (iter != token2label_map_.end()) {
  987. /* Some tokens may not have survived the pruned determinization. */
  988. Label token_label = iter->second;
  989. bool ret = token_label2final_cost.insert({token_label, cost}).second;
  990. KALDI_ASSERT(ret); /* Make sure it was inserted. */
  991. }
  992. }
  993. }
  994. /* Note: these final-probs won't affect the next chunk, only the lattice
  995. returned from GetLattice(). They are kind of temporaries. */
  996. determinizer_.SetFinalCosts(token_label2final_cost.empty() ? NULL :
  997. &token_label2final_cost);
  998. return determinizer_.GetLattice();
  999. }
  1000. template <typename FST, typename Token>
  1001. int32 LatticeIncrementalDecoderTpl<FST, Token>::GetNumToksForFrame(int32 frame) {
  1002. int32 r = 0;
  1003. for (Token *tok = active_toks_[frame].toks; tok; tok = tok->next) r++;
  1004. return r;
  1005. }
  1006. /* This utility function adds an arc to a Lattice, but where the source is a
  1007. CompactLatticeArc. If the CompactLatticeArc has a string with length greater
  1008. than 1, this will require adding extra states to `lat`.
  1009. */
  1010. static void AddCompactLatticeArcToLattice(
  1011. const CompactLatticeArc &clat_arc,
  1012. LatticeArc::StateId src_state,
  1013. Lattice *lat) {
  1014. const std::vector<int32> &string = clat_arc.weight.String();
  1015. size_t N = string.size();
  1016. if (N == 0) {
  1017. LatticeArc arc;
  1018. arc.ilabel = 0;
  1019. arc.olabel = clat_arc.ilabel;
  1020. arc.nextstate = clat_arc.nextstate;
  1021. arc.weight = clat_arc.weight.Weight();
  1022. lat->AddArc(src_state, arc);
  1023. } else {
  1024. LatticeArc::StateId cur_state = src_state;
  1025. for (size_t i = 0; i < N; i++) {
  1026. LatticeArc arc;
  1027. arc.ilabel = string[i];
  1028. arc.olabel = (i == 0 ? clat_arc.ilabel : 0);
  1029. arc.nextstate = (i + 1 == N ? clat_arc.nextstate : lat->AddState());
  1030. arc.weight = (i == 0 ? clat_arc.weight.Weight() : LatticeWeight::One());
  1031. lat->AddArc(cur_state, arc);
  1032. cur_state = arc.nextstate;
  1033. }
  1034. }
  1035. }
  1036. void LatticeIncrementalDeterminizer::Init() {
  1037. non_final_redet_states_.clear();
  1038. clat_.DeleteStates();
  1039. final_arcs_.clear();
  1040. forward_costs_.clear();
  1041. arcs_in_.clear();
  1042. }
  1043. CompactLattice::StateId LatticeIncrementalDeterminizer::AddStateToClat() {
  1044. CompactLattice::StateId ans = clat_.AddState();
  1045. forward_costs_.push_back(std::numeric_limits<BaseFloat>::infinity());
  1046. KALDI_ASSERT(forward_costs_.size() == ans + 1);
  1047. arcs_in_.resize(ans + 1);
  1048. return ans;
  1049. }
  1050. void LatticeIncrementalDeterminizer::AddArcToClat(
  1051. CompactLattice::StateId state,
  1052. const CompactLatticeArc &arc) {
  1053. BaseFloat forward_cost = forward_costs_[state] +
  1054. ConvertToCost(arc.weight);
  1055. if (forward_cost == std::numeric_limits<BaseFloat>::infinity())
  1056. return;
  1057. int32 arc_idx = clat_.NumArcs(state);
  1058. clat_.AddArc(state, arc);
  1059. arcs_in_[arc.nextstate].push_back({state, arc_idx});
  1060. if (forward_cost < forward_costs_[arc.nextstate])
  1061. forward_costs_[arc.nextstate] = forward_cost;
  1062. }
  1063. // See documentation in header
  1064. void LatticeIncrementalDeterminizer::IdentifyTokenFinalStates(
  1065. const CompactLattice &chunk_clat,
  1066. std::unordered_map<CompactLattice::StateId, CompactLatticeArc::Label> *token_map) const {
  1067. token_map->clear();
  1068. using StateId = CompactLattice::StateId;
  1069. using Label = CompactLatticeArc::Label;
  1070. StateId num_states = chunk_clat.NumStates();
  1071. for (StateId state = 0; state < num_states; state++) {
  1072. for (fst::ArcIterator<CompactLattice> aiter(chunk_clat, state);
  1073. !aiter.Done(); aiter.Next()) {
  1074. const CompactLatticeArc &arc = aiter.Value();
  1075. if (arc.olabel >= kTokenLabelOffset && arc.olabel < kMaxTokenLabel) {
  1076. StateId nextstate = arc.nextstate;
  1077. auto r = token_map->insert({nextstate, arc.olabel});
  1078. // Check consistency of labels on incoming arcs
  1079. KALDI_ASSERT(r.first->second == arc.olabel);
  1080. }
  1081. }
  1082. }
  1083. }
  1084. void LatticeIncrementalDeterminizer::GetNonFinalRedetStates() {
  1085. using StateId = CompactLattice::StateId;
  1086. non_final_redet_states_.clear();
  1087. non_final_redet_states_.reserve(final_arcs_.size());
  1088. std::vector<StateId> state_queue;
  1089. for (const CompactLatticeArc &arc: final_arcs_) {
  1090. // Note: we abuse the .nextstate field to store the state which is really
  1091. // the source of that arc.
  1092. StateId redet_state = arc.nextstate;
  1093. if (forward_costs_[redet_state] != std::numeric_limits<BaseFloat>::infinity()) {
  1094. // if it is accessible..
  1095. if (non_final_redet_states_.insert(redet_state).second) {
  1096. // it was not already there
  1097. state_queue.push_back(redet_state);
  1098. }
  1099. }
  1100. }
  1101. // Add any states that are reachable from the states above.
  1102. while (!state_queue.empty()) {
  1103. StateId s = state_queue.back();
  1104. state_queue.pop_back();
  1105. for (fst::ArcIterator<CompactLattice> aiter(clat_, s); !aiter.Done();
  1106. aiter.Next()) {
  1107. const CompactLatticeArc &arc = aiter.Value();
  1108. StateId nextstate = arc.nextstate;
  1109. if (non_final_redet_states_.insert(nextstate).second)
  1110. state_queue.push_back(nextstate); // it was not already there
  1111. }
  1112. }
  1113. }
  1114. void LatticeIncrementalDeterminizer::InitializeRawLatticeChunk(
  1115. Lattice *olat,
  1116. unordered_map<Label, LatticeArc::StateId> *token_label2state) {
  1117. using namespace fst;
  1118. olat->DeleteStates();
  1119. LatticeArc::StateId start_state = olat->AddState();
  1120. olat->SetStart(start_state);
  1121. token_label2state->clear();
  1122. // redet_state_map maps from state-ids in clat_ to state-ids in olat. This
  1123. // will be the set of states from which the arcs to final-states in the
  1124. // canonical appended lattice leave (physically, these are in the .nextstate
  1125. // elements of arcs_, since we use that field for the source state), plus any
  1126. // states reachable from those states.
  1127. unordered_map<CompactLattice::StateId, LatticeArc::StateId> redet_state_map;
  1128. for (CompactLattice::StateId redet_state: non_final_redet_states_)
  1129. redet_state_map[redet_state] = olat->AddState();
  1130. // First, process any arcs leaving the non-final redeterminized states that
  1131. // are not to final-states. (What we mean by "not to final states" is, not to
  1132. // stats that are final in the `canonical appended lattice`.. they may
  1133. // actually be physically final in clat_, because we make clat_ what we want
  1134. // to return to the user.
  1135. for (CompactLattice::StateId redet_state: non_final_redet_states_) {
  1136. LatticeArc::StateId lat_state = redet_state_map[redet_state];
  1137. for (ArcIterator<CompactLattice> aiter(clat_, redet_state);
  1138. !aiter.Done(); aiter.Next()) {
  1139. const CompactLatticeArc &arc = aiter.Value();
  1140. CompactLattice::StateId nextstate = arc.nextstate;
  1141. LatticeArc::StateId lat_nextstate = olat->NumStates();
  1142. auto r = redet_state_map.insert({nextstate, lat_nextstate});
  1143. if (r.second) { // Was inserted.
  1144. LatticeArc::StateId s = olat->AddState();
  1145. KALDI_ASSERT(s == lat_nextstate);
  1146. } else {
  1147. // was not inserted -> was already there.
  1148. lat_nextstate = r.first->second;
  1149. }
  1150. CompactLatticeArc clat_arc(arc);
  1151. clat_arc.nextstate = lat_nextstate;
  1152. AddCompactLatticeArcToLattice(clat_arc, lat_state, olat);
  1153. }
  1154. clat_.DeleteArcs(redet_state);
  1155. clat_.SetFinal(redet_state, CompactLatticeWeight::Zero());
  1156. }
  1157. for (const CompactLatticeArc &arc: final_arcs_) {
  1158. // We abuse the `nextstate` field to store the source state.
  1159. CompactLattice::StateId src_state = arc.nextstate;
  1160. auto iter = redet_state_map.find(src_state);
  1161. if (forward_costs_[src_state] == std::numeric_limits<BaseFloat>::infinity())
  1162. continue; /* Unreachable state */
  1163. KALDI_ASSERT(iter != redet_state_map.end());
  1164. LatticeArc::StateId src_lat_state = iter->second;
  1165. Label token_label = arc.ilabel; // will be == arc.olabel.
  1166. KALDI_ASSERT(token_label >= kTokenLabelOffset &&
  1167. token_label < kMaxTokenLabel);
  1168. auto r = token_label2state->insert({token_label,
  1169. olat->NumStates()});
  1170. LatticeArc::StateId dest_lat_state = r.first->second;
  1171. if (r.second) { // was inserted
  1172. LatticeArc::StateId new_state = olat->AddState();
  1173. KALDI_ASSERT(new_state == dest_lat_state);
  1174. }
  1175. CompactLatticeArc new_arc;
  1176. new_arc.nextstate = dest_lat_state;
  1177. /* We convert the token-label to epsilon; it's not needed anymore. */
  1178. new_arc.ilabel = new_arc.olabel = 0;
  1179. new_arc.weight = arc.weight;
  1180. AddCompactLatticeArcToLattice(new_arc, src_lat_state, olat);
  1181. }
  1182. // Now deal with the initial-probs. Arcs from initial-states to
  1183. // redeterminized-states in the raw lattice have an olabel that identifies the
  1184. // id of that redeterminized-state in clat_, and a cost that is derived from
  1185. // its entry in forward_costs_. These forward-probs are used to get the
  1186. // pruned lattice determinization to behave correctly, and will be canceled
  1187. // out later on.
  1188. //
  1189. // In the paper this is the second-from-last bullet in Sec. 5.2. NOTE: in the
  1190. // paper we state that we only include such arcs for "each redeterminized
  1191. // state that is either initial in det(A) or that has an arc entering it from
  1192. // a state that is not a redeterminized state." In fact, we include these
  1193. // arcs for all redeterminized states. I realized that it won't make a
  1194. // difference to the outcome, and it's easier to do it this way.
  1195. for (CompactLattice::StateId state_id: non_final_redet_states_) {
  1196. BaseFloat forward_cost = forward_costs_[state_id];
  1197. LatticeArc arc;
  1198. arc.ilabel = 0;
  1199. // The olabel (which appears where the word-id would) is what
  1200. // we call a 'state-label'. It identifies a state in clat_.
  1201. arc.olabel = state_id + kStateLabelOffset;
  1202. // It doesn't matter what field we put forward_cost in (or whether we
  1203. // divide it among them both; the effect on pruning is the same, and
  1204. // we will cancel it out later anyway.
  1205. arc.weight = LatticeWeight(forward_cost, 0);
  1206. auto iter = redet_state_map.find(state_id);
  1207. KALDI_ASSERT(iter != redet_state_map.end());
  1208. arc.nextstate = iter->second;
  1209. olat->AddArc(start_state, arc);
  1210. }
  1211. }
  1212. void LatticeIncrementalDeterminizer::GetRawLatticeFinalCosts(
  1213. const Lattice &raw_fst,
  1214. std::unordered_map<Label, BaseFloat> *old_final_costs) {
  1215. LatticeArc::StateId raw_fst_num_states = raw_fst.NumStates();
  1216. for (LatticeArc::StateId s = 0; s < raw_fst_num_states; s++) {
  1217. for (fst::ArcIterator<Lattice> aiter(raw_fst, s); !aiter.Done();
  1218. aiter.Next()) {
  1219. const LatticeArc &value = aiter.Value();
  1220. if (value.olabel >= (Label)kTokenLabelOffset &&
  1221. value.olabel < (Label)kMaxTokenLabel) {
  1222. LatticeWeight final_weight = raw_fst.Final(value.nextstate);
  1223. if (final_weight != LatticeWeight::Zero() &&
  1224. final_weight.Value2() != 0) {
  1225. KALDI_ERR << "Label " << value.olabel << " from state " << s
  1226. << " looks like a token-label but its next-state "
  1227. << value.nextstate <<
  1228. " has unexpected final-weight " << final_weight.Value1() << ','
  1229. << final_weight.Value2();
  1230. }
  1231. auto r = old_final_costs->insert({value.olabel,
  1232. final_weight.Value1()});
  1233. if (!r.second && r.first->second != final_weight.Value1()) {
  1234. // For any given token-label, all arcs in raw_fst with that
  1235. // olabel should go to the same state, so this should be
  1236. // impossible.
  1237. KALDI_ERR << "Unexpected mismatch in final-costs for tokens, "
  1238. << r.first->second << " vs " << final_weight.Value1();
  1239. }
  1240. }
  1241. }
  1242. }
  1243. }
  1244. bool LatticeIncrementalDeterminizer::ProcessArcsFromChunkStartState(
  1245. const CompactLattice &chunk_clat,
  1246. std::unordered_map<CompactLattice::StateId, CompactLattice::StateId> *state_map) {
  1247. using StateId = CompactLattice::StateId;
  1248. StateId clat_num_states = clat_.NumStates();
  1249. // Process arcs leaving the start state of chunk_clat. These arcs will have
  1250. // state-labels on them (unless this is the first chunk).
  1251. // For destination-states of those arcs, work out which states in
  1252. // clat_ they correspond to and update their forward_costs.
  1253. for (fst::ArcIterator<CompactLattice> aiter(chunk_clat, chunk_clat.Start());
  1254. !aiter.Done(); aiter.Next()) {
  1255. const CompactLatticeArc &arc = aiter.Value();
  1256. Label label = arc.ilabel; // ilabel == olabel; would be the olabel
  1257. // in a Lattice.
  1258. if (!(label >= kStateLabelOffset &&
  1259. label - kStateLabelOffset < clat_num_states)) {
  1260. // The label was not a state-label. This should only be possible on the
  1261. // first chunk.
  1262. KALDI_ASSERT(state_map->empty());
  1263. return true; // this is the first chunk.
  1264. }
  1265. StateId clat_state = label - kStateLabelOffset;
  1266. StateId chunk_state = arc.nextstate;
  1267. auto p = state_map->insert({chunk_state, clat_state});
  1268. StateId dest_clat_state = p.first->second;
  1269. // We deleted all its arcs in InitializeRawLatticeChunk
  1270. KALDI_ASSERT(clat_.NumArcs(clat_state) == 0);
  1271. /*
  1272. In almost all cases, dest_clat_state and clat_state will be the same state;
  1273. but there may be situations where two arcs with different state-labels
  1274. left the start state and entered the same next-state in chunk_clat; and in
  1275. these cases, they will be different.
  1276. We didn't address this issue in the paper (or actually realize it could be
  1277. a problem). What we do is pick one of the clat_states as the "canonical"
  1278. one, and redirect all incoming transitions of the others to enter the
  1279. "canonical" one. (Search below for new_in_arc.nextstate =
  1280. dest_clat_state).
  1281. */
  1282. if (clat_state != dest_clat_state) {
  1283. // Check that the start state isn't getting merged with any other state.
  1284. // If this were possible, we'd need to deal with it specially, but it
  1285. // can't be, because to be merged, 2 states must have identical arcs
  1286. // leaving them with identical weights, so we'd need to have another state
  1287. // on frame 0 identical to the start state, which is not possible if the
  1288. // lattice is deterministic and epsilon-free.
  1289. KALDI_ASSERT(clat_state != 0 && dest_clat_state != 0);
  1290. }
  1291. // in_weight is an extra weight that we'll include on arcs entering this
  1292. // state from the previous chunk. We need to cancel out
  1293. // `forward_costs[clat_state]`, which was included in the corresponding arc
  1294. // in the raw lattice for pruning purposes; and we need to include the
  1295. // weight on the arc from the start-state of `chunk_clat` to this state.
  1296. CompactLatticeWeight extra_weight_in = arc.weight;
  1297. extra_weight_in.SetWeight(
  1298. fst::Times(extra_weight_in.Weight(),
  1299. LatticeWeight(-forward_costs_[clat_state], 0.0)));
  1300. // We don't allow state 0 to be a redeterminized-state; calling code assures
  1301. // this. Search for `determinizer_.GetLattice().Final(0) !=
  1302. // CompactLatticeWeight::Zero())` to find that calling code.
  1303. KALDI_ASSERT(clat_state != 0);
  1304. // Note: 0 is the start state of clat_. This was checked.
  1305. forward_costs_[clat_state] = (clat_state == 0 ? 0 :
  1306. std::numeric_limits<BaseFloat>::infinity());
  1307. std::vector<std::pair<StateId, int32> > arcs_in;
  1308. arcs_in.swap(arcs_in_[clat_state]);
  1309. for (auto p: arcs_in) {
  1310. // Note: we'll be doing `continue` below if this input arc came from
  1311. // another redeterminized-state, because we did DeleteArcs() for them in
  1312. // InitializeRawLatticeChunk(). Those arcs will be transferred
  1313. // from chunk_clat later on.
  1314. CompactLattice::StateId src_state = p.first;
  1315. int32 arc_pos = p.second;
  1316. if (arc_pos >= (int32)clat_.NumArcs(src_state))
  1317. continue;
  1318. fst::MutableArcIterator<CompactLattice> aiter(&clat_, src_state);
  1319. aiter.Seek(arc_pos);
  1320. if (aiter.Value().nextstate != clat_state)
  1321. continue; // This arc record has become invalidated.
  1322. CompactLatticeArc new_in_arc(aiter.Value());
  1323. // In most cases we will have dest_clat_state == clat_state, so the next
  1324. // line won't change the value of .nextstate
  1325. new_in_arc.nextstate = dest_clat_state;
  1326. new_in_arc.weight = fst::Times(new_in_arc.weight, extra_weight_in);
  1327. aiter.SetValue(new_in_arc);
  1328. BaseFloat new_forward_cost = forward_costs_[src_state] +
  1329. ConvertToCost(new_in_arc.weight);
  1330. if (new_forward_cost < forward_costs_[dest_clat_state])
  1331. forward_costs_[dest_clat_state] = new_forward_cost;
  1332. arcs_in_[dest_clat_state].push_back(p);
  1333. }
  1334. }
  1335. return false; // this is not the first chunk.
  1336. }
  1337. void LatticeIncrementalDeterminizer::TransferArcsToClat(
  1338. const CompactLattice &chunk_clat,
  1339. bool is_first_chunk,
  1340. const std::unordered_map<CompactLattice::StateId, CompactLattice::StateId> &state_map,
  1341. const std::unordered_map<CompactLattice::StateId, Label> &chunk_state_to_token,
  1342. const std::unordered_map<Label, BaseFloat> &old_final_costs) {
  1343. using StateId = CompactLattice::StateId;
  1344. StateId chunk_num_states = chunk_clat.NumStates();
  1345. // Now transfer arcs from chunk_clat to clat_.
  1346. for (StateId chunk_state = (is_first_chunk ? 0 : 1);
  1347. chunk_state < chunk_num_states; chunk_state++) {
  1348. auto iter = state_map.find(chunk_state);
  1349. if (iter == state_map.end()) {
  1350. KALDI_ASSERT(chunk_state_to_token.count(chunk_state) != 0);
  1351. // Don't process token-final states. Anyway they have no arcs leaving
  1352. // them.
  1353. continue;
  1354. }
  1355. StateId clat_state = iter->second;
  1356. // We know that this point that `clat_state` is not a token-final state
  1357. // (see glossary for definition) as if it were, we would have done
  1358. // `continue` above.
  1359. //
  1360. // Only in the last chunk of the lattice would be there be a final-prob on
  1361. // states that are not `token-final states`; these final-probs would
  1362. // normally all be Zero() at this point. So in almost all cases the following
  1363. // call will do nothing.
  1364. clat_.SetFinal(clat_state, chunk_clat.Final(chunk_state));
  1365. // Process arcs leaving this state.
  1366. for (fst::ArcIterator<CompactLattice> aiter(chunk_clat, chunk_state);
  1367. !aiter.Done(); aiter.Next()) {
  1368. CompactLatticeArc arc(aiter.Value());
  1369. auto next_iter = state_map.find(arc.nextstate);
  1370. if (next_iter != state_map.end()) {
  1371. // The normal case (when the .nextstate has a corresponding
  1372. // state in clat_) is very simple. Just copy the arc over.
  1373. arc.nextstate = next_iter->second;
  1374. KALDI_ASSERT(arc.ilabel < kTokenLabelOffset ||
  1375. arc.ilabel > kMaxTokenLabel);
  1376. AddArcToClat(clat_state, arc);
  1377. } else {
  1378. // This is the case when the arc is to a `token-final` state (see
  1379. // glossary.)
  1380. // TODO: remove the following slightly excessive assertion?
  1381. KALDI_ASSERT(chunk_clat.Final(arc.nextstate) != CompactLatticeWeight::Zero() &&
  1382. arc.olabel >= (Label)kTokenLabelOffset &&
  1383. arc.olabel < (Label)kMaxTokenLabel &&
  1384. chunk_state_to_token.count(arc.nextstate) != 0 &&
  1385. old_final_costs.count(arc.olabel) != 0);
  1386. // Include the final-cost of the next state (which should be final)
  1387. // in arc.weight.
  1388. arc.weight = fst::Times(arc.weight,
  1389. chunk_clat.Final(arc.nextstate));
  1390. auto cost_iter = old_final_costs.find(arc.olabel);
  1391. KALDI_ASSERT(cost_iter != old_final_costs.end());
  1392. BaseFloat old_final_cost = cost_iter->second;
  1393. // `arc` is going to become an element of final_arcs_. These
  1394. // contain information about transitions from states in clat_ to
  1395. // `token-final` states (i.e. states that have a token-label on the arc
  1396. // to them and that are final in the canonical compact lattice).
  1397. // We subtract the old_final_cost as it was just a temporary cost
  1398. // introduced for pruning purposes.
  1399. arc.weight.SetWeight(fst::Times(arc.weight.Weight(),
  1400. LatticeWeight{-old_final_cost, 0.0}));
  1401. // In a slight abuse of the Arc data structure, the nextstate is set to
  1402. // the source state. The label (ilabel == olabel) indicates the
  1403. // token it is associated with.
  1404. arc.nextstate = clat_state;
  1405. final_arcs_.push_back(arc);
  1406. }
  1407. }
  1408. }
  1409. }
  1410. bool LatticeIncrementalDeterminizer::AcceptRawLatticeChunk(
  1411. Lattice *raw_fst) {
  1412. using Label = CompactLatticeArc::Label;
  1413. using StateId = CompactLattice::StateId;
  1414. // old_final_costs is a map from a `token-label` (see glossary) to the
  1415. // associated final-prob in a final-state of `raw_fst`, that is associated
  1416. // with that Token. These are Tokens that were active at the end of the
  1417. // chunk. The final-probs may arise from beta (backward) costs, introduced
  1418. // for pruning purposes, and/or from final-probs in HCLG. Those costs will
  1419. // not be included in anything we store permamently in this class; they used
  1420. // only to guide pruned determinization, and we will use `old_final_costs`
  1421. // later to cancel them out.
  1422. std::unordered_map<Label, BaseFloat> old_final_costs;
  1423. GetRawLatticeFinalCosts(*raw_fst, &old_final_costs);
  1424. CompactLattice chunk_clat;
  1425. bool determinized_till_beam = DeterminizeLatticePhonePrunedWrapper(
  1426. trans_model_, raw_fst, config_.lattice_beam, &chunk_clat,
  1427. config_.det_opts);
  1428. TopSortCompactLatticeIfNeeded(&chunk_clat);
  1429. std::unordered_map<StateId, Label> chunk_state_to_token;
  1430. IdentifyTokenFinalStates(chunk_clat,
  1431. &chunk_state_to_token);
  1432. StateId chunk_num_states = chunk_clat.NumStates();
  1433. if (chunk_num_states == 0) {
  1434. // This will be an error but user-level calling code can detect it from the
  1435. // lattice being empty.
  1436. KALDI_WARN << "Empty lattice, something went wrong.";
  1437. clat_.DeleteStates();
  1438. return false;
  1439. }
  1440. StateId start_state = chunk_clat.Start(); // would be 0.
  1441. KALDI_ASSERT(start_state == 0);
  1442. // Process arcs leaving the start state of chunk_clat. Unless this is the
  1443. // first chunk in the lattice, all arcs leaving the start state of chunk_clat
  1444. // will have `state labels` on them (identifying redeterminized-states in
  1445. // clat_), and will transition to a state in `chunk_clat` that we can identify
  1446. // with that redeterminized-state.
  1447. // state_map maps from (non-initial, non-token-final state s in chunk_clat) to
  1448. // a state in clat_.
  1449. std::unordered_map<StateId, StateId> state_map;
  1450. bool is_first_chunk = ProcessArcsFromChunkStartState(chunk_clat, &state_map);
  1451. // Remove any existing arcs in clat_ that leave redeterminized-states, and
  1452. // make those states non-final. Below, we'll add arcs leaving those states
  1453. // (and possibly new final-probs.)
  1454. for (StateId clat_state: non_final_redet_states_) {
  1455. clat_.DeleteArcs(clat_state);
  1456. clat_.SetFinal(clat_state, CompactLatticeWeight::Zero());
  1457. }
  1458. // The previous final-arc info is no longer relevant; we'll recreate it below.
  1459. final_arcs_.clear();
  1460. // assume chunk_lat.Start() == 0; we asserted it above. Allocate state-ids
  1461. // for all remaining states in chunk_clat, except for token-final states.
  1462. for (StateId state = (is_first_chunk ? 0 : 1);
  1463. state < chunk_num_states; state++) {
  1464. if (chunk_state_to_token.count(state) != 0)
  1465. continue; // these `token-final` states don't get a state allocated.
  1466. StateId new_clat_state = clat_.NumStates();
  1467. if (state_map.insert({state, new_clat_state}).second) {
  1468. // If it was inserted then we need to actually allocate that state
  1469. StateId s = AddStateToClat();
  1470. KALDI_ASSERT(s == new_clat_state);
  1471. } // else do nothing; it would have been a redeterminized-state and no
  1472. } // allocation is needed since they already exist in clat_. and
  1473. // in state_map.
  1474. if (is_first_chunk) {
  1475. auto iter = state_map.find(start_state);
  1476. KALDI_ASSERT(iter != state_map.end());
  1477. CompactLattice::StateId clat_start_state = iter->second;
  1478. KALDI_ASSERT(clat_start_state == 0); // topological order.
  1479. clat_.SetStart(clat_start_state);
  1480. forward_costs_[clat_start_state] = 0.0;
  1481. }
  1482. TransferArcsToClat(chunk_clat, is_first_chunk,
  1483. state_map, chunk_state_to_token, old_final_costs);
  1484. GetNonFinalRedetStates();
  1485. return determinized_till_beam;
  1486. }
  1487. void LatticeIncrementalDeterminizer::SetFinalCosts(
  1488. const unordered_map<Label, BaseFloat> *token_label2final_cost) {
  1489. if (final_arcs_.empty()) {
  1490. KALDI_WARN << "SetFinalCosts() called when final_arcs_.empty()... possibly "
  1491. "means you are calling this after Finalize()? Not allowed: could "
  1492. "indicate a code error. Or possibly decoding failed somehow.";
  1493. }
  1494. /*
  1495. prefinal states a terminology that does not appear in the paper. What it
  1496. means is: the set of states that have an arc with a Token-label as the label
  1497. leaving them in the canonical appended lattice.
  1498. */
  1499. std::unordered_set<int32> &prefinal_states(temp_);
  1500. prefinal_states.clear();
  1501. for (const auto &arc: final_arcs_) {
  1502. /* Caution: `state` is actually the state the arc would
  1503. leave from in the canonical appended lattice; we just store
  1504. that in the .nextstate field. */
  1505. CompactLattice::StateId state = arc.nextstate;
  1506. prefinal_states.insert(state);
  1507. }
  1508. for (int32 state: prefinal_states)
  1509. clat_.SetFinal(state, CompactLatticeWeight::Zero());
  1510. for (const CompactLatticeArc &arc: final_arcs_) {
  1511. Label token_label = arc.ilabel;
  1512. /* Note: we store the source state in the .nextstate field. */
  1513. CompactLattice::StateId src_state = arc.nextstate;
  1514. BaseFloat graph_final_cost;
  1515. if (token_label2final_cost == NULL) {
  1516. graph_final_cost = 0.0;
  1517. } else {
  1518. auto iter = token_label2final_cost->find(token_label);
  1519. if (iter == token_label2final_cost->end())
  1520. continue;
  1521. else
  1522. graph_final_cost = iter->second;
  1523. }
  1524. /* It might seem odd to set a final-prob on the src-state of the arc..
  1525. the point is that the symbol on the arc is a token-label, which should not
  1526. appear in the lattice the user sees, so after that token-label is removed
  1527. the arc would just become a final-prob.
  1528. */
  1529. clat_.SetFinal(src_state,
  1530. fst::Plus(clat_.Final(src_state),
  1531. fst::Times(arc.weight,
  1532. CompactLatticeWeight(
  1533. LatticeWeight(graph_final_cost, 0), {}))));
  1534. }
  1535. }
  1536. // Instantiate the template for the combination of token types and FST types
  1537. // that we'll need.
  1538. template class LatticeIncrementalDecoderTpl<fst::Fst<fst::StdArc>, decoder::StdToken>;
  1539. template class LatticeIncrementalDecoderTpl<fst::VectorFst<fst::StdArc>,
  1540. decoder::StdToken>;
  1541. template class LatticeIncrementalDecoderTpl<fst::ConstFst<fst::StdArc>,
  1542. decoder::StdToken>;
  1543. template class LatticeIncrementalDecoderTpl<fst::ConstGrammarFst ,
  1544. decoder::StdToken>;
  1545. template class LatticeIncrementalDecoderTpl<fst::VectorGrammarFst,
  1546. decoder::StdToken>;
  1547. template class LatticeIncrementalDecoderTpl<fst::Fst<fst::StdArc>,
  1548. decoder::BackpointerToken>;
  1549. template class LatticeIncrementalDecoderTpl<fst::VectorFst<fst::StdArc>,
  1550. decoder::BackpointerToken>;
  1551. template class LatticeIncrementalDecoderTpl<fst::ConstFst<fst::StdArc>,
  1552. decoder::BackpointerToken>;
  1553. template class LatticeIncrementalDecoderTpl<fst::ConstGrammarFst,
  1554. decoder::BackpointerToken>;
  1555. template class LatticeIncrementalDecoderTpl<fst::VectorGrammarFst,
  1556. decoder::BackpointerToken>;
  1557. } // end namespace kaldi.