summaryrefslogtreecommitdiff
path: root/training/candidate_set.cc
blob: e2ca9ad23af71fa322a4bef0663bf63f187a0a0d (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
#include "candidate_set.h"

#include <tr1/unordered_set>

#include <boost/functional/hash.hpp>

#include "ns.h"
#include "filelib.h"
#include "wordid.h"
#include "tdict.h"
#include "hg.h"
#include "kbest.h"
#include "viterbi.h"

using namespace std;

namespace training {

struct ApproxVectorHasher {
  static const size_t MASK = 0xFFFFFFFFull;
  union UType {
    double f;   // leave as double
    size_t i;
  };
  static inline double round(const double x) {
    UType t;
    t.f = x;
    size_t r = t.i & MASK;
    if ((r << 1) > MASK)
      t.i += MASK - r + 1;
    else
      t.i &= (1ull - MASK);
    return t.f;
  }
  size_t operator()(const SparseVector<double>& x) const {
    size_t h = 0x573915839;
    for (SparseVector<double>::const_iterator it = x.begin(); it != x.end(); ++it) {
      UType t;
      t.f = it->second;
      if (t.f) {
        size_t z = (t.i >> 32);
        boost::hash_combine(h, it->first);
        boost::hash_combine(h, z);
      }
    }
    return h;
  }
};

struct ApproxVectorEquals {
  bool operator()(const SparseVector<double>& a, const SparseVector<double>& b) const {
    SparseVector<double>::const_iterator bit = b.begin();
    for (SparseVector<double>::const_iterator ait = a.begin(); ait != a.end(); ++ait) {
      if (bit == b.end() ||
          ait->first != bit->first ||
          ApproxVectorHasher::round(ait->second) != ApproxVectorHasher::round(bit->second))
        return false;
      ++bit;
    }
    if (bit != b.end()) return false;
    return true;
  }
};

struct CandidateCompare {
  bool operator()(const Candidate& a, const Candidate& b) const {
    ApproxVectorEquals eq;
    return (a.ewords == b.ewords && eq(a.fmap,b.fmap));
  }
};

struct CandidateHasher {
  size_t operator()(const Candidate& x) const {
    boost::hash<vector<WordID> > hhasher;
    ApproxVectorHasher vhasher;
    size_t ha = hhasher(x.ewords);
    boost::hash_combine(ha, vhasher(x.fmap));
    return ha;
  }
};

static void ParseSparseVector(string& line, size_t cur, SparseVector<double>* out) {
  SparseVector<double>& x = *out;
  size_t last_start = cur;
  size_t last_comma = string::npos;
  while(cur <= line.size()) {
    if (line[cur] == ' ' || cur == line.size()) {
      if (!(cur > last_start && last_comma != string::npos && cur > last_comma)) {
        cerr << "[ERROR] " << line << endl << "  position = " << cur << endl;
        exit(1);
      }
      const int fid = FD::Convert(line.substr(last_start, last_comma - last_start));
      if (cur < line.size()) line[cur] = 0;
      const double val = strtod(&line[last_comma + 1], NULL);
      x.set_value(fid, val);

      last_comma = string::npos;
      last_start = cur+1;
    } else {
      if (line[cur] == '=')
        last_comma = cur;
    }
    ++cur;
  }
}

void CandidateSet::WriteToFile(const string& file) const {
  WriteFile wf(file);
  ostream& out = *wf.stream();
  out.precision(10);
  string ss;
  for (unsigned i = 0; i < cs.size(); ++i) {
    out << TD::GetString(cs[i].ewords) << endl;
    out << cs[i].fmap << endl;
    cs[i].score_stats.Encode(&ss);
    out << ss << endl;
  }
}

void CandidateSet::ReadFromFile(const string& file) {
  cerr << "Reading candidates from " << file << endl;
  ReadFile rf(file);
  istream& in = *rf.stream();
  string cand;
  string feats;
  string ss;
  while(getline(in, cand)) {
    getline(in, feats);
    getline(in, ss);
    assert(in);
    cs.push_back(Candidate());
    TD::ConvertSentence(cand, &cs.back().ewords);
    ParseSparseVector(feats, 0, &cs.back().fmap);
    cs.back().score_stats = SufficientStats(ss);
  }
  cerr << "  read " << cs.size() << " candidates\n";
}

void CandidateSet::Dedup() {
  cerr << "Dedup in=" << cs.size();
  tr1::unordered_set<Candidate, CandidateHasher, CandidateCompare> u;
  while(cs.size() > 0) {
    u.insert(cs.back());
    cs.pop_back();
  }
  tr1::unordered_set<Candidate, CandidateHasher, CandidateCompare>::iterator it = u.begin();
  while (it != u.end()) {
    cs.push_back(*it);
    it = u.erase(it);
  }
  cerr << "  out=" << cs.size() << endl;
}

void CandidateSet::AddKBestCandidates(const Hypergraph& hg, size_t kbest_size, const SegmentEvaluator* scorer) {
  KBest::KBestDerivations<vector<WordID>, ESentenceTraversal> kbest(hg, kbest_size);

  for (unsigned i = 0; i < kbest_size; ++i) {
    const KBest::KBestDerivations<vector<WordID>, ESentenceTraversal>::Derivation* d =
      kbest.LazyKthBest(hg.nodes_.size() - 1, i);
    if (!d) break;
    cs.push_back(Candidate(d->yield, d->feature_values));
    if (scorer)
      scorer->Evaluate(d->yield, &cs.back().score_stats);
  }
  Dedup();
}

}