tensorrt_engine_op.h 4.2 KB
Newer Older
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
/* 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. */

#pragma once

#ifdef PADDLE_WITH_CUDA

#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/inference/analysis/helper.h"
#include "paddle/fluid/inference/tensorrt/engine.h"

namespace paddle {
namespace operators {

class TensorRTEngineOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {}

  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
35
    auto input0 = ctx.Inputs("Xs").front();
36
    framework::OpKernelType kt = framework::OpKernelType(
37 38 39 40
        framework::ToDataType(ctx.scope()
                                  .FindVar(input0)
                                  ->GetMutable<framework::LoDTensor>()
                                  ->type()),
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
        platform::CPUPlace());
    return kt;
  }
};

template <typename DeviceContext, typename T>
class TensorRTEngineKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& context) const override {
    if (!engine_) {
      Prepare(context);
    }
    auto input_names = context.op().Inputs("Xs");
    PADDLE_ENFORCE(!input_names.empty(), "should pass more than one inputs");
    // Try to determine a batch_size
56 57 58
    auto& tensor0 = inference::analysis::GetFromScope<framework::LoDTensor>(
        context.scope(), input_names.front());
    int batch_size = tensor0.dims()[0];
59 60 61 62 63
    PADDLE_ENFORCE_LE(batch_size, max_batch_);

    // Convert input tensor from fluid to engine.
    for (const auto& x : context.Inputs("Xs")) {
      // convert input and copy to TRT engine's buffer
64 65
      auto& t = inference::analysis::GetFromScope<framework::LoDTensor>(
          context.scope(), x);
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
      if (platform::is_cpu_place(t.place())) {
        engine_->SetInputFromCPU(x, static_cast<const void*>(t.data<void>()),
                                 t.memory_size());
      } else {
        engine_->SetInputFromGPU(x, static_cast<const void*>(t.data<void>()),
                                 t.memory_size());
      }
    }
    // Execute the engine.
    PADDLE_ENFORCE_GT(batch_size, 0);
    engine_->Execute(batch_size);
    // Convert output tensor from engine to fluid
    for (const auto& y : context.Outputs("Ys")) {
      // convert output and copy to fluid.
      nvinfer1::ITensor* trt_t = engine_->GetITensor(y);
      auto dims = trt_t->getDimensions();
      // Use the output ITensor's dims to reshape the Fluid Tensor.
      std::vector<int> ddim(dims.d, dims.d + dims.nbDims);

      auto* fluid_v = context.scope().FindVar(y);
      PADDLE_ENFORCE_NOT_NULL(fluid_v, "no output variable called %s", y);
      auto* fluid_t = fluid_v->GetMutable<framework::LoDTensor>();
      fluid_t->Resize(framework::make_ddim(ddim));
      auto size = inference::analysis::AccuDims(dims.d, dims.nbDims);
      if (platform::is_cpu_place(fluid_t->place())) {
91
        // TODO(Superjomn) change this float to dtype size.
92
        engine_->GetOutputInCPU(
93 94
            y, fluid_t->mutable_data<float>(platform::CPUPlace()),
            size * sizeof(float));
95 96
      } else {
        engine_->GetOutputInGPU(
97 98
            y, fluid_t->mutable_data<float>(platform::CUDAPlace()),
            size * sizeof(float));
99 100
      }
    }
101 102

    cudaStreamSynchronize(stream_);
103 104 105 106 107 108 109
  }

 protected:
  // Build the engine.
  void Prepare(const framework::ExecutionContext& context) const;

 private:
110 111
  mutable cudaStream_t stream_;
  mutable inference::tensorrt::TensorRTEngine* engine_{nullptr};
112 113 114 115 116 117 118
  mutable int max_batch_{0};
};

}  // namespace operators
}  // namespace paddle

#endif  // PADDLE_WITH_CUDA