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.

1357 lines
54 KiB

  1. // fstext/determinize-lattice-inl.h
  2. // Copyright 2009-2012 Microsoft Corporation
  3. // 2012-2013 Johns Hopkins University (Author: Daniel Povey)
  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_FSTEXT_DETERMINIZE_LATTICE_INL_H_
  19. #define KALDI_FSTEXT_DETERMINIZE_LATTICE_INL_H_
  20. // Do not include this file directly. It is included by determinize-lattice.h
  21. #include <algorithm>
  22. #include <climits>
  23. #include <deque>
  24. #include <string>
  25. #include <unordered_map>
  26. #include <unordered_set>
  27. #include <utility>
  28. #include <vector>
  29. namespace fst {
  30. // This class maps back and forth from/to integer id's to sequences of strings.
  31. // used in determinization algorithm. It is constructed in such a way that
  32. // finding the string-id of the successor of (string, next-label) has constant
  33. // time.
  34. // Note: class IntType, typically int32, is the type of the element in the
  35. // string (typically a template argument of the CompactLatticeWeightTpl).
  36. template <class IntType>
  37. class LatticeStringRepository {
  38. public:
  39. struct Entry {
  40. const Entry* parent; // NULL for empty string.
  41. IntType i;
  42. inline bool operator==(const Entry& other) const {
  43. return (parent == other.parent && i == other.i);
  44. }
  45. Entry() {}
  46. Entry(const Entry& e) : parent(e.parent), i(e.i) {}
  47. };
  48. // Note: all Entry* pointers returned in function calls are
  49. // owned by the repository itself, not by the caller!
  50. // Interface guarantees empty string is NULL.
  51. inline const Entry* EmptyString() { return NULL; }
  52. // Returns string of "parent" with i appended. Pointer
  53. // owned by repository
  54. const Entry* Successor(const Entry* parent, IntType i) {
  55. new_entry_->parent = parent;
  56. new_entry_->i = i;
  57. std::pair<typename SetType::iterator, bool> pr = set_.insert(new_entry_);
  58. if (pr.second) { // Was successfully inserted (was not there). We need to
  59. // replace the element we inserted, which resides on the
  60. // stack, with one from the heap.
  61. const Entry* ans = new_entry_;
  62. new_entry_ = new Entry();
  63. return ans;
  64. } else { // Was not inserted because an equivalent Entry already
  65. // existed.
  66. return *pr.first;
  67. }
  68. }
  69. const Entry* Concatenate(const Entry* a, const Entry* b) {
  70. if (a == NULL)
  71. return b;
  72. else if (b == NULL)
  73. return a;
  74. std::vector<IntType> v;
  75. ConvertToVector(b, &v);
  76. const Entry* ans = a;
  77. for (size_t i = 0; i < v.size(); i++) ans = Successor(ans, v[i]);
  78. return ans;
  79. }
  80. const Entry* CommonPrefix(const Entry* a, const Entry* b) {
  81. std::vector<IntType> a_vec, b_vec;
  82. ConvertToVector(a, &a_vec);
  83. ConvertToVector(b, &b_vec);
  84. const Entry* ans = NULL;
  85. for (size_t i = 0;
  86. i < a_vec.size() && i < b_vec.size() && a_vec[i] == b_vec[i]; i++)
  87. ans = Successor(ans, a_vec[i]);
  88. return ans;
  89. }
  90. // removes any elements from b that are not part of
  91. // a common prefix with a.
  92. void ReduceToCommonPrefix(const Entry* a, std::vector<IntType>* b) {
  93. size_t a_size = Size(a), b_size = b->size();
  94. while (a_size > b_size) {
  95. a = a->parent;
  96. a_size--;
  97. }
  98. if (b_size > a_size) b_size = a_size;
  99. typename std::vector<IntType>::iterator b_begin = b->begin();
  100. while (a_size != 0) {
  101. if (a->i != *(b_begin + a_size - 1)) b_size = a_size - 1;
  102. a = a->parent;
  103. a_size--;
  104. }
  105. if (b_size != b->size()) b->resize(b_size);
  106. }
  107. // removes the first n elements of a.
  108. const Entry* RemovePrefix(const Entry* a, size_t n) {
  109. if (n == 0) return a;
  110. std::vector<IntType> a_vec;
  111. ConvertToVector(a, &a_vec);
  112. assert(a_vec.size() >= n);
  113. const Entry* ans = NULL;
  114. for (size_t i = n; i < a_vec.size(); i++) ans = Successor(ans, a_vec[i]);
  115. return ans;
  116. }
  117. // Returns true if a is a prefix of b. If a is prefix of b,
  118. // time taken is |b| - |a|. Else, time taken is |b|.
  119. bool IsPrefixOf(const Entry* a, const Entry* b) const {
  120. if (a == NULL) return true; // empty string prefix of all.
  121. if (a == b) return true;
  122. if (b == NULL) return false;
  123. return IsPrefixOf(a, b->parent);
  124. }
  125. inline size_t Size(const Entry* entry) const {
  126. size_t ans = 0;
  127. while (entry != NULL) {
  128. ans++;
  129. entry = entry->parent;
  130. }
  131. return ans;
  132. }
  133. void ConvertToVector(const Entry* entry, std::vector<IntType>* out) const {
  134. size_t length = Size(entry);
  135. out->resize(length);
  136. if (entry != NULL) {
  137. typename std::vector<IntType>::reverse_iterator iter = out->rbegin();
  138. while (entry != NULL) {
  139. *iter = entry->i;
  140. entry = entry->parent;
  141. ++iter;
  142. }
  143. }
  144. }
  145. const Entry* ConvertFromVector(const std::vector<IntType>& vec) {
  146. const Entry* e = NULL;
  147. for (size_t i = 0; i < vec.size(); i++) e = Successor(e, vec[i]);
  148. return e;
  149. }
  150. LatticeStringRepository() { new_entry_ = new Entry; }
  151. void Destroy() {
  152. for (typename SetType::iterator iter = set_.begin(); iter != set_.end();
  153. ++iter)
  154. delete *iter;
  155. SetType tmp;
  156. tmp.swap(set_);
  157. if (new_entry_) {
  158. delete new_entry_;
  159. new_entry_ = NULL;
  160. }
  161. }
  162. // Rebuild will rebuild this object, guaranteeing only
  163. // to preserve the Entry values that are in the vector pointed
  164. // to (this list does not have to be unique). The point of
  165. // this is to save memory.
  166. void Rebuild(const std::vector<const Entry*>& to_keep) {
  167. SetType tmp_set;
  168. for (typename std::vector<const Entry*>::const_iterator iter =
  169. to_keep.begin();
  170. iter != to_keep.end(); ++iter)
  171. RebuildHelper(*iter, &tmp_set);
  172. // Now delete all elems not in tmp_set.
  173. for (typename SetType::iterator iter = set_.begin(); iter != set_.end();
  174. ++iter) {
  175. if (tmp_set.count(*iter) == 0)
  176. delete (*iter); // delete the Entry; not needed.
  177. }
  178. set_.swap(tmp_set);
  179. }
  180. ~LatticeStringRepository() { Destroy(); }
  181. int32 MemSize() const {
  182. return set_.size() * sizeof(Entry) * 2; // this is a lower bound
  183. // on the size this structure might take.
  184. }
  185. private:
  186. class EntryKey { // Hash function object.
  187. public:
  188. inline size_t operator()(const Entry* entry) const {
  189. size_t prime = 49109;
  190. return static_cast<size_t>(entry->i) +
  191. prime * reinterpret_cast<size_t>(entry->parent);
  192. }
  193. };
  194. class EntryEqual {
  195. public:
  196. inline bool operator()(const Entry* e1, const Entry* e2) const {
  197. return (*e1 == *e2);
  198. }
  199. };
  200. typedef std::unordered_set<const Entry*, EntryKey, EntryEqual> SetType;
  201. void RebuildHelper(const Entry* to_add, SetType* tmp_set) {
  202. while (true) {
  203. if (to_add == NULL) return;
  204. typename SetType::iterator iter = tmp_set->find(to_add);
  205. if (iter == tmp_set->end()) { // not in tmp_set.
  206. tmp_set->insert(to_add);
  207. to_add = to_add->parent; // and loop.
  208. } else {
  209. return;
  210. }
  211. }
  212. }
  213. KALDI_DISALLOW_COPY_AND_ASSIGN(LatticeStringRepository);
  214. Entry* new_entry_; // We always have a pre-allocated Entry ready to use,
  215. // to avoid unnecessary news and deletes.
  216. SetType set_;
  217. };
  218. // class LatticeDeterminizer is templated on the same types that
  219. // CompactLatticeWeight is templated on: the base weight (Weight), typically
  220. // LatticeWeightTpl<float> etc. but could also be e.g. TropicalWeight, and the
  221. // IntType, typically int32, used for the output symbols in the compact
  222. // representation of strings [note: the output symbols would usually be
  223. // p.d.f. id's in the anticipated use of this code] It has a special requirement
  224. // on the Weight type: that there should be a Compare function on the weights
  225. // such that Compare(w1, w2) returns -1 if w1 < w2, 0 if w1 == w2, and +1 if w1
  226. // > w2. This requires that there be a total order on the weights.
  227. template <class Weight, class IntType>
  228. class LatticeDeterminizer {
  229. public:
  230. // Output to Gallic acceptor (so the strings go on weights, and there is a 1-1
  231. // correspondence between our states and the states in ofst. If destroy ==
  232. // true, release memory as we go (but we cannot output again).
  233. typedef CompactLatticeWeightTpl<Weight, IntType> CompactWeight;
  234. typedef ArcTpl<CompactWeight>
  235. CompactArc; // arc in compact, acceptor form of lattice
  236. typedef ArcTpl<Weight> Arc; // arc in non-compact version of lattice
  237. // Output to standard FST with CompactWeightTpl<Weight> as its weight type
  238. // (the weight stores the original output-symbol strings). If destroy ==
  239. // true, release memory as we go (but we cannot output again).
  240. void Output(MutableFst<CompactArc>* ofst, bool destroy = true) {
  241. assert(determinized_);
  242. typedef typename Arc::StateId StateId;
  243. StateId nStates = static_cast<StateId>(output_arcs_.size());
  244. if (destroy) FreeMostMemory();
  245. ofst->DeleteStates();
  246. ofst->SetStart(kNoStateId);
  247. if (nStates == 0) {
  248. return;
  249. }
  250. for (StateId s = 0; s < nStates; s++) {
  251. OutputStateId news = ofst->AddState();
  252. assert(news == s);
  253. }
  254. ofst->SetStart(0);
  255. // now process transitions.
  256. for (StateId this_state = 0; this_state < nStates; this_state++) {
  257. std::vector<TempArc>& this_vec(output_arcs_[this_state]);
  258. typename std::vector<TempArc>::const_iterator iter = this_vec.begin(),
  259. end = this_vec.end();
  260. for (; iter != end; ++iter) {
  261. const TempArc& temp_arc(*iter);
  262. CompactArc new_arc;
  263. std::vector<Label> seq;
  264. repository_.ConvertToVector(temp_arc.string, &seq);
  265. CompactWeight weight(temp_arc.weight, seq);
  266. if (temp_arc.nextstate == kNoStateId) { // is really final weight.
  267. ofst->SetFinal(this_state, weight);
  268. } else { // is really an arc.
  269. new_arc.nextstate = temp_arc.nextstate;
  270. new_arc.ilabel = temp_arc.ilabel;
  271. new_arc.olabel = temp_arc.ilabel; // acceptor. input == output.
  272. new_arc.weight = weight; // includes string and weight.
  273. ofst->AddArc(this_state, new_arc);
  274. }
  275. }
  276. // Free up memory. Do this inside the loop as ofst is also allocating
  277. // memory
  278. if (destroy) {
  279. std::vector<TempArc> temp;
  280. std::swap(temp, this_vec);
  281. }
  282. }
  283. if (destroy) {
  284. std::vector<std::vector<TempArc> > temp;
  285. std::swap(temp, output_arcs_);
  286. }
  287. }
  288. // Output to standard FST with Weight as its weight type. We will create
  289. // extra states to handle sequences of symbols on the output. If destroy ==
  290. // true, release memory as we go (but we cannot output again).
  291. void Output(MutableFst<Arc>* ofst, bool destroy = true) {
  292. // Outputs to standard fst.
  293. OutputStateId nStates = static_cast<OutputStateId>(output_arcs_.size());
  294. ofst->DeleteStates();
  295. if (nStates == 0) {
  296. ofst->SetStart(kNoStateId);
  297. return;
  298. }
  299. if (destroy) FreeMostMemory();
  300. // Add basic states-- but we will add extra ones to account for strings on
  301. // output.
  302. for (OutputStateId s = 0; s < nStates; s++) {
  303. OutputStateId news = ofst->AddState();
  304. assert(news == s);
  305. }
  306. ofst->SetStart(0);
  307. for (OutputStateId this_state = 0; this_state < nStates; this_state++) {
  308. std::vector<TempArc>& this_vec(output_arcs_[this_state]);
  309. typename std::vector<TempArc>::const_iterator iter = this_vec.begin(),
  310. end = this_vec.end();
  311. for (; iter != end; ++iter) {
  312. const TempArc& temp_arc(*iter);
  313. std::vector<Label> seq;
  314. repository_.ConvertToVector(temp_arc.string, &seq);
  315. if (temp_arc.nextstate == kNoStateId) { // Really a final weight.
  316. // Make a sequence of states going to a final state, with the strings
  317. // as labels. Put the weight on the first arc.
  318. OutputStateId cur_state = this_state;
  319. for (size_t i = 0; i < seq.size(); i++) {
  320. OutputStateId next_state = ofst->AddState();
  321. Arc arc;
  322. arc.nextstate = next_state;
  323. arc.weight = (i == 0 ? temp_arc.weight : Weight::One());
  324. arc.ilabel = 0; // epsilon.
  325. arc.olabel = seq[i];
  326. ofst->AddArc(cur_state, arc);
  327. cur_state = next_state;
  328. }
  329. ofst->SetFinal(cur_state,
  330. (seq.size() == 0 ? temp_arc.weight : Weight::One()));
  331. } else { // Really an arc.
  332. OutputStateId cur_state = this_state;
  333. // Have to be careful with this integer comparison (i+1 < seq.size())
  334. // because unsigned. i < seq.size()-1 could fail for zero-length
  335. // sequences.
  336. for (size_t i = 0; i + 1 < seq.size(); i++) {
  337. // for all but the last element of seq, create new state.
  338. OutputStateId next_state = ofst->AddState();
  339. Arc arc;
  340. arc.nextstate = next_state;
  341. arc.weight = (i == 0 ? temp_arc.weight : Weight::One());
  342. arc.ilabel = (i == 0 ? temp_arc.ilabel
  343. : 0); // put ilabel on first element of seq.
  344. arc.olabel = seq[i];
  345. ofst->AddArc(cur_state, arc);
  346. cur_state = next_state;
  347. }
  348. // Add the final arc in the sequence.
  349. Arc arc;
  350. arc.nextstate = temp_arc.nextstate;
  351. arc.weight = (seq.size() <= 1 ? temp_arc.weight : Weight::One());
  352. arc.ilabel = (seq.size() <= 1 ? temp_arc.ilabel : 0);
  353. arc.olabel = (seq.size() > 0 ? seq.back() : 0);
  354. ofst->AddArc(cur_state, arc);
  355. }
  356. }
  357. // Free up memory. Do this inside the loop as ofst is also allocating
  358. // memory
  359. if (destroy) {
  360. std::vector<TempArc> temp;
  361. temp.swap(this_vec);
  362. }
  363. }
  364. if (destroy) {
  365. std::vector<std::vector<TempArc> > temp;
  366. temp.swap(output_arcs_);
  367. repository_.Destroy();
  368. }
  369. }
  370. // Initializer. After initializing the object you will typically
  371. // call Determinize() and then call one of the Output functions.
  372. // Note: ifst.Copy() will generally do a
  373. // shallow copy. We do it like this for memory safety, rather than
  374. // keeping a reference or pointer to ifst_.
  375. LatticeDeterminizer(const Fst<Arc>& ifst, DeterminizeLatticeOptions opts)
  376. : num_arcs_(0),
  377. num_elems_(0),
  378. ifst_(ifst.Copy()),
  379. opts_(opts),
  380. equal_(opts_.delta),
  381. determinized_(false),
  382. minimal_hash_(3, hasher_, equal_),
  383. initial_hash_(3, hasher_, equal_) {
  384. KALDI_ASSERT(Weight::Properties() & kIdempotent); // this algorithm won't
  385. // work correctly otherwise.
  386. }
  387. // frees all except output_arcs_, which contains the important info
  388. // we need to output the FST.
  389. void FreeMostMemory() {
  390. if (ifst_) {
  391. delete ifst_;
  392. ifst_ = NULL;
  393. }
  394. for (typename MinimalSubsetHash::iterator iter = minimal_hash_.begin();
  395. iter != minimal_hash_.end(); ++iter)
  396. delete iter->first;
  397. {
  398. MinimalSubsetHash tmp;
  399. tmp.swap(minimal_hash_);
  400. }
  401. for (typename InitialSubsetHash::iterator iter = initial_hash_.begin();
  402. iter != initial_hash_.end(); ++iter)
  403. delete iter->first;
  404. {
  405. InitialSubsetHash tmp;
  406. tmp.swap(initial_hash_);
  407. }
  408. {
  409. std::vector<std::vector<Element>*> output_states_tmp;
  410. output_states_tmp.swap(output_states_);
  411. }
  412. {
  413. std::vector<char> tmp;
  414. tmp.swap(isymbol_or_final_);
  415. }
  416. {
  417. std::vector<OutputStateId> tmp;
  418. tmp.swap(queue_);
  419. }
  420. {
  421. std::vector<std::pair<Label, Element> > tmp;
  422. tmp.swap(all_elems_tmp_);
  423. }
  424. }
  425. ~LatticeDeterminizer() {
  426. FreeMostMemory(); // rest is deleted by destructors.
  427. }
  428. void RebuildRepository() { // rebuild the string repository,
  429. // freeing stuff we don't need.. we call this when memory usage
  430. // passes a supplied threshold. We need to accumulate all the
  431. // strings we need the repository to "remember", then tell it
  432. // to clean the repository.
  433. std::vector<StringId> needed_strings;
  434. for (size_t i = 0; i < output_arcs_.size(); i++)
  435. for (size_t j = 0; j < output_arcs_[i].size(); j++)
  436. needed_strings.push_back(output_arcs_[i][j].string);
  437. // the following loop covers strings present in minimal_hash_
  438. // which are also accessible via output_states_.
  439. for (size_t i = 0; i < output_states_.size(); i++)
  440. for (size_t j = 0; j < output_states_[i]->size(); j++)
  441. needed_strings.push_back((*(output_states_[i]))[j].string);
  442. // the following loop covers strings present in initial_hash_.
  443. for (typename InitialSubsetHash::const_iterator iter =
  444. initial_hash_.begin();
  445. iter != initial_hash_.end(); ++iter) {
  446. const std::vector<Element>& vec = *(iter->first);
  447. Element elem = iter->second;
  448. for (size_t i = 0; i < vec.size(); i++)
  449. needed_strings.push_back(vec[i].string);
  450. needed_strings.push_back(elem.string);
  451. }
  452. std::sort(needed_strings.begin(), needed_strings.end());
  453. needed_strings.erase(
  454. std::unique(needed_strings.begin(), needed_strings.end()),
  455. needed_strings.end()); // uniq the strings.
  456. repository_.Rebuild(needed_strings);
  457. }
  458. bool CheckMemoryUsage() {
  459. int32 repo_size = repository_.MemSize(),
  460. arcs_size = num_arcs_ * sizeof(TempArc),
  461. elems_size = num_elems_ * sizeof(Element),
  462. total_size = repo_size + arcs_size + elems_size;
  463. if (opts_.max_mem > 0 &&
  464. total_size > opts_.max_mem) { // We passed the memory threshold.
  465. // This is usually due to the repository getting large, so we
  466. // clean this out.
  467. RebuildRepository();
  468. int32 new_repo_size = repository_.MemSize(),
  469. new_total_size = new_repo_size + arcs_size + elems_size;
  470. KALDI_VLOG(2) << "Rebuilt repository in determinize-lattice: repository "
  471. "shrank from "
  472. << repo_size << " to " << new_repo_size
  473. << " bytes (approximately)";
  474. if (new_total_size > static_cast<int32>(opts_.max_mem * 0.8)) {
  475. // Rebuilding didn't help enough-- we need a margin to stop
  476. // having to rebuild too often.
  477. KALDI_WARN << "Failure in determinize-lattice: size exceeds maximum "
  478. << opts_.max_mem << " bytes; (repo,arcs,elems) = ("
  479. << repo_size << "," << arcs_size << "," << elems_size
  480. << "), after rebuilding, repo size was " << new_repo_size;
  481. return false;
  482. }
  483. }
  484. return true;
  485. }
  486. // Returns true on success. Can fail for out-of-memory
  487. // or max-states related reasons.
  488. bool Determinize(bool* debug_ptr) {
  489. assert(!determinized_);
  490. // This determinizes the input fst but leaves it in the "special format"
  491. // in "output_arcs_". Must be called after Initialize(). To get the
  492. // output, call one of the Output routines.
  493. try {
  494. InitializeDeterminization(); // some start-up tasks.
  495. while (!queue_.empty()) {
  496. OutputStateId out_state = queue_.back();
  497. queue_.pop_back();
  498. ProcessState(out_state);
  499. if (debug_ptr && *debug_ptr) Debug(); // will exit.
  500. if (!CheckMemoryUsage()) return false;
  501. }
  502. return (determinized_ = true);
  503. } catch (const std::bad_alloc&) {
  504. int32 repo_size = repository_.MemSize(),
  505. arcs_size = num_arcs_ * sizeof(TempArc),
  506. elems_size = num_elems_ * sizeof(Element),
  507. total_size = repo_size + arcs_size + elems_size;
  508. KALDI_WARN
  509. << "Memory allocation error doing lattice determinization; using "
  510. << total_size << " bytes (max = " << opts_.max_mem
  511. << " (repo,arcs,elems) = (" << repo_size << "," << arcs_size << ","
  512. << elems_size << ")";
  513. return (determinized_ = false);
  514. } catch (const std::runtime_error&) {
  515. KALDI_WARN << "Caught exception doing lattice determinization";
  516. return (determinized_ = false);
  517. }
  518. }
  519. private:
  520. typedef typename Arc::Label Label;
  521. typedef typename Arc::StateId
  522. StateId; // use this when we don't know if it's input or output.
  523. typedef typename Arc::StateId InputStateId; // state in the input FST.
  524. typedef typename Arc::StateId OutputStateId; // same as above but distinguish
  525. // states in output Fst.
  526. typedef LatticeStringRepository<IntType> StringRepositoryType;
  527. typedef const typename StringRepositoryType::Entry* StringId;
  528. // Element of a subset [of original states]
  529. struct Element {
  530. StateId state; // use StateId as this is usually InputStateId but in one
  531. // case OutputStateId.
  532. StringId string;
  533. Weight weight;
  534. bool operator!=(const Element& other) const {
  535. return (state != other.state || string != other.string ||
  536. weight != other.weight);
  537. }
  538. // This operator is only intended to support sorting in EpsilonClosure()
  539. bool operator<(const Element& other) const { return state < other.state; }
  540. };
  541. // Arcs in the format we temporarily create in this class (a representation,
  542. // essentially of a Gallic Fst).
  543. struct TempArc {
  544. Label ilabel;
  545. StringId string; // Look it up in the StringRepository, it's a sequence of
  546. // Labels.
  547. OutputStateId nextstate; // or kNoState for final weights.
  548. Weight weight;
  549. };
  550. // Hashing function used in hash of subsets.
  551. // A subset is a pointer to vector<Element>.
  552. // The Elements are in sorted order on state id, and without repeated states.
  553. // Because the order of Elements is fixed, we can use a hashing function that
  554. // is order-dependent. However the weights are not included in the hashing
  555. // function-- we hash subsets that differ only in weight to the same key. This
  556. // is not optimal in terms of the O(N) performance but typically if we have a
  557. // lot of determinized states that differ only in weight then the input
  558. // probably was pathological in some way, or even non-determinizable.
  559. // We don't quantize the weights, in order to avoid inexactness in simple
  560. // cases.
  561. // Instead we apply the delta when comparing subsets for equality, and allow a
  562. // small difference.
  563. class SubsetKey {
  564. public:
  565. size_t operator()(const std::vector<Element>* subset)
  566. const { // hashes only the state and string.
  567. size_t hash = 0, factor = 1;
  568. for (typename std::vector<Element>::const_iterator iter = subset->begin();
  569. iter != subset->end(); ++iter) {
  570. hash *= factor;
  571. hash += iter->state + reinterpret_cast<size_t>(iter->string);
  572. factor *= 23531; // these numbers are primes.
  573. }
  574. return hash;
  575. }
  576. };
  577. // This is the equality operator on subsets. It checks for exact match on
  578. // state-id and string, and approximate match on weights.
  579. class SubsetEqual {
  580. public:
  581. bool operator()(const std::vector<Element>* s1,
  582. const std::vector<Element>* s2) const {
  583. size_t sz = s1->size();
  584. assert(sz >= 0);
  585. if (sz != s2->size()) return false;
  586. typename std::vector<Element>::const_iterator iter1 = s1->begin(),
  587. iter1_end = s1->end(),
  588. iter2 = s2->begin();
  589. for (; iter1 < iter1_end; ++iter1, ++iter2) {
  590. if (iter1->state != iter2->state || iter1->string != iter2->string ||
  591. !ApproxEqual(iter1->weight, iter2->weight, delta_))
  592. return false;
  593. }
  594. return true;
  595. }
  596. float delta_;
  597. explicit SubsetEqual(float delta) : delta_(delta) {}
  598. SubsetEqual() : delta_(kDelta) {}
  599. };
  600. // Operator that says whether two Elements have the same states.
  601. // Used only for debug.
  602. class SubsetEqualStates {
  603. public:
  604. bool operator()(const std::vector<Element>* s1,
  605. const std::vector<Element>* s2) const {
  606. size_t sz = s1->size();
  607. assert(sz >= 0);
  608. if (sz != s2->size()) return false;
  609. typename std::vector<Element>::const_iterator iter1 = s1->begin(),
  610. iter1_end = s1->end(),
  611. iter2 = s2->begin();
  612. for (; iter1 < iter1_end; ++iter1, ++iter2) {
  613. if (iter1->state != iter2->state) return false;
  614. }
  615. return true;
  616. }
  617. };
  618. // Define the hash type we use to map subsets (in minimal
  619. // representation) to OutputStateId.
  620. typedef std::unordered_map<const std::vector<Element>*, OutputStateId,
  621. SubsetKey, SubsetEqual>
  622. MinimalSubsetHash;
  623. // Define the hash type we use to map subsets (in initial
  624. // representation) to OutputStateId, together with an
  625. // extra weight. [note: we interpret the Element.state in here
  626. // as an OutputStateId even though it's declared as InputStateId;
  627. // these types are the same anyway].
  628. typedef std::unordered_map<const std::vector<Element>*, Element, SubsetKey,
  629. SubsetEqual>
  630. InitialSubsetHash;
  631. // converts the representation of the subset from canonical (all states) to
  632. // minimal (only states with output symbols on arcs leaving them, and final
  633. // states). Output is not necessarily normalized, even if input_subset was.
  634. void ConvertToMinimal(std::vector<Element>* subset) {
  635. assert(!subset->empty());
  636. typename std::vector<Element>::iterator cur_in = subset->begin(),
  637. cur_out = subset->begin(),
  638. end = subset->end();
  639. while (cur_in != end) {
  640. if (IsIsymbolOrFinal(cur_in->state)) { // keep it...
  641. *cur_out = *cur_in;
  642. cur_out++;
  643. }
  644. cur_in++;
  645. }
  646. subset->resize(cur_out - subset->begin());
  647. }
  648. // Takes a minimal, normalized subset, and converts it to an OutputStateId.
  649. // Involves a hash lookup, and possibly adding a new OutputStateId.
  650. // If it creates a new OutputStateId, it adds it to the queue.
  651. OutputStateId MinimalToStateId(const std::vector<Element>& subset) {
  652. typename MinimalSubsetHash::const_iterator iter =
  653. minimal_hash_.find(&subset);
  654. if (iter != minimal_hash_.end()) // Found a matching subset.
  655. return iter->second;
  656. OutputStateId ans = static_cast<OutputStateId>(output_arcs_.size());
  657. std::vector<Element>* subset_ptr = new std::vector<Element>(subset);
  658. output_states_.push_back(subset_ptr);
  659. num_elems_ += subset_ptr->size();
  660. output_arcs_.push_back(std::vector<TempArc>());
  661. minimal_hash_[subset_ptr] = ans;
  662. queue_.push_back(ans);
  663. return ans;
  664. }
  665. // Given a normalized initial subset of elements (i.e. before epsilon
  666. // closure), compute the corresponding output-state.
  667. OutputStateId InitialToStateId(const std::vector<Element>& subset_in,
  668. Weight* remaining_weight,
  669. StringId* common_prefix) {
  670. typename InitialSubsetHash::const_iterator iter =
  671. initial_hash_.find(&subset_in);
  672. if (iter != initial_hash_.end()) { // Found a matching subset.
  673. const Element& elem = iter->second;
  674. *remaining_weight = elem.weight;
  675. *common_prefix = elem.string;
  676. if (elem.weight == Weight::Zero()) KALDI_WARN << "Zero weight!"; // TEMP
  677. return elem.state;
  678. }
  679. // else no matching subset-- have to work it out.
  680. std::vector<Element> subset(subset_in);
  681. // Follow through epsilons. Will add no duplicate states. note: after
  682. // EpsilonClosure, it is the same as "canonical" subset, except not
  683. // normalized (actually we never compute the normalized canonical subset,
  684. // only the normalized minimal one).
  685. EpsilonClosure(&subset); // follow epsilons.
  686. ConvertToMinimal(&subset); // remove all but emitting and final states.
  687. Element elem; // will be used to store remaining weight and string, and
  688. // OutputStateId, in initial_hash_;
  689. NormalizeSubset(&subset, &elem.weight,
  690. &elem.string); // normalize subset; put
  691. // common string and weight in "elem". The subset is now a minimal,
  692. // normalized subset.
  693. OutputStateId ans = MinimalToStateId(subset);
  694. *remaining_weight = elem.weight;
  695. *common_prefix = elem.string;
  696. if (elem.weight == Weight::Zero()) KALDI_WARN << "Zero weight!"; // TEMP
  697. // Before returning "ans", add the initial subset to the hash,
  698. // so that we can bypass the epsilon-closure etc., next time
  699. // we process the same initial subset.
  700. std::vector<Element>* initial_subset_ptr =
  701. new std::vector<Element>(subset_in);
  702. elem.state = ans;
  703. initial_hash_[initial_subset_ptr] = elem;
  704. num_elems_ += initial_subset_ptr->size(); // keep track of memory usage.
  705. return ans;
  706. }
  707. // returns the Compare value (-1 if a < b, 0 if a == b, 1 if a > b) according
  708. // to the ordering we defined on strings for the CompactLatticeWeightTpl.
  709. // see function
  710. // inline int Compare (const CompactLatticeWeightTpl<WeightType,IntType> &w1,
  711. // const CompactLatticeWeightTpl<WeightType,IntType> &w2)
  712. // in lattice-weight.h.
  713. // this is the same as that, but optimized for our data structures.
  714. inline int Compare(const Weight& a_w, StringId a_str, const Weight& b_w,
  715. StringId b_str) const {
  716. int weight_comp = fst::Compare(a_w, b_w);
  717. if (weight_comp != 0) return weight_comp;
  718. // now comparing strings.
  719. if (a_str == b_str) return 0;
  720. std::vector<IntType> a_vec, b_vec;
  721. repository_.ConvertToVector(a_str, &a_vec);
  722. repository_.ConvertToVector(b_str, &b_vec);
  723. // First compare their lengths.
  724. int a_len = a_vec.size(), b_len = b_vec.size();
  725. // use opposite order on the string lengths (c.f. Compare in
  726. // lattice-weight.h)
  727. if (a_len > b_len)
  728. return -1;
  729. else if (a_len < b_len)
  730. return 1;
  731. for (int i = 0; i < a_len; i++) {
  732. if (a_vec[i] < b_vec[i])
  733. return -1;
  734. else if (a_vec[i] > b_vec[i])
  735. return 1;
  736. }
  737. assert(
  738. 0); // because we checked if a_str == b_str above, shouldn't reach here
  739. return 0;
  740. }
  741. // This function computes epsilon closure of subset of states by following
  742. // epsilon links. Called by InitialToStateId and Initialize. Has no side
  743. // effects except on the string repository. The "output_subset" is not
  744. // necessarily normalized (in the sense of there being no common substring),
  745. // unless input_subset was.
  746. void EpsilonClosure(std::vector<Element>* subset) {
  747. // at input, subset must have only one example of each StateId. [will still
  748. // be so at output]. This function follows input-epsilons, and augments the
  749. // subset accordingly.
  750. std::deque<Element> queue;
  751. std::unordered_map<InputStateId, Element> cur_subset;
  752. typedef
  753. typename std::unordered_map<InputStateId, Element>::iterator MapIter;
  754. typedef typename std::vector<Element>::const_iterator VecIter;
  755. for (VecIter iter = subset->begin(); iter != subset->end(); ++iter) {
  756. queue.push_back(*iter);
  757. cur_subset[iter->state] = *iter;
  758. }
  759. // find whether input fst is known to be sorted on input label.
  760. bool sorted =
  761. ((ifst_->Properties(kILabelSorted, false) & kILabelSorted) != 0);
  762. bool replaced_elems = false; // relates to an optimization, see below.
  763. int counter =
  764. 0; // stops infinite loops here for non-lattice-determinizable input;
  765. // useful in testing.
  766. while (queue.size() != 0) {
  767. Element elem = queue.front();
  768. queue.pop_front();
  769. // The next if-statement is a kind of optimization. It's to prevent us
  770. // unnecessarily repeating the processing of a state. "cur_subset" always
  771. // contains only one Element with a particular state. The issue is that
  772. // whenever we modify the Element corresponding to that state in
  773. // "cur_subset", both the new (optimal) and old (less-optimal) Element
  774. // will still be in "queue". The next if-statement stops us from wasting
  775. // compute by processing the old Element.
  776. if (replaced_elems && cur_subset[elem.state] != elem) continue;
  777. if (opts_.max_loop > 0 && counter++ > opts_.max_loop) {
  778. KALDI_ERR << "Lattice determinization aborted since looped more than "
  779. << opts_.max_loop << " times during epsilon closure";
  780. }
  781. for (ArcIterator<Fst<Arc> > aiter(*ifst_, elem.state); !aiter.Done();
  782. aiter.Next()) {
  783. const Arc& arc = aiter.Value();
  784. if (sorted && arc.ilabel != 0)
  785. break; // Break from the loop: due to sorting there will be no
  786. // more transitions with epsilons as input labels.
  787. if (arc.ilabel == 0 &&
  788. arc.weight != Weight::Zero()) { // Epsilon transition.
  789. Element next_elem;
  790. next_elem.state = arc.nextstate;
  791. next_elem.weight = Times(elem.weight, arc.weight);
  792. // now must append strings
  793. if (arc.olabel == 0)
  794. next_elem.string = elem.string;
  795. else
  796. next_elem.string = repository_.Successor(elem.string, arc.olabel);
  797. MapIter iter = cur_subset.find(next_elem.state);
  798. if (iter == cur_subset.end()) {
  799. // was no such StateId: insert and add to queue.
  800. cur_subset[next_elem.state] = next_elem;
  801. queue.push_back(next_elem);
  802. } else {
  803. // was not inserted because one already there. In normal
  804. // determinization we'd add the weights. Here, we find which one
  805. // has the better weight, and keep its corresponding string.
  806. int comp = Compare(next_elem.weight, next_elem.string,
  807. iter->second.weight, iter->second.string);
  808. if (comp ==
  809. 1) { // next_elem is better, so use its (weight, string)
  810. iter->second.string = next_elem.string;
  811. iter->second.weight = next_elem.weight;
  812. queue.push_back(next_elem);
  813. replaced_elems = true;
  814. }
  815. // else it is the same or worse, so use original one.
  816. }
  817. }
  818. }
  819. }
  820. { // copy cur_subset to subset.
  821. subset->clear();
  822. subset->reserve(cur_subset.size());
  823. MapIter iter = cur_subset.begin(), end = cur_subset.end();
  824. for (; iter != end; ++iter) subset->push_back(iter->second);
  825. // sort by state ID, because the subset hash function is
  826. // order-dependent(see SubsetKey)
  827. std::sort(subset->begin(), subset->end());
  828. }
  829. }
  830. // This function works out the final-weight of the determinized state.
  831. // called by ProcessSubset.
  832. // Has no side effects except on the variable repository_, and output_arcs_.
  833. void ProcessFinal(OutputStateId output_state) {
  834. const std::vector<Element>& minimal_subset =
  835. *(output_states_[output_state]);
  836. // processes final-weights for this subset.
  837. // minimal_subset may be empty if the graphs is not connected/trimmed, I
  838. // think, do don't check that it's nonempty.
  839. bool is_final = false;
  840. StringId final_string = NULL; // = NULL to keep compiler happy.
  841. Weight final_weight = Weight::Zero();
  842. typename std::vector<Element>::const_iterator iter = minimal_subset.begin(),
  843. end = minimal_subset.end();
  844. for (; iter != end; ++iter) {
  845. const Element& elem = *iter;
  846. Weight this_final_weight = Times(elem.weight, ifst_->Final(elem.state));
  847. StringId this_final_string = elem.string;
  848. if (this_final_weight != Weight::Zero() &&
  849. (!is_final || Compare(this_final_weight, this_final_string,
  850. final_weight, final_string) == 1)) { // the new
  851. // (weight, string) pair is more in semiring than our current
  852. // one.
  853. is_final = true;
  854. final_weight = this_final_weight;
  855. final_string = this_final_string;
  856. }
  857. }
  858. if (is_final) {
  859. // store final weights in TempArc structure, just like a transition.
  860. TempArc temp_arc;
  861. temp_arc.ilabel = 0;
  862. temp_arc.nextstate =
  863. kNoStateId; // special marker meaning "final weight".
  864. temp_arc.string = final_string;
  865. temp_arc.weight = final_weight;
  866. output_arcs_[output_state].push_back(temp_arc);
  867. num_arcs_++;
  868. }
  869. }
  870. // NormalizeSubset normalizes the subset "elems" by
  871. // removing any common string prefix (putting it in common_str),
  872. // and dividing by the total weight (putting it in tot_weight).
  873. void NormalizeSubset(std::vector<Element>* elems, Weight* tot_weight,
  874. StringId* common_str) {
  875. if (elems->empty()) { // just set common_str, tot_weight
  876. KALDI_WARN << "[empty subset]"; // TEMP
  877. // to defaults and return...
  878. *common_str = repository_.EmptyString();
  879. *tot_weight = Weight::Zero();
  880. return;
  881. }
  882. size_t size = elems->size();
  883. std::vector<IntType> common_prefix;
  884. repository_.ConvertToVector((*elems)[0].string, &common_prefix);
  885. Weight weight = (*elems)[0].weight;
  886. for (size_t i = 1; i < size; i++) {
  887. weight = Plus(weight, (*elems)[i].weight);
  888. repository_.ReduceToCommonPrefix((*elems)[i].string, &common_prefix);
  889. }
  890. assert(weight != Weight::Zero()); // we made sure to ignore arcs with zero
  891. // weights on them, so we shouldn't have zero here.
  892. size_t prefix_len = common_prefix.size();
  893. for (size_t i = 0; i < size; i++) {
  894. (*elems)[i].weight = Divide((*elems)[i].weight, weight, DIVIDE_LEFT);
  895. (*elems)[i].string =
  896. repository_.RemovePrefix((*elems)[i].string, prefix_len);
  897. }
  898. *common_str = repository_.ConvertFromVector(common_prefix);
  899. *tot_weight = weight;
  900. }
  901. // Take a subset of Elements that is sorted on state, and
  902. // merge any Elements that have the same state (taking the best
  903. // (weight, string) pair in the semiring).
  904. void MakeSubsetUnique(std::vector<Element>* subset) {
  905. typedef typename std::vector<Element>::iterator IterType;
  906. // This assert is designed to fail (usually) if the subset is not sorted on
  907. // state.
  908. assert(subset->size() < 2 || (*subset)[0].state <= (*subset)[1].state);
  909. IterType cur_in = subset->begin(), cur_out = cur_in, end = subset->end();
  910. size_t num_out = 0;
  911. // Merge elements with same state-id
  912. while (cur_in != end) { // while we have more elements to process.
  913. // At this point, cur_out points to location of next place we want to put
  914. // an element, cur_in points to location of next element we want to
  915. // process.
  916. if (cur_in != cur_out) *cur_out = *cur_in;
  917. cur_in++;
  918. while (cur_in != end && cur_in->state == cur_out->state) {
  919. if (Compare(cur_in->weight, cur_in->string, cur_out->weight,
  920. cur_out->string) == 1) {
  921. // if *cur_in > *cur_out in semiring, then take *cur_in.
  922. cur_out->string = cur_in->string;
  923. cur_out->weight = cur_in->weight;
  924. }
  925. cur_in++;
  926. }
  927. cur_out++;
  928. num_out++;
  929. }
  930. subset->resize(num_out);
  931. }
  932. // ProcessTransition is called from "ProcessTransitions". Broken out for
  933. // clarity. Processes a transition from state "state". The set of Elements
  934. // represents a set of next-states with associated weights and strings, each
  935. // one arising from an arc from some state in a determinized-state; the
  936. // next-states are not necessarily unique (i.e. there may be >1 entry
  937. // associated with each), and any such sets of Elements have to be merged
  938. // within this routine (we take the [weight, string] pair that's better in the
  939. // semiring).
  940. void ProcessTransition(OutputStateId state, Label ilabel,
  941. std::vector<Element>* subset) {
  942. MakeSubsetUnique(subset); // remove duplicates with the same state.
  943. StringId common_str;
  944. Weight tot_weight;
  945. NormalizeSubset(subset, &tot_weight, &common_str);
  946. OutputStateId nextstate;
  947. {
  948. Weight next_tot_weight;
  949. StringId next_common_str;
  950. nextstate = InitialToStateId(*subset, &next_tot_weight, &next_common_str);
  951. common_str = repository_.Concatenate(common_str, next_common_str);
  952. tot_weight = Times(tot_weight, next_tot_weight);
  953. }
  954. // Now add an arc to the next state (would have been created if necessary by
  955. // InitialToStateId).
  956. TempArc temp_arc;
  957. temp_arc.ilabel = ilabel;
  958. temp_arc.nextstate = nextstate;
  959. temp_arc.string = common_str;
  960. temp_arc.weight = tot_weight;
  961. output_arcs_[state].push_back(temp_arc); // record the arc.
  962. num_arcs_++;
  963. }
  964. // "less than" operator for pair<Label, Element>. Used in
  965. // ProcessTransitions. Lexicographical order, which only compares the state
  966. // when ordering the "Element" member of the pair.
  967. class PairComparator {
  968. public:
  969. inline bool operator()(const std::pair<Label, Element>& p1,
  970. const std::pair<Label, Element>& p2) {
  971. if (p1.first < p2.first) {
  972. return true;
  973. } else if (p1.first > p2.first) {
  974. return false;
  975. } else {
  976. return p1.second.state < p2.second.state;
  977. }
  978. }
  979. };
  980. // ProcessTransitions processes emitting transitions (transitions
  981. // with ilabels) out of this subset of states.
  982. // Does not consider final states. Breaks the emitting transitions up by
  983. // ilabel, and creates a new transition in the determinized FST for each
  984. // unique ilabel. Does this by creating a big vector of pairs <Label, Element>
  985. // and then sorting them using a lexicographical ordering, and calling
  986. // ProcessTransition for each range with the same ilabel. Side effects on
  987. // repository, and (via ProcessTransition) on Q_, hash_, and output_arcs_.
  988. void ProcessTransitions(OutputStateId output_state) {
  989. const std::vector<Element>& minimal_subset =
  990. *(output_states_[output_state]);
  991. // it's possible that minimal_subset could be empty if there are
  992. // unreachable parts of the graph, so don't check that it's nonempty.
  993. std::vector<std::pair<Label, Element> >& all_elems(
  994. all_elems_tmp_); // use class member
  995. // to avoid memory allocation/deallocation.
  996. {
  997. // Push back into "all_elems", elements corresponding to all
  998. // non-epsilon-input transitions out of all states in "minimal_subset".
  999. typename std::vector<Element>::const_iterator iter =
  1000. minimal_subset.begin(),
  1001. end = minimal_subset.end();
  1002. for (; iter != end; ++iter) {
  1003. const Element& elem = *iter;
  1004. for (ArcIterator<Fst<Arc> > aiter(*ifst_, elem.state); !aiter.Done();
  1005. aiter.Next()) {
  1006. const Arc& arc = aiter.Value();
  1007. if (arc.ilabel != 0 &&
  1008. arc.weight != Weight::Zero()) { // Non-epsilon transition --
  1009. // ignore epsilons here.
  1010. std::pair<Label, Element> this_pr;
  1011. this_pr.first = arc.ilabel;
  1012. Element& next_elem(this_pr.second);
  1013. next_elem.state = arc.nextstate;
  1014. next_elem.weight = Times(elem.weight, arc.weight);
  1015. if (arc.olabel == 0) // output epsilon
  1016. next_elem.string = elem.string;
  1017. else
  1018. next_elem.string = repository_.Successor(elem.string, arc.olabel);
  1019. all_elems.push_back(this_pr);
  1020. }
  1021. }
  1022. }
  1023. }
  1024. PairComparator pc;
  1025. std::sort(all_elems.begin(), all_elems.end(), pc);
  1026. // now sorted first on input label, then on state.
  1027. typedef typename std::vector<std::pair<Label, Element> >::const_iterator
  1028. PairIter;
  1029. PairIter cur = all_elems.begin(), end = all_elems.end();
  1030. std::vector<Element> this_subset;
  1031. while (cur != end) {
  1032. // Process ranges that share the same input symbol.
  1033. Label ilabel = cur->first;
  1034. this_subset.clear();
  1035. while (cur != end && cur->first == ilabel) {
  1036. this_subset.push_back(cur->second);
  1037. cur++;
  1038. }
  1039. // We now have a subset for this ilabel.
  1040. assert(!this_subset.empty()); // temp.
  1041. ProcessTransition(output_state, ilabel, &this_subset);
  1042. }
  1043. all_elems.clear(); // as it's a class variable-- want it to stay
  1044. // emtpy.
  1045. }
  1046. // ProcessState does the processing of a determinized state, i.e. it creates
  1047. // transitions out of it and the final-probability if any.
  1048. void ProcessState(OutputStateId output_state) {
  1049. ProcessFinal(output_state);
  1050. ProcessTransitions(output_state);
  1051. }
  1052. void Debug() { // this function called if you send a signal
  1053. // SIGUSR1 to the process (and it's caught by the handler in
  1054. // fstdeterminizestar). It prints out some traceback
  1055. // info and exits.
  1056. KALDI_WARN << "Debug function called (probably SIGUSR1 caught)";
  1057. // free up memory from the hash as we need a little memory
  1058. {
  1059. MinimalSubsetHash hash_tmp;
  1060. hash_tmp.swap(minimal_hash_);
  1061. }
  1062. if (output_arcs_.size() <= 2) {
  1063. KALDI_ERR << "Nothing to trace back";
  1064. }
  1065. size_t max_state = output_arcs_.size() - 2; // Don't take the last
  1066. // one as we might be halfway into constructing it.
  1067. std::vector<OutputStateId> predecessor(max_state + 1, kNoStateId);
  1068. for (size_t i = 0; i < max_state; i++) {
  1069. for (size_t j = 0; j < output_arcs_[i].size(); j++) {
  1070. OutputStateId nextstate = output_arcs_[i][j].nextstate;
  1071. // Always find an earlier-numbered predecessor; this
  1072. // is always possible because of the way the algorithm
  1073. // works.
  1074. if (nextstate <= max_state && nextstate > i) predecessor[nextstate] = i;
  1075. }
  1076. }
  1077. std::vector<std::pair<Label, StringId> > traceback;
  1078. // 'traceback' is a pair of (ilabel, olabel-seq).
  1079. OutputStateId cur_state = max_state; // A recently constructed state.
  1080. while (cur_state != 0 && cur_state != kNoStateId) {
  1081. OutputStateId last_state = predecessor[cur_state];
  1082. std::pair<Label, StringId> p;
  1083. size_t i;
  1084. for (i = 0; i < output_arcs_[last_state].size(); i++) {
  1085. if (output_arcs_[last_state][i].nextstate == cur_state) {
  1086. p.first = output_arcs_[last_state][i].ilabel;
  1087. p.second = output_arcs_[last_state][i].string;
  1088. traceback.push_back(p);
  1089. break;
  1090. }
  1091. }
  1092. KALDI_ASSERT(i != output_arcs_[last_state].size()); // Or fell off loop.
  1093. cur_state = last_state;
  1094. }
  1095. if (cur_state == kNoStateId)
  1096. KALDI_WARN << "Traceback did not reach start state "
  1097. << "(possibly debug-code error)";
  1098. std::stringstream ss;
  1099. ss << "Traceback follows in format "
  1100. << "ilabel (olabel olabel) ilabel (olabel) ... :";
  1101. for (ssize_t i = traceback.size() - 1; i >= 0; i--) {
  1102. ss << ' ' << traceback[i].first << " ( ";
  1103. std::vector<Label> seq;
  1104. repository_.ConvertToVector(traceback[i].second, &seq);
  1105. for (size_t j = 0; j < seq.size(); j++) ss << seq[j] << ' ';
  1106. ss << ')';
  1107. }
  1108. KALDI_ERR << ss.str();
  1109. }
  1110. bool IsIsymbolOrFinal(InputStateId state) { // returns true if this state
  1111. // of the input FST either is final or has an osymbol on an arc out of it.
  1112. // Uses the vector isymbol_or_final_ as a cache for this info.
  1113. assert(state >= 0);
  1114. if (isymbol_or_final_.size() <= state)
  1115. isymbol_or_final_.resize(state + 1, static_cast<char>(OSF_UNKNOWN));
  1116. if (isymbol_or_final_[state] == static_cast<char>(OSF_NO))
  1117. return false;
  1118. else if (isymbol_or_final_[state] == static_cast<char>(OSF_YES))
  1119. return true;
  1120. // else work it out...
  1121. isymbol_or_final_[state] = static_cast<char>(OSF_NO);
  1122. if (ifst_->Final(state) != Weight::Zero())
  1123. isymbol_or_final_[state] = static_cast<char>(OSF_YES);
  1124. for (ArcIterator<Fst<Arc> > aiter(*ifst_, state); !aiter.Done();
  1125. aiter.Next()) {
  1126. const Arc& arc = aiter.Value();
  1127. if (arc.ilabel != 0 && arc.weight != Weight::Zero()) {
  1128. isymbol_or_final_[state] = static_cast<char>(OSF_YES);
  1129. return true;
  1130. }
  1131. }
  1132. return IsIsymbolOrFinal(state); // will only recurse once.
  1133. }
  1134. void InitializeDeterminization() {
  1135. if (ifst_->Properties(kExpanded, false) != 0) { // if we know the number of
  1136. // states in ifst_, it might be a bit more efficient
  1137. // to pre-size the hashes so we're not constantly rebuilding them.
  1138. #if !(__GNUC__ == 4 && __GNUC_MINOR__ == 0)
  1139. StateId num_states =
  1140. down_cast<const ExpandedFst<Arc>*, const Fst<Arc> >(ifst_)
  1141. ->NumStates();
  1142. minimal_hash_.rehash(num_states / 2 + 3);
  1143. initial_hash_.rehash(num_states / 2 + 3);
  1144. #endif
  1145. }
  1146. InputStateId start_id = ifst_->Start();
  1147. if (start_id != kNoStateId) {
  1148. /* Insert determinized-state corresponding to the start state into hash
  1149. and queue. Unlike all the other states, we don't "normalize" the
  1150. representation of this determinized-state before we put it into
  1151. minimal_hash_. This is actually what we want, as otherwise we'd have
  1152. problems dealing with any extra weight and string and might have to
  1153. create a "super-initial" state which would make the output
  1154. nondeterministic. Normalization is only needed to make the
  1155. determinized output more minimal anyway, it's not needed for
  1156. correctness. Note, we don't put anything in the initial_hash_. The
  1157. initial_hash_ is only a lookaside buffer anyway, so this isn't a
  1158. problem-- it will get populated later if it needs to be.
  1159. */
  1160. Element elem;
  1161. elem.state = start_id;
  1162. elem.weight = Weight::One();
  1163. elem.string = repository_.EmptyString(); // Id of empty sequence.
  1164. std::vector<Element> subset;
  1165. subset.push_back(elem);
  1166. EpsilonClosure(&subset); // follow through epsilon-inputs links
  1167. ConvertToMinimal(&subset); // remove all but final states and
  1168. // states with input-labels on arcs out of them.
  1169. std::vector<Element>* subset_ptr = new std::vector<Element>(subset);
  1170. assert(output_arcs_.empty() && output_states_.empty());
  1171. // add the new state...
  1172. output_states_.push_back(subset_ptr);
  1173. output_arcs_.push_back(std::vector<TempArc>());
  1174. OutputStateId initial_state = 0;
  1175. minimal_hash_[subset_ptr] = initial_state;
  1176. queue_.push_back(initial_state);
  1177. }
  1178. }
  1179. KALDI_DISALLOW_COPY_AND_ASSIGN(LatticeDeterminizer);
  1180. std::vector<std::vector<Element>*>
  1181. output_states_; // maps from output state to
  1182. // minimal representation [normalized].
  1183. // View pointers as owned in
  1184. // minimal_hash_.
  1185. std::vector<std::vector<TempArc> >
  1186. output_arcs_; // essentially an FST in our format.
  1187. int num_arcs_; // keep track of memory usage: number of arcs in output_arcs_
  1188. int num_elems_; // keep track of memory usage: number of elems in
  1189. // output_states_
  1190. const Fst<Arc>* ifst_;
  1191. DeterminizeLatticeOptions opts_;
  1192. SubsetKey hasher_; // object that computes keys-- has no data members.
  1193. SubsetEqual
  1194. equal_; // object that compares subsets-- only data member is delta_.
  1195. bool determinized_; // set to true when user called Determinize(); used to
  1196. // make
  1197. // sure this object is used correctly.
  1198. MinimalSubsetHash
  1199. minimal_hash_; // hash from Subset to OutputStateId. Subset is "minimal
  1200. // representation" (only include final and states and
  1201. // states with nonzero ilabel on arc out of them. Owns
  1202. // the pointers in its keys.
  1203. InitialSubsetHash initial_hash_; // hash from Subset to Element, which
  1204. // represents the OutputStateId together
  1205. // with an extra weight and string. Subset
  1206. // is "initial representation". The extra
  1207. // weight and string is needed because after
  1208. // we convert to minimal representation and
  1209. // normalize, there may be an extra weight
  1210. // and string. Owns the pointers
  1211. // in its keys.
  1212. std::vector<OutputStateId>
  1213. queue_; // Queue of output-states to process. Starts with
  1214. // state 0, and increases and then (hopefully) decreases in length during
  1215. // determinization. LIFO queue (queue discipline doesn't really matter).
  1216. std::vector<std::pair<Label, Element> >
  1217. all_elems_tmp_; // temporary vector used in ProcessTransitions.
  1218. enum IsymbolOrFinal { OSF_UNKNOWN = 0, OSF_NO = 1, OSF_YES = 2 };
  1219. std::vector<char> isymbol_or_final_; // A kind of cache; it says whether
  1220. // each state is (emitting or final) where emitting means it has at least one
  1221. // non-epsilon output arc. Only accessed by IsIsymbolOrFinal()
  1222. LatticeStringRepository<IntType>
  1223. repository_; // defines a compact and fast way of
  1224. // storing sequences of labels.
  1225. };
  1226. // normally Weight would be LatticeWeight<float> (which has two floats),
  1227. // or possibly TropicalWeightTpl<float>, and IntType would be int32.
  1228. template <class Weight, class IntType>
  1229. bool DeterminizeLattice(const Fst<ArcTpl<Weight> >& ifst,
  1230. MutableFst<ArcTpl<Weight> >* ofst,
  1231. DeterminizeLatticeOptions opts, bool* debug_ptr) {
  1232. ofst->SetInputSymbols(ifst.InputSymbols());
  1233. ofst->SetOutputSymbols(ifst.OutputSymbols());
  1234. LatticeDeterminizer<Weight, IntType> det(ifst, opts);
  1235. if (!det.Determinize(debug_ptr)) return false;
  1236. det.Output(ofst);
  1237. return true;
  1238. }
  1239. // normally Weight would be LatticeWeight<float> (which has two floats),
  1240. // or possibly TropicalWeightTpl<float>, and IntType would be int32.
  1241. template <class Weight, class IntType>
  1242. bool DeterminizeLattice(
  1243. const Fst<ArcTpl<Weight> >& ifst,
  1244. MutableFst<ArcTpl<CompactLatticeWeightTpl<Weight, IntType> > >* ofst,
  1245. DeterminizeLatticeOptions opts, bool* debug_ptr) {
  1246. ofst->SetInputSymbols(ifst.InputSymbols());
  1247. ofst->SetOutputSymbols(ifst.OutputSymbols());
  1248. LatticeDeterminizer<Weight, IntType> det(ifst, opts);
  1249. if (!det.Determinize(debug_ptr)) return false;
  1250. det.Output(ofst);
  1251. return true;
  1252. }
  1253. } // namespace fst
  1254. #endif // KALDI_FSTEXT_DETERMINIZE_LATTICE_INL_H_