post_latgen_faster_mapped.cc 10.1 KB
Newer Older
Y
Yibing Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

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. */

#include "post_latgen_faster_mapped.h"
16 17
#include <limits>
#include "ThreadPool.h"
Y
Yibing Liu 已提交
18 19 20 21 22 23 24 25 26 27 28

using namespace kaldi;
typedef kaldi::int32 int32;
using fst::SymbolTable;
using fst::Fst;
using fst::StdArc;

Decoder::Decoder(std::string trans_model_in_filename,
                 std::string word_syms_filename,
                 std::string fst_in_filename,
                 std::string logprior_in_filename,
Y
Yibing Liu 已提交
29
                 size_t beam_size,
Y
Yibing Liu 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
                 kaldi::BaseFloat acoustic_scale) {
  const char *usage =
      "Generate lattices using neural net model.\n"
      "Usage: post-latgen-faster-mapped [options] <trans-model> "
      "<fst-in|fsts-rspecifier> <logprior> <posts-rspecifier>"
      " <lattice-wspecifier> [ <words-wspecifier> [<alignments-wspecifier>] "
      "]\n";
  ParseOptions po(usage);
  allow_partial = false;
  this->acoustic_scale = acoustic_scale;

  config.Register(&po);
  int32 beam = 11;
  po.Register("acoustic-scale",
              &acoustic_scale,
              "Scaling factor for acoustic likelihoods");
  po.Register("word-symbol-table",
              &word_syms_filename,
              "Symbol table for words [for debug output]");
  po.Register("allow-partial",
              &allow_partial,
              "If true, produce output even if end state was not reached.");

53 54
  int argc = 2;
  char *argv[] = {(char *)"post-latgen-faster-mapped",
Y
Yibing Liu 已提交
55
                  (char *)("--beam=" + std::to_string(beam_size)).c_str()};
Y
Yibing Liu 已提交
56

57 58
  po.Read(argc, argv);

Y
Yibing Liu 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
  std::ifstream is_logprior(logprior_in_filename);
  logprior.Read(is_logprior, false);

  {
    bool binary;
    Input ki(trans_model_in_filename, &binary);
    this->trans_model.Read(ki.Stream(), binary);
  }

  this->determinize = config.determinize_lattice;

  this->word_syms = NULL;
  if (word_syms_filename != "") {
    if (!(word_syms = fst::SymbolTable::ReadText(word_syms_filename))) {
      KALDI_ERR << "Could not read symbol table from file "
                << word_syms_filename;
    }
  }

  // Input FST is just one FST, not a table of FSTs.
  this->decode_fst = fst::ReadFstKaldiGeneric(fst_in_filename);

81 82 83
  kaldi::LatticeFasterDecoder *decoder =
      new LatticeFasterDecoder(*decode_fst, config);
  decoder_pool.emplace_back(decoder);
Y
Yibing Liu 已提交
84 85 86 87 88

  std::string lattice_wspecifier =
      "ark:|gzip -c > mapped_decoder_data/lat.JOB.gz";
  if (!(determinize ? compact_lattice_writer.Open(lattice_wspecifier)
                    : lattice_writer.Open(lattice_wspecifier)))
89 90
    KALDI_ERR << "Could not open table for writing lattices: "
              << lattice_wspecifier;
Y
Yibing Liu 已提交
91 92 93 94 95 96 97 98

  words_writer = new Int32VectorWriter("");
  alignment_writer = new Int32VectorWriter("");
}

Decoder::~Decoder() {
  if (!this->word_syms) delete this->word_syms;
  delete this->decode_fst;
99 100 101
  for (size_t i = 0; i < decoder_pool.size(); ++i) {
    delete decoder_pool[i];
  }
Y
Yibing Liu 已提交
102 103 104 105 106
  delete words_writer;
  delete alignment_writer;
}


107 108
void Decoder::decode_from_file(std::string posterior_rspecifier,
                               size_t num_processes) {
109 110 111 112 113 114 115 116 117 118 119 120
  try {
    double tot_like = 0.0;
    kaldi::int64 frame_count = 0;
    // int num_success = 0, num_fail = 0;

    KALDI_ASSERT(ClassifyRspecifier(fst_in_filename, NULL, NULL) ==
                 kNoRspecifier);
    SequentialBaseFloatMatrixReader posterior_reader("ark:" +
                                                     posterior_rspecifier);

    Timer timer;
    timer.Reset();
121 122 123 124 125 126 127 128 129
    double elapsed = 0.0;

    for (size_t n = decoder_pool.size(); n < num_processes; ++n) {
      kaldi::LatticeFasterDecoder *decoder =
          new LatticeFasterDecoder(*decode_fst, config);
      decoder_pool.emplace_back(decoder);
    }
    elapsed = timer.Elapsed();
    ThreadPool thread_pool(num_processes);
130

131 132 133 134
    while (!posterior_reader.Done()) {
      timer.Reset();
      std::vector<std::future<std::string>> que;
      for (size_t i = 0; i < num_processes && !posterior_reader.Done(); ++i) {
135 136
        std::string utt = posterior_reader.Key();
        Matrix<BaseFloat> &loglikes(posterior_reader.Value());
137 138 139 140 141 142 143
        que.emplace_back(thread_pool.enqueue(std::bind(
            &Decoder::decode_internal, this, decoder_pool[i], utt, loglikes)));
        posterior_reader.Next();
      }
      timer.Reset();
      for (size_t i = 0; i < que.size(); ++i) {
        std::cout << que[i].get() << std::endl;
144 145 146 147 148 149 150 151
      }
    }

  } catch (const std::exception &e) {
    std::cerr << e.what();
  }
}

152
inline kaldi::Matrix<kaldi::BaseFloat> vector2kaldi_mat(
153 154 155 156 157 158 159 160 161 162
    const std::vector<std::vector<kaldi::BaseFloat>> &log_probs) {
  size_t num_frames = log_probs.size();
  size_t dim_label = log_probs[0].size();
  kaldi::Matrix<kaldi::BaseFloat> loglikes(
      num_frames, dim_label, kaldi::kSetZero, kaldi::kStrideEqualNumCols);
  for (size_t i = 0; i < num_frames; ++i) {
    memcpy(loglikes.Data() + i * dim_label,
           log_probs[i].data(),
           sizeof(kaldi::BaseFloat) * dim_label);
  }
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
  return loglikes;
}

std::vector<std::string> Decoder::decode_batch(
    std::vector<std::string> keys,
    const std::vector<std::vector<std::vector<kaldi::BaseFloat>>>
        &log_probs_batch,
    size_t num_processes) {
  ThreadPool thread_pool(num_processes);
  std::vector<std::string> decoding_results;  //(keys.size(), "");

  for (size_t n = decoder_pool.size(); n < num_processes; ++n) {
    kaldi::LatticeFasterDecoder *decoder =
        new LatticeFasterDecoder(*decode_fst, config);
    decoder_pool.emplace_back(decoder);
  }
179

180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
  size_t index = 0;
  while (index < keys.size()) {
    std::vector<std::future<std::string>> res_in_que;
    for (size_t t = 0; t < num_processes && index < keys.size(); ++t) {
      kaldi::Matrix<kaldi::BaseFloat> loglikes =
          vector2kaldi_mat(log_probs_batch[index]);
      res_in_que.emplace_back(
          thread_pool.enqueue(std::bind(&Decoder::decode_internal,
                                        this,
                                        decoder_pool[t],
                                        keys[index],
                                        loglikes)));
      index++;
    }
    for (size_t i = 0; i < res_in_que.size(); ++i) {
      decoding_results.emplace_back(res_in_que[i].get());
    }
  }
  return decoding_results;
199 200
}

201 202 203 204 205 206
std::string Decoder::decode(
    std::string key,
    const std::vector<std::vector<kaldi::BaseFloat>> &log_probs) {
  kaldi::Matrix<kaldi::BaseFloat> loglikes = vector2kaldi_mat(log_probs);
  return decode_internal(decoder_pool[0], key, loglikes);
}
207

208 209 210 211 212

std::string Decoder::decode_internal(
    LatticeFasterDecoder *decoder,
    std::string key,
    kaldi::Matrix<kaldi::BaseFloat> &loglikes) {
Y
Yibing Liu 已提交
213 214 215 216 217 218 219 220 221 222 223 224
  if (loglikes.NumRows() == 0) {
    KALDI_WARN << "Zero-length utterance: " << key;
    // num_fail++;
  }
  KALDI_ASSERT(loglikes.NumCols() == logprior.Dim());

  loglikes.ApplyLog();
  loglikes.AddVecToRows(-1.0, logprior);

  DecodableMatrixScaledMapped matrix_decodable(
      trans_model, loglikes, acoustic_scale);
  double like;
225 226
  return this->DecodeUtteranceLatticeFaster(
      decoder, matrix_decodable, key, &like);
227 228 229 230
}


std::string Decoder::DecodeUtteranceLatticeFaster(
231
    LatticeFasterDecoder *decoder,
232 233 234 235
    DecodableInterface &decodable,  // not const but is really an input.
    std::string utt,
    double *like_ptr) {  // puts utterance's like in like_ptr on success.
  using fst::VectorFst;
236
  std::string ret = utt + ' ';
237 238 239

  if (!decoder->Decode(&decodable)) {
    KALDI_WARN << "Failed to decode file " << utt;
240
    return ret;
241 242 243 244 245 246 247 248 249
  }
  if (!decoder->ReachedFinal()) {
    if (allow_partial) {
      KALDI_WARN << "Outputting partial output for utterance " << utt
                 << " since no final-state reached\n";
    } else {
      KALDI_WARN << "Not producing output for utterance " << utt
                 << " since no final-state reached and "
                 << "--allow-partial=false.\n";
250
      return ret;
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    }
  }

  double likelihood;
  LatticeWeight weight;
  int32 num_frames;
  {  // First do some stuff with word-level traceback...
    VectorFst<LatticeArc> decoded;
    if (!decoder->GetBestPath(&decoded))
      // Shouldn't really reach this point as already checked success.
      KALDI_ERR << "Failed to get traceback for utterance " << utt;

    std::vector<int32> alignment;
    std::vector<int32> words;
    GetLinearSymbolSequence(decoded, &alignment, &words, &weight);
    num_frames = alignment.size();
267
    // if (alignment_writer->IsOpen()) alignment_writer->Write(utt, alignment);
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
    if (word_syms != NULL) {
      for (size_t i = 0; i < words.size(); i++) {
        std::string s = word_syms->Find(words[i]);
        ret += s + ' ';
      }
    }
    likelihood = -(weight.Value1() + weight.Value2());
  }

  // Get lattice, and do determinization if requested.
  Lattice lat;
  decoder->GetRawLattice(&lat);
  if (lat.NumStates() == 0)
    KALDI_ERR << "Unexpected problem getting lattice for utterance " << utt;
  fst::Connect(&lat);
  if (determinize) {
    CompactLattice clat;
    if (!DeterminizeLatticePhonePrunedWrapper(
            trans_model,
            &lat,
            decoder->GetOptions().lattice_beam,
            &clat,
            decoder->GetOptions().det_opts))
      KALDI_WARN << "Determinization finished earlier than the beam for "
                 << "utterance " << utt;
    // We'll write the lattice without acoustic scaling.
    if (acoustic_scale != 0.0)
      fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &clat);
Y
Yibing Liu 已提交
296 297
    // disable output lattice temporarily
    // compact_lattice_writer.Write(utt, clat);
298 299 300 301
  } else {
    // We'll write the lattice without acoustic scaling.
    if (acoustic_scale != 0.0)
      fst::ScaleLattice(fst::AcousticLatticeScale(1.0 / acoustic_scale), &lat);
Y
Yibing Liu 已提交
302
    // lattice_writer.Write(utt, lat);
Y
Yibing Liu 已提交
303
  }
304
  return ret;
Y
Yibing Liu 已提交
305
}