nnet-nnet.cc 28 KB
Newer Older
1
// nnet2/nnet-nnet.cc
2 3

// Copyright 2011-2012  Karel Vesely
4
//           2012-2014  Johns Hopkins University (author: Daniel Povey)
5

6 7
// See ../../COPYING for clarification regarding multiple authors
//
8 9 10 11 12 13 14 15 16 17 18 19 20
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.

21 22 23
#include <algorithm>
#include <set>
#include <string>
24
#include "nnet2/nnet-nnet.h"
25 26 27
#include "util/stl-utils.h"

namespace kaldi {
28
namespace nnet2 {
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44


int32 Nnet::OutputDim() const {
  KALDI_ASSERT(!components_.empty());
  return components_.back()->OutputDim();
}

int32 Nnet::InputDim() const {
  KALDI_ASSERT(!components_.empty());
  return components_.front()->InputDim();
}


int32 Nnet::LeftContext() const {
  KALDI_ASSERT(!components_.empty());
  int32 ans = 0;
45 46 47 48 49 50 51 52 53
  for (size_t i = 0; i < components_.size(); i++) {
    ans += components_[i]->Context().front();
  }
  return -1*ans;
  // nnet-components return left context as a non-positive integer
  // however the nnet-update, nnet-compute, train-nnet-perturbed expect a
  // non-negative left context. In addition, the NnetExample also stores data
  // left context as positive integer. To be compatible with these other classes
  // Nnet::LeftContext() returns a non-negative left context.
54 55 56 57 58
}

int32 Nnet::RightContext() const {
  KALDI_ASSERT(!components_.empty());
  int32 ans = 0;
59 60 61
  for (size_t i = 0; i < components_.size(); i++) {
    ans += components_[i]->Context().back();
  }
62 63 64
  return ans;
}

65
void Nnet::ComputeChunkInfo(int32 input_chunk_size,
66 67
                            int32 num_chunks,
                            std::vector<ChunkInfo> *chunk_info_out) const {
Vijayaditya Peddinti's avatar
Vijayaditya Peddinti committed
68 69
  // First compute the output-chunk indices for the last component in the
  // network. we assume that the numbering of the input starts from zero.
70 71
  int32 output_chunk_size = input_chunk_size - LeftContext() - RightContext();
  KALDI_ASSERT(output_chunk_size > 0);
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
  std::vector<int32> current_output_inds;
  for (int32 i = 0; i < output_chunk_size; i++)
    current_output_inds.push_back(i + LeftContext());

  (*chunk_info_out).resize(NumComponents() + 1);

  // indexes for last component is empty, since the last component's chunk is
  // always contiguous
  // component's output is always contiguous
  (*chunk_info_out)[NumComponents()] = ChunkInfo(
      GetComponent(NumComponents() - 1).OutputDim(),
      num_chunks, current_output_inds.front(),
      current_output_inds.back());

  std::vector<int32> current_input_inds;
  for (int32 i = NumComponents() - 1; i >= 0; i--) {
    std::vector<int32> current_context = GetComponent(i).Context();
    std::set<int32> current_input_ind_set;
Vijayaditya Peddinti's avatar
Vijayaditya Peddinti committed
90
    for (size_t j = 0; j < current_context.size(); j++)
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
      for (size_t k = 0; k < current_output_inds.size(); k++)
        current_input_ind_set.insert(current_context[j] +
                                     current_output_inds[k]);
    current_output_inds.resize(current_input_ind_set.size());
    std::copy(current_input_ind_set.begin(),
              current_input_ind_set.end(),
              current_output_inds.begin());

    // checking if the vector has contiguous data
    // assign indexes only if the data is not contiguous
    if (current_output_inds.size() !=
        current_output_inds.back() - current_output_inds.front() + 1) {
      (*chunk_info_out)[i] = ChunkInfo(GetComponent(i).InputDim(),
                                       num_chunks,
                                       current_output_inds);
    } else  {
      (*chunk_info_out)[i] = ChunkInfo(GetComponent(i).InputDim(),
                                       num_chunks,
                                       current_output_inds.front(),
                                       current_output_inds.back());
    }
  }

  // TODO: Make a set of components which can deal with data rearrangement.
  // Define this set in an appropriate place so that
  // users adding new components can simply update the list.
  const char *dinit[] = {"SpliceComponent", "SpliceMaxComponent"};
  std::vector< std::string > data_rearrange_components(dinit, dinit + 2);

  // Ensuring that all components until the first component capable of data
  // rearrangement (e.g. SpliceComponent|SpliceMaxComponent) operate on
  // contiguous chunks at the input
  for (size_t i = 0 ; i < NumComponents() ; i++) {
      (*chunk_info_out)[i].MakeOffsetsContiguous();
      // Check if the current component is present in the set of components
      // capable of data rearrangement.
      if (std::find(data_rearrange_components.begin(),
                    data_rearrange_components.end(),
                    components_[i]->Type())
          != data_rearrange_components.end())
          break;
  }

  // sanity testing for chunk_info_out vector
  for (size_t i = 0; i < chunk_info_out->size(); i++) {
    (*chunk_info_out)[i].Check();
    // (*chunk_info_out)[i].ToString();
  }
}

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
const Component& Nnet::GetComponent(int32 component) const {
  KALDI_ASSERT(static_cast<size_t>(component) < components_.size());
  return *(components_[component]);
}

Component& Nnet::GetComponent(int32 component) {
  KALDI_ASSERT(static_cast<size_t>(component) < components_.size());
  return *(components_[component]);
}

void Nnet::SetZero(bool treat_as_gradient) {
  for (size_t i = 0; i < components_.size(); i++) {
    UpdatableComponent *uc = dynamic_cast<UpdatableComponent*>(components_[i]);
    if (uc != NULL) uc->SetZero(treat_as_gradient);
    NonlinearComponent *nc = dynamic_cast<NonlinearComponent*>(components_[i]);
    if (nc != NULL) nc->Scale(0.0);
  }
}

void Nnet::Write(std::ostream &os, bool binary) const {
161
  Check();
162 163 164 165 166 167 168 169 170 171
  WriteToken(os, binary, "<Nnet>");
  int32 num_components = components_.size();
  WriteToken(os, binary, "<NumComponents>");
  WriteBasicType(os, binary, num_components);
  WriteToken(os, binary, "<Components>");
  for (int32 c = 0; c < num_components; c++) {
    components_[c]->Write(os, binary);
    if (!binary) os << std::endl;
  }
  WriteToken(os, binary, "</Components>");
172
  WriteToken(os, binary, "</Nnet>");
173 174 175 176 177 178 179 180 181 182
}

void Nnet::Read(std::istream &is, bool binary) {
  Destroy();
  ExpectToken(is, binary, "<Nnet>");
  int32 num_components;
  ExpectToken(is, binary, "<NumComponents>");
  ReadBasicType(is, binary, &num_components);
  ExpectToken(is, binary, "<Components>");
  components_.resize(num_components);
183
  for (int32 c = 0; c < num_components; c++)
184 185
    components_[c] = Component::ReadNew(is, binary);
  ExpectToken(is, binary, "</Components>");
186 187
  ExpectToken(is, binary, "</Nnet>");
  SetIndexes();
188
  Check();
189 190 191 192 193 194 195 196
}


void Nnet::ZeroStats() {
  for (size_t i = 0; i < components_.size(); i++) {
    NonlinearComponent *nonlinear_component =
        dynamic_cast<NonlinearComponent*>(components_[i]);
    if (nonlinear_component != NULL)
197
      nonlinear_component->Scale(0.0);  // Zero the stats this way.
198 199 200 201 202 203 204 205 206 207 208 209
  }
}
void Nnet::Destroy() {
  while (!components_.empty()) {
    delete components_.back();
    components_.pop_back();
  }
}

void Nnet::ComponentDotProducts(
    const Nnet &other,
    VectorBase<BaseFloat> *dot_prod) const {
210 211
  KALDI_ASSERT(dot_prod->Dim() == NumUpdatableComponents());
  int32 index = 0;
212 213 214 215 216
  for (size_t i = 0; i < components_.size(); i++) {
    UpdatableComponent *uc1 = dynamic_cast<UpdatableComponent*>(components_[i]);
    const UpdatableComponent *uc2 = dynamic_cast<const UpdatableComponent*>(
        &(other.GetComponent(i)));
    KALDI_ASSERT((uc1 != NULL) == (uc2 != NULL));
217 218 219 220
    if (uc1 != NULL) {
      (*dot_prod)(index) = uc1->DotProduct(*uc2);
      index++;
    }
221
  }
222
  KALDI_ASSERT(index == NumUpdatableComponents());
223 224 225 226 227 228
}


Nnet::Nnet(const Nnet &other): components_(other.components_.size()) {
  for (size_t i = 0; i < other.components_.size(); i++)
    components_[i] = other.components_[i]->Copy();
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
  SetIndexes();
  Check();
}

Nnet::Nnet(const Nnet &other1, const Nnet &other2) {
  int32 dim1 = other1.OutputDim(), dim2 = other2.InputDim();
  if (dim1 != dim2)
    KALDI_ERR << "Concatenating neural nets: dimension mismatch "
              << dim1 << " vs. " << dim2;
  for (size_t i = 0; i < other1.components_.size(); i++)
    components_.push_back(other1.components_[i]->Copy());
  for (size_t i = 0; i < other2.components_.size(); i++)
    components_.push_back(other2.components_[i]->Copy());
  SetIndexes();
  Check();
244 245 246 247 248 249 250 251
}


Nnet &Nnet::operator = (const Nnet &other) {
  Destroy();
  components_.resize(other.components_.size());
  for (size_t i = 0; i < other.components_.size(); i++)
    components_[i] = other.components_[i]->Copy();
252 253
  SetIndexes();
  Check();
254 255 256 257 258 259
  return *this;
}

std::string Nnet::Info() const {
  std::ostringstream ostr;
  ostr << "num-components " << NumComponents() << std::endl;
260
  ostr << "num-updatable-components " << NumUpdatableComponents() << std::endl;
261 262 263 264
  ostr << "left-context " << LeftContext() << std::endl;
  ostr << "right-context " << RightContext() << std::endl;
  ostr << "input-dim " << InputDim() << std::endl;
  ostr << "output-dim " << OutputDim() << std::endl;
265
  ostr << "parameter-dim " << GetParameterDim() << std::endl;
266
  for (int32 i = 0; i < NumComponents(); i++)
267 268 269 270 271 272 273 274 275 276
    ostr << "component " << i << " : " << components_[i]->Info() << std::endl;
  return ostr.str();
}

void Nnet::Check() const {
  for (size_t i = 0; i + 1 < components_.size(); i++) {
    KALDI_ASSERT(components_[i] != NULL);
    int32 output_dim = components_[i]->OutputDim(),
      next_input_dim = components_[i+1]->InputDim();
    KALDI_ASSERT(output_dim == next_input_dim);
277
    KALDI_ASSERT(components_[i]->Index() == static_cast<int32>(i));
278 279 280 281 282 283 284 285 286 287
  }
}

void Nnet::Init(std::istream &is) {
  Destroy();
  std::string line;
  /* example config file as follows.  The things in brackets specify the context
     splicing for each layer, and after that is the info about the actual layer.
     Imagine the input dim is 13, and the speaker dim is 40, so (13 x 9) + 40 =  527.
     The config file might be as follows; the lines beginning with # are comments.
288

289 290 291 292 293 294
     # layer-type layer-options
     AffineLayer 0.01 0.001 527 1000 0.04356
  */
  components_.clear();
  while (getline(is, line)) {
    std::istringstream line_is(line);
295 296
    line_is >> std::ws;  // Eat up whitespace.
    if (line_is.peek() == '#' || line_is.eof()) continue;  // Comment or empty.
297 298
    Component *c = Component::NewFromString(line);
    KALDI_ASSERT(c != NULL);
299
    components_.push_back(c);
300
  }
301
  SetIndexes();
302 303 304 305 306 307
  Check();
}

void Nnet::Init(std::vector<Component*> *components) {
  Destroy();
  components_.swap(*components);
308
  SetIndexes();
309 310 311 312 313 314 315 316
  Check();
}


void Nnet::ScaleLearningRates(BaseFloat factor) {
  std::ostringstream ostr;
  for (int32 c = 0; c < NumComponents(); c++) {
    UpdatableComponent *uc = dynamic_cast<UpdatableComponent*>(components_[c]);
317
    if (uc != NULL) {  // Updatable component...
318 319 320 321 322 323 324 325 326
      uc->SetLearningRate(uc->LearningRate() * factor);
      ostr << uc->LearningRate() << " ";
    }
  }
  KALDI_LOG << "Scaled learning rates by " << factor
            << ", new learning rates are "
            << ostr.str();
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
void Nnet::ScaleLearningRates(std::map<std::string, BaseFloat> scale_factors) {
  std::ostringstream ostr;
  for (int32 c = 0; c < NumComponents(); c++) {
    UpdatableComponent *uc = dynamic_cast<UpdatableComponent*>(components_[c]);
    if (uc != NULL) {  // Updatable component...
      // check if scaling factor was specified for a component of this type
      std::map<std::string, BaseFloat>::const_iterator lr_iterator =
        scale_factors.find(uc->Type());
      if (lr_iterator != scale_factors.end())  {
        uc->SetLearningRate(uc->LearningRate() * lr_iterator->second);
        ostr << uc->LearningRate() << " ";
      }
    }
  }
  KALDI_LOG << "Scaled learning rates by component-type specific factor, "
            << "new learning rates are "
            << ostr.str();
}

346 347 348
void Nnet::SetLearningRates(BaseFloat learning_rate) {
  for (int32 c = 0; c < NumComponents(); c++) {
    UpdatableComponent *uc = dynamic_cast<UpdatableComponent*>(components_[c]);
349
    if (uc != NULL) {  // Updatable component...
350 351 352 353 354 355
      uc->SetLearningRate(learning_rate);
    }
  }
  KALDI_LOG << "Set learning rates to " << learning_rate;
}

Dan Povey's avatar
Dan Povey committed
356 357 358 359
void Nnet::ResizeOutputLayer(int32 new_num_pdfs) {
  KALDI_ASSERT(new_num_pdfs > 0);
  KALDI_ASSERT(NumComponents() > 2);
  int32 nc = NumComponents();
Vijayaditya Peddinti's avatar
Vijayaditya Peddinti committed
360 361
  SumGroupComponent *sgc =
      dynamic_cast<SumGroupComponent*>(components_[nc - 1]);
Dan Povey's avatar
Dan Povey committed
362 363 364
  if (sgc != NULL) {
    // Remove it.  We'll resize things later.
    delete sgc;
365 366
    components_.erase(components_.begin() + nc - 1,
                      components_.begin() + nc);
Dan Povey's avatar
Dan Povey committed
367
    nc--;
368
  }
369 370 371
  SoftmaxComponent *sc;
  if ((sc = dynamic_cast<SoftmaxComponent*>(components_[nc - 1])) == NULL)
    KALDI_ERR << "Expected last component to be SoftmaxComponent.";
372

373 374 375 376 377 378 379 380 381
  // check if nc-1 has a FixedScaleComponent
  bool has_fixed_scale_component = false;
  int32 fixed_scale_component_index = -1;
  int32 final_affine_component_index = nc - 2;
  int32 softmax_component_index = nc - 1;
  FixedScaleComponent *fsc =
      dynamic_cast<FixedScaleComponent*>(
          components_[final_affine_component_index]);
  if (fsc != NULL)  {
Vijayaditya Peddinti's avatar
Vijayaditya Peddinti committed
382
    has_fixed_scale_component = true;
383 384 385
    fixed_scale_component_index = nc - 2;
    final_affine_component_index = nc - 3;
  }
Dan Povey's avatar
Dan Povey committed
386
  // note: it could be child class of AffineComponent.
387 388
  AffineComponent *ac = dynamic_cast<AffineComponent*>(
      components_[final_affine_component_index]);
Dan Povey's avatar
Dan Povey committed
389 390 391
  if (ac == NULL)
    KALDI_ERR << "Network doesn't have expected structure (didn't find final "
              << "AffineComponent).";
392 393
  if (has_fixed_scale_component)  {
    // collapse the fixed_scale_component with the affine_component before it
Vijayaditya Peddinti's avatar
Vijayaditya Peddinti committed
394 395
    AffineComponent *ac_new =
        dynamic_cast<AffineComponent*>(ac->CollapseWithNext(*fsc));
396 397 398 399 400 401 402 403 404
    KALDI_ASSERT(ac_new != NULL);
    delete fsc;
    delete ac;
    components_.erase(components_.begin() + fixed_scale_component_index,
                      components_.begin() + (fixed_scale_component_index + 1));
    components_[final_affine_component_index] = ac_new;
    ac = ac_new;
    softmax_component_index = softmax_component_index - 1;
  }
Dan Povey's avatar
Dan Povey committed
405 406
  ac->Resize(ac->InputDim(), new_num_pdfs);
  // Remove the softmax component, and replace it with a new one
407 408
  delete components_[softmax_component_index];
  components_[softmax_component_index] = new SoftmaxComponent(new_num_pdfs);
Vijayaditya Peddinti's avatar
Vijayaditya Peddinti committed
409
  this->SetIndexes();  // used for debugging
Dan Povey's avatar
Dan Povey committed
410 411
  this->Check();
}
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

int32 Nnet::NumUpdatableComponents() const {
  int32 ans = 0;
  for (int32 i = 0; i < NumComponents(); i++)
    if (dynamic_cast<const UpdatableComponent*>(&(GetComponent(i))) != NULL)
      ans++;
  return ans;
}

void Nnet::ScaleComponents(const VectorBase<BaseFloat> &scale_params) {
  KALDI_ASSERT(scale_params.Dim() == this->NumUpdatableComponents());
  int32 i = 0;
  for (int32 j = 0; j < NumComponents(); j++) {
    UpdatableComponent *uc =
        dynamic_cast<UpdatableComponent*>(&(GetComponent(j)));
    if (uc!= NULL) {
      uc->Scale(scale_params(i));
      i++;
    }
  }
  KALDI_ASSERT(i == scale_params.Dim());
}

// Scales all UpdatableComponents and all NonlinearComponents.
void Nnet::Scale(BaseFloat scale) {
  for (int32 i = 0; i < NumComponents(); i++) {
    UpdatableComponent *uc =
        dynamic_cast<UpdatableComponent*>(&(GetComponent(i)));
    if (uc != NULL) uc->Scale(scale);
    NonlinearComponent *nc =
        dynamic_cast<NonlinearComponent*>(&(GetComponent(i)));
    if (nc != NULL) nc->Scale(scale);
  }
}

void Nnet::CopyStatsFrom(const Nnet &other) {
  KALDI_ASSERT(NumComponents() == other.NumComponents());
  for (int32 i = 0; i < NumComponents(); i++) {
    NonlinearComponent *nc =
        dynamic_cast<NonlinearComponent*>(&(GetComponent(i)));
    const NonlinearComponent *nc_other =
        dynamic_cast<const NonlinearComponent*>(&(other.GetComponent(i)));
    if (nc != NULL) {
      nc->Scale(0.0);
      nc->Add(1.0, *nc_other);
    }
  }
}

void Nnet::SetLearningRates(const VectorBase<BaseFloat> &learning_rates) {
  KALDI_ASSERT(learning_rates.Dim() == this->NumUpdatableComponents());
463
  KALDI_ASSERT(learning_rates.Min() >= 0.0);  // we allow zero learning rate.
464 465 466 467 468 469 470 471 472 473 474 475
  int32 i = 0;
  for (int32 j = 0; j < NumComponents(); j++) {
    UpdatableComponent *uc =
        dynamic_cast<UpdatableComponent*>(&(GetComponent(j)));
    if (uc!= NULL) {
      uc->SetLearningRate(learning_rates(i));
      i++;
    }
  }
  KALDI_ASSERT(i == learning_rates.Dim());
}

476 477 478 479 480 481 482 483 484 485 486 487 488 489
void Nnet::GetLearningRates(VectorBase<BaseFloat> *learning_rates) const {
  KALDI_ASSERT(learning_rates->Dim() == this->NumUpdatableComponents());
  int32 i = 0;
  for (int32 j = 0; j < NumComponents(); j++) {
    const UpdatableComponent *uc =
        dynamic_cast<const UpdatableComponent*>(&(GetComponent(j)));
    if (uc!= NULL) {
      (*learning_rates)(i) = uc->LearningRate();
      i++;
    }
  }
  KALDI_ASSERT(i == learning_rates->Dim());
}

490 491 492 493 494 495 496 497 498 499 500 501
void Nnet::Resize(int32 new_size) {
  KALDI_ASSERT(new_size <= static_cast<int32>(components_.size()));
  for (size_t i = new_size; i < components_.size(); i++)
    delete components_[i];
  components_.resize(new_size);
}

void Nnet::RemoveDropout() {
  std::vector<Component*> components;
  int32 removed = 0;
  for (size_t i = 0; i < components_.size(); i++) {
    if (dynamic_cast<DropoutComponent*>(components_[i]) != NULL ||
502
        dynamic_cast<AdditiveNoiseComponent*>(components_[i]) != NULL) {
503 504 505 506 507 508 509 510 511
      delete components_[i];
      removed++;
    } else {
      components.push_back(components_[i]);
    }
  }
  components_ = components;
  if (removed > 0)
    KALDI_LOG << "Removed " << removed << " dropout components.";
512 513
  SetIndexes();
  Check();
514 515
}

516 517 518 519 520 521 522 523 524 525 526 527
void Nnet::SetDropoutScale(BaseFloat scale) {
  size_t n_set = 0;
  for (size_t i = 0; i < components_.size(); i++) {
    DropoutComponent *dc =
        dynamic_cast<DropoutComponent*>(components_[i]);
    if (dc != NULL) {
      dc->SetDropoutScale(scale);
      n_set++;
    }
  }
  KALDI_LOG << "Set dropout scale to " << scale
            << " for " << n_set << " components.";
528
}
529 530


531 532 533 534 535 536 537
void Nnet::RemovePreconditioning() {
  for (size_t i = 0; i < components_.size(); i++) {
    if (dynamic_cast<AffineComponentPreconditioned*>(components_[i]) != NULL) {
      AffineComponent *ac = new AffineComponent(
          *(dynamic_cast<AffineComponent*>(components_[i])));
      delete components_[i];
      components_[i] = ac;
538 539 540 541 542 543
    } else if (dynamic_cast<AffineComponentPreconditionedOnline*>(
        components_[i]) != NULL) {
      AffineComponent *ac = new AffineComponent(
          *(dynamic_cast<AffineComponent*>(components_[i])));
      delete components_[i];
      components_[i] = ac;
544 545
    }
  }
546 547
  SetIndexes();
  Check();
548 549
}

550

551 552 553 554
void Nnet::SwitchToOnlinePreconditioning(int32 rank_in, int32 rank_out,
                                         int32 update_period,
                                         BaseFloat num_samples_history,
                                         BaseFloat alpha) {
555 556
  int32 switched = 0;
  for (size_t i = 0; i < components_.size(); i++) {
557
    if (dynamic_cast<AffineComponent*>(components_[i]) != NULL) {
558 559
      AffineComponentPreconditionedOnline *ac =
          new AffineComponentPreconditionedOnline(
560
              *(dynamic_cast<AffineComponent*>(components_[i])),
561
              rank_in, rank_out, update_period, num_samples_history, alpha);
562 563 564 565 566 567
      delete components_[i];
      components_[i] = ac;
      switched++;
    }
  }
  KALDI_LOG << "Switched " << switched << " components to use online "
568 569 570
            << "preconditioning, with (input, output) rank = "
            << rank_in << ", " << rank_out << " and num_samples_history = "
            << num_samples_history;
571 572 573 574 575
  SetIndexes();
  Check();
}


576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
void Nnet::AddNnet(const VectorBase<BaseFloat> &scale_params,
                   const Nnet &other) {
  KALDI_ASSERT(scale_params.Dim() == this->NumUpdatableComponents());
  int32 i = 0;
  for (int32 j = 0; j < NumComponents(); j++) {
    UpdatableComponent *uc =
        dynamic_cast<UpdatableComponent*>(&(GetComponent(j)));
    const UpdatableComponent *uc_other =
        dynamic_cast<const UpdatableComponent*>(&(other.GetComponent(j)));
    if (uc != NULL) {
      KALDI_ASSERT(uc_other != NULL);
      BaseFloat alpha = scale_params(i);
      uc->Add(alpha, *uc_other);
      i++;
    }
  }
  KALDI_ASSERT(i == scale_params.Dim());
}

void Nnet::AddNnet(BaseFloat alpha,
                   const Nnet &other) {
  for (int32 i = 0; i < NumComponents(); i++) {
    UpdatableComponent *uc =
        dynamic_cast<UpdatableComponent*>(&(GetComponent(i)));
    const UpdatableComponent *uc_other =
        dynamic_cast<const UpdatableComponent*>(&(other.GetComponent(i)));
    if (uc != NULL) {
      KALDI_ASSERT(uc_other != NULL);
      uc->Add(alpha, *uc_other);
    }
    NonlinearComponent *nc =
        dynamic_cast<NonlinearComponent*>(&(GetComponent(i)));
    const NonlinearComponent *nc_other =
        dynamic_cast<const NonlinearComponent*>(&(other.GetComponent(i)));
    if (nc != NULL) {
      KALDI_ASSERT(nc_other != NULL);
      nc->Add(alpha, *nc_other);
    }
  }
}

617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
void Nnet::AddNnet(BaseFloat alpha,
                   Nnet *other,
                   BaseFloat beta) {
  for (int32 i = 0; i < NumComponents(); i++) {
    UpdatableComponent *uc =
        dynamic_cast<UpdatableComponent*>(&(GetComponent(i)));
    UpdatableComponent *uc_other =
        dynamic_cast<UpdatableComponent*>(&(other->GetComponent(i)));
    if (uc != NULL) {
      KALDI_ASSERT(uc_other != NULL);
      uc->Add(alpha, *uc_other);
      uc_other->Scale(beta);
    }
    NonlinearComponent *nc =
        dynamic_cast<NonlinearComponent*>(&(GetComponent(i)));
    NonlinearComponent *nc_other =
        dynamic_cast<NonlinearComponent*>(&(other->GetComponent(i)));
    if (nc != NULL) {
      KALDI_ASSERT(nc_other != NULL);
      nc->Add(alpha, *nc_other);
      nc_other->Scale(beta);
    }
  }
}


643 644
void Nnet::Append(Component *new_component) {
  components_.push_back(new_component);
645
  SetIndexes();
646 647 648 649 650 651 652
  Check();
}

void Nnet::SetComponent(int32 c, Component *component) {
  KALDI_ASSERT(static_cast<size_t>(c) < components_.size());
  delete components_[c];
  components_[c] = component;
653
  SetIndexes();
654
  Check();  // Check that all the dimensions still match up.
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
}

int32 Nnet::GetParameterDim() const {
  int32 ans = 0;
  for (int32 c = 0; c < NumComponents(); c++) {
    const UpdatableComponent *uc = dynamic_cast<const UpdatableComponent*>(
        &(GetComponent(c)));
    if (uc != NULL)
      ans += uc->GetParameterDim();
  }
  return ans;
}

void Nnet::Vectorize(VectorBase<BaseFloat> *params) const {
  int32 offset = 0;
  for (int32 c = 0; c < NumComponents(); c++) {
    const UpdatableComponent *uc = dynamic_cast<const UpdatableComponent*>(
        &(GetComponent(c)));
    if (uc != NULL) {
      int32 size = uc->GetParameterDim();
      SubVector<BaseFloat> temp(*params, offset, size);
      uc->Vectorize(&temp);
      offset += size;
    }
  }
  KALDI_ASSERT(offset == GetParameterDim());
}

Vijayaditya Peddinti's avatar
Vijayaditya Peddinti committed
683 684 685
void Nnet::ResetGenerators() {
  // resets random-number generators for all random
  // components.
686 687 688 689 690 691 692 693
  for (int32 c = 0; c < NumComponents(); c++) {
    RandomComponent *rc = dynamic_cast<RandomComponent*>(
        &(GetComponent(c)));
    if (rc != NULL)
      rc->ResetGenerator();
  }
}

694 695 696 697 698 699 700 701 702 703 704 705 706 707
void Nnet::UnVectorize(const VectorBase<BaseFloat> &params) {
  int32 offset = 0;
  for (int32 c = 0; c < NumComponents(); c++) {
    UpdatableComponent *uc = dynamic_cast<UpdatableComponent*>(
        &(GetComponent(c)));
    if (uc != NULL) {
      int32 size = uc->GetParameterDim();
      uc->UnVectorize(params.Range(offset, size));
      offset += size;
    }
  }
  KALDI_ASSERT(offset == GetParameterDim());
}

708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
void Nnet::LimitRankOfLastLayer(int32 dim) {
  for (int32 i = components_.size() - 1; i >= 0; i--) {
    AffineComponent *a = NULL, *b = NULL,
        *c = dynamic_cast<AffineComponent*>(components_[i]);
    if (c != NULL) {
      c->LimitRank(dim, &a, &b);
      delete c;
      components_[i] = a;
      components_.insert(components_.begin() + i + 1, b);
      this->SetIndexes();
      this->Check();
      return;
    }
  }
  KALDI_ERR << "No affine component found in neural net.";
}

void Nnet::SetIndexes() {
  for (size_t i = 0; i < components_.size(); i++)
    components_[i]->SetIndex(i);
}

void Nnet::Collapse(bool match_updatableness) {
  int32 num_collapsed = 0;
  bool changed = true;
  while (changed) {
    changed = false;
    for (size_t i = 0; i + 1 < components_.size(); i++) {
      AffineComponent *a1 = dynamic_cast<AffineComponent*>(components_[i]),
          *a2 = dynamic_cast<AffineComponent*>(components_[i + 1]);
      FixedAffineComponent
          *f1 = dynamic_cast<FixedAffineComponent*>(components_[i]),
          *f2 = dynamic_cast<FixedAffineComponent*>(components_[i + 1]);
      Component *c = NULL;
      if (a1 != NULL && a2 != NULL) {
        c = a1->CollapseWithNext(*a2);
      } else if (a1 != NULL && f2 != NULL && !match_updatableness) {
        c = a1->CollapseWithNext(*f2);
      } else if (f1 != NULL && a2 != NULL && !match_updatableness) {
        c = a2->CollapseWithPrevious(*f1);
      }
      if (c != NULL) {
        delete components_[i];
        delete components_[i + 1];
        components_[i] = c;
        // This was causing valgrind errors, so doing it differently.  Either
        // a standard-library bug or I misunderstood something.
        // components_.erase(components_.begin() + i + i,
        //                   components_.begin() + i + 2);
        for (size_t j = i + 1; j + 1 < components_.size(); j++)
          components_[j] = components_[j + 1];
        components_.pop_back();
        changed = true;
        num_collapsed++;
      }
    }
  }
  this->SetIndexes();
  this->Check();
767 768 769
  KALDI_LOG << "Collapsed " << num_collapsed << " components."
            << (num_collapsed == 0 && match_updatableness == true ?
                "  Try --match-updatableness=false." : "");
770 771
}

772 773 774 775
Nnet *GenRandomNnet(int32 input_dim,
                    int32 output_dim) {
  std::vector<Component*> components;
  int32 cur_dim = input_dim;
776 777
  // have up to 10 layers before the final one.
  for (size_t i = 0; i < 10; i++) {
778 779 780 781 782 783 784 785 786 787 788 789 790 791
    if (rand() % 2 == 0) {
      // add an affine component.
      int32 next_dim = 50 + rand() % 100;
      BaseFloat learning_rate = 0.0001, param_stddev = 0.001,
          bias_stddev = 0.1;
      AffineComponent *component = new AffineComponent();
      component->Init(learning_rate, cur_dim, next_dim,
                      param_stddev, bias_stddev);
      components.push_back(component);
      cur_dim = next_dim;
    } else if (rand() % 2 == 0) {
      components.push_back(new SigmoidComponent(cur_dim));
    } else if (rand() % 2 == 0 && cur_dim < 200) {
      SpliceComponent *component = new SpliceComponent();
792 793 794 795 796 797 798 799 800 801 802
      std::vector<int32> context;
      while (true) {
        context.clear();
        for (int32 i = -3; i <= 3; i++) {
          if (rand() % 3 == 0)
            context.push_back(i);
        }
        if (!context.empty() && context.front() <= 0 &&
            context.back() >= 0)
          break;
      }
803
      component->Init(cur_dim, context);
804
      components.push_back(component);
805
      cur_dim = cur_dim * context.size();
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
    } else {
      break;
    }
  }

  {
    AffineComponent *component = new AffineComponent();
    BaseFloat learning_rate = 0.0001, param_stddev = 0.001,
        bias_stddev = 0.1;
    component->Init(learning_rate, cur_dim, output_dim,
                    param_stddev, bias_stddev);
    components.push_back(component);
    cur_dim = output_dim;
  }

  components.push_back(new SoftmaxComponent(cur_dim));

  Nnet *ans = new Nnet();
  ans->Init(&components);
  return ans;
}

Dan Povey's avatar
Dan Povey committed
828 829 830 831 832 833 834
int32 Nnet::FirstUpdatableComponent() const {
  for (int32 i = 0; i < NumComponents(); i++) {
    if (dynamic_cast<UpdatableComponent*>(components_[i]) != NULL)
      return i;
  }
  return NumComponents();
}
835 836


837 838 839
int32 Nnet::LastUpdatableComponent() const {
  for (int32 i = NumComponents() - 1; i >= 0; i--)
    if (dynamic_cast<UpdatableComponent*>(components_[i]) != NULL)
Dan Povey's avatar
Dan Povey committed
840 841
      return i;
  return -1;
842 843
}

844 845
}  // namespace nnet2
}  // namespace kaldi
846