broadcast.cpp 10.0 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
    auto&& op = def.cast_final_safe<Broadcast>();
55 56
    size_t nr_inp = inputs.size();
    auto&& src = inputs[0];
57
    TensorShape out_shape;
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
    if (nr_inp == 1) {
        out_shape.ndim = op.shape.size();
        for (size_t i = 0; i < out_shape.ndim; ++i) {
            out_shape[i] = op.shape[i];
        }
    } else {
        auto&& tshp = inputs[1];
        if (tshp.layout.ndim == 0 || tshp.value.empty()) {
            out_shape.ndim = 0;
            return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}},
                    false};
        }
        mgb_assert(
                tshp.layout.ndim == 1,
                "target shape of Broadcast expects ndim=1; got ndim=%lu actually",
                tshp.layout.ndim);
        size_t target_ndim = tshp.layout.shape[0];
        out_shape.ndim = target_ndim;
        auto* ptr = tshp.value.ptr<dt_int32>();
        for (size_t i = 0; i < target_ndim; ++i) {
            out_shape[i] = ptr[i];
        }
80
    }
M
Megvii Engine Team 已提交
81 82 83 84
    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());
85
    return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, true};
86 87
}

88
SmallVector<TensorPtr> apply_on_physical_tensor(
89 90
        const OpDef& def, const SmallVector<TensorPtr>& inputs,
        SmallVector<LogicalTensorDesc>& output_descs, const bool& validated) {
91
    auto&& op = def.cast_final_safe<Broadcast>();
92
    size_t nr_inp = inputs.size();
93
    TensorShape tshp;
94 95
    auto&& src = inputs[0];
    auto slayout = src->layout();
96 97 98 99 100 101 102 103 104 105
    if (nr_inp == 1) {
        tshp.ndim = op.shape.size();
        for (size_t i = 0; i < tshp.ndim; ++i) {
            tshp[i] = op.shape[i];
        }
    } else {
        auto&& tshp_nd = inputs[1];
        cg::copy_tensor_value_to_shape(
                tshp, tshp_nd->get_value().proxy_to_default_cpu());
    }
106 107 108
    TensorLayout tlayout = slayout.broadcast(tshp);
    // memory forward
    return {Tensor::make(src->blob(), src->offset(), tlayout)};
109 110
}

111 112 113 114 115 116
SmallVector<VarNode::LayoutConstraintCallback> get_input_layout_constraint(
        const OpDef& def, const SmallVector<TensorPtr>& inputs) {
    SmallVector<VarNode::LayoutConstraintCallback> layout_checker(inputs.size());
    return layout_checker;
}

117
OP_TRAIT_REG(Broadcast, Broadcast, opr::Broadcast)
M
Megvii Engine Team 已提交
118 119 120
        .make_from_op_node(make_from_op_node)
        .apply_on_var_node(apply_on_var_node)
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
121
        .apply_on_physical_tensor(apply_on_physical_tensor)
122
        .get_input_layout_constraint(get_input_layout_constraint)
M
Megvii Engine Team 已提交
123 124
        .fallback();
}  // namespace broadcast
125 126 127

namespace reshape {

128 129 130 131 132
auto make_from_op_node(const cg::OperatorNodeBase* node) {
    auto& opr = node->cast_final_safe<opr::Reshape>();
    return Reshape::make(opr.param(), std::vector<int32_t>());
}

M
Megvii Engine Team 已提交
133
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
134 135
    auto&& op = static_cast<const Reshape&>(def);
    mgb_assert(inputs.size() == 2);
136 137
    OperatorNodeConfig config{op.make_name()};
    return opr::Reshape::make(inputs[0], inputs[1], op.param(), config);
138 139 140
}

std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
M
Megvii Engine Team 已提交
141
        const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
142 143 144 145
    auto&& op = def.cast_final_safe<Reshape>();
    size_t nr_inp = inputs.size();
    auto&& src = inputs[0];

146
    TensorShape out_shape;
147

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    if (nr_inp == 1) {
        if (src.layout.ndim == 0 && op.axis != opr::Reshape::Param::INVALID_AXIS) {
            return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}},
                    false};
        }
        out_shape.ndim = op.shape.size();
        for (size_t i = 0; i < out_shape.ndim; ++i) {
            out_shape[i] = op.shape[i];
        }
        if (src.layout.ndim == 0) {
            return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}},
                    false};
        }
    } else {
        auto&& tshp = inputs[1];
        if (tshp.layout.ndim == 0 || tshp.value.empty()) {
            out_shape.ndim = 0;
            return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}},
                    false};
        }
        mgb_assert(
                tshp.layout.ndim == 1,
                "target shape of Reshape expects ndim=1; got ndim=%lu actually",
                tshp.layout.ndim);
        if (src.layout.ndim == 0 && op.axis != opr::Reshape::Param::INVALID_AXIS) {
            return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}},
                    false};
        }
        size_t target_ndim = tshp.layout.shape[0];
        out_shape.ndim = target_ndim;
        auto* ptr = tshp.value.ptr<dt_int32>();
        for (size_t i = 0; i < target_ndim; ++i) {
            out_shape[i] = ptr[i];
        }
        if (src.layout.ndim == 0) {
            return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}},
                    false};
        }
186 187
    }
    if (op.axis != opr::Reshape::Param::INVALID_AXIS) {
188 189
        mgb_assert(out_shape[op.axis] == -1);
        out_shape[op.axis] = 1;
M
Megvii Engine Team 已提交
190 191 192 193
        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());
194
        out_shape[op.axis] = src.layout.total_nr_elems() / out_shape.total_nr_elems();
195
    } else {
M
Megvii Engine Team 已提交
196 197 198 199
        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());
200
    }
201
    return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, true};
202 203
}

204
SmallVector<TensorPtr> apply_on_physical_tensor(
205 206
        const OpDef& def, const SmallVector<TensorPtr>& inputs,
        SmallVector<LogicalTensorDesc>& output_descs, const bool& validated) {
207
    auto&& op = def.cast_final_safe<Reshape>();
208 209 210 211
    size_t nr_inp = inputs.size();
    auto&& src = inputs[0];
    auto slayout = src->layout();
    TensorShape tshp;
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227

    if (nr_inp == 1) {
        tshp.ndim = op.shape.size();
        for (size_t i = 0; i < tshp.ndim; ++i) {
            tshp[i] = op.shape[i];
        }
    } else {
        auto&& tshp_nd = inputs[1];

        cg::copy_tensor_value_to_shape(
                tshp, tshp_nd->get_value().proxy_to_default_cpu());
    }
    if (op.axis != opr::Reshape::Param::INVALID_AXIS) {
        mgb_assert(tshp[op.axis] == -1);
        tshp[op.axis] = 1;
        tshp[op.axis] = src->layout().total_nr_elems() / tshp.total_nr_elems();
228
    }
229 230 231 232 233 234 235
    TensorLayout tlayout;
    mgb_assert(slayout.try_reshape(tlayout, tshp));
    return {Tensor::make(src->blob(), src->offset(), tlayout)};
}

SmallVector<VarNode::LayoutConstraintCallback> get_input_layout_constraint(
        const OpDef& def, const SmallVector<TensorPtr>& inputs) {
236
    auto&& op = def.cast_final_safe<Reshape>();
237 238 239 240
    SmallVector<VarNode::LayoutConstraintCallback> layout_checker(inputs.size());
    layout_checker[0] = [&](const TensorLayout& layout) {
        TensorShape tshp;
        TensorLayout ret;
241 242 243 244 245 246 247 248 249 250 251 252 253
        if (inputs.size() == 1) {
            tshp.ndim = op.shape.size();
            for (size_t i = 0; i < tshp.ndim; ++i) {
                tshp[i] = op.shape[i];
            }
        } else {
            cg::copy_tensor_value_to_shape(
                    tshp, inputs[1]->get_value().proxy_to_default_cpu());
        }
        if (op.axis != opr::Reshape::Param::INVALID_AXIS) {
            mgb_assert(tshp[op.axis] == -1);
            tshp[op.axis] = 1;
            tshp[op.axis] = layout.total_nr_elems() / tshp.total_nr_elems();
254 255 256 257 258 259 260 261
        }
        if (layout.try_reshape(ret, tshp)) {
            return true;
        } else {
            return false;
        }
    };
    return layout_checker;
262 263
}

264
OP_TRAIT_REG(Reshape, Reshape)
M
Megvii Engine Team 已提交
265 266
        .apply_on_var_node(apply_on_var_node)
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
267
        .apply_on_physical_tensor(apply_on_physical_tensor)
268
        .get_input_layout_constraint(get_input_layout_constraint)
269
        .make_from_op_node(make_from_op_node)
M
Megvii Engine Team 已提交
270 271
        .fallback();
}  // namespace reshape
272 273 274 275 276

}  // namespace imperative
}  // namespace mgb

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