/usr/include/ngram/ngram-randgen.h is in libngram-dev 1.3.2-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2005-2016 Brian Roark and Google, Inc.
// Classes to generate random sentences from an LM or more generally
// paths through any FST where epsilons are treated as failure transitions.
#ifndef NGRAM_NGRAM_RANDGEN_H_
#define NGRAM_NGRAM_RANDGEN_H_
#include <sys/types.h>
#include <unistd.h>
#include <vector>
// Faster multinomial sampling possible if Gnu Scientific Library available.
#ifdef HAVE_GSL
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#endif // HAVE_GSL
#include <fst/fst.h>
#include <fst/randgen.h>
#include <ngram/util.h>
namespace ngram {
using fst::Fst;
using fst::ArcIterator;
using fst::LogWeight;
using fst::Log64Weight;
// Same as FastLogProbArcSelector but treats *all* epsilons as
// failure transitions that have a backoff weight. The LM must
// be fully normalized.
template <class A>
class NGramArcSelector {
public:
typedef typename A::StateId StateId;
typedef typename A::Weight Weight;
explicit NGramArcSelector(int seed = time(0) + getpid()) : seed_(seed) {
srand(seed);
}
// Samples one transition.
size_t operator()(const Fst<A> &fst, StateId s, double total_prob,
fst::CacheLogAccumulator<A> *accumulator) const {
double r = rand() / (RAND_MAX + 1.0);
// In effect, subtract out excess mass from the cumulative distribution.
// Requires the backoff epsilon be the initial transition.
double z = r + total_prob - 1.0;
if (z <= 0.0) return 0;
ArcIterator<Fst<A> > aiter(fst, s);
return accumulator->LowerBound(-log(z), &aiter);
}
int Seed() const { return seed_; }
private:
int seed_;
fst::WeightConvert<Weight, LogWeight> to_log_weight_;
};
} // namespace ngram
namespace fst {
// Specialization for NGramArcSelector.
template <class A>
class ArcSampler<A, ngram::NGramArcSelector<A> > {
public:
typedef ngram::NGramArcSelector<A> S;
typedef typename A::StateId StateId;
typedef typename A::Weight Weight;
typedef typename A::Label Label;
typedef CacheLogAccumulator<A> C;
ArcSampler(const Fst<A> &fst, const S &arc_selector, int max_length = INT_MAX)
: fst_(fst),
arc_selector_(arc_selector),
max_length_(max_length),
matcher_(fst_, MATCH_INPUT) {
// Ensure the input FST has any epsilons as the initial transitions.
if (!fst_.Properties(kILabelSorted, true))
NGRAMERROR() << "ArcSampler: is not input-label sorted";
accumulator_.reset(new C());
accumulator_->Init(fst);
#ifdef HAVE_GSL
rng_ = gsl_rng_alloc(gsl_rng_taus);
gsl_rng_set(rng_, arc_selector.Seed());
#endif // HAVE_GSL
}
ArcSampler(const ArcSampler<A, S> &sampler, const Fst<A> *fst = 0)
: fst_(fst ? *fst : sampler.fst_),
arc_selector_(sampler.arc_selector_),
max_length_(sampler.max_length_),
matcher_(fst_, MATCH_INPUT) {
if (fst) {
accumulator_.reset(new C());
accumulator_->Init(*fst);
} else { // shallow copy
accumulator_.reset(new C(*sampler.accumulator_));
}
}
~ArcSampler() {
#ifdef HAVE_GSL
gsl_rng_free(rng_);
#endif // HAVE_GSL
}
bool Sample(const RandState<A> &rstate) {
sample_map_.clear();
forbidden_labels_.clear();
if ((fst_.NumArcs(rstate.state_id) == 0 &&
fst_.Final(rstate.state_id) == Weight::Zero()) ||
rstate.length == max_length_) {
Reset();
return false;
}
double total_prob = TotalProb(rstate.state_id);
#ifdef HAVE_GSL
if (fst_.NumArcs(rstate.state_id) + 1 < rstate.nsamples) {
Weight numer_weight, denom_weight;
BackoffWeight(rstate.state_id, total_prob, &numer_weight, &denom_weight);
MultinomialSample(rstate, numer_weight);
Reset();
return true;
}
#endif // HAVE_GSL
ArcIterator<Fst<A> > aiter(fst_, rstate.state_id);
for (size_t i = 0; i < rstate.nsamples; ++i) {
size_t pos = 0;
Label label = kNoLabel;
do {
pos = arc_selector_(fst_, rstate.state_id, total_prob,
accumulator_.get());
if (pos < fst_.NumArcs(rstate.state_id)) {
aiter.Seek(pos);
label = aiter.Value().ilabel;
} else {
label = kNoLabel;
}
} while (ForbiddenLabel(label, rstate));
++sample_map_[pos];
}
Reset();
return true;
}
bool Done() const { return sample_iter_ == sample_map_.end(); }
void Next() { ++sample_iter_; }
std::pair<size_t, size_t> Value() const { return *sample_iter_; }
void Reset() { sample_iter_ = sample_map_.begin(); }
bool Error() const { return false; }
private:
double TotalProb(StateId s) {
// Get cumulative weight at the state.
ArcIterator<Fst<A> > aiter(fst_, s);
accumulator_->SetState(s);
Weight total_weight =
accumulator_->Sum(fst_.Final(s), &aiter, 0, fst_.NumArcs(s));
return exp(-to_log_weight_(total_weight).Value());
}
void BackoffWeight(StateId s, double total_prob, Weight *numer_weight,
Weight *denom_weight);
#ifdef HAVE_GSL
void MultinomialSample(const RandState<A> &rstate, Weight fail_weight);
#endif // HAVE_GSL
bool ForbiddenLabel(Label l, const RandState<A> &rstate);
const Fst<A> &fst_;
const S &arc_selector_;
int max_length_;
// Stores (N, K) as described for Value().
std::map<size_t, size_t> sample_map_;
std::map<size_t, size_t>::const_iterator sample_iter_;
std::unique_ptr<C> accumulator_;
#ifdef HAVE_GSL
gsl_rng *rng_; // GNU Sci Lib random number generator
vector<double> pr_; // multinomial parameters
vector<unsigned int> pos_; // sample positions
vector<unsigned int> n_; // sample counts
#endif // HAVE_GSL
WeightConvert<Log64Weight, Weight> to_weight_;
WeightConvert<Weight, Log64Weight> to_log_weight_;
std::set<Label>
forbidden_labels_; // labels forbidden for failure transitions
Matcher<Fst<A> > matcher_;
};
// Finds and decomposes the backoff probability into its numerator and
// denominator.
template <class A>
void ArcSampler<A, ngram::NGramArcSelector<A> >::BackoffWeight(
StateId s, double total, Weight *numer_weight, Weight *denom_weight) {
// Get backoff prob.
double backoff = 0.0;
matcher_.SetState(s);
matcher_.Find(0);
for (; !matcher_.Done(); matcher_.Next()) {
const A &arc = matcher_.Value();
if (arc.ilabel != kNoLabel) { // not an implicit epsilon loop
backoff = exp(-to_log_weight_(arc.weight).Value());
break;
}
}
if (backoff == 0.0) { // no backoff transition
*numer_weight = Weight::Zero();
*denom_weight = Weight::Zero();
return;
}
// total = 1 - numer + backoff
double numer = 1.0 + backoff - total;
*numer_weight = to_weight_(-log(numer));
// backoff = numer/denom
double denom = numer / backoff;
*denom_weight = to_weight_(-log(denom));
}
#ifdef HAVE_GSL
template <class A>
void ArcSampler<A, ngram::NGramArcSelector<A> >::MultinomialSample(
const RandState<A> &rstate, Weight fail_weight) {
pr_.clear();
pos_.clear();
n_.clear();
size_t pos = 0;
for (ArcIterator<Fst<A> > aiter(fst_, rstate.state_id); !aiter.Done();
aiter.Next(), ++pos) {
const A &arc = aiter.Value();
if (!ForbiddenLabel(arc.ilabel, rstate)) {
pos_.push_back(pos);
Weight weight = arc.ilabel == 0 ? fail_weight : arc.weight;
pr_.push_back(exp(-to_log_weight_(weight).Value()));
}
}
if (fst_.Final(rstate.state_id) != Weight::Zero() &&
!ForbiddenLabel(kNoLabel, rstate)) {
pos_.push_back(pos);
pr_.push_back(exp(-to_log_weight_(fst_.Final(rstate.state_id)).Value()));
}
if (rstate.nsamples < UINT_MAX) {
n_.resize(pr_.size());
gsl_ran_multinomial(rng_, pr_.size(), rstate.nsamples, &(pr_[0]), &(n_[0]));
for (size_t i = 0; i < n_.size(); ++i)
if (n_[i] != 0) sample_map_[pos_[i]] = n_[i];
} else {
for (size_t i = 0; i < pr_.size(); ++i)
sample_map_[pos_[i]] = ceil(pr_[i] * rstate.nsamples);
}
}
#endif // HAVE_GSL
template <class A>
bool ArcSampler<A, ngram::NGramArcSelector<A> >::ForbiddenLabel(
Label l, const RandState<A> &rstate) {
if (l == 0) return false;
if (fst_.NumArcs(rstate.state_id) > rstate.nsamples) {
for (const RandState<A> *rs = &rstate; rs->parent != 0; rs = rs->parent) {
StateId parent_id = rs->parent->state_id;
ArcIterator<Fst<A> > aiter(fst_, parent_id);
aiter.Seek(rs->select);
if (aiter.Value().ilabel != 0) // not backoff transition
return false;
if (l == kNoLabel) { // super-final label
return fst_.Final(parent_id) != Weight::Zero();
} else {
matcher_.SetState(parent_id);
if (matcher_.Find(l)) return true;
}
}
return false;
} else {
if (forbidden_labels_.empty()) {
for (const RandState<A> *rs = &rstate; rs->parent != 0; rs = rs->parent) {
StateId parent_id = rs->parent->state_id;
ArcIterator<Fst<A> > aiter(fst_, parent_id);
aiter.Seek(rs->select);
if (aiter.Value().ilabel != 0) // not backoff transition
break;
for (aiter.Reset(); !aiter.Done(); aiter.Next()) {
Label l = aiter.Value().ilabel;
if (l != 0) forbidden_labels_.insert(l);
}
if (fst_.Final(parent_id) != Weight::Zero())
forbidden_labels_.insert(kNoLabel);
}
}
return forbidden_labels_.count(l) > 0;
}
}
} // namespace fst
#endif // NGRAM_NGRAM_RANDGEN_H_
|