broadcast.cpp 5.6 KB
Newer Older
1 2 3 4
/**
 * \file imperative/src/impl/ops/broadcast.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6 7 8 9 10 11
 *
 * 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.
 */

12 13 14
#include "megbrain/imperative/ops/autogen.h"
#include "megbrain/opr/tensor_manip.h"

15 16
#include "megbrain/graph/helper.h"

17 18 19 20 21
#include "../op_trait.h"

namespace mgb {
namespace imperative {

22
namespace broadcast {
23 24 25 26 27 28

std::shared_ptr<OpDef> make_from_op_node(cg::OperatorNodeBase* node_) {
    node_->cast_final_safe<opr::Broadcast>();
    return Broadcast::make();
}

M
Megvii Engine Team 已提交
29
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
30
    auto&& op = def.cast_final_safe<Broadcast>();
31 32
    size_t nr_inp = inputs.size();
    mgb_assert(nr_inp == 2, "Broadcast expects 2 inputs; got %lu actually", nr_inp);
33
    OperatorNodeConfig config{op.make_name()};
34
    return opr::Broadcast::make(inputs[0], inputs[1], config);
35 36
}

M
Megvii Engine Team 已提交
37
bool valid_broadcast(const TensorShape& src_shape, const TensorShape& tar_shape) {
38 39 40 41
    size_t src_ndim = src_shape.ndim, tar_ndim = tar_shape.ndim;
    if (src_ndim > tar_ndim) {
        return false;
    }
42
    size_t min_ndim = src_ndim;
43 44 45 46 47 48 49 50 51
    for (size_t i = 0; i < min_ndim; ++i) {
        if (src_shape[src_ndim - i - 1] != 1 &&
            src_shape[src_ndim - i - 1] != tar_shape[tar_ndim - i - 1]) {
            return false;
        }
    }
    return true;
}

52
std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
M
Megvii Engine Team 已提交
53
        const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
54 55 56 57 58 59
    def.cast_final_safe<Broadcast>();
    size_t nr_inp = inputs.size();
    mgb_assert(nr_inp == 2, "Broadcast expects 2 inputs; got %lu actually", nr_inp);
    auto&& src = inputs[0];
    auto&& tshp = inputs[1];

60
    TensorShape out_shape;
61
    if (tshp.layout.ndim == 0 || tshp.value.empty()) {
62 63
        out_shape.ndim = 0;
        return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, false};
64 65
    }
    mgb_assert(
M
Megvii Engine Team 已提交
66 67 68
            tshp.layout.ndim == 1,
            "target shape of Broadcast expects ndim=1; got ndim=%lu actually",
            tshp.layout.ndim);
69 70

    size_t target_ndim = tshp.layout.shape[0];
71
    out_shape.ndim = target_ndim;
72
    auto* ptr = tshp.value.ptr<dt_int32>();
73
    for (size_t i = 0; i < target_ndim; ++i) {
74
        out_shape[i] = ptr[i];
75
    }
M
Megvii Engine Team 已提交
76 77 78 79
    mgb_assert(
            valid_broadcast(src.layout, out_shape),
            "the input shape %s can not be broadcasted to target shape %s",
            src.layout.to_string().c_str(), out_shape.to_string().c_str());
80

81
    return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, true};
82 83 84
}

OP_TRAIT_REG(Broadcast, Broadcast, opr::Broadcast)
M
Megvii Engine Team 已提交
85 86 87 88 89
        .make_from_op_node(make_from_op_node)
        .apply_on_var_node(apply_on_var_node)
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .fallback();
}  // namespace broadcast
90 91 92

namespace reshape {

M
Megvii Engine Team 已提交
93
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
94 95
    auto&& op = static_cast<const Reshape&>(def);
    mgb_assert(inputs.size() == 2);
96 97
    OperatorNodeConfig config{op.make_name()};
    return opr::Reshape::make(inputs[0], inputs[1], op.param(), config);
98 99 100
}

std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
M
Megvii Engine Team 已提交
101
        const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
102 103 104 105 106 107
    auto&& op = def.cast_final_safe<Reshape>();
    size_t nr_inp = inputs.size();
    mgb_assert(nr_inp == 2, "Reshape expects 2 inputs; got %lu actually", nr_inp);
    auto&& src = inputs[0];
    auto&& tshp = inputs[1];

108
    TensorShape out_shape;
109
    if (tshp.layout.ndim == 0 || tshp.value.empty()) {
110 111
        out_shape.ndim = 0;
        return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, false};
112 113
    }
    mgb_assert(
M
Megvii Engine Team 已提交
114 115 116
            tshp.layout.ndim == 1,
            "target shape of Reshape expects ndim=1; got ndim=%lu actually",
            tshp.layout.ndim);
117

118 119 120 121
    if (src.layout.ndim == 0 && op.axis != opr::Reshape::Param::INVALID_AXIS) {
        return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, false};
    }

122
    size_t target_ndim = tshp.layout.shape[0];
123
    out_shape.ndim = target_ndim;
124 125
    auto* ptr = tshp.value.ptr<dt_int32>();
    for (size_t i = 0; i < target_ndim; ++i) {
126
        out_shape[i] = ptr[i];
127 128 129
    }

    if (src.layout.ndim == 0) {
130
        return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, false};
131 132 133
    }

    if (op.axis != opr::Reshape::Param::INVALID_AXIS) {
134 135
        mgb_assert(out_shape[op.axis] == -1);
        out_shape[op.axis] = 1;
M
Megvii Engine Team 已提交
136 137 138 139
        mgb_assert(
                src.layout.total_nr_elems() % out_shape.total_nr_elems() == 0,
                "can not reshape from %s to %s", src.layout.to_string().c_str(),
                out_shape.to_string().c_str());
140
        out_shape[op.axis] = src.layout.total_nr_elems() / out_shape.total_nr_elems();
141
    } else {
M
Megvii Engine Team 已提交
142 143 144 145
        mgb_assert(
                src.layout.total_nr_elems() == out_shape.total_nr_elems(),
                "can not reshape from %s to %s", src.layout.to_string().c_str(),
                out_shape.to_string().c_str());
146
    }
147
    return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, true};
148 149 150
}

OP_TRAIT_REG(Reshape, Reshape)
M
Megvii Engine Team 已提交
151 152 153 154
        .apply_on_var_node(apply_on_var_node)
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .fallback();
}  // namespace reshape
155 156 157 158 159

}  // namespace imperative
}  // namespace mgb

// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}