broadcast.cpp 13.9 KB
Newer Older
1 2
#include <numeric>
#include "megbrain/graph/helper.h"
3
#include "megbrain/imperative/ops/autogen.h"
4
#include "megbrain/opr/io.h"
5 6
#include "megbrain/opr/tensor_manip.h"

7 8 9 10
#include "../op_trait.h"

namespace mgb {
namespace imperative {
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
namespace meshgrid {
SmallVector<VarNode::LayoutConstraintCallback> get_input_layout_constraint(
        const OpDef& def, const SmallVector<TensorPtr>& inputs) {
    return SmallVector<VarNode::LayoutConstraintCallback>(inputs.size());
}

std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
        const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
    for (size_t i = 0; i < inputs.size() - 1; i++) {
        mgb_assert(inputs[i].layout.dtype == inputs[i + 1].layout.dtype);
        mgb_assert(inputs[i].comp_node == inputs[i + 1].comp_node);
    }
    auto&& op = def.cast_final_safe<MeshGrid>();
    mgb_assert(op.indexing == "xy" || op.indexing == "ij");
    bool success = true;
    SmallVector<size_t> shp;
    for (size_t i = 0; i < inputs.size(); i++) {
        mgb_assert(inputs[i].layout.ndim <= 1);
        if (inputs[i].layout.ndim == 0) {
            success = false;
        }
        shp.push_back(inputs[i].layout.total_nr_elems());
    }
    if (op.indexing == "xy" and shp.size() >= 2) {
        std::swap(shp[0], shp[1]);
    }
    TensorShape tshp(shp);
    SmallVector<LogicalTensorDesc> descs;
39

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 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 122 123 124 125 126
    for (size_t i = 0; i < inputs.size(); i++) {
        if (success) {
            descs.push_back(
                    {TensorLayout(tshp, inputs[0].layout.dtype), inputs[0].comp_node});
        } else {
            descs.push_back(
                    {TensorLayout(inputs[0].layout.dtype), inputs[0].comp_node});
        }
    }
    return {descs, success};
}
VarNodeArray apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
    auto&& op = def.cast_final_safe<MeshGrid>();
    std::vector<size_t> indexs(inputs.size());
    std::iota(indexs.begin(), indexs.end(), 0);
    auto cn = inputs[0]->comp_node();
    auto graph = inputs[0]->owner_graph();
    if (op.indexing == "xy") {
        if (indexs.size() >= 2) {
            std::swap(indexs[0], indexs[1]);
        }
    } else {
        mgb_assert(op.indexing == "ij", "meshgrid only support \"ij\" or \"xy\"");
    }
    VarNodeArray shps;
    for (size_t ind = 0; ind < inputs.size(); ind++) {
        auto&& inp = inputs[indexs[ind]];
        shps.push_back(opr::GetVarShape::make(inp).node());
    }
    VarNode* tshp = opr::Concat::make(shps, 0, cn).node();
    VarNodeArray results;
    auto t_ndim = inputs.size();
    for (size_t ind = 0; ind < inputs.size(); ind++) {
        auto axis = indexs[ind];
        HostTensorND hv = HostTensorND(cn, {t_ndim}, dtype::Int32());
        auto* ptr = hv.ptr<dt_int32>();
        std::fill_n(ptr, t_ndim, 1);
        ptr[axis] = -1;
        auto shp = opr::ImmutableTensor::make(*graph, hv, cn).node();
        auto tmp = opr::Reshape::make(inputs[ind], shp, axis).node();
        results.push_back(opr::Broadcast::make(tmp, tshp).node());
    }
    return results;
}
SmallVector<TensorPtr> apply_on_physical_tensor(
        const OpDef& def, const SmallVector<TensorPtr>& inputs,
        SmallVector<LogicalTensorDesc>& output_descs, const bool& validated) {
    auto&& op = def.cast_final_safe<MeshGrid>();
    TensorShape tshp;
    TensorShape view_shp;
    tshp.ndim = inputs.size();
    view_shp.ndim = inputs.size();
    std::vector<size_t> indexs(inputs.size());
    std::iota(indexs.begin(), indexs.end(), 0);

    if (op.indexing == "xy") {
        if (indexs.size() >= 2) {
            std::swap(indexs[0], indexs[1]);
        }
    } else {
        mgb_assert(op.indexing == "ij", "meshgrid only support \"ij\" or \"xy\"");
    }
    for (size_t ind = 0; ind < inputs.size(); ind++) {
        auto&& inp = inputs[indexs[ind]];
        mgb_assert(inp->layout().ndim <= 1);
        tshp[ind] = inp->layout().total_nr_elems();
        view_shp[ind] = 1;
    }
    SmallVector<TensorPtr> grids;
    for (size_t i = 0; i < inputs.size(); i++) {
        auto&& src = inputs[i];
        TensorLayout layout;
        view_shp[indexs[i]] = src->layout().total_nr_elems();
        mgb_assert(src->layout().try_reshape(layout, view_shp));
        layout = layout.broadcast(tshp);
        view_shp[indexs[i]] = 1;
        grids.push_back(Tensor::make(src->blob(), src->offset(), layout));
    }
    return grids;
}
OP_TRAIT_REG(MeshGrid, MeshGrid)
        .apply_on_var_node(apply_on_var_node)
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .apply_on_physical_tensor(apply_on_physical_tensor)
        .get_input_layout_constraint(get_input_layout_constraint)
        .fallback();
}  // namespace meshgrid
127
namespace broadcast {
128 129 130 131 132 133

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

M
Megvii Engine Team 已提交
134
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
135
    auto&& op = def.cast_final_safe<Broadcast>();
136 137
    size_t nr_inp = inputs.size();
    mgb_assert(nr_inp == 2, "Broadcast expects 2 inputs; got %lu actually", nr_inp);
138
    OperatorNodeConfig config{op.make_name()};
139
    return opr::Broadcast::make(inputs[0], inputs[1], config);
140 141
}

M
Megvii Engine Team 已提交
142
bool valid_broadcast(const TensorShape& src_shape, const TensorShape& tar_shape) {
143 144 145 146
    size_t src_ndim = src_shape.ndim, tar_ndim = tar_shape.ndim;
    if (src_ndim > tar_ndim) {
        return false;
    }
147
    size_t min_ndim = src_ndim;
148 149 150 151 152 153 154 155 156
    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;
}

157
std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
M
Megvii Engine Team 已提交
158
        const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
159
    auto&& op = def.cast_final_safe<Broadcast>();
160 161
    size_t nr_inp = inputs.size();
    auto&& src = inputs[0];
162
    TensorShape out_shape;
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    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];
        }
185
    }
M
Megvii Engine Team 已提交
186 187 188 189
    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());
190
    return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, true};
191 192
}

193
SmallVector<TensorPtr> apply_on_physical_tensor(
194 195
        const OpDef& def, const SmallVector<TensorPtr>& inputs,
        SmallVector<LogicalTensorDesc>& output_descs, const bool& validated) {
196
    auto&& op = def.cast_final_safe<Broadcast>();
197
    size_t nr_inp = inputs.size();
198
    TensorShape tshp;
199 200
    auto&& src = inputs[0];
    auto slayout = src->layout();
201 202 203 204 205 206 207 208 209 210
    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());
    }
211 212 213
    TensorLayout tlayout = slayout.broadcast(tshp);
    // memory forward
    return {Tensor::make(src->blob(), src->offset(), tlayout)};
214 215
}

216 217 218 219 220 221
SmallVector<VarNode::LayoutConstraintCallback> get_input_layout_constraint(
        const OpDef& def, const SmallVector<TensorPtr>& inputs) {
    SmallVector<VarNode::LayoutConstraintCallback> layout_checker(inputs.size());
    return layout_checker;
}

222
OP_TRAIT_REG(Broadcast, Broadcast, opr::Broadcast)
M
Megvii Engine Team 已提交
223 224 225
        .make_from_op_node(make_from_op_node)
        .apply_on_var_node(apply_on_var_node)
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
226
        .apply_on_physical_tensor(apply_on_physical_tensor)
227
        .get_input_layout_constraint(get_input_layout_constraint)
M
Megvii Engine Team 已提交
228 229
        .fallback();
}  // namespace broadcast
230 231 232

namespace reshape {

233 234 235 236 237
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 已提交
238
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
239 240
    auto&& op = static_cast<const Reshape&>(def);
    mgb_assert(inputs.size() == 2);
241 242
    OperatorNodeConfig config{op.make_name()};
    return opr::Reshape::make(inputs[0], inputs[1], op.param(), config);
243 244 245
}

std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
M
Megvii Engine Team 已提交
246
        const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
247 248 249 250
    auto&& op = def.cast_final_safe<Reshape>();
    size_t nr_inp = inputs.size();
    auto&& src = inputs[0];

251
    TensorShape out_shape;
252

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    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};
        }
291 292
    }
    if (op.axis != opr::Reshape::Param::INVALID_AXIS) {
293 294
        mgb_assert(out_shape[op.axis] == -1);
        out_shape[op.axis] = 1;
M
Megvii Engine Team 已提交
295 296 297 298
        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());
299
        out_shape[op.axis] = src.layout.total_nr_elems() / out_shape.total_nr_elems();
300
    } else {
M
Megvii Engine Team 已提交
301 302 303 304
        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());
305
    }
306
    return {{{TensorLayout(out_shape, src.layout.dtype), src.comp_node}}, true};
307 308
}

309
SmallVector<TensorPtr> apply_on_physical_tensor(
310 311
        const OpDef& def, const SmallVector<TensorPtr>& inputs,
        SmallVector<LogicalTensorDesc>& output_descs, const bool& validated) {
312
    auto&& op = def.cast_final_safe<Reshape>();
313 314 315 316
    size_t nr_inp = inputs.size();
    auto&& src = inputs[0];
    auto slayout = src->layout();
    TensorShape tshp;
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

    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) {
        tshp[op.axis] = 1;
        tshp[op.axis] = src->layout().total_nr_elems() / tshp.total_nr_elems();
332
    }
333 334 335 336 337 338 339
    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) {
340
    auto&& op = def.cast_final_safe<Reshape>();
341 342 343 344
    SmallVector<VarNode::LayoutConstraintCallback> layout_checker(inputs.size());
    layout_checker[0] = [&](const TensorLayout& layout) {
        TensorShape tshp;
        TensorLayout ret;
345 346 347 348 349 350 351 352 353 354 355 356
        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) {
            tshp[op.axis] = 1;
            tshp[op.axis] = layout.total_nr_elems() / tshp.total_nr_elems();
357 358 359 360 361 362 363 364
        }
        if (layout.try_reshape(ret, tshp)) {
            return true;
        } else {
            return false;
        }
    };
    return layout_checker;
365 366
}

367
OP_TRAIT_REG(Reshape, Reshape, opr::Reshape)
M
Megvii Engine Team 已提交
368 369
        .apply_on_var_node(apply_on_var_node)
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
370
        .apply_on_physical_tensor(apply_on_physical_tensor)
371
        .get_input_layout_constraint(get_input_layout_constraint)
372
        .make_from_op_node(make_from_op_node)
M
Megvii Engine Team 已提交
373 374
        .fallback();
}  // namespace reshape
375 376 377 378 379

}  // namespace imperative
}  // namespace mgb

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