lattice-biglm-faster-decoder.h 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. // decoder/lattice-biglm-faster-decoder.h
  2. // Copyright 2009-2011 Microsoft Corporation, Mirko Hannemann,
  3. // Gilles Boulianne
  4. // See ../../COPYING for clarification regarding multiple authors
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License");
  7. // you may not use this file except in compliance with the License.
  8. // You may obtain a copy of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  14. // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  15. // MERCHANTABLITY OR NON-INFRINGEMENT.
  16. // See the Apache 2 License for the specific language governing permissions and
  17. // limitations under the License.
  18. #ifndef KALDI_DECODER_LATTICE_BIGLM_FASTER_DECODER_H_
  19. #define KALDI_DECODER_LATTICE_BIGLM_FASTER_DECODER_H_
  20. #include "util/stl-utils.h"
  21. #include "util/hash-list.h"
  22. #include "fst/fstlib.h"
  23. #include "itf/decodable-itf.h"
  24. #include "fstext/fstext-lib.h"
  25. #include "lat/kaldi-lattice.h"
  26. #include "decoder/lattice-faster-decoder.h" // for options.
  27. namespace kaldi {
  28. // The options are the same as for lattice-faster-decoder.h for now.
  29. typedef LatticeFasterDecoderConfig LatticeBiglmFasterDecoderConfig;
  30. /** This is as LatticeFasterDecoder, but does online composition between
  31. HCLG and the "difference language model", which is a deterministic
  32. FST that represents the difference between the language model you want
  33. and the language model you compiled HCLG with. The class
  34. DeterministicOnDemandFst follows through the epsilons in G for you
  35. (assuming G is a standard backoff language model) and makes it look
  36. like a determinized FST.
  37. */
  38. class LatticeBiglmFasterDecoder {
  39. public:
  40. typedef fst::StdArc Arc;
  41. typedef Arc::Label Label;
  42. typedef Arc::StateId StateId;
  43. // A PairId will be constructed as: (StateId in fst) + (StateId in lm_diff_fst) << 32;
  44. typedef uint64 PairId;
  45. typedef Arc::Weight Weight;
  46. // instantiate this class once for each thing you have to decode.
  47. LatticeBiglmFasterDecoder(
  48. const fst::Fst<fst::StdArc> &fst,
  49. const LatticeBiglmFasterDecoderConfig &config,
  50. fst::DeterministicOnDemandFst<fst::StdArc> *lm_diff_fst):
  51. fst_(fst), lm_diff_fst_(lm_diff_fst), config_(config),
  52. warned_noarc_(false), num_toks_(0) {
  53. config.Check();
  54. KALDI_ASSERT(fst.Start() != fst::kNoStateId &&
  55. lm_diff_fst->Start() != fst::kNoStateId);
  56. toks_.SetSize(1000); // just so on the first frame we do something reasonable.
  57. }
  58. void SetOptions(const LatticeBiglmFasterDecoderConfig &config) { config_ = config; }
  59. LatticeBiglmFasterDecoderConfig GetOptions() { return config_; }
  60. ~LatticeBiglmFasterDecoder() {
  61. DeleteElems(toks_.Clear());
  62. ClearActiveTokens();
  63. }
  64. // Returns true if any kind of traceback is available (not necessarily from
  65. // a final state).
  66. bool Decode(DecodableInterface *decodable) {
  67. // clean up from last time:
  68. DeleteElems(toks_.Clear());
  69. ClearActiveTokens();
  70. warned_ = false;
  71. final_active_ = false;
  72. final_costs_.clear();
  73. num_toks_ = 0;
  74. PairId start_pair = ConstructPair(fst_.Start(), lm_diff_fst_->Start());
  75. active_toks_.resize(1);
  76. Token *start_tok = new Token(0.0, 0.0, NULL, NULL);
  77. active_toks_[0].toks = start_tok;
  78. toks_.Insert(start_pair, start_tok);
  79. num_toks_++;
  80. ProcessNonemitting(0);
  81. // We use 1-based indexing for frames in this decoder (if you view it in
  82. // terms of features), but note that the decodable object uses zero-based
  83. // numbering, which we have to correct for when we call it.
  84. for (int32 frame = 1; !decodable->IsLastFrame(frame-2); frame++) {
  85. active_toks_.resize(frame+1); // new column
  86. ProcessEmitting(decodable, frame);
  87. ProcessNonemitting(frame);
  88. if (decodable->IsLastFrame(frame-1))
  89. PruneActiveTokensFinal(frame);
  90. else if (frame % config_.prune_interval == 0)
  91. PruneActiveTokens(frame, config_.lattice_beam * 0.1); // use larger delta.
  92. }
  93. // Returns true if we have any kind of traceback available (not necessarily
  94. // to the end state; query ReachedFinal() for that).
  95. return !final_costs_.empty();
  96. }
  97. /// says whether a final-state was active on the last frame. If it was not, the
  98. /// lattice (or traceback) will end with states that are not final-states.
  99. bool ReachedFinal() const { return final_active_; }
  100. // Outputs an FST corresponding to the single best path
  101. // through the lattice.
  102. bool GetBestPath(fst::MutableFst<LatticeArc> *ofst,
  103. bool use_final_probs = true) const {
  104. fst::VectorFst<LatticeArc> fst;
  105. if (!GetRawLattice(&fst, use_final_probs)) return false;
  106. // std::cout << "Raw lattice is:\n";
  107. // fst::FstPrinter<LatticeArc> fstprinter(fst, NULL, NULL, NULL, false, true);
  108. // fstprinter.Print(&std::cout, "standard output");
  109. ShortestPath(fst, ofst);
  110. return true;
  111. }
  112. // Outputs an FST corresponding to the raw, state-level
  113. // tracebacks.
  114. bool GetRawLattice(fst::MutableFst<LatticeArc> *ofst,
  115. bool use_final_probs = true) const {
  116. typedef LatticeArc Arc;
  117. typedef Arc::StateId StateId;
  118. // A PairId will be constructed as: (StateId in fst) + (StateId in lm_diff_fst) << 32;
  119. typedef uint64 PairId;
  120. typedef Arc::Weight Weight;
  121. typedef Arc::Label Label;
  122. ofst->DeleteStates();
  123. // num-frames plus one (since frames are one-based, and we have
  124. // an extra frame for the start-state).
  125. int32 num_frames = active_toks_.size() - 1;
  126. KALDI_ASSERT(num_frames > 0);
  127. unordered_map<Token*, StateId> tok_map(num_toks_/2 + 3); // bucket count
  128. // First create all states.
  129. for (int32 f = 0; f <= num_frames; f++) {
  130. if (active_toks_[f].toks == NULL) {
  131. KALDI_WARN << "GetRawLattice: no tokens active on frame " << f
  132. << ": not producing lattice.\n";
  133. return false;
  134. }
  135. for (Token *tok = active_toks_[f].toks; tok != NULL; tok = tok->next)
  136. tok_map[tok] = ofst->AddState();
  137. // The next statement sets the start state of the output FST.
  138. // Because we always add new states to the head of the list
  139. // active_toks_[f].toks, and the start state was the first one
  140. // added, it will be the last one added to ofst.
  141. if (f == 0 && ofst->NumStates() > 0)
  142. ofst->SetStart(ofst->NumStates()-1);
  143. }
  144. KALDI_VLOG(3) << "init:" << num_toks_/2 + 3 << " buckets:"
  145. << tok_map.bucket_count() << " load:" << tok_map.load_factor()
  146. << " max:" << tok_map.max_load_factor();
  147. // Now create all arcs.
  148. StateId cur_state = 0; // we rely on the fact that we numbered these
  149. // consecutively (AddState() returns the numbers in order..)
  150. for (int32 f = 0; f <= num_frames; f++) {
  151. for (Token *tok = active_toks_[f].toks; tok != NULL; tok = tok->next,
  152. cur_state++) {
  153. for (ForwardLink *l = tok->links;
  154. l != NULL;
  155. l = l->next) {
  156. unordered_map<Token*, StateId>::const_iterator iter =
  157. tok_map.find(l->next_tok);
  158. StateId nextstate = iter->second;
  159. KALDI_ASSERT(iter != tok_map.end());
  160. Arc arc(l->ilabel, l->olabel,
  161. Weight(l->graph_cost, l->acoustic_cost),
  162. nextstate);
  163. ofst->AddArc(cur_state, arc);
  164. }
  165. if (f == num_frames) {
  166. if (use_final_probs && !final_costs_.empty()) {
  167. std::map<Token*, BaseFloat>::const_iterator iter =
  168. final_costs_.find(tok);
  169. if (iter != final_costs_.end())
  170. ofst->SetFinal(cur_state, LatticeWeight(iter->second, 0));
  171. } else {
  172. ofst->SetFinal(cur_state, LatticeWeight::One());
  173. }
  174. }
  175. }
  176. }
  177. KALDI_ASSERT(cur_state == ofst->NumStates());
  178. return (cur_state != 0);
  179. }
  180. // This function is now deprecated, since now we do determinization from
  181. // outside the LatticeBiglmFasterDecoder class.
  182. // Outputs an FST corresponding to the lattice-determinized
  183. // lattice (one path per word sequence).
  184. bool GetLattice(fst::MutableFst<CompactLatticeArc> *ofst,
  185. bool use_final_probs = true) const {
  186. Lattice raw_fst;
  187. if (!GetRawLattice(&raw_fst, use_final_probs)) return false;
  188. Invert(&raw_fst); // make it so word labels are on the input.
  189. if (!TopSort(&raw_fst)) // topological sort makes lattice-determinization more efficient
  190. KALDI_WARN << "Topological sorting of state-level lattice failed "
  191. "(probably your lexicon has empty words or your LM has epsilon cycles; this "
  192. " is a bad idea.)";
  193. // (in phase where we get backward-costs).
  194. fst::ILabelCompare<LatticeArc> ilabel_comp;
  195. ArcSort(&raw_fst, ilabel_comp); // sort on ilabel; makes
  196. // lattice-determinization more efficient.
  197. fst::DeterminizeLatticePrunedOptions lat_opts;
  198. lat_opts.max_mem = config_.det_opts.max_mem;
  199. DeterminizeLatticePruned(raw_fst, config_.lattice_beam, ofst, lat_opts);
  200. raw_fst.DeleteStates(); // Free memory-- raw_fst no longer needed.
  201. Connect(ofst); // Remove unreachable states... there might be
  202. // a small number of these, in some cases.
  203. return true;
  204. }
  205. private:
  206. inline PairId ConstructPair(StateId fst_state, StateId lm_state) {
  207. return static_cast<PairId>(fst_state) + (static_cast<PairId>(lm_state) << 32);
  208. }
  209. static inline StateId PairToState(PairId state_pair) {
  210. return static_cast<StateId>(static_cast<uint32>(state_pair));
  211. }
  212. static inline StateId PairToLmState(PairId state_pair) {
  213. return static_cast<StateId>(static_cast<uint32>(state_pair >> 32));
  214. }
  215. struct Token;
  216. // ForwardLinks are the links from a token to a token on the next frame.
  217. // or sometimes on the current frame (for input-epsilon links).
  218. struct ForwardLink {
  219. Token *next_tok; // the next token [or NULL if represents final-state]
  220. Label ilabel; // ilabel on link.
  221. Label olabel; // olabel on link.
  222. BaseFloat graph_cost; // graph cost of traversing link (contains LM, etc.)
  223. BaseFloat acoustic_cost; // acoustic cost (pre-scaled) of traversing link
  224. ForwardLink *next; // next in singly-linked list of forward links from a
  225. // token.
  226. inline ForwardLink(Token *next_tok, Label ilabel, Label olabel,
  227. BaseFloat graph_cost, BaseFloat acoustic_cost,
  228. ForwardLink *next):
  229. next_tok(next_tok), ilabel(ilabel), olabel(olabel),
  230. graph_cost(graph_cost), acoustic_cost(acoustic_cost),
  231. next(next) { }
  232. };
  233. // Token is what's resident in a particular state at a particular time.
  234. // In this decoder a Token actually contains *forward* links.
  235. // When first created, a Token just has the (total) cost. We add forward
  236. // links to it when we process the next frame.
  237. struct Token {
  238. BaseFloat tot_cost; // would equal weight.Value()... cost up to this point.
  239. BaseFloat extra_cost; // >= 0. After calling PruneForwardLinks, this equals
  240. // the minimum difference between the cost of the best path, and the cost of
  241. // this is on, and the cost of the absolute best path, under the assumption
  242. // that any of the currently active states at the decoding front may
  243. // eventually succeed (e.g. if you were to take the currently active states
  244. // one by one and compute this difference, and then take the minimum).
  245. ForwardLink *links; // Head of singly linked list of ForwardLinks
  246. Token *next; // Next in list of tokens for this frame.
  247. inline Token(BaseFloat tot_cost, BaseFloat extra_cost, ForwardLink *links,
  248. Token *next): tot_cost(tot_cost), extra_cost(extra_cost),
  249. links(links), next(next) { }
  250. inline void DeleteForwardLinks() {
  251. ForwardLink *l = links, *m;
  252. while (l != NULL) {
  253. m = l->next;
  254. delete l;
  255. l = m;
  256. }
  257. links = NULL;
  258. }
  259. };
  260. // head and tail of per-frame list of Tokens (list is in topological order),
  261. // and something saying whether we ever pruned it using PruneForwardLinks.
  262. struct TokenList {
  263. Token *toks;
  264. bool must_prune_forward_links;
  265. bool must_prune_tokens;
  266. TokenList(): toks(NULL), must_prune_forward_links(true),
  267. must_prune_tokens(true) { }
  268. };
  269. typedef HashList<PairId, Token*>::Elem Elem;
  270. void PossiblyResizeHash(size_t num_toks) {
  271. size_t new_sz = static_cast<size_t>(static_cast<BaseFloat>(num_toks)
  272. * config_.hash_ratio);
  273. if (new_sz > toks_.Size()) {
  274. toks_.SetSize(new_sz);
  275. }
  276. }
  277. // FindOrAddToken either locates a token in hash of toks_,
  278. // or if necessary inserts a new, empty token (i.e. with no forward links)
  279. // for the current frame. [note: it's inserted if necessary into hash toks_
  280. // and also into the singly linked list of tokens active on this frame
  281. // (whose head is at active_toks_[frame]).
  282. inline Elem *FindOrAddToken(PairId state_pair, int32 frame,
  283. BaseFloat tot_cost, bool emitting, bool *changed) {
  284. // Returns the Token pointer. Sets "changed" (if non-NULL) to true
  285. // if the token was newly created or the cost changed.
  286. KALDI_ASSERT(frame < active_toks_.size());
  287. Token *&toks = active_toks_[frame].toks;
  288. Elem *e_found = toks_.Insert(state_pair, NULL);
  289. if (e_found->val == NULL) { // no such token presently.
  290. const BaseFloat extra_cost = 0.0;
  291. // tokens on the currently final frame have zero extra_cost
  292. // as any of them could end up
  293. // on the winning path.
  294. Token *new_tok = new Token (tot_cost, extra_cost, NULL, toks);
  295. // NULL: no forward links yet
  296. toks = new_tok;
  297. num_toks_++;
  298. e_found->val = new_tok;
  299. if (changed) *changed = true;
  300. return e_found;
  301. } else {
  302. Token *tok = e_found->val; // There is an existing Token for this state.
  303. if (tok->tot_cost > tot_cost) { // replace old token
  304. tok->tot_cost = tot_cost;
  305. // we don't allocate a new token, the old stays linked in active_toks_
  306. // we only replace the tot_cost
  307. // in the current frame, there are no forward links (and no extra_cost)
  308. // only in ProcessNonemitting we have to delete forward links
  309. // in case we visit a state for the second time
  310. // those forward links, that lead to this replaced token before:
  311. // they remain and will hopefully be pruned later (PruneForwardLinks...)
  312. if (changed) *changed = true;
  313. } else {
  314. if (changed) *changed = false;
  315. }
  316. return e_found;
  317. }
  318. }
  319. // prunes outgoing links for all tokens in active_toks_[frame]
  320. // it's called by PruneActiveTokens
  321. // all links, that have link_extra_cost > lattice_beam are pruned
  322. void PruneForwardLinks(int32 frame, bool *extra_costs_changed,
  323. bool *links_pruned,
  324. BaseFloat delta) {
  325. // delta is the amount by which the extra_costs must change
  326. // If delta is larger, we'll tend to go back less far
  327. // toward the beginning of the file.
  328. // extra_costs_changed is set to true if extra_cost was changed for any token
  329. // links_pruned is set to true if any link in any token was pruned
  330. *extra_costs_changed = false;
  331. *links_pruned = false;
  332. KALDI_ASSERT(frame >= 0 && frame < active_toks_.size());
  333. if (active_toks_[frame].toks == NULL ) { // empty list; should not happen.
  334. if (!warned_) {
  335. KALDI_WARN << "No tokens alive [doing pruning].. warning first "
  336. "time only for each utterance\n";
  337. warned_ = true;
  338. }
  339. }
  340. // We have to iterate until there is no more change, because the links
  341. // are not guaranteed to be in topological order.
  342. bool changed = true; // difference new minus old extra cost >= delta ?
  343. while (changed) {
  344. changed = false;
  345. for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
  346. ForwardLink *link, *prev_link=NULL;
  347. // will recompute tok_extra_cost for tok.
  348. BaseFloat tok_extra_cost = std::numeric_limits<BaseFloat>::infinity();
  349. // tok_extra_cost is the best (min) of link_extra_cost of outgoing links
  350. for (link = tok->links; link != NULL; ) {
  351. // See if we need to excise this link...
  352. Token *next_tok = link->next_tok;
  353. BaseFloat link_extra_cost = next_tok->extra_cost +
  354. ((tok->tot_cost + link->acoustic_cost + link->graph_cost)
  355. - next_tok->tot_cost); // difference in brackets is >= 0
  356. // link_exta_cost is the difference in score between the best paths
  357. // through link source state and through link destination state
  358. KALDI_ASSERT(link_extra_cost == link_extra_cost); // check for NaN
  359. if (link_extra_cost > config_.lattice_beam) { // excise link
  360. ForwardLink *next_link = link->next;
  361. if (prev_link != NULL) prev_link->next = next_link;
  362. else tok->links = next_link;
  363. delete link;
  364. link = next_link; // advance link but leave prev_link the same.
  365. *links_pruned = true;
  366. } else { // keep the link and update the tok_extra_cost if needed.
  367. if (link_extra_cost < 0.0) { // this is just a precaution.
  368. if (link_extra_cost < -0.01)
  369. KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
  370. link_extra_cost = 0.0;
  371. }
  372. if (link_extra_cost < tok_extra_cost)
  373. tok_extra_cost = link_extra_cost;
  374. prev_link = link; // move to next link
  375. link = link->next;
  376. }
  377. } // for all outgoing links
  378. if (fabs(tok_extra_cost - tok->extra_cost) > delta)
  379. changed = true; // difference new minus old is bigger than delta
  380. tok->extra_cost = tok_extra_cost;
  381. // will be +infinity or <= lattice_beam_.
  382. // infinity indicates, that no forward link survived pruning
  383. } // for all Token on active_toks_[frame]
  384. if (changed) *extra_costs_changed = true;
  385. // Note: it's theoretically possible that aggressive compiler
  386. // optimizations could cause an infinite loop here for small delta and
  387. // high-dynamic-range scores.
  388. } // while changed
  389. }
  390. // PruneForwardLinksFinal is a version of PruneForwardLinks that we call
  391. // on the final frame. If there are final tokens active, it uses
  392. // the final-probs for pruning, otherwise it treats all tokens as final.
  393. void PruneForwardLinksFinal(int32 frame) {
  394. KALDI_ASSERT(static_cast<size_t>(frame+1) == active_toks_.size());
  395. if (active_toks_[frame].toks == NULL ) // empty list; should not happen.
  396. KALDI_WARN << "No tokens alive at end of file\n";
  397. // First go through, working out the best token (do it in parallel
  398. // including final-probs and not including final-probs; we'll take
  399. // the one with final-probs if it's valid).
  400. const BaseFloat infinity = std::numeric_limits<BaseFloat>::infinity();
  401. BaseFloat best_cost_final = infinity,
  402. best_cost_nofinal = infinity;
  403. unordered_map<Token*, BaseFloat> tok_to_final_cost;
  404. Elem *cur_toks = toks_.Clear(); // swapping prev_toks_ / cur_toks_
  405. for (Elem *e = cur_toks, *e_tail; e != NULL; e = e_tail) {
  406. PairId state_pair = e->key;
  407. StateId state = PairToState(state_pair),
  408. lm_state = PairToLmState(state_pair);
  409. Token *tok = e->val;
  410. BaseFloat final_cost = fst_.Final(state).Value() +
  411. lm_diff_fst_->Final(lm_state).Value();
  412. tok_to_final_cost[tok] = final_cost;
  413. best_cost_final = std::min(best_cost_final, tok->tot_cost + final_cost);
  414. best_cost_nofinal = std::min(best_cost_nofinal, tok->tot_cost);
  415. e_tail = e->tail;
  416. toks_.Delete(e);
  417. }
  418. final_active_ = (best_cost_final != infinity);
  419. // Now go through tokens on this frame, pruning forward links... may have
  420. // to iterate a few times until there is no more change, because the list is
  421. // not in topological order.
  422. bool changed = true;
  423. BaseFloat delta = 1.0e-05;
  424. while (changed) {
  425. changed = false;
  426. for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
  427. ForwardLink *link, *prev_link=NULL;
  428. // will recompute tok_extra_cost. It has a term in it that corresponds
  429. // to the "final-prob", so instead of initializing tok_extra_cost to infinity
  430. // below we set it to the difference between the (score+final_prob) of this token,
  431. // and the best such (score+final_prob).
  432. BaseFloat tok_extra_cost;
  433. if (final_active_) {
  434. BaseFloat final_cost = tok_to_final_cost[tok];
  435. tok_extra_cost = (tok->tot_cost + final_cost) - best_cost_final;
  436. } else
  437. tok_extra_cost = tok->tot_cost - best_cost_nofinal;
  438. for (link = tok->links; link != NULL; ) {
  439. // See if we need to excise this link...
  440. Token *next_tok = link->next_tok;
  441. BaseFloat link_extra_cost = next_tok->extra_cost +
  442. ((tok->tot_cost + link->acoustic_cost + link->graph_cost)
  443. - next_tok->tot_cost);
  444. if (link_extra_cost > config_.lattice_beam) { // excise link
  445. ForwardLink *next_link = link->next;
  446. if (prev_link != NULL) prev_link->next = next_link;
  447. else tok->links = next_link;
  448. delete link;
  449. link = next_link; // advance link but leave prev_link the same.
  450. } else { // keep the link and update the tok_extra_cost if needed.
  451. if (link_extra_cost < 0.0) { // this is just a precaution.
  452. if (link_extra_cost < -0.01)
  453. KALDI_WARN << "Negative extra_cost: " << link_extra_cost;
  454. link_extra_cost = 0.0;
  455. }
  456. if (link_extra_cost < tok_extra_cost)
  457. tok_extra_cost = link_extra_cost;
  458. prev_link = link;
  459. link = link->next;
  460. }
  461. }
  462. // prune away tokens worse than lattice_beam above best path. This step
  463. // was not necessary in the non-final case because then, this case
  464. // showed up as having no forward links. Here, the tok_extra_cost has
  465. // an extra component relating to the final-prob.
  466. if (tok_extra_cost > config_.lattice_beam)
  467. tok_extra_cost = infinity;
  468. // to be pruned in PruneTokensForFrame
  469. if (!ApproxEqual(tok->extra_cost, tok_extra_cost, delta))
  470. changed = true;
  471. tok->extra_cost = tok_extra_cost; // will be +infinity or <= lattice_beam_.
  472. }
  473. } // while changed
  474. // Now put surviving Tokens in the final_costs_ hash, which is a class
  475. // member (unlike tok_to_final_costs).
  476. for (Token *tok = active_toks_[frame].toks; tok != NULL; tok = tok->next) {
  477. if (tok->extra_cost != infinity) {
  478. // If the token was not pruned away,
  479. if (final_active_) {
  480. BaseFloat final_cost = tok_to_final_cost[tok];
  481. if (final_cost != infinity)
  482. final_costs_[tok] = final_cost;
  483. } else {
  484. final_costs_[tok] = 0;
  485. }
  486. }
  487. }
  488. }
  489. // Prune away any tokens on this frame that have no forward links.
  490. // [we don't do this in PruneForwardLinks because it would give us
  491. // a problem with dangling pointers].
  492. // It's called by PruneActiveTokens if any forward links have been pruned
  493. void PruneTokensForFrame(int32 frame) {
  494. KALDI_ASSERT(frame >= 0 && frame < active_toks_.size());
  495. Token *&toks = active_toks_[frame].toks;
  496. if (toks == NULL)
  497. KALDI_WARN << "No tokens alive [doing pruning]\n";
  498. Token *tok, *next_tok, *prev_tok = NULL;
  499. for (tok = toks; tok != NULL; tok = next_tok) {
  500. next_tok = tok->next;
  501. if (tok->extra_cost == std::numeric_limits<BaseFloat>::infinity()) {
  502. // token is unreachable from end of graph; (no forward links survived)
  503. // excise tok from list and delete tok.
  504. if (prev_tok != NULL) prev_tok->next = tok->next;
  505. else toks = tok->next;
  506. delete tok;
  507. num_toks_--;
  508. } else { // fetch next Token
  509. prev_tok = tok;
  510. }
  511. }
  512. }
  513. // Go backwards through still-alive tokens, pruning them. note: cur_frame is
  514. // where hash toks_ are (so we do not want to mess with it because these tokens
  515. // don't yet have forward pointers), but we do all previous frames, unless we
  516. // know that we can safely ignore them because the frame after them was unchanged.
  517. // delta controls when it considers a cost to have changed enough to continue
  518. // going backward and propagating the change.
  519. // for a larger delta, we will recurse less far back
  520. void PruneActiveTokens(int32 cur_frame, BaseFloat delta) {
  521. int32 num_toks_begin = num_toks_;
  522. for (int32 frame = cur_frame-1; frame >= 0; frame--) {
  523. // Reason why we need to prune forward links in this situation:
  524. // (1) we have never pruned them (new TokenList)
  525. // (2) we have not yet pruned the forward links to the next frame,
  526. // after any of those tokens have changed their extra_cost.
  527. if (active_toks_[frame].must_prune_forward_links) {
  528. bool extra_costs_changed = false, links_pruned = false;
  529. PruneForwardLinks(frame, &extra_costs_changed, &links_pruned, delta);
  530. if (extra_costs_changed && frame > 0) // any token has changed extra_cost
  531. active_toks_[frame-1].must_prune_forward_links = true;
  532. if (links_pruned) // any link was pruned
  533. active_toks_[frame].must_prune_tokens = true;
  534. active_toks_[frame].must_prune_forward_links = false; // job done
  535. }
  536. if (frame+1 < cur_frame && // except for last frame (no forward links)
  537. active_toks_[frame+1].must_prune_tokens) {
  538. PruneTokensForFrame(frame+1);
  539. active_toks_[frame+1].must_prune_tokens = false;
  540. }
  541. }
  542. KALDI_VLOG(3) << "PruneActiveTokens: pruned tokens from " << num_toks_begin
  543. << " to " << num_toks_;
  544. }
  545. // Version of PruneActiveTokens that we call on the final frame.
  546. // Takes into account the final-prob of tokens.
  547. void PruneActiveTokensFinal(int32 cur_frame) {
  548. // returns true if there were final states active
  549. // else returns false and treats all states as final while doing the pruning
  550. // (this can be useful if you want partial lattice output,
  551. // although it can be dangerous, depending what you want the lattices for).
  552. // final_active_ and final_probs_ (a hash) are set internally
  553. // by PruneForwardLinksFinal
  554. int32 num_toks_begin = num_toks_;
  555. PruneForwardLinksFinal(cur_frame); // prune final frame (with final-probs)
  556. // sets final_active_ and final_probs_
  557. for (int32 frame = cur_frame-1; frame >= 0; frame--) {
  558. bool b1, b2; // values not used.
  559. BaseFloat dontcare = 0.0; // delta of zero means we must always update
  560. PruneForwardLinks(frame, &b1, &b2, dontcare);
  561. PruneTokensForFrame(frame+1);
  562. }
  563. PruneTokensForFrame(0);
  564. KALDI_VLOG(3) << "PruneActiveTokensFinal: pruned tokens from " << num_toks_begin
  565. << " to " << num_toks_;
  566. }
  567. /// Gets the weight cutoff. Also counts the active tokens.
  568. BaseFloat GetCutoff(Elem *list_head, size_t *tok_count,
  569. BaseFloat *adaptive_beam, Elem **best_elem) {
  570. BaseFloat best_weight = std::numeric_limits<BaseFloat>::infinity();
  571. // positive == high cost == bad.
  572. size_t count = 0;
  573. if (config_.max_active == std::numeric_limits<int32>::max()) {
  574. for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
  575. BaseFloat w = static_cast<BaseFloat>(e->val->tot_cost);
  576. if (w < best_weight) {
  577. best_weight = w;
  578. if (best_elem) *best_elem = e;
  579. }
  580. }
  581. if (tok_count != NULL) *tok_count = count;
  582. if (adaptive_beam != NULL) *adaptive_beam = config_.beam;
  583. return best_weight + config_.beam;
  584. } else {
  585. tmp_array_.clear();
  586. for (Elem *e = list_head; e != NULL; e = e->tail, count++) {
  587. BaseFloat w = e->val->tot_cost;
  588. tmp_array_.push_back(w);
  589. if (w < best_weight) {
  590. best_weight = w;
  591. if (best_elem) *best_elem = e;
  592. }
  593. }
  594. if (tok_count != NULL) *tok_count = count;
  595. if (tmp_array_.size() <= static_cast<size_t>(config_.max_active)) {
  596. if (adaptive_beam) *adaptive_beam = config_.beam;
  597. return best_weight + config_.beam;
  598. } else {
  599. // the lowest elements (lowest costs, highest likes)
  600. // will be put in the left part of tmp_array.
  601. std::nth_element(tmp_array_.begin(),
  602. tmp_array_.begin()+config_.max_active,
  603. tmp_array_.end());
  604. // return the tighter of the two beams.
  605. BaseFloat ans = std::min(best_weight + config_.beam,
  606. *(tmp_array_.begin()+config_.max_active));
  607. if (adaptive_beam)
  608. *adaptive_beam = std::min(config_.beam,
  609. ans - best_weight + config_.beam_delta);
  610. return ans;
  611. }
  612. }
  613. }
  614. inline StateId PropagateLm(StateId lm_state,
  615. Arc *arc) { // returns new LM state.
  616. if (arc->olabel == 0) {
  617. return lm_state; // no change in LM state if no word crossed.
  618. } else { // Propagate in the LM-diff FST.
  619. Arc lm_arc;
  620. bool ans = lm_diff_fst_->GetArc(lm_state, arc->olabel, &lm_arc);
  621. if (!ans) { // this case is unexpected for statistical LMs.
  622. if (!warned_noarc_) {
  623. warned_noarc_ = true;
  624. KALDI_WARN << "No arc available in LM (unlikely to be correct "
  625. "if a statistical language model); will not warn again";
  626. }
  627. arc->weight = Weight::Zero();
  628. return lm_state; // doesn't really matter what we return here; will
  629. // be pruned.
  630. } else {
  631. arc->weight = Times(arc->weight, lm_arc.weight);
  632. arc->olabel = lm_arc.olabel; // probably will be the same.
  633. return lm_arc.nextstate; // return the new LM state.
  634. }
  635. }
  636. }
  637. void ProcessEmitting(DecodableInterface *decodable, int32 frame) {
  638. // Processes emitting arcs for one frame. Propagates from prev_toks_ to cur_toks_.
  639. Elem *last_toks = toks_.Clear(); // swapping prev_toks_ / cur_toks_
  640. Elem *best_elem = NULL;
  641. BaseFloat adaptive_beam;
  642. size_t tok_cnt;
  643. BaseFloat cur_cutoff = GetCutoff(last_toks, &tok_cnt, &adaptive_beam, &best_elem);
  644. PossiblyResizeHash(tok_cnt); // This makes sure the hash is always big enough.
  645. BaseFloat next_cutoff = std::numeric_limits<BaseFloat>::infinity();
  646. // pruning "online" before having seen all tokens
  647. // First process the best token to get a hopefully
  648. // reasonably tight bound on the next cutoff.
  649. if (best_elem) {
  650. PairId state_pair = best_elem->key;
  651. StateId state = PairToState(state_pair), // state in "fst"
  652. lm_state = PairToLmState(state_pair);
  653. Token *tok = best_elem->val;
  654. for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
  655. !aiter.Done();
  656. aiter.Next()) {
  657. Arc arc = aiter.Value();
  658. if (arc.ilabel != 0) { // propagate..
  659. PropagateLm(lm_state, &arc); // may affect "arc.weight".
  660. // We don't need the return value (the new LM state).
  661. arc.weight = Times(arc.weight,
  662. Weight(-decodable->LogLikelihood(frame-1, arc.ilabel)));
  663. BaseFloat new_weight = arc.weight.Value() + tok->tot_cost;
  664. if (new_weight + adaptive_beam < next_cutoff)
  665. next_cutoff = new_weight + adaptive_beam;
  666. }
  667. }
  668. }
  669. // the tokens are now owned here, in last_toks, and the hash is empty.
  670. // 'owned' is a complex thing here; the point is we need to call DeleteElem
  671. // on each elem 'e' to let toks_ know we're done with them.
  672. for (Elem *e = last_toks, *e_tail; e != NULL; e = e_tail) {
  673. // loop this way because we delete "e" as we go.
  674. PairId state_pair = e->key;
  675. StateId state = PairToState(state_pair),
  676. lm_state = PairToLmState(state_pair);
  677. Token *tok = e->val;
  678. if (tok->tot_cost <= cur_cutoff) {
  679. for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
  680. !aiter.Done();
  681. aiter.Next()) {
  682. const Arc &arc_ref = aiter.Value();
  683. if (arc_ref.ilabel != 0) { // propagate..
  684. Arc arc(arc_ref);
  685. StateId next_lm_state = PropagateLm(lm_state, &arc);
  686. BaseFloat ac_cost = -decodable->LogLikelihood(frame-1, arc.ilabel),
  687. graph_cost = arc.weight.Value(),
  688. cur_cost = tok->tot_cost,
  689. tot_cost = cur_cost + ac_cost + graph_cost;
  690. if (tot_cost >= next_cutoff) continue;
  691. else if (tot_cost + adaptive_beam < next_cutoff)
  692. next_cutoff = tot_cost + adaptive_beam; // prune by best current token
  693. PairId next_pair = ConstructPair(arc.nextstate, next_lm_state);
  694. Elem *e_next = FindOrAddToken(next_pair, frame, tot_cost, true, NULL);
  695. // true: emitting, NULL: no change indicator needed
  696. // Add ForwardLink from tok to next_tok (put on head of list tok->links)
  697. tok->links = new ForwardLink(e_next->val, arc.ilabel, arc.olabel,
  698. graph_cost, ac_cost, tok->links);
  699. }
  700. } // for all arcs
  701. }
  702. e_tail = e->tail;
  703. toks_.Delete(e); // delete Elem
  704. }
  705. }
  706. void ProcessNonemitting(int32 frame) {
  707. // note: "frame" is the same as emitting states just processed.
  708. // Processes nonemitting arcs for one frame. Propagates within toks_.
  709. // Note-- this queue structure is is not very optimal as
  710. // it may cause us to process states unnecessarily (e.g. more than once),
  711. // but in the baseline code, turning this vector into a set to fix this
  712. // problem did not improve overall speed.
  713. KALDI_ASSERT(queue_.empty());
  714. BaseFloat best_cost = std::numeric_limits<BaseFloat>::infinity();
  715. for (const Elem *e = toks_.GetList(); e != NULL; e = e->tail) {
  716. queue_.push_back(e);
  717. // for pruning with current best token
  718. best_cost = std::min(best_cost, static_cast<BaseFloat>(e->val->tot_cost));
  719. }
  720. if (queue_.empty()) {
  721. if (!warned_) {
  722. KALDI_ERR << "Error in ProcessNonemitting: no surviving tokens: frame is "
  723. << frame;
  724. warned_ = true;
  725. }
  726. }
  727. BaseFloat cutoff = best_cost + config_.beam;
  728. while (!queue_.empty()) {
  729. const Elem *e = queue_.back();
  730. queue_.pop_back();
  731. PairId state_pair = e->key;
  732. Token *tok = e->val; // would segfault if state not in
  733. // toks_ but this can't happen.
  734. BaseFloat cur_cost = tok->tot_cost;
  735. if (cur_cost >= cutoff) // Don't bother processing successors.
  736. continue;
  737. StateId state = PairToState(state_pair),
  738. lm_state = PairToLmState(state_pair);
  739. // If "tok" has any existing forward links, delete them,
  740. // because we're about to regenerate them. This is a kind
  741. // of non-optimality (remember, this is the simple decoder),
  742. // but since most states are emitting it's not a huge issue.
  743. tok->DeleteForwardLinks(); // necessary when re-visiting
  744. tok->links = NULL;
  745. for (fst::ArcIterator<fst::Fst<Arc> > aiter(fst_, state);
  746. !aiter.Done();
  747. aiter.Next()) {
  748. const Arc &arc_ref = aiter.Value();
  749. if (arc_ref.ilabel == 0) { // propagate nonemitting only...
  750. Arc arc(arc_ref);
  751. StateId next_lm_state = PropagateLm(lm_state, &arc);
  752. BaseFloat graph_cost = arc.weight.Value(),
  753. tot_cost = cur_cost + graph_cost;
  754. if (tot_cost < cutoff) {
  755. bool changed;
  756. PairId next_pair = ConstructPair(arc.nextstate, next_lm_state);
  757. Elem *e_new = FindOrAddToken(next_pair, frame, tot_cost,
  758. false, &changed); // false: non-emit
  759. tok->links = new ForwardLink(e_new->val, 0, arc.olabel,
  760. graph_cost, 0, tok->links);
  761. // "changed" tells us whether the new token has a different
  762. // cost from before, or is new [if so, add into queue].
  763. if (changed) queue_.push_back(e_new);
  764. }
  765. }
  766. } // for all arcs
  767. } // while queue not empty
  768. }
  769. // HashList defined in ../util/hash-list.h. It actually allows us to maintain
  770. // more than one list (e.g. for current and previous frames), but only one of
  771. // them at a time can be indexed by StateId.
  772. HashList<PairId, Token*> toks_;
  773. std::vector<TokenList> active_toks_; // Lists of tokens, indexed by
  774. // frame (members of TokenList are toks, must_prune_forward_links,
  775. // must_prune_tokens).
  776. std::vector<const Elem* > queue_; // temp variable used in ProcessNonemitting,
  777. std::vector<BaseFloat> tmp_array_; // used in GetCutoff.
  778. // make it class member to avoid internal new/delete.
  779. const fst::Fst<fst::StdArc> &fst_;
  780. fst::DeterministicOnDemandFst<fst::StdArc> *lm_diff_fst_;
  781. LatticeBiglmFasterDecoderConfig config_;
  782. bool warned_noarc_;
  783. int32 num_toks_; // current total #toks allocated...
  784. bool warned_;
  785. bool final_active_; // use this to say whether we found active final tokens
  786. // on the last frame.
  787. std::map<Token*, BaseFloat> final_costs_; // A cache of final-costs
  788. // of tokens on the last frame-- it's just convenient to store it this way.
  789. // It might seem unclear why we call DeleteElems(toks_.Clear()).
  790. // There are two separate cleanup tasks we need to do at when we start a new file.
  791. // one is to delete the Token objects in the list; the other is to delete
  792. // the Elem objects. toks_.Clear() just clears them from the hash and gives ownership
  793. // to the caller, who then has to call toks_.Delete(e) for each one. It was designed
  794. // this way for convenience in propagating tokens from one frame to the next.
  795. void DeleteElems(Elem *list) {
  796. for (Elem *e = list, *e_tail; e != NULL; e = e_tail) {
  797. e_tail = e->tail;
  798. toks_.Delete(e);
  799. }
  800. toks_.Clear();
  801. }
  802. void ClearActiveTokens() { // a cleanup routine, at utt end/begin
  803. for (size_t i = 0; i < active_toks_.size(); i++) {
  804. // Delete all tokens alive on this frame, and any forward
  805. // links they may have.
  806. for (Token *tok = active_toks_[i].toks; tok != NULL; ) {
  807. tok->DeleteForwardLinks();
  808. Token *next_tok = tok->next;
  809. delete tok;
  810. num_toks_--;
  811. tok = next_tok;
  812. }
  813. }
  814. active_toks_.clear();
  815. KALDI_ASSERT(num_toks_ == 0);
  816. }
  817. };
  818. } // end namespace kaldi.
  819. #endif