PageRenderTime 47ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/moses-cmd/src/LatticeMBRGrid.cpp

https://bitbucket.org/ufal/mosesdecoder
C++ | 213 lines | 141 code | 27 blank | 45 comment | 29 complexity | ad92db1c022210b02097b09bad38496c MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-3.0, LGPL-3.0
  1. // $Id: LatticeMBRGrid.cpp 3045 2010-04-05 13:07:29Z hieuhoang1972 $
  2. /***********************************************************************
  3. Moses - factored phrase-based language decoder
  4. Copyright (c) 2010 University of Edinburgh
  5. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without modification,
  7. are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above copyright notice,
  9. this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above copyright notice,
  11. this list of conditions and the following disclaimer in the documentation
  12. and/or other materials provided with the distribution.
  13. * Neither the name of the University of Edinburgh nor the names of its contributors
  14. may be used to endorse or promote products derived from this software
  15. without specific prior written permission.
  16. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  18. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  19. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
  20. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  21. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  22. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  23. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  24. IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  25. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  26. POSSIBILITY OF SUCH DAMAGE.
  27. ***********************************************************************/
  28. /**
  29. * Lattice MBR grid search. Enables a grid search through the four parameters (p,r,scale and prune) used in lattice MBR.
  30. See 'Lattice Minimum Bayes-Risk Decoding for Statistical Machine Translation by Tromble, Kumar, Och and Macherey,
  31. EMNLP 2008 for details of the parameters.
  32. The grid search is controlled by specifying comma separated lists for the lmbr parameters (-lmbr-p, -lmbr-r,
  33. -lmbr-pruning-factor and -mbr-scale). All other parameters are passed through to moses. If any of the lattice mbr
  34. parameters are missing, then they are set to their default values. Output is of the form:
  35. sentence-id ||| p r prune scale ||| translation-hypothesis
  36. **/
  37. #include <cstdlib>
  38. #include <iostream>
  39. #include <map>
  40. #include <stdexcept>
  41. #include <set>
  42. #include "IOWrapper.h"
  43. #include "LatticeMBR.h"
  44. #include "Manager.h"
  45. #include "StaticData.h"
  46. using namespace std;
  47. using namespace Moses;
  48. using namespace MosesCmd;
  49. //keys
  50. enum gridkey {lmbr_p,lmbr_r,lmbr_prune,lmbr_scale};
  51. namespace MosesCmd
  52. {
  53. class Grid
  54. {
  55. public:
  56. /** Add a parameter with key, command line argument, and default value */
  57. void addParam(gridkey key, const string& arg, float defaultValue) {
  58. m_args[arg] = key;
  59. CHECK(m_grid.find(key) == m_grid.end());
  60. m_grid[key].push_back(defaultValue);
  61. }
  62. /** Parse the arguments, removing those that define the grid and returning a copy of the rest */
  63. void parseArgs(int& argc, char**& argv) {
  64. char** newargv = new char*[argc+1]; //Space to add mbr parameter
  65. int newargc = 0;
  66. for (int i = 0; i < argc; ++i) {
  67. bool consumed = false;
  68. for (map<string,gridkey>::const_iterator argi = m_args.begin(); argi != m_args.end(); ++argi) {
  69. if (!strcmp(argv[i], argi->first.c_str())) {
  70. ++i;
  71. if (i >= argc) {
  72. cerr << "Error: missing parameter for " << argi->first << endl;
  73. throw runtime_error("Missing parameter");
  74. } else {
  75. string value = argv[i];
  76. gridkey key = argi->second;
  77. if (m_grid[key].size() != 1) {
  78. throw runtime_error("Duplicate grid argument");
  79. }
  80. m_grid[key].clear();
  81. char delim = ',';
  82. string::size_type lastpos = value.find_first_not_of(delim);
  83. string::size_type pos = value.find_first_of(delim,lastpos);
  84. while (string::npos != pos || string::npos != lastpos) {
  85. float param = atof(value.substr(lastpos, pos-lastpos).c_str());
  86. if (!param) {
  87. cerr << "Error: Illegal grid parameter for " << argi->first << endl;
  88. throw runtime_error("Illegal grid parameter");
  89. }
  90. m_grid[key].push_back(param);
  91. lastpos = value.find_first_not_of(delim,pos);
  92. pos = value.find_first_of(delim,lastpos);
  93. }
  94. consumed = true;
  95. }
  96. if (consumed) break;
  97. }
  98. }
  99. if (!consumed) {
  100. newargv[newargc] = new char[strlen(argv[i]) + 1];
  101. strcpy(newargv[newargc],argv[i]);
  102. ++newargc;
  103. }
  104. }
  105. argc = newargc;
  106. argv = newargv;
  107. }
  108. /** Get the grid for a particular key.*/
  109. const vector<float>& getGrid(gridkey key) const {
  110. map<gridkey,vector<float> >::const_iterator iter = m_grid.find(key);
  111. assert (iter != m_grid.end());
  112. return iter->second;
  113. }
  114. private:
  115. map<gridkey,vector<float> > m_grid;
  116. map<string,gridkey> m_args;
  117. };
  118. } // namespace
  119. int main(int argc, char* argv[])
  120. {
  121. cerr << "Lattice MBR Grid search" << endl;
  122. Grid grid;
  123. grid.addParam(lmbr_p, "-lmbr-p", 0.5);
  124. grid.addParam(lmbr_r, "-lmbr-r", 0.5);
  125. grid.addParam(lmbr_prune, "-lmbr-pruning-factor",30.0);
  126. grid.addParam(lmbr_scale, "-mbr-scale",1.0);
  127. grid.parseArgs(argc,argv);
  128. Parameter* params = new Parameter();
  129. if (!params->LoadParam(argc,argv)) {
  130. params->Explain();
  131. exit(1);
  132. }
  133. if (!StaticData::LoadDataStatic(params, argv[0])) {
  134. exit(1);
  135. }
  136. StaticData& staticData = const_cast<StaticData&>(StaticData::Instance());
  137. staticData.SetUseLatticeMBR(true);
  138. IOWrapper* ioWrapper = GetIOWrapper(staticData);
  139. if (!ioWrapper) {
  140. throw runtime_error("Failed to initialise IOWrapper");
  141. }
  142. size_t nBestSize = staticData.GetMBRSize();
  143. if (nBestSize <= 0) {
  144. throw new runtime_error("Non-positive size specified for n-best list");
  145. }
  146. size_t lineCount = 0;
  147. InputType* source = NULL;
  148. const vector<float>& pgrid = grid.getGrid(lmbr_p);
  149. const vector<float>& rgrid = grid.getGrid(lmbr_r);
  150. const vector<float>& prune_grid = grid.getGrid(lmbr_prune);
  151. const vector<float>& scale_grid = grid.getGrid(lmbr_scale);
  152. while(ReadInput(*ioWrapper,staticData.GetInputType(),source)) {
  153. ++lineCount;
  154. Sentence sentence;
  155. const TranslationSystem& system = staticData.GetTranslationSystem(TranslationSystem::DEFAULT);
  156. Manager manager(lineCount, *source, staticData.GetSearchAlgorithm(), &system);
  157. manager.ProcessSentence();
  158. TrellisPathList nBestList;
  159. manager.CalcNBest(nBestSize, nBestList,true);
  160. //grid search
  161. for (vector<float>::const_iterator pi = pgrid.begin(); pi != pgrid.end(); ++pi) {
  162. float p = *pi;
  163. staticData.SetLatticeMBRPrecision(p);
  164. for (vector<float>::const_iterator ri = rgrid.begin(); ri != rgrid.end(); ++ri) {
  165. float r = *ri;
  166. staticData.SetLatticeMBRPRatio(r);
  167. for (vector<float>::const_iterator prune_i = prune_grid.begin(); prune_i != prune_grid.end(); ++prune_i) {
  168. size_t prune = (size_t)(*prune_i);
  169. staticData.SetLatticeMBRPruningFactor(prune);
  170. for (vector<float>::const_iterator scale_i = scale_grid.begin(); scale_i != scale_grid.end(); ++scale_i) {
  171. float scale = *scale_i;
  172. staticData.SetMBRScale(scale);
  173. cout << lineCount << " ||| " << p << " " << r << " " << prune << " " << scale << " ||| ";
  174. vector<Word> mbrBestHypo = doLatticeMBR(manager,nBestList);
  175. OutputBestHypo(mbrBestHypo, lineCount, staticData.GetReportSegmentation(),
  176. staticData.GetReportAllFactors(),cout);
  177. }
  178. }
  179. }
  180. }
  181. }
  182. }