You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

556 lines
25 KiB

  1. // decoder/lattice-faster-decoder.h
  2. // Copyright 2009-2013 Microsoft Corporation; Mirko Hannemann;
  3. // 2013-2014 Johns Hopkins University (Author: Daniel Povey)
  4. // 2014 Guoguo Chen
  5. // 2018 Zhehuai Chen
  6. // 2021 Binbin Zhang, Zhendong Peng
  7. // See ../../COPYING for clarification regarding multiple authors
  8. //
  9. // Licensed under the Apache License, Version 2.0 (the "License");
  10. // you may not use this file except in compliance with the License.
  11. // You may obtain a copy of the License at
  12. //
  13. // http://www.apache.org/licenses/LICENSE-2.0
  14. //
  15. // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  17. // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  18. // MERCHANTABLITY OR NON-INFRINGEMENT.
  19. // See the Apache 2 License for the specific language governing permissions and
  20. // limitations under the License.
  21. #ifndef KALDI_DECODER_LATTICE_FASTER_DECODER_H_
  22. #define KALDI_DECODER_LATTICE_FASTER_DECODER_H_
  23. #include <limits>
  24. #include <memory>
  25. #include <unordered_map>
  26. #include <vector>
  27. #include "base/kaldi-common.h"
  28. #include "decoder/context_graph.h"
  29. #include "fst/fstlib.h"
  30. #include "fstext/fstext-lib.h"
  31. #include "itf/decodable-itf.h"
  32. #include "lat/determinize-lattice-pruned.h"
  33. #include "lat/kaldi-lattice.h"
  34. #include "util/hash-list.h"
  35. namespace kaldi {
  36. struct LatticeFasterDecoderConfig {
  37. BaseFloat beam;
  38. int32 max_active;
  39. int32 min_active;
  40. BaseFloat lattice_beam;
  41. int32 prune_interval;
  42. bool determinize_lattice; // not inspected by this class... used in
  43. // command-line program.
  44. BaseFloat beam_delta;
  45. BaseFloat hash_ratio;
  46. // Note: we don't make prune_scale configurable on the command line, it's not
  47. // a very important parameter. It affects the algorithm that prunes the
  48. // tokens as we go.
  49. BaseFloat prune_scale;
  50. BaseFloat length_penalty; // for balancing the del/ins ratio, suggested -3.0
  51. // Most of the options inside det_opts are not actually queried by the
  52. // LatticeFasterDecoder class itself, but by the code that calls it, for
  53. // example in the function DecodeUtteranceLatticeFaster.
  54. fst::DeterminizeLatticePhonePrunedOptions det_opts;
  55. LatticeFasterDecoderConfig()
  56. : beam(16.0),
  57. max_active(std::numeric_limits<int32>::max()),
  58. min_active(200),
  59. lattice_beam(10.0),
  60. prune_interval(25),
  61. determinize_lattice(true),
  62. beam_delta(0.5),
  63. hash_ratio(2.0),
  64. prune_scale(0.1),
  65. length_penalty(0.0) {}
  66. void Register(OptionsItf* opts) {
  67. det_opts.Register(opts);
  68. opts->Register("beam", &beam,
  69. "Decoding beam. Larger->slower, more accurate.");
  70. opts->Register("max-active", &max_active,
  71. "Decoder max active states. Larger->slower; "
  72. "more accurate");
  73. opts->Register("min-active", &min_active,
  74. "Decoder minimum #active states.");
  75. opts->Register("lattice-beam", &lattice_beam,
  76. "Lattice generation beam. Larger->slower, "
  77. "and deeper lattices");
  78. opts->Register("prune-interval", &prune_interval,
  79. "Interval (in frames) at "
  80. "which to prune tokens");
  81. opts->Register(
  82. "determinize-lattice", &determinize_lattice,
  83. "If true, "
  84. "determinize the lattice (lattice-determinization, keeping only "
  85. "best pdf-sequence for each word-sequence).");
  86. opts->Register(
  87. "beam-delta", &beam_delta,
  88. "Increment used in decoding-- this "
  89. "parameter is obscure and relates to a speedup in the way the "
  90. "max-active constraint is applied. Larger is more accurate.");
  91. opts->Register("hash-ratio", &hash_ratio,
  92. "Setting used in decoder to "
  93. "control hash behavior");
  94. }
  95. void Check() const {
  96. KALDI_ASSERT(beam > 0.0 && max_active > 1 && lattice_beam > 0.0 &&
  97. min_active <= max_active && prune_interval > 0 &&
  98. beam_delta > 0.0 && hash_ratio >= 1.0 && prune_scale > 0.0 &&
  99. prune_scale < 1.0);
  100. }
  101. };
  102. namespace decoder {
  103. // We will template the decoder on the token type as well as the FST type; this
  104. // is a mechanism so that we can use the same underlying decoder code for
  105. // versions of the decoder that support quickly getting the best path
  106. // (LatticeFasterOnlineDecoder, see lattice-faster-online-decoder.h) and also
  107. // those that do not (LatticeFasterDecoder).
  108. // ForwardLinks are the links from a token to a token on the next frame.
  109. // or sometimes on the current frame (for input-epsilon links).
  110. template <typename Token>
  111. struct ForwardLink {
  112. using Label = fst::StdArc::Label;
  113. Token* next_tok; // the next token [or NULL if represents final-state]
  114. Label ilabel; // ilabel on arc
  115. Label olabel; // olabel on arc
  116. BaseFloat graph_cost; // graph cost of traversing arc (contains LM, etc.)
  117. BaseFloat acoustic_cost; // acoustic cost (pre-scaled) of traversing arc
  118. float context_score;
  119. ForwardLink* next; // next in singly-linked list of forward arcs (arcs
  120. // in the state-level lattice) from a token.
  121. inline ForwardLink(Token* next_tok, Label ilabel, Label olabel,
  122. BaseFloat graph_cost, BaseFloat acoustic_cost,
  123. ForwardLink* next)
  124. : next_tok(next_tok),
  125. ilabel(ilabel),
  126. olabel(olabel),
  127. graph_cost(graph_cost),
  128. acoustic_cost(acoustic_cost),
  129. context_score(0),
  130. next(next) {}
  131. };
  132. struct StdToken {
  133. using ForwardLinkT = ForwardLink<StdToken>;
  134. using Token = StdToken;
  135. // Standard token type for LatticeFasterDecoder. Each active HCLG
  136. // (decoding-graph) state on each frame has one token.
  137. // tot_cost is the total (LM + acoustic) cost from the beginning of the
  138. // utterance up to this point. (but see cost_offset_, which is subtracted
  139. // to keep it in a good numerical range).
  140. BaseFloat tot_cost;
  141. // exta_cost is >= 0. After calling PruneForwardLinks, this equals the
  142. // minimum difference between the cost of the best path that this link is a
  143. // part of, and the cost of the absolute best path, under the assumption that
  144. // any of the currently active states at the decoding front may eventually
  145. // succeed (e.g. if you were to take the currently active states one by one
  146. // and compute this difference, and then take the minimum).
  147. BaseFloat extra_cost;
  148. int ilabel = -1;
  149. int context_state = 0;
  150. // 'links' is the head of singly-linked list of ForwardLinks, which is what we
  151. // use for lattice generation.
  152. ForwardLinkT* links;
  153. // 'next' is the next in the singly-linked list of tokens for this frame.
  154. Token* next;
  155. // This function does nothing and should be optimized out; it's needed
  156. // so we can share the regular LatticeFasterDecoderTpl code and the code
  157. // for LatticeFasterOnlineDecoder that supports fast traceback.
  158. inline void SetBackpointer(Token* backpointer) {}
  159. // This constructor just ignores the 'backpointer' argument. That argument is
  160. // needed so that we can use the same decoder code for LatticeFasterDecoderTpl
  161. // and LatticeFasterOnlineDecoderTpl (which needs backpointers to support a
  162. // fast way to obtain the best path).
  163. inline StdToken(BaseFloat tot_cost, BaseFloat extra_cost, ForwardLinkT* links,
  164. Token* next, Token* backpointer)
  165. : tot_cost(tot_cost),
  166. extra_cost(extra_cost),
  167. links(links),
  168. context_state(0),
  169. next(next) {}
  170. };
  171. struct BackpointerToken {
  172. using ForwardLinkT = ForwardLink<BackpointerToken>;
  173. using Token = BackpointerToken;
  174. // BackpointerToken is like Token but also
  175. // Standard token type for LatticeFasterDecoder. Each active HCLG
  176. // (decoding-graph) state on each frame has one token.
  177. // tot_cost is the total (LM + acoustic) cost from the beginning of the
  178. // utterance up to this point. (but see cost_offset_, which is subtracted
  179. // to keep it in a good numerical range).
  180. BaseFloat tot_cost;
  181. // exta_cost is >= 0. After calling PruneForwardLinks, this equals
  182. // the minimum difference between the cost of the best path, and the cost of
  183. // this is on, and the cost of the absolute best path, under the assumption
  184. // that any of the currently active states at the decoding front may
  185. // eventually succeed (e.g. if you were to take the currently active states
  186. // one by one and compute this difference, and then take the minimum).
  187. BaseFloat extra_cost;
  188. int ilabel = -1;
  189. int context_state = 0;
  190. // 'links' is the head of singly-linked list of ForwardLinks, which is what we
  191. // use for lattice generation.
  192. ForwardLinkT* links;
  193. // 'next' is the next in the singly-linked list of tokens for this frame.
  194. BackpointerToken* next;
  195. // Best preceding BackpointerToken (could be a on this frame, connected to
  196. // this via an epsilon transition, or on a previous frame). This is only
  197. // required for an efficient GetBestPath function in
  198. // LatticeFasterOnlineDecoderTpl; it plays no part in the lattice generation
  199. // (the "links" list is what stores the forward links, for that).
  200. Token* backpointer;
  201. inline void SetBackpointer(Token* backpointer) {
  202. this->backpointer = backpointer;
  203. }
  204. inline BackpointerToken(BaseFloat tot_cost, BaseFloat extra_cost,
  205. ForwardLinkT* links, Token* next, Token* backpointer)
  206. : tot_cost(tot_cost),
  207. extra_cost(extra_cost),
  208. links(links),
  209. next(next),
  210. backpointer(backpointer),
  211. context_state(0) {}
  212. };
  213. } // namespace decoder
  214. /** This is the "normal" lattice-generating decoder.
  215. See \ref lattices_generation \ref decoders_faster and \ref decoders_simple
  216. for more information.
  217. The decoder is templated on the FST type and the token type. The token type
  218. will normally be StdToken, but also may be BackpointerToken which is to
  219. support quick lookup of the current best path (see
  220. lattice-faster-online-decoder.h)
  221. The FST you invoke this decoder which is expected to equal
  222. Fst::Fst<fst::StdArc>, a.k.a. StdFst, or GrammarFst. If you invoke it with
  223. FST == StdFst and it notices that the actual FST type is
  224. fst::VectorFst<fst::StdArc> or fst::ConstFst<fst::StdArc>, the decoder object
  225. will internally cast itself to one that is templated on those more specific
  226. types; this is an optimization for speed.
  227. */
  228. template <typename FST, typename Token = decoder::StdToken>
  229. class LatticeFasterDecoderTpl {
  230. public:
  231. using Arc = typename FST::Arc;
  232. using Label = typename Arc::Label;
  233. using StateId = typename Arc::StateId;
  234. using Weight = typename Arc::Weight;
  235. using ForwardLinkT = decoder::ForwardLink<Token>;
  236. // Instantiate this class once for each thing you have to decode.
  237. // This version of the constructor does not take ownership of
  238. // 'fst'.
  239. LatticeFasterDecoderTpl(
  240. const FST& fst, const LatticeFasterDecoderConfig& config,
  241. const std::shared_ptr<wenet::ContextGraph>& context_graph = nullptr);
  242. // This version of the constructor takes ownership of the fst, and will delete
  243. // it when this object is destroyed.
  244. LatticeFasterDecoderTpl(const LatticeFasterDecoderConfig& config, FST* fst);
  245. void SetOptions(const LatticeFasterDecoderConfig& config) {
  246. config_ = config;
  247. }
  248. const LatticeFasterDecoderConfig& GetOptions() const { return config_; }
  249. ~LatticeFasterDecoderTpl();
  250. /// Decodes until there are no more frames left in the "decodable" object..
  251. /// note, this may block waiting for input if the "decodable" object blocks.
  252. /// Returns true if any kind of traceback is available (not necessarily from a
  253. /// final state).
  254. bool Decode(DecodableInterface* decodable);
  255. /// says whether a final-state was active on the last frame. If it was not,
  256. /// the lattice (or traceback) will end with states that are not final-states.
  257. bool ReachedFinal() const {
  258. return FinalRelativeCost() != std::numeric_limits<BaseFloat>::infinity();
  259. }
  260. /// Outputs an FST corresponding to the single best path through the lattice.
  261. /// Returns true if result is nonempty (using the return status is deprecated,
  262. /// it will become void). If "use_final_probs" is true AND we reached the
  263. /// final-state of the graph then it will include those as final-probs, else
  264. /// it will treat all final-probs as one. Note: this just calls
  265. /// GetRawLattice() and figures out the shortest path.
  266. bool GetBestPath(Lattice* ofst, bool use_final_probs = true) const;
  267. /// Outputs an FST corresponding to the raw, state-level
  268. /// tracebacks. Returns true if result is nonempty.
  269. /// If "use_final_probs" is true AND we reached the final-state
  270. /// of the graph then it will include those as final-probs, else
  271. /// it will treat all final-probs as one.
  272. /// The raw lattice will be topologically sorted.
  273. ///
  274. /// See also GetRawLatticePruned in lattice-faster-online-decoder.h,
  275. /// which also supports a pruning beam, in case for some reason
  276. /// you want it pruned tighter than the regular lattice beam.
  277. /// We could put that here in future needed.
  278. bool GetRawLattice(Lattice* ofst, bool use_final_probs = true) const;
  279. /// [Deprecated, users should now use GetRawLattice and determinize it
  280. /// themselves, e.g. using DeterminizeLatticePhonePrunedWrapper].
  281. /// Outputs an FST corresponding to the lattice-determinized
  282. /// lattice (one path per word sequence). Returns true if result is
  283. /// nonempty. If "use_final_probs" is true AND we reached the final-state of
  284. /// the graph then it will include those as final-probs, else it will treat
  285. /// all final-probs as one.
  286. bool GetLattice(CompactLattice* ofst, bool use_final_probs = true) const;
  287. /// InitDecoding initializes the decoding, and should only be used if you
  288. /// intend to call AdvanceDecoding(). If you call Decode(), you don't need to
  289. /// call this. You can also call InitDecoding if you have already decoded an
  290. /// utterance and want to start with a new utterance.
  291. void InitDecoding();
  292. /// This will decode until there are no more frames ready in the decodable
  293. /// object. You can keep calling it each time more frames become available.
  294. /// If max_num_frames is specified, it specifies the maximum number of frames
  295. /// the function will decode before returning.
  296. void AdvanceDecoding(DecodableInterface* decodable,
  297. int32 max_num_frames = -1);
  298. /// This function may be optionally called after AdvanceDecoding(), when you
  299. /// do not plan to decode any further. It does an extra pruning step that
  300. /// will help to prune the lattices output by GetLattice and (particularly)
  301. /// GetRawLattice more completely, particularly toward the end of the
  302. /// utterance. If you call this, you cannot call AdvanceDecoding again (it
  303. /// will fail), and you cannot call GetLattice() and related functions with
  304. /// use_final_probs = false. Used to be called PruneActiveTokensFinal().
  305. void FinalizeDecoding();
  306. /// FinalRelativeCost() serves the same purpose as ReachedFinal(), but gives
  307. /// more information. It returns the difference between the best (final-cost
  308. /// plus cost) of any token on the final frame, and the best cost of any token
  309. /// on the final frame. If it is infinity it means no final-states were
  310. /// present on the final frame. It will usually be nonnegative. If it not
  311. /// too positive (e.g. < 5 is my first guess, but this is not tested) you can
  312. /// take it as a good indication that we reached the final-state with
  313. /// reasonable likelihood.
  314. BaseFloat FinalRelativeCost() const;
  315. // Returns the number of frames decoded so far. The value returned changes
  316. // whenever we call ProcessEmitting().
  317. inline int32 NumFramesDecoded() const { return active_toks_.size() - 1; }
  318. protected:
  319. // we make things protected instead of private, as code in
  320. // LatticeFasterOnlineDecoderTpl, which inherits from this, also uses the
  321. // internals.
  322. // Deletes the elements of the singly linked list tok->links.
  323. inline static void DeleteForwardLinks(Token* tok);
  324. // head of per-frame list of Tokens (list is in topological order),
  325. // and something saying whether we ever pruned it using PruneForwardLinks.
  326. struct TokenList {
  327. Token* toks;
  328. bool must_prune_forward_links;
  329. bool must_prune_tokens;
  330. TokenList()
  331. : toks(NULL), must_prune_forward_links(true), must_prune_tokens(true) {}
  332. };
  333. using Elem = typename HashList<StateId, Token*>::Elem;
  334. // Equivalent to:
  335. // struct Elem {
  336. // StateId key;
  337. // Token *val;
  338. // Elem *tail;
  339. // };
  340. void PossiblyResizeHash(size_t num_toks);
  341. // FindOrAddToken either locates a token in hash of toks_, or if necessary
  342. // inserts a new, empty token (i.e. with no forward links) for the current
  343. // frame. [note: it's inserted if necessary into hash toks_ and also into the
  344. // singly linked list of tokens active on this frame (whose head is at
  345. // active_toks_[frame]). The frame_plus_one argument is the acoustic frame
  346. // index plus one, which is used to index into the active_toks_ array.
  347. // Returns the Token pointer. Sets "changed" (if non-NULL) to true if the
  348. // token was newly created or the cost changed.
  349. // If Token == StdToken, the 'backpointer' argument has no purpose (and will
  350. // hopefully be optimized out).
  351. inline Elem* FindOrAddToken(StateId state, int32 frame_plus_one,
  352. BaseFloat tot_cost, Token* backpointer,
  353. bool* changed);
  354. // prunes outgoing links for all tokens in active_toks_[frame]
  355. // it's called by PruneActiveTokens
  356. // all links, that have link_extra_cost > lattice_beam are pruned
  357. // delta is the amount by which the extra_costs must change
  358. // before we set *extra_costs_changed = true.
  359. // If delta is larger, we'll tend to go back less far
  360. // toward the beginning of the file.
  361. // extra_costs_changed is set to true if extra_cost was changed for any token
  362. // links_pruned is set to true if any link in any token was pruned
  363. void PruneForwardLinks(int32 frame_plus_one, bool* extra_costs_changed,
  364. bool* links_pruned, BaseFloat delta);
  365. // This function computes the final-costs for tokens active on the final
  366. // frame. It outputs to final-costs, if non-NULL, a map from the Token*
  367. // pointer to the final-prob of the corresponding state, for all Tokens
  368. // that correspond to states that have final-probs. This map will be
  369. // empty if there were no final-probs. It outputs to
  370. // final_relative_cost, if non-NULL, the difference between the best
  371. // forward-cost including the final-prob cost, and the best forward-cost
  372. // without including the final-prob cost (this will usually be positive), or
  373. // infinity if there were no final-probs. [c.f. FinalRelativeCost(), which
  374. // outputs this quanitity]. It outputs to final_best_cost, if
  375. // non-NULL, the lowest for any token t active on the final frame, of
  376. // forward-cost[t] + final-cost[t], where final-cost[t] is the final-cost in
  377. // the graph of the state corresponding to token t, or the best of
  378. // forward-cost[t] if there were no final-probs active on the final frame.
  379. // You cannot call this after FinalizeDecoding() has been called; in that
  380. // case you should get the answer from class-member variables.
  381. void ComputeFinalCosts(unordered_map<Token*, BaseFloat>* final_costs,
  382. BaseFloat* final_relative_cost,
  383. BaseFloat* final_best_cost) const;
  384. // PruneForwardLinksFinal is a version of PruneForwardLinks that we call
  385. // on the final frame. If there are final tokens active, it uses
  386. // the final-probs for pruning, otherwise it treats all tokens as final.
  387. void PruneForwardLinksFinal();
  388. // Prune away any tokens on this frame that have no forward links.
  389. // [we don't do this in PruneForwardLinks because it would give us
  390. // a problem with dangling pointers].
  391. // It's called by PruneActiveTokens if any forward links have been pruned
  392. void PruneTokensForFrame(int32 frame_plus_one);
  393. // Go backwards through still-alive tokens, pruning them if the
  394. // forward+backward cost is more than lat_beam away from the best path. It's
  395. // possible to prove that this is "correct" in the sense that we won't lose
  396. // anything outside of lat_beam, regardless of what happens in the future.
  397. // delta controls when it considers a cost to have changed enough to continue
  398. // going backward and propagating the change. larger delta -> will recurse
  399. // less far.
  400. void PruneActiveTokens(BaseFloat delta);
  401. /// Gets the weight cutoff. Also counts the active tokens.
  402. BaseFloat GetCutoff(Elem* list_head, size_t* tok_count,
  403. BaseFloat* adaptive_beam, Elem** best_elem);
  404. /// Processes emitting arcs for one frame. Propagates from prev_toks_ to
  405. /// cur_toks_. Returns the cost cutoff for subsequent ProcessNonemitting() to
  406. /// use.
  407. BaseFloat ProcessEmitting(DecodableInterface* decodable);
  408. /// Processes nonemitting (epsilon) arcs for one frame. Called after
  409. /// ProcessEmitting() on each frame. The cost cutoff is computed by the
  410. /// preceding ProcessEmitting().
  411. void ProcessNonemitting(BaseFloat cost_cutoff);
  412. // HashList defined in ../util/hash-list.h. It actually allows us to maintain
  413. // more than one list (e.g. for current and previous frames), but only one of
  414. // them at a time can be indexed by StateId. It is indexed by frame-index
  415. // plus one, where the frame-index is zero-based, as used in decodable object.
  416. // That is, the emitting probs of frame t are accounted for in tokens at
  417. // toks_[t+1]. The zeroth frame is for nonemitting transition at the start of
  418. // the graph.
  419. HashList<StateId, Token*> toks_;
  420. std::vector<TokenList> active_toks_; // Lists of tokens, indexed by
  421. // frame (members of TokenList are toks, must_prune_forward_links,
  422. // must_prune_tokens).
  423. std::vector<const Elem*> queue_; // temp variable used in ProcessNonemitting,
  424. std::vector<BaseFloat> tmp_array_; // used in GetCutoff.
  425. // fst_ is a pointer to the FST we are decoding from.
  426. const FST* fst_;
  427. // delete_fst_ is true if the pointer fst_ needs to be deleted when this
  428. // object is destroyed.
  429. bool delete_fst_;
  430. std::vector<BaseFloat> cost_offsets_; // This contains, for each
  431. // frame, an offset that was added to the acoustic log-likelihoods on that
  432. // frame in order to keep everything in a nice dynamic range i.e. close to
  433. // zero, to reduce roundoff errors.
  434. LatticeFasterDecoderConfig config_;
  435. int32 num_toks_; // current total #toks allocated...
  436. bool warned_;
  437. /// decoding_finalized_ is true if someone called FinalizeDecoding(). [note,
  438. /// calling this is optional]. If true, it's forbidden to decode more. Also,
  439. /// if this is set, then the output of ComputeFinalCosts() is in the next
  440. /// three variables. The reason we need to do this is that after
  441. /// FinalizeDecoding() calls PruneTokensForFrame() for the final frame, some
  442. /// of the tokens on the last frame are freed, so we free the list from toks_
  443. /// to avoid having dangling pointers hanging around.
  444. bool decoding_finalized_;
  445. /// For the meaning of the next 3 variables, see the comment for
  446. /// decoding_finalized_ above., and ComputeFinalCosts().
  447. unordered_map<Token*, BaseFloat> final_costs_;
  448. BaseFloat final_relative_cost_;
  449. BaseFloat final_best_cost_;
  450. std::shared_ptr<wenet::ContextGraph> context_graph_ = nullptr;
  451. // There are various cleanup tasks... the toks_ structure contains
  452. // singly linked lists of Token pointers, where Elem is the list type.
  453. // It also indexes them in a hash, indexed by state (this hash is only
  454. // maintained for the most recent frame). toks_.Clear()
  455. // deletes them from the hash and returns the list of Elems. The
  456. // function DeleteElems calls toks_.Delete(elem) for each elem in
  457. // the list, which returns ownership of the Elem to the toks_ structure
  458. // for reuse, but does not delete the Token pointer. The Token pointers
  459. // are reference-counted and are ultimately deleted in PruneTokensForFrame,
  460. // but are also linked together on each frame by their own linked-list,
  461. // using the "next" pointer. We delete them manually.
  462. void DeleteElems(Elem* list);
  463. // This function takes a singly linked list of tokens for a single frame, and
  464. // outputs a list of them in topological order (it will crash if no such order
  465. // can be found, which will typically be due to decoding graphs with epsilon
  466. // cycles, which are not allowed). Note: the output list may contain NULLs,
  467. // which the caller should pass over; it just happens to be more efficient for
  468. // the algorithm to output a list that contains NULLs.
  469. static void TopSortTokens(Token* tok_list,
  470. std::vector<Token*>* topsorted_list);
  471. void ClearActiveTokens();
  472. void UpdateFinalContext();
  473. KALDI_DISALLOW_COPY_AND_ASSIGN(LatticeFasterDecoderTpl);
  474. };
  475. typedef LatticeFasterDecoderTpl<fst::StdFst, decoder::StdToken>
  476. LatticeFasterDecoder;
  477. } // end namespace kaldi.
  478. #endif // KALDI_DECODER_LATTICE_FASTER_DECODER_H_