cinn_launch_op.h 5.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright (c) 2021 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

#include <memory>
#include <string>
#include <unordered_map>
20
#include <unordered_set>
21
#include "cinn/common/target.h"
22
#include "paddle/fluid/framework/data_type.h"
23 24 25
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/paddle2cinn/cinn_compiler.h"
26
#include "paddle/fluid/operators/cinn/cinn_launch_context.h"
27
#include "paddle/fluid/operators/cinn/cinn_op_helper.h"
28 29 30 31 32

namespace paddle {
namespace operators {

using LoDTensor = framework::LoDTensor;
33 34 35 36 37 38 39 40 41 42 43
using CinnCompiler = framework::paddle2cinn::CinnCompiler;
using CinnCompiledObject = framework::paddle2cinn::CinnCompiledObject;

namespace details {

// Tranform Paddle place to CINN target
const ::cinn::common::Target& PlaceToCinnTarget(const platform::Place& place);

// Print detailed compilation result of graph for debug
void DebugCinnCompiledResult(const CinnCompiledObject& result);

44 45
// Launch cinn to execute compiled executable program and wait done
void LaunchCinnExecution(const CinnCompiledObject& compiled_obj,
46
                         const CinnLaunchContext& context, void* stream);
47 48 49

// Set cinn FLAGS (such as FLAGS_cinn_cudnn_deterministic) with paddle's FLAGS.
void SetCinnRuntimeFlags();
50

51
}  // namespace details
52 53 54 55 56

template <typename DeviceContext, typename T>
class CinnLaunchOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
57 58
    const auto& scope = ctx.scope();
    const auto& place = ctx.GetPlace();
59
    void* stream = details::GetStream<DeviceContext>(ctx);
60 61 62 63 64 65 66
    // Step 1. Find graph object and prepare input
    PADDLE_ENFORCE_EQ(ctx.HasAttr(kCompilationKey), true,
                      platform::errors::NotFound(
                          "No Attribute(%s) found for CinnLaunchOp operator.",
                          kCompilationKey));
    const auto& compilation_key =
        ctx.template Attr<std::string>(kCompilationKey);
67
    VLOG(4) << "CinnLaunchOp attribute(" << kCompilationKey << ") "
68 69
            << "value:\n"
            << CinnCompiler::GetInstance()->ReadableKey(compilation_key);
70

71
    std::map<std::string, const LoDTensor*> inputs_name2tensor;
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    std::vector<std::string> input_x_variable_names;
    std::vector<std::string> input_no_need_buffer_variable_names;
    auto add_name2tensor_fn = [&inputs_name2tensor](
        const std::vector<std::string>& variable_names,
        const std::vector<const LoDTensor*>& tensors) {
      std::transform(
          variable_names.begin(), variable_names.end(), tensors.begin(),
          std::inserter(inputs_name2tensor, inputs_name2tensor.end()),
          [](const std::string& name, const LoDTensor* tensor) {
            return std::make_pair(name, tensor);
          });
    };

    auto input_x_tensors = ctx.MultiInput<LoDTensor>(kX);
    if (!input_x_tensors.empty()) {
      input_x_variable_names = std::move(ctx.InputNames(kX));
      add_name2tensor_fn(input_x_variable_names, input_x_tensors);
    }
    auto input_no_need_buffer_tensors =
        ctx.MultiInput<LoDTensor>(kNoNeedBufferX);
    if (!input_no_need_buffer_tensors.empty()) {
      input_no_need_buffer_variable_names =
          std::move(ctx.InputNames(kNoNeedBufferX));
      add_name2tensor_fn(input_no_need_buffer_variable_names,
                         input_no_need_buffer_tensors);
    }
98 99

    // Step 2. Get compilation result of the graph
100
    auto target = details::PlaceToCinnTarget(place);
101
    const auto& cinn_compiled_object = CinnCompiler::GetInstance()->Compile(
102
        compilation_key, inputs_name2tensor, target, stream);
103
    details::DebugCinnCompiledResult(cinn_compiled_object);
104

105
    auto* launch_context = cinn_compiled_object.launch_context.get();
106 107
    // Step 3. check the computational consistency of the subgraph
    //         before and after the compilation
108 109 110 111 112 113 114 115 116 117
    // 3.1 Input variables: tensors of input variables have
    //     been initialized before graph compiled, just check the
    //     equiality between tensors of paddle and cinn.
    for (const auto& var_name : input_x_variable_names) {
      // some input variables don't need for cinn because they are
      // eliminated by optimized passes or some cinn operators use
      // less variables
      if (!launch_context->IsVariableUsed(var_name)) {
        VLOG(4) << "Input variable" << var_name << " not used by cinn";
        continue;
118
      }
119 120
      launch_context->CheckTensorEquivalent(var_name,
                                            *inputs_name2tensor.at(var_name));
121
    }
122

123 124 125
    // Step 4. Set CINN runtime FLAGS, such as FLAGS_cinn_cudnn_deterministic.
    details::SetCinnRuntimeFlags();

126 127 128 129 130 131
    // Step 5. use PE to execute the compiled CINN instructions
    //         in nodes of the runtime graph
    VLOG(4) << "Execute the runtime graph by PE";
    framework::Scope& exec_scope = scope.NewScope();
    auto* pe = launch_context->InitializePE(place, &exec_scope);
    pe->RunWithoutFetch(launch_context->GetSkipEagerVars());
132
    VLOG(4) << "CinnLaunchOp launch execution done.";
133 134 135 136 137
  }
};

}  // namespace operators
}  // namespace paddle