Welcome to mirror list, hosted at ThFree Co, Russian Federation.

util.h « src - github.com/moses-smt/nplm.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a8453aac0619003b7326d217073faeb3583d6695 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#pragma once

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/functional/hash.hpp>
#ifdef USE_CHRONO
#include <boost/chrono.hpp>
#endif

//#include <../3rdparty/Eigen/Dense>
#include <Eigen/Dense>

#include "maybe_omp.h"

// Make matrices hashable

namespace Eigen {
    template <typename Derived>
    size_t hash_value(const DenseBase<Derived> &m)
    {
        size_t h=0;
	for (int i=0; i<m.rows(); i++)
	    for (int j=0; j<m.cols(); j++)
	        boost::hash_combine(h, m(i,j));
	return h;
    }
}

namespace nplm
{

void splitBySpace(const std::string &line, std::vector<std::string> &items);
void readWordsFile(std::ifstream &TRAININ, std::vector<std::string> &word_list);
void readWordsFile(const std::string &file, std::vector<std::string> &word_list);
void writeWordsFile(const std::vector<std::string> &words, std::ofstream &file);
void writeWordsFile(const std::vector<std::string> &words, const std::string &filename);
void readDataFile(const std::string &filename, int &ngram_size, std::vector<int> &data, int minibatch_size=0);
void readUnigramProbs(const std::string &unigram_probs_file, std::vector<double> &unigram_probs);
void readWeightsFile(std::ifstream &TRAININ, std::vector<float> &weights);
//template <typename T> readSentFile(const std::string &file, T &sentences);


template <typename T>
void readSentFile(const std::string &file, T &sentences)
{
  std::cerr << "Reading sentences from: " << file << std::endl;

  std::ifstream TRAININ;
  TRAININ.open(file.c_str());
  if (! TRAININ)
  {
    std::cerr << "Error: can't read from file " << file<< std::endl;
    exit(-1);
  }

  std::string line;
  while (getline(TRAININ, line))
  {
    std::vector<std::string> words;
    splitBySpace(line, words);
    sentences.push_back(words);
  }

  TRAININ.close();
}

inline void intgerize(std::vector<std::string> &ngram,std::vector<int> &int_ngram){
        int ngram_size = ngram.size();
        for (int i=0;i<ngram_size;i++)
        int_ngram.push_back(boost::lexical_cast<int>(ngram[i]));
}

// Functions that take non-const matrices as arguments
// are supposed to declare them const and then use this
// to cast away constness.
#define UNCONST(t,c,uc) Eigen::MatrixBase<t> &uc = const_cast<Eigen::MatrixBase<t>&>(c);

template <typename Derived>
void initMatrix(boost::random::mt19937 &engine,
		const Eigen::MatrixBase<Derived> &p_const,
		bool init_normal, double range)
{
    UNCONST(Derived, p_const, p);
    if (init_normal == 0)
     // initialize with uniform distribution in [-range, range]
    {
        boost::random::uniform_real_distribution<> unif_real(-range, range); 
        for (int i = 0; i < p.rows(); i++)
        {
            for (int j = 0; j< p.cols(); j++)
            {
                p(i,j) = unif_real(engine);    
            }
        }

    }
    else 
      // initialize with gaussian distribution with mean 0 and stdev range
    {
        boost::random::normal_distribution<double> unif_normal(0., range);
        for (int i = 0; i < p.rows(); i++)
        {
            for (int j = 0; j < p.cols(); j++)
            {
                p(i,j) = unif_normal(engine);    
            }
        }
    }
}

template <typename Derived>
void initBias(boost::random::mt19937 &engine,
		const Eigen::MatrixBase<Derived> &p_const,
		bool init_normal, double range)
{
    UNCONST(Derived, p_const, p);
    if (init_normal == 0)
     // initialize with uniform distribution in [-range, range]
    {
        boost::random::uniform_real_distribution<> unif_real(-range, range); 
        for (int i = 0; i < p.size(); i++)
        {
            p(i) = unif_real(engine);    
        }

    }
    else 
      // initialize with gaussian distribution with mean 0 and stdev range
    {
        boost::random::normal_distribution<double> unif_normal(0., range);
        for (int i = 0; i < p.size(); i++)
        {
            p(i) = unif_normal(engine);    
        }
    }
}


template <typename Derived>
void readMatrix(std::ifstream &TRAININ, Eigen::MatrixBase<Derived> &param_const)
{
    UNCONST(Derived, param_const, param);

    int i = 0;
    std::string line;
    std::vector<std::string> fields;
    
    while (std::getline(TRAININ, line) && line != "")
    {
        splitBySpace(line, fields);
	if (fields.size() != param.cols())
	{
	    std::ostringstream err;
	    err << "error: wrong number of columns (expected " << param.cols() << ", found " << fields.size() << ")";
	    throw std::runtime_error(err.str());
	}
	
	if (i >= param.rows())
	{
	    std::ostringstream err;
	    err << "error: wrong number of rows (expected " << param.rows() << ", found " << i << ")";
	    throw std::runtime_error(err.str());
	}
	
	for (int j=0; j<fields.size(); j++)
	{
	    param(i,j) = boost::lexical_cast<typename Derived::Scalar>(fields[j]);
	}
	i++;
    }
    
    if (i != param.rows())
    {
        std::ostringstream err;
	err << "error: wrong number of rows (expected " << param.rows() << ", found more)";
	throw std::runtime_error(err.str());
    }
}

template <typename Derived>
void readMatrix(const std::string &param_file, const Eigen::MatrixBase<Derived> &param_const)
{
    UNCONST(Derived, param_const, param);
    std::cerr << "Reading data from file: " << param_file << std::endl;
    
    std::ifstream TRAININ(param_file.c_str());
    if (!TRAININ)
    {
        std::cerr << "Error: can't read training data from file " << param_file << std::endl;
	exit(-1);
    }
    readMatrix(TRAININ, param);
    TRAININ.close();
}

template <typename Derived>
void writeMatrix(const Eigen::MatrixBase<Derived> &param, const std::string &filename)
{
    std::cerr << "Writing parameters to " << filename << std::endl;

    std::ofstream OUT;
    OUT.precision(16);
    OUT.open(filename.c_str());
    if (! OUT)
    {
      std::cerr << "Error: can't write to file " << filename<< std::endl;
      exit(-1);
    }
    writeMatrix(param, OUT);
    OUT.close();
}

template <typename Derived>
void writeMatrix(const Eigen::MatrixBase<Derived> &param, std::ofstream &OUT)
{
    for (int row = 0;row < param.rows();row++)
    {
        int col;
        for (col = 0;col < param.cols()-1;col++)
        {
            OUT<<param(row,col)<<"\t";
        }
        //dont want an extra tab at the end
        OUT<<param(row,col)<<std::endl;
    }
}

template <typename Derived>
double logsum(const Eigen::MatrixBase<Derived> &v)
{
    int mi; 
    double m = v.maxCoeff(&mi);
    double logz = 0.0;
    for (int i=0; i<v.rows(); i++)
        if (i != mi)
	    logz += std::exp(v(i) - m);
    logz = log1p(logz) + m;
    return logz;
}

double logadd(double x, double y);

#ifdef USE_CHRONO
class Timer 
{
    typedef boost::chrono::high_resolution_clock clock_type;
    typedef clock_type::time_point time_type;
    typedef clock_type::duration duration_type;
    std::vector<time_type> m_start;
    std::vector<duration_type> m_total;
public:
    Timer() { }
    Timer(int n) { resize(n); }
    void resize(int n) { m_start.resize(n); m_total.resize(n); }
    int size() const { return m_start.size(); }
    void start(int i);
    void stop(int i);
    void reset(int i);
    double get(int i) const;
};

extern Timer timer;
#define start_timer(x) timer.start(x)
#define stop_timer(x) timer.stop(x)
#else
#define start_timer(x) 0
#define stop_timer(x) 0
#endif

int setup_threads(int n_threads);

} // namespace nplm