broadcast.cpp 7.4 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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
SmallVector<TensorPtr> apply_on_physical_tensor(
        const OpDef& def, const SmallVector<TensorPtr>& inputs) {
    auto& input = inputs[0];
    TensorShape target_shape;
    cg::copy_tensor_value_to_shape(
            target_shape, inputs[1]->get_value().proxy_to_default_cpu());
    TensorPtr output = Tensor::make(
            TensorLayout(target_shape, input->dtype()), input->comp_node());
    if (output->layout().is_empty()) {
        return {output};
    }
    if (input->shape().eq_shape(output->shape())) {
        mgb_assert(input->layout().eq_layout(output->layout()));
        output->dev_tensor().copy_from_fixlayout(input->dev_tensor());
    } else {
        TensorLayout input_layout = input->layout().broadcast(output->shape());
        output->dev_tensor().copy_from_fixlayout(
                input->dev_tensor().sub(SubTensorSpec::make_from_layout(input_layout)));
    }
    return {output};
}

106
OP_TRAIT_REG(Broadcast, Broadcast, opr::Broadcast)
M
Megvii Engine Team 已提交
107 108 109
        .make_from_op_node(make_from_op_node)
        .apply_on_var_node(apply_on_var_node)
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
110
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
111 112
        .fallback();
}  // namespace broadcast
113 114 115

namespace reshape {

M
Megvii Engine Team 已提交
116
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
117 118
    auto&& op = static_cast<const Reshape&>(def);
    mgb_assert(inputs.size() == 2);
119 120
    OperatorNodeConfig config{op.make_name()};
    return opr::Reshape::make(inputs[0], inputs[1], op.param(), config);
121 122 123
}

std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
M
Megvii Engine Team 已提交
124
        const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
125 126 127 128 129 130
    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];

131
    TensorShape out_shape;
132
    if (tshp.layout.ndim == 0 || tshp.value.empty()) {
133 134
        out_shape.ndim = 0;
        return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, false};
135 136
    }
    mgb_assert(
M
Megvii Engine Team 已提交
137 138 139
            tshp.layout.ndim == 1,
            "target shape of Reshape expects ndim=1; got ndim=%lu actually",
            tshp.layout.ndim);
140

141 142 143 144
    if (src.layout.ndim == 0 && op.axis != opr::Reshape::Param::INVALID_AXIS) {
        return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, false};
    }

145
    size_t target_ndim = tshp.layout.shape[0];
146
    out_shape.ndim = target_ndim;
147 148
    auto* ptr = tshp.value.ptr<dt_int32>();
    for (size_t i = 0; i < target_ndim; ++i) {
149
        out_shape[i] = ptr[i];
150 151 152
    }

    if (src.layout.ndim == 0) {
153
        return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, false};
154 155 156
    }

    if (op.axis != opr::Reshape::Param::INVALID_AXIS) {
157 158
        mgb_assert(out_shape[op.axis] == -1);
        out_shape[op.axis] = 1;
M
Megvii Engine Team 已提交
159 160 161 162
        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());
163
        out_shape[op.axis] = src.layout.total_nr_elems() / out_shape.total_nr_elems();
164
    } else {
M
Megvii Engine Team 已提交
165 166 167 168
        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());
169
    }
170
    return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, true};
171 172
}

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
SmallVector<TensorPtr> apply_on_physical_tensor(
        const OpDef& def, const SmallVector<TensorPtr>& inputs) {
    auto&& op_def = 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_nd = inputs[1];
    auto slayout = src->layout();

    TensorShape tshp;
    cg::copy_tensor_value_to_shape(tshp, tshp_nd->get_value().proxy_to_default_cpu());
    if (op_def.axis != opr::Reshape::Param::INVALID_AXIS) {
        mgb_assert(tshp[op_def.axis] == -1);
        tshp[op_def.axis] = 1;
        tshp[op_def.axis] = src->layout().total_nr_elems() / tshp.total_nr_elems();
    }
    TensorLayout tlayout = slayout.reshape(tshp);
    // memory forward
    return {Tensor::make(src->blob(), 0, tlayout)};
}

194
OP_TRAIT_REG(Reshape, Reshape)
M
Megvii Engine Team 已提交
195 196
        .apply_on_var_node(apply_on_var_node)
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
197
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
198 199
        .fallback();
}  // namespace reshape
200 201 202 203 204

}  // namespace imperative
}  // namespace mgb

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