broadcast.cpp 8.5 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();
}

29
auto apply_on_var_node(
30 31
        const OpDef& def,
        const VarNodeArray& inputs) {
32
    auto&& op = def.cast_final_safe<Broadcast>();
33 34
    size_t nr_inp = inputs.size();
    mgb_assert(nr_inp == 2, "Broadcast expects 2 inputs; got %lu actually", nr_inp);
35
    OperatorNodeConfig config{op.make_name()};
36
    return opr::Broadcast::make(inputs[0], inputs[1], config);
37 38 39 40 41 42 43 44
}

bool valid_broadcast(const TensorShape& src_shape,
                     const TensorShape& tar_shape) {
    size_t src_ndim = src_shape.ndim, tar_ndim = tar_shape.ndim;
    if (src_ndim > tar_ndim) {
        return false;
    }
45
    size_t min_ndim = src_ndim;
46 47 48 49 50 51 52 53 54
    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;
}

55
std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
56 57 58 59 60 61 62 63
        const OpDef& def,
        const SmallVector<LogicalTensorDesc>& inputs) {
    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];

64
    TensorShape out_shape;
65
    if (tshp.layout.ndim == 0 || tshp.value.empty()) {
66 67
        out_shape.ndim = 0;
        return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, false};
68 69
    }
    mgb_assert(
70 71
        tshp.layout.ndim == 1,
        "target shape of Broadcast expects ndim=1; got ndim=%lu actually",
72 73 74
        tshp.layout.ndim);

    size_t target_ndim = tshp.layout.shape[0];
75
    out_shape.ndim = target_ndim;
76
    auto* ptr = tshp.value.ptr<dt_int32>();
77
    for (size_t i = 0; i < target_ndim; ++i) {
78
        out_shape[i] = ptr[i];
79
    }
80
    mgb_assert(valid_broadcast(src.layout, out_shape),
81
               "the input shape %s can not be broadcasted to target shape %s", 
82 83
               src.layout.to_string().c_str(),
               out_shape.to_string().c_str());
84

85
    return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, true};
86 87
}

88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
std::tuple<SmallVector<MemoryDesc>, SmallVector<MemoryDesc>> infer_output_mem_desc(
        const OpDef& def,
        const SmallVector<TensorPtr>& inputs_tensors,
        const SmallVector<MemoryDesc>& inputs_mems) {
    auto& input = inputs_tensors[0];
    TensorShape target_shape;
    cg::copy_tensor_value_to_shape(target_shape, inputs_tensors[1]->get_value().proxy_to_default_cpu());
    // TODO: memory forward
    // if (input->shape().eq_shape(target_shape)) {
    //     return {{{input->layout(), 0, input->comp_node(), StorageIdentifier::make(&inputs_mems[0])}}, {}};
    // }
    return {{{{target_shape, input->dtype()}, 0, input->comp_node(), StorageIdentifier::make(0)}}, {}};
}

void execute(
        const OpDef& def,
        SmallVector<TensorPtr> inputs,
        SmallVector<TensorPtr> outputs,
        SmallVector<TensorPtr> workspace) {
    if (outputs[0]->layout().is_empty()) {
        return;
    }
    if (inputs[0]->shape().eq_shape(outputs[0]->shape())) {
        mgb_assert(inputs[0]->layout().eq_layout(outputs[0]->layout()));
        // TODO: memory forward
        // mgb_assert(inputs[0]->offset() == outputs[0]->offset());
        // mgb_assert(inputs[0]->blob() == outputs[0]->blob());
        outputs[0]->dev_tensor().copy_from_fixlayout(inputs[0]->dev_tensor());
    } else {
        TensorLayout input_layout = inputs[0]->layout().broadcast(outputs[0]->shape());
        outputs[0]->dev_tensor().copy_from_fixlayout(inputs[0]->dev_tensor().sub(SubTensorSpec::make_from_layout(input_layout)));
    }
}

122 123 124 125
OP_TRAIT_REG(Broadcast, Broadcast, opr::Broadcast)
    .make_from_op_node(make_from_op_node)
    .apply_on_var_node(apply_on_var_node)
    .infer_output_attrs_fallible(infer_output_attrs_fallible)
126 127
    .infer_output_mem_desc(infer_output_mem_desc)
    .execute(execute)
128
    .fallback();
129 130 131 132 133 134 135 136 137
} // broadcast

namespace reshape {

auto apply_on_var_node(
        const OpDef& def,
        const VarNodeArray& inputs) {
    auto&& op = static_cast<const Reshape&>(def);
    mgb_assert(inputs.size() == 2);
138 139
    OperatorNodeConfig config{op.make_name()};
    return opr::Reshape::make(inputs[0], inputs[1], op.param(), config);
140 141 142 143 144 145 146 147 148 149 150
}

std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
        const OpDef& def,
        const SmallVector<LogicalTensorDesc>& inputs) {
    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];

151
    TensorShape out_shape;
152
    if (tshp.layout.ndim == 0 || tshp.value.empty()) {
153 154
        out_shape.ndim = 0;
        return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, false};
155 156 157
    }
    mgb_assert(
        tshp.layout.ndim == 1,
158
        "target shape of Reshape expects ndim=1; got ndim=%lu actually",
159 160
        tshp.layout.ndim);

161 162 163 164
    if (src.layout.ndim == 0 && op.axis != opr::Reshape::Param::INVALID_AXIS) {
        return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, false};
    }

165
    size_t target_ndim = tshp.layout.shape[0];
166
    out_shape.ndim = target_ndim;
167 168
    auto* ptr = tshp.value.ptr<dt_int32>();
    for (size_t i = 0; i < target_ndim; ++i) {
169
        out_shape[i] = ptr[i];
170 171 172
    }

    if (src.layout.ndim == 0) {
173
        return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, false};
174 175 176
    }

    if (op.axis != opr::Reshape::Param::INVALID_AXIS) {
177 178 179
        mgb_assert(out_shape[op.axis] == -1);
        out_shape[op.axis] = 1;
        mgb_assert(src.layout.total_nr_elems() % out_shape.total_nr_elems() == 0,
180 181
            "can not reshape from %s to %s",
            src.layout.to_string().c_str(),
182 183
            out_shape.to_string().c_str());
        out_shape[op.axis] = src.layout.total_nr_elems() / out_shape.total_nr_elems();
184
    } else {
185
        mgb_assert(src.layout.total_nr_elems() == out_shape.total_nr_elems(),
186 187
            "can not reshape from %s to %s",
            src.layout.to_string().c_str(),
188
            out_shape.to_string().c_str());
189
    }
190
    return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, true};
191 192
}

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
std::tuple<SmallVector<MemoryDesc>, SmallVector<MemoryDesc>> infer_output_mem_desc(
        const OpDef& def,
        const SmallVector<TensorPtr>& inputs,
        const SmallVector<MemoryDesc>& inputs_mems) {
    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 {{{tlayout, 0, src->comp_node(), StorageIdentifier::make(&inputs_mems[0])}}, {}};
}

void execute(
        const OpDef& def,
        SmallVector<TensorPtr> inputs,
        SmallVector<TensorPtr> outputs,
        SmallVector<TensorPtr> workspace) {
    mgb_assert(inputs[0]->offset() == outputs[0]->offset());
    mgb_assert(inputs[0]->blob() == outputs[0]->blob());
}

225 226 227
OP_TRAIT_REG(Reshape, Reshape)
    .apply_on_var_node(apply_on_var_node)
    .infer_output_attrs_fallible(infer_output_attrs_fallible)
228 229
    .infer_output_mem_desc(infer_output_mem_desc)
    .execute(execute)
230 231
    .fallback();
} // reshape
232 233 234 235 236

}  // namespace imperative
}  // namespace mgb

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