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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
|
#include <iostream>
#include <tr1/unordered_map>
#include <boost/shared_ptr.hpp>
#include <boost/functional.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "tdict.h"
#include "filelib.h"
#include "sampler.h"
#include "ccrp_onetable.h"
#include "array2d.h"
using namespace std;
using namespace std::tr1;
namespace po = boost::program_options;
void PrintTopCustomers(const CCRP_OneTable<WordID>& crp) {
for (CCRP_OneTable<WordID>::const_iterator it = crp.begin(); it != crp.end(); ++it) {
cerr << " " << TD::Convert(it->first) << " = " << it->second << endl;
}
}
void PrintAlignment(const vector<WordID>& src, const vector<WordID>& trg, const vector<unsigned char>& a) {
cerr << TD::GetString(src) << endl << TD::GetString(trg) << endl;
Array2D<bool> al(src.size(), trg.size());
for (int i = 0; i < a.size(); ++i)
if (a[i] != 255) al(a[i], i) = true;
cerr << al << endl;
}
void InitCommandLine(int argc, char** argv, po::variables_map* conf) {
po::options_description opts("Configuration options");
opts.add_options()
("samples,s",po::value<unsigned>()->default_value(1000),"Number of samples")
("input,i",po::value<string>(),"Read parallel data from")
("random_seed,S",po::value<uint32_t>(), "Random seed");
po::options_description clo("Command line options");
clo.add_options()
("config", po::value<string>(), "Configuration file")
("help,h", "Print this help message and exit");
po::options_description dconfig_options, dcmdline_options;
dconfig_options.add(opts);
dcmdline_options.add(opts).add(clo);
po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
if (conf->count("config")) {
ifstream config((*conf)["config"].as<string>().c_str());
po::store(po::parse_config_file(config, dconfig_options), *conf);
}
po::notify(*conf);
if (conf->count("help") || (conf->count("input") == 0)) {
cerr << dcmdline_options << endl;
exit(1);
}
}
struct Unigram;
struct Bigram {
Bigram() : trg(), cond() {}
Bigram(WordID prev, WordID cur, WordID t) : trg(t) { cond.first = prev; cond.second = cur; }
const pair<WordID,WordID>& ConditioningPair() const {
return cond;
}
WordID& prev_src() { return cond.first; }
WordID& cur_src() { return cond.second; }
const WordID& prev_src() const { return cond.first; }
const WordID& cur_src() const { return cond.second; }
WordID trg;
private:
pair<WordID, WordID> cond;
};
struct Unigram {
Unigram() : cur_src(), trg() {}
Unigram(WordID s, WordID t) : cur_src(s), trg(t) {}
WordID cur_src;
WordID trg;
};
ostream& operator<<(ostream& os, const Bigram& b) {
os << "( " << TD::Convert(b.trg) << " | " << TD::Convert(b.prev_src()) << " , " << TD::Convert(b.cur_src()) << " )";
return os;
}
ostream& operator<<(ostream& os, const Unigram& u) {
os << "( " << TD::Convert(u.trg) << " | " << TD::Convert(u.cur_src) << " )";
return os;
}
bool operator==(const Bigram& a, const Bigram& b) {
return a.trg == b.trg && a.cur_src() == b.cur_src() && a.prev_src() == b.prev_src();
}
bool operator==(const Unigram& a, const Unigram& b) {
return a.trg == b.trg && a.cur_src == b.cur_src;
}
size_t hash_value(const Bigram& b) {
size_t h = boost::hash_value(b.prev_src());
boost::hash_combine(h, boost::hash_value(b.cur_src()));
boost::hash_combine(h, boost::hash_value(b.trg));
return h;
}
size_t hash_value(const Unigram& u) {
size_t h = boost::hash_value(u.cur_src);
boost::hash_combine(h, boost::hash_value(u.trg));
return h;
}
void ReadParallelCorpus(const string& filename,
vector<vector<WordID> >* f,
vector<vector<WordID> >* e,
set<WordID>* vocab_f,
set<WordID>* vocab_e) {
f->clear();
e->clear();
vocab_f->clear();
vocab_e->clear();
istream* in;
if (filename == "-")
in = &cin;
else
in = new ifstream(filename.c_str());
assert(*in);
string line;
const WordID kDIV = TD::Convert("|||");
vector<WordID> tmp;
while(*in) {
getline(*in, line);
if (line.empty() && !*in) break;
e->push_back(vector<int>());
f->push_back(vector<int>());
vector<int>& le = e->back();
vector<int>& lf = f->back();
tmp.clear();
TD::ConvertSentence(line, &tmp);
bool isf = true;
for (unsigned i = 0; i < tmp.size(); ++i) {
const int cur = tmp[i];
if (isf) {
if (kDIV == cur) { isf = false; } else {
lf.push_back(cur);
vocab_f->insert(cur);
}
} else {
assert(cur != kDIV);
le.push_back(cur);
vocab_e->insert(cur);
}
}
assert(isf == false);
}
if (in != &cin) delete in;
}
struct UnigramModel {
UnigramModel(size_t src_voc_size, size_t trg_voc_size) :
unigrams(TD::NumWords() + 1, CCRP_OneTable<WordID>(1,1,1,1)),
p0(1.0 / trg_voc_size) {}
void increment(const Bigram& b) {
unigrams[b.cur_src()].increment(b.trg);
}
void decrement(const Bigram& b) {
unigrams[b.cur_src()].decrement(b.trg);
}
double prob(const Bigram& b) const {
const double q0 = unigrams[b.cur_src()].prob(b.trg, p0);
return q0;
}
double LogLikelihood() const {
double llh = 0;
for (unsigned i = 0; i < unigrams.size(); ++i) {
const CCRP_OneTable<WordID>& crp = unigrams[i];
if (crp.num_customers() > 0) {
llh += crp.log_crp_prob();
llh += crp.num_tables() * log(p0);
}
}
return llh;
}
void ResampleHyperparameters(MT19937* rng) {
for (unsigned i = 0; i < unigrams.size(); ++i)
unigrams[i].resample_hyperparameters(rng);
}
vector<CCRP_OneTable<WordID> > unigrams; // unigrams[src].prob(trg, p0) = p(trg|src)
const double p0;
};
struct BigramModel {
BigramModel(size_t src_voc_size, size_t trg_voc_size) :
unigrams(TD::NumWords() + 1, CCRP_OneTable<WordID>(1,1,1,1)),
p0(1.0 / trg_voc_size) {}
void increment(const Bigram& b) {
BigramMap::iterator it = bigrams.find(b.ConditioningPair());
if (it == bigrams.end()) {
it = bigrams.insert(make_pair(b.ConditioningPair(), CCRP_OneTable<WordID>(1,1,1,1))).first;
}
if (it->second.increment(b.trg))
unigrams[b.cur_src()].increment(b.trg);
}
void decrement(const Bigram& b) {
BigramMap::iterator it = bigrams.find(b.ConditioningPair());
assert(it != bigrams.end());
if (it->second.decrement(b.trg)) {
unigrams[b.cur_src()].decrement(b.trg);
if (it->second.num_customers() == 0)
bigrams.erase(it);
}
}
double prob(const Bigram& b) const {
const double q0 = unigrams[b.cur_src()].prob(b.trg, p0);
const BigramMap::const_iterator it = bigrams.find(b.ConditioningPair());
if (it == bigrams.end()) return q0;
return it->second.prob(b.trg, q0);
}
double LogLikelihood() const {
double llh = 0;
for (unsigned i = 0; i < unigrams.size(); ++i) {
const CCRP_OneTable<WordID>& crp = unigrams[i];
if (crp.num_customers() > 0) {
llh += crp.log_crp_prob();
llh += crp.num_tables() * log(p0);
}
}
for (BigramMap::const_iterator it = bigrams.begin(); it != bigrams.end(); ++it) {
const CCRP_OneTable<WordID>& crp = it->second;
const WordID cur_src = it->first.second;
llh += crp.log_crp_prob();
for (CCRP_OneTable<WordID>::const_iterator bit = crp.begin(); bit != crp.end(); ++bit) {
llh += log(unigrams[cur_src].prob(bit->second, p0));
}
}
return llh;
}
void ResampleHyperparameters(MT19937* rng) {
for (unsigned i = 0; i < unigrams.size(); ++i)
unigrams[i].resample_hyperparameters(rng);
for (BigramMap::iterator it = bigrams.begin(); it != bigrams.end(); ++it)
it->second.resample_hyperparameters(rng);
}
typedef unordered_map<pair<WordID,WordID>, CCRP_OneTable<WordID>, boost::hash<pair<WordID,WordID> > > BigramMap;
BigramMap bigrams; // bigrams[(src-1,src)].prob(trg, q0) = p(trg|src,src-1)
vector<CCRP_OneTable<WordID> > unigrams; // unigrams[src].prob(trg, p0) = p(trg|src)
const double p0;
};
struct BigramAlignmentModel {
BigramAlignmentModel(size_t src_voc_size, size_t trg_voc_size) : bigrams(TD::NumWords() + 1, CCRP_OneTable<WordID>(1,1,1,1)), p0(1.0 / src_voc_size) {}
void increment(WordID prev, WordID next) {
bigrams[prev].increment(next); // hierarchy?
}
void decrement(WordID prev, WordID next) {
bigrams[prev].decrement(next); // hierarchy?
}
double prob(WordID prev, WordID next) {
return bigrams[prev].prob(next, p0);
}
double LogLikelihood() const {
double llh = 0;
for (unsigned i = 0; i < bigrams.size(); ++i) {
const CCRP_OneTable<WordID>& crp = bigrams[i];
if (crp.num_customers() > 0) {
llh += crp.log_crp_prob();
llh += crp.num_tables() * log(p0);
}
}
return llh;
}
vector<CCRP_OneTable<WordID> > bigrams; // bigrams[prev].prob(next, p0) = p(next|prev)
const double p0;
};
struct Alignment {
vector<unsigned char> a;
};
int main(int argc, char** argv) {
po::variables_map conf;
InitCommandLine(argc, argv, &conf);
const unsigned samples = conf["samples"].as<unsigned>();
boost::shared_ptr<MT19937> prng;
if (conf.count("random_seed"))
prng.reset(new MT19937(conf["random_seed"].as<uint32_t>()));
else
prng.reset(new MT19937);
MT19937& rng = *prng;
vector<vector<WordID> > corpuse, corpusf;
set<WordID> vocabe, vocabf;
cerr << "Reading corpus...\n";
ReadParallelCorpus(conf["input"].as<string>(), &corpusf, &corpuse, &vocabf, &vocabe);
cerr << "F-corpus size: " << corpusf.size() << " sentences\t (" << vocabf.size() << " word types)\n";
cerr << "E-corpus size: " << corpuse.size() << " sentences\t (" << vocabe.size() << " word types)\n";
assert(corpusf.size() == corpuse.size());
const size_t corpus_len = corpusf.size();
const WordID kNULL = TD::Convert("<eps>");
const WordID kBOS = TD::Convert("<s>");
const WordID kEOS = TD::Convert("</s>");
Bigram TT(kBOS, TD::Convert("我"), TD::Convert("i"));
Bigram TT2(kBOS, TD::Convert("要"), TD::Convert("i"));
UnigramModel model(vocabf.size(), vocabe.size());
vector<Alignment> alignments(corpus_len);
for (unsigned ci = 0; ci < corpus_len; ++ci) {
const vector<WordID>& src = corpusf[ci];
const vector<WordID>& trg = corpuse[ci];
vector<unsigned char>& alg = alignments[ci].a;
alg.resize(trg.size());
int lenp1 = src.size() + 1;
WordID prev_src = kBOS;
for (int j = 0; j < trg.size(); ++j) {
int samp = lenp1 * rng.next();
--samp;
if (samp < 0) samp = 255;
alg[j] = samp;
WordID cur_src = (samp == 255 ? kNULL : src[alg[j]]);
Bigram b(prev_src, cur_src, trg[j]);
model.increment(b);
prev_src = cur_src;
}
Bigram b(prev_src, kEOS, kEOS);
model.increment(b);
}
cerr << "Initial LLH: " << model.LogLikelihood() << endl;
SampleSet<double> ss;
for (unsigned si = 0; si < 50; ++si) {
for (unsigned ci = 0; ci < corpus_len; ++ci) {
const vector<WordID>& src = corpusf[ci];
const vector<WordID>& trg = corpuse[ci];
vector<unsigned char>& alg = alignments[ci].a;
WordID prev_src = kBOS;
for (unsigned j = 0; j < trg.size(); ++j) {
unsigned char& a_j = alg[j];
WordID cur_e_a_j = (a_j == 255 ? kNULL : src[a_j]);
Bigram b(prev_src, cur_e_a_j, trg[j]);
//cerr << "DEC: " << b << "\t" << nextb << endl;
model.decrement(b);
ss.clear();
for (unsigned i = 0; i <= src.size(); ++i) {
const WordID cur_src = (i ? src[i-1] : kNULL);
b.cur_src() = cur_src;
ss.add(model.prob(b));
}
int sampled_a_j = rng.SelectSample(ss);
a_j = (sampled_a_j ? sampled_a_j - 1 : 255);
cur_e_a_j = (a_j == 255 ? kNULL : src[a_j]);
b.cur_src() = cur_e_a_j;
//cerr << "INC: " << b << "\t" << nextb << endl;
model.increment(b);
prev_src = cur_e_a_j;
}
}
cerr << '.' << flush;
if (si % 10 == 9) {
cerr << "[LLH prev=" << model.LogLikelihood();
//model.ResampleHyperparameters(&rng);
cerr << " new=" << model.LogLikelihood() << "]\n";
//pair<WordID,WordID> xx = make_pair(kBOS, TD::Convert("我"));
//PrintTopCustomers(model.bigrams.find(xx)->second);
cerr << "p(" << TT << ") = " << model.prob(TT) << endl;
cerr << "p(" << TT2 << ") = " << model.prob(TT2) << endl;
PrintAlignment(corpusf[0], corpuse[0], alignments[0].a);
}
}
{
// MODEL 2
BigramModel model(vocabf.size(), vocabe.size());
BigramAlignmentModel amodel(vocabf.size(), vocabe.size());
for (unsigned ci = 0; ci < corpus_len; ++ci) {
const vector<WordID>& src = corpusf[ci];
const vector<WordID>& trg = corpuse[ci];
vector<unsigned char>& alg = alignments[ci].a;
WordID prev_src = kBOS;
for (int j = 0; j < trg.size(); ++j) {
WordID cur_src = (alg[j] == 255 ? kNULL : src[alg[j]]);
Bigram b(prev_src, cur_src, trg[j]);
model.increment(b);
amodel.increment(prev_src, cur_src);
prev_src = cur_src;
}
amodel.increment(prev_src, kEOS);
Bigram b(prev_src, kEOS, kEOS);
model.increment(b);
}
cerr << "Initial LLH: " << model.LogLikelihood() << " " << amodel.LogLikelihood() << endl;
SampleSet<double> ss;
for (unsigned si = 0; si < samples; ++si) {
for (unsigned ci = 0; ci < corpus_len; ++ci) {
const vector<WordID>& src = corpusf[ci];
const vector<WordID>& trg = corpuse[ci];
vector<unsigned char>& alg = alignments[ci].a;
WordID prev_src = kBOS;
for (unsigned j = 0; j < trg.size(); ++j) {
unsigned char& a_j = alg[j];
WordID cur_e_a_j = (a_j == 255 ? kNULL : src[a_j]);
Bigram b(prev_src, cur_e_a_j, trg[j]);
WordID next_src = kEOS;
WordID next_trg = kEOS;
if (j < (trg.size() - 1)) {
next_src = (alg[j+1] == 255 ? kNULL : src[alg[j + 1]]);
next_trg = trg[j + 1];
}
Bigram nextb(cur_e_a_j, next_src, next_trg);
//cerr << "DEC: " << b << "\t" << nextb << endl;
model.decrement(b);
model.decrement(nextb);
amodel.decrement(prev_src, cur_e_a_j);
amodel.decrement(cur_e_a_j, next_src);
ss.clear();
for (unsigned i = 0; i <= src.size(); ++i) {
const WordID cur_src = (i ? src[i-1] : kNULL);
b.cur_src() = cur_src;
ss.add(model.prob(b) * model.prob(nextb) * amodel.prob(prev_src, cur_src) * amodel.prob(cur_src, next_src));
//cerr << log(ss[ss.size() - 1]) << "\t" << b << endl;
}
int sampled_a_j = rng.SelectSample(ss);
a_j = (sampled_a_j ? sampled_a_j - 1 : 255);
cur_e_a_j = (a_j == 255 ? kNULL : src[a_j]);
b.cur_src() = cur_e_a_j;
nextb.prev_src() = cur_e_a_j;
//cerr << "INC: " << b << "\t" << nextb << endl;
//exit(1);
model.increment(b);
model.increment(nextb);
amodel.increment(prev_src, cur_e_a_j);
amodel.increment(cur_e_a_j, next_src);
prev_src = cur_e_a_j;
}
}
cerr << '.' << flush;
if (si % 10 == 9) {
cerr << "[LLH prev=" << (model.LogLikelihood() + amodel.LogLikelihood());
//model.ResampleHyperparameters(&rng);
cerr << " new=" << model.LogLikelihood() << "]\n";
pair<WordID,WordID> xx = make_pair(kBOS, TD::Convert("我"));
cerr << "p(" << TT << ") = " << model.prob(TT) << endl;
cerr << "p(" << TT2 << ") = " << model.prob(TT2) << endl;
pair<WordID,WordID> xx2 = make_pair(kBOS, TD::Convert("要"));
PrintTopCustomers(model.bigrams.find(xx)->second);
//PrintTopCustomers(amodel.bigrams[TD::Convert("<s>")]);
//PrintTopCustomers(model.unigrams[TD::Convert("<eps>")]);
PrintAlignment(corpusf[0], corpuse[0], alignments[0].a);
}
}
}
return 0;
}
|