module_trace.h 1.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/**
 * \file imperative/python/src/module_trace.h
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

#pragma once

14 15 16
#include "megbrain/imperative/transformations/trace.h"
#include "megbrain/imperative/utils/map.h"

17 18 19 20
#include "./tensor.h"

namespace mgb::imperative::python {

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
namespace py = pybind11;

class ModuleTraceTransformation final : public Transformation {
private:
    py::function m_hook_fn;
    int m_enabled = 0;

    std::vector<ValueRef> apply_module_trace_hook(
            const OpDef& op, Span<ValueRef> input_values) {
        py::list input_tws;
        for (auto&& input_value : input_values) {
            input_tws.append(TensorWrapper::make(py_tensor_type, input_value));
        }
        py::list output_tws = m_hook_fn(py::cast(op.shared_from_this()), *input_tws);
        std::vector<ValueRef> outputs;
        for (auto&& output_tw : output_tws) {
            outputs.push_back(
                    TensorWrapper::try_cast(output_tw.ptr())->m_tensor->data());
        }
        return outputs;
    }

public:
    ModuleTraceTransformation(py::function hook_fn) : m_hook_fn(hook_fn) {}
    std::vector<ValueRef> apply_transformation(
            const Operator& op, Span<ValueRef> inputs) override {
        if (op.is<ApplyOp>() && m_enabled > 0) {
            auto outputs = apply_module_trace_hook(op.cast<ApplyOp>().op(), inputs);
            return outputs;
        } else {
            return imperative::apply(op, inputs);
        }
    }

    ValueRef unwrap(ValueRef value) override { return value; }

    std::string name() const override { return "ModuleTraceTransformation"; }
};
59

M
Megvii Engine Team 已提交
60
}  // namespace mgb::imperative::python