SamplingIdLayer.cpp 2.6 KB
Newer Older
Z
zhangjinchao01 已提交
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
/* Copyright (c) 2016 Baidu, Inc. All Rights Reserve.

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 <memory>
#include <random>

#include "Layer.h"

namespace paddle {

/**
 * @brief A layer for sampling id from multinomial distribution from the
 * input layer. Sampling one id for one sample. The result is stored in
 * output_.ids.
 *
 * The config file api is sampling_id_layer.
 */
class SamplingIdLayer : public Layer {
  /// Produces random floating-point values, uniformly distributed on [0, 1).
  std::uniform_real_distribution<double> rand1_;
  std::vector<Argument> tmpCpuInput_;

public:
  explicit SamplingIdLayer(const LayerConfig& config)
      : Layer(config), rand1_(0, 1) {}

  virtual bool init(const LayerMap& layerMap,
                    const ParameterMap& parameterMap) {
    bool ret = Layer::init(layerMap, parameterMap);
    CHECK_EQ(1UL, inputLayers_.size());
    if (useGpu_) {
      tmpCpuInput_.reserve(inputLayers_.size());
      for (size_t i = 0; i < inputLayers_.size(); i++) {
        tmpCpuInput_.push_back(Argument());
      }
    }
    return ret;
  }

  void forward(PassType passType) {
    Layer::forward(passType);
    if (useGpu_) {
      for (size_t i = 0; i < inputLayers_.size(); i++) {
        tmpCpuInput_[i].resizeAndCopyFrom(getInput(i), false, HPPL_STREAM_1);
      }
      forwardImp(tmpCpuInput_[0]);
    } else {
      forwardImp(getInput(0));
    }
  }

  void forwardImp(const Argument& input) {
    size_t batchSize = input.getBatchSize();
    IVector::resizeOrCreate(output_.ids, batchSize, useGpu_);
    real* buf = input.value->getData();
    int dim = input.value->getWidth();
    std::vector<int> ids(batchSize);
    auto& reng = ThreadLocalRandomEngine::get();
    for (size_t i = 0; i < batchSize; ++i) {
      double r = rand1_(reng);
      int id = dim - 1;
      for (int j = 0; j < dim; ++j) {
        if ((r -= buf[i * dim + j]) < 0) {
          id = j;
          break;
        }
      }
      ids[i] = id;
    }
    output_.ids->copyFrom(ids.data(), batchSize);
  }

  virtual void backward(const UpdateCallback& callback) {}
};

REGISTER_LAYER(sampling_id, SamplingIdLayer);

}  // namespace paddle