FunctionTest.h 6.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Copyright (c) 2016 PaddlePaddle Authors. 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 "Function.h"
#include "paddle/math/Vector.h"
#include "paddle/math/tests/TensorCheck.h"
H
hedaoyuan 已提交
18
#include "paddle/testing/TestUtil.h"
19 20 21

namespace paddle {

H
hedaoyuan 已提交
22 23
typedef std::shared_ptr<BufferArg> BufferArgPtr;

H
hedaoyuan 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/**
 * \brief A class for comparing CPU and GPU implementations of Function.
 *
 *
 * Use case:
 *  // Initializes a test object, the corresponding cpu and gpu Function
 *  // are constructed according to FunctionName and FuncConfig.
 *  FunctionCompare test(FunctionName, FuncConfig);
 *  // Prepare inputs and outputs arguments.
 *  // Here the input and output can not contain real data,
 *  // only contains the argument type and shape.
 *  test.addInputs(input1);
 *  test.addInputs(input2);
 *  test.addOutputs(output1);
 *  test.addOutputs(output2);
 *  // Run.
 *  // Will according to the type and shape of arguments(inputs_/outputs_),
 *  // automatic initialization cpu and gpu function required arguments
 *  // (cpuInputs_/cpuOutputs_/gpuInputs_/gpuOutputs_).
 *  // Call the CPU and GPU Function calculation results.
 *  // Compares CPU and GPU calculation results for consistency.
 *  test.run();
 */
47 48 49
class FunctionCompare {
public:
  FunctionCompare(const std::string& name, const FuncConfig& config)
H
hedaoyuan 已提交
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
      : cpuFunc_(FunctionBase::funcRegistrar_.createByType(name + "-CPU")),
        gpuFunc_(FunctionBase::funcRegistrar_.createByType(name + "-GPU")) {
    cpuFunc_->init(config);
    gpuFunc_->init(config);
  }

  ~FunctionCompare() {}

  // input need only contains shape, do not contains data.
  void addInputs(const BufferArg& input) {
    size_t size =
        input.shape().getElements() * sizeOfValuType(input.valueType());
    cpuMemory_.emplace_back(std::make_shared<CpuMemoryHandle>(size));
    gpuMemory_.emplace_back(std::make_shared<GpuMemoryHandle>(size));

    cpuInputs_.emplace_back(std::make_shared<BufferArg>(
        cpuMemory_.back()->getBuf(), input.valueType(), input.shape()));
    gpuInputs_.emplace_back(std::make_shared<BufferArg>(
        gpuMemory_.back()->getBuf(), input.valueType(), input.shape()));
  }

  // output need only contains shape, do not contains data.
  void addOutputs(const BufferArg& output) {
    size_t size =
        output.shape().getElements() * sizeOfValuType(output.valueType());
    cpuMemory_.emplace_back(std::make_shared<CpuMemoryHandle>(size));
    gpuMemory_.emplace_back(std::make_shared<GpuMemoryHandle>(size));

    cpuOutputs_.emplace_back(
        std::make_shared<BufferArg>(cpuMemory_.back()->getBuf(),
                                    output.valueType(),
                                    output.shape(),
                                    ASSIGN_TO));
    gpuOutputs_.emplace_back(
        std::make_shared<BufferArg>(gpuMemory_.back()->getBuf(),
                                    output.valueType(),
                                    output.shape(),
                                    ASSIGN_TO));
88 89
  }

H
hedaoyuan 已提交
90 91 92 93 94 95 96
  void addInputs(const SequenceArg& input) {
    size_t batchSize = input.shape()[0];
    size_t numSeqs = batchSize / 10 + 1;

    size_t sizeId = (numSeqs + 1) * sizeOfValuType(VALUE_TYPE_INT32);
    cpuMemory_.emplace_back(std::make_shared<CpuMemoryHandle>(sizeId));
    gpuMemory_.emplace_back(std::make_shared<GpuMemoryHandle>(sizeId));
H
hedaoyuan 已提交
97

H
hedaoyuan 已提交
98 99 100 101 102 103 104 105 106 107 108
    TensorShape seqsId({numSeqs + 1});
    // void* cpuBuffer = cpuMemory_.back()->getBuf();
    // void* gpuBuffer = gpuMemory_.back()->getBuf();

    size_t size =
        input.shape().getElements() * sizeOfValuType(input.valueType());
    cpuMemory_.emplace_back(std::make_shared<CpuMemoryHandle>(size));
    gpuMemory_.emplace_back(std::make_shared<GpuMemoryHandle>(size));

    // TODO: need be implemented.
  }
H
hedaoyuan 已提交
109 110 111

  void run() {
    // prepare cpu/gpu arguments
H
hedaoyuan 已提交
112
    initInputs();
H
hedaoyuan 已提交
113 114

    // function calculate
H
hedaoyuan 已提交
115 116 117 118 119 120 121
    auto callFunction = [](FunctionBase* function,
                           std::vector<BufferArgPtr>& inputs,
                           std::vector<BufferArgPtr>& outputs) {
      BufferArgs inArgs;
      BufferArgs outArgs;
      for (auto arg : inputs) {
        inArgs.addArg(*arg);
H
hedaoyuan 已提交
122
      }
H
hedaoyuan 已提交
123 124
      for (auto arg : outputs) {
        outArgs.addArg(*arg);
125
      }
H
hedaoyuan 已提交
126
      function->calc(inArgs, outArgs);
127 128
    };

H
hedaoyuan 已提交
129 130
    callFunction(cpuFunc_.get(), cpuInputs_, cpuOutputs_);
    callFunction(gpuFunc_.get(), gpuInputs_, gpuOutputs_);
131 132

    // check outputs and inouts
H
hedaoyuan 已提交
133
    compareOutputs();
134 135
  }

H
hedaoyuan 已提交
136
  std::shared_ptr<FunctionBase> getCpuFunction() const { return cpuFunc_; }
137

H
hedaoyuan 已提交
138
  std::shared_ptr<FunctionBase> getGpuFunction() const { return gpuFunc_; }
139

H
hedaoyuan 已提交
140
protected:
H
hedaoyuan 已提交
141 142 143
  void initInputs() {
    for (size_t i = 0; i < cpuInputs_.size(); i++) {
      initArg(*cpuInputs_[i]);
H
hedaoyuan 已提交
144

H
hedaoyuan 已提交
145 146 147 148 149
      // TODO: Need a BufferCopy used to copy from one BufferArg to another.
      CpuVector cpuVector(cpuInputs_[i]->shape().getElements(),
                          (real*)cpuInputs_[i]->data());
      GpuVector gpuVector(gpuInputs_[i]->shape().getElements(),
                          (real*)gpuInputs_[i]->data());
H
hedaoyuan 已提交
150

H
hedaoyuan 已提交
151 152
      gpuVector.copyFrom(cpuVector);
    }
H
hedaoyuan 已提交
153 154
  }

H
hedaoyuan 已提交
155 156 157 158 159 160 161
  void compareOutputs() {
    for (size_t i = 0; i < cpuOutputs_.size(); i++) {
      // TODO, Need a BufferCheck used to compare the two buffers.
      auto cpu = cpuOutputs_[i];
      auto gpu = gpuOutputs_[i];
      CpuVector cpuVector(cpu->shape().getElements(), (real*)cpu->data());
      GpuVector gpuVector(cpu->shape().getElements(), (real*)gpu->data());
H
hedaoyuan 已提交
162

H
hedaoyuan 已提交
163 164
      autotest::TensorCheckErr(cpuVector, gpuVector);
    }
H
hedaoyuan 已提交
165 166 167 168 169 170 171 172 173 174
  }

  // only init cpu argument, gpu argument copy from cpu argument.
  void initArg(BufferArg& arg) {
    CpuVector vector(arg.shape().getElements(), (real*)arg.data());
    vector.uniform(0.001, 1);
  }

  void initArg(SequenceIdArg& arg, size_t batchSize) {
    size_t numSeqs = arg.numSeqs();
H
hedaoyuan 已提交
175
    int* buf = reinterpret_cast<int*>(arg.data());
H
hedaoyuan 已提交
176 177
    int pos = 0;
    size_t maxLen = 2 * batchSize / numSeqs;
H
hedaoyuan 已提交
178
    for (int i = 0; i < (int)numSeqs; ++i) {
H
hedaoyuan 已提交
179 180 181 182 183 184 185 186 187 188
      int len = uniformRandom(
                    std::min<int64_t>(maxLen, batchSize - pos - numSeqs + i)) +
                1;
      buf[i] = pos;
      pos += len;
      VLOG(1) << " len=" << len;
    }
    buf[numSeqs] = batchSize;
  }

189
protected:
H
hedaoyuan 已提交
190 191
  std::shared_ptr<FunctionBase> cpuFunc_;
  std::shared_ptr<FunctionBase> gpuFunc_;
H
hedaoyuan 已提交
192 193
  std::vector<CpuMemHandlePtr> cpuMemory_;
  std::vector<GpuMemHandlePtr> gpuMemory_;
H
hedaoyuan 已提交
194 195 196 197
  std::vector<BufferArgPtr> cpuInputs_;
  std::vector<BufferArgPtr> cpuOutputs_;
  std::vector<BufferArgPtr> gpuInputs_;
  std::vector<BufferArgPtr> gpuOutputs_;
198 199 200
};

}  // namespace paddle