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

#include "megbrain/opr/dnn/convolution.h"
13 14 15
#include "../algo_chooser.h"
#include "../blob_manager_impl.h"
#include "../dnn_op_helper.h"
16
#include "../op_trait.h"
17 18
#include "megbrain/imperative/ops/autogen.h"
#include "megbrain/opr/internal/megdnn_opr_wrapper.h"
19 20 21 22

namespace mgb {
namespace imperative {

M
Megvii Engine Team 已提交
23
namespace {
24 25 26 27 28 29

size_t infer_conv_shape(size_t inp, size_t flt, size_t stride, size_t pad) {
    mgb_assert(inp + 2 * pad >= flt, "input=%zu padding=%zu filter=%zu", inp, pad, flt);
    return (inp + 2 * pad - flt) / stride + 1;
}

M
Megvii Engine Team 已提交
30
namespace convolution {
31 32 33 34 35
std::shared_ptr<OpDef> make_from_op_node(cg::OperatorNodeBase* node_) {
    auto* node = &node_->cast_final_safe<opr::Convolution>();
    return Convolution::make(node->param(), node->execution_policy());
}

M
Megvii Engine Team 已提交
36
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
37 38
    auto&& conv = static_cast<const Convolution&>(def);
    OperatorNodeConfig config{conv.make_name()};
M
Megvii Engine Team 已提交
39 40
    return opr::Convolution::make(
            inputs[0], inputs[1], conv.param(), conv.policy(), config);
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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
TensorLayout do_shape_infer(
        const OpDef& def, size_t src_ndim, TensorLayout src, TensorLayout filter) {
    auto&& conv = static_cast<const Convolution&>(def);
    using Param = ::megdnn::param::Convolution;

    auto img_ndim = src_ndim - 2;
    mgb_assert(
            img_ndim == 2,
            "only 2D convolution is supported, and input should be 4-dim; "
            "got input dim = %zu",
            src_ndim);
    size_t group = 1;
    size_t flt_start, flt_spatial_start, ocpg_pos, icpg_pos;
    if (conv.sparse == Param::Sparse::DENSE) {
        mgb_assert(
                filter.ndim == img_ndim + 2 || filter.ndim == img_ndim + 4,
                "bad filter ndim for dense convolution: "
                "spatial_ndim=%zu filter_ndim=%zu",
                img_ndim, filter.ndim);
        group = 1;
        flt_start = 0;
    } else {  // Param::Sparse::GROUP
        mgb_assert(
                filter.ndim == img_ndim + 3 || filter.ndim == img_ndim + 5,
                "bad filter ndim for group convolution: "
                "spatial_ndim=%zu filter_ndim=%zu",
                img_ndim, filter.ndim);
        // grp, oc, ic, dims[]
        group = filter[0];
        flt_start = 1;
    }

    uint32_t ic_block_size = 1, oc_block_size = 1;
    size_t src_or_dst_c_pos = 0;
    size_t src_or_dst_spatial_start = 0;
    if (conv.format == Param::Format::NCHW) {
        // filter should be (oc, ic, fh, fw)
        flt_spatial_start = 2;
        ocpg_pos = 0;
        icpg_pos = 1;
        src_or_dst_c_pos = 1;
        src_or_dst_spatial_start = 2;
    } else {  // Param::Format::NHWC
        // filter should be (oc, fh, fw, ic)
        flt_spatial_start = 1;
        ocpg_pos = 0;
        icpg_pos = 3;
        src_or_dst_c_pos = 3;
        src_or_dst_spatial_start = 1;
    }
    size_t ocpg = filter[flt_start + ocpg_pos] * oc_block_size;
    size_t icpg = filter[flt_start + icpg_pos] * ic_block_size;
    uint32_t dilation[2], dilated_spatial[2], stride[2], padding[2];
    dilation[0] = conv.dilate_h;
    dilation[1] = conv.dilate_w;
    stride[0] = conv.stride_h;
    stride[1] = conv.stride_w;
    padding[0] = conv.pad_h;
    padding[1] = conv.pad_w;
    for (size_t i = 0; i < img_ndim; ++i) {
        mgb_assert(
                dilation[i] > 0, "invalid dilation on spatial dim %zu: %u", i,
                dilation[i]);
        dilated_spatial[i] =
                (filter[i + flt_start + flt_spatial_start] - 1) * dilation[i] + 1;
    }
    mgb_assert(icpg * group == src[src_or_dst_c_pos], "group conv invalid");

    TensorLayout dst{src.dtype};
    dst.ndim = src_ndim;
    dst[0] = src[0];
    dst[src_or_dst_c_pos] = ocpg * group;
    for (size_t i = 0; i < img_ndim; ++i) {
        dst[i + src_or_dst_spatial_start] = infer_conv_shape(
                src[i + src_or_dst_spatial_start], dilated_spatial[i], stride[i],
                padding[i]);
    }
    dst.init_contiguous_stride();
    return dst;
}

std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
        const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
    auto&& conv = static_cast<const Convolution&>(def);

    using Param = ::megdnn::param::Convolution;

    SmallVector<LogicalTensorDesc> dests(1);
    auto&& desc = dests[0];
    desc.comp_node = inputs[0].comp_node;

    TensorLayout src = inputs[0].layout;
    size_t src_ndim = src.ndim;
    if (src_ndim == 0) {
        desc.layout = src;
        return {dests, false};
    }

    TensorLayout filter = inputs[1].layout;
    desc.layout = do_shape_infer(def, src_ndim, src, filter);
    return {dests, true};
}

SmallVector<TensorPtr> apply_on_physical_tensor(
        const OpDef& def, const SmallVector<TensorPtr>& inputs,
        SmallVector<LogicalTensorDesc>& output_descs, const bool& validated) {
    // create megdnn opr
    auto&& conv = static_cast<const Convolution&>(def);
    CompNode cn = inputs[0]->comp_node();

    TensorLayout out_layout = output_descs[0].layout;
    if (!validated)
        out_layout = do_shape_infer(
                def, inputs[0]->layout().ndim, inputs[0]->layout(),
                inputs[1]->layout());

    DeviceTensorND out =
            BlobManager::inst()->alloc_workspace_with_defrag(cn, out_layout);

    using TensorND = megdnn::TensorND;
    SmallVector<TensorND> inp_tensornds(inputs.size());
    TensorLayoutArray inp_shapes(inputs.size()), oup_shapes(output_descs.size());
    for (unsigned i = 0; i < inputs.size(); ++i) {
        inp_tensornds[i] = inputs[i]->dnn_tensor();
        inp_shapes[i] = inputs[i]->layout();
    }
    oup_shapes[0] = out_layout;
    auto&& dnn_opr = opr::intl::create_megdnn_opr<megdnn::ConvBiasForward>(cn);
    dnn_opr->param().pad_h = conv.pad_h;
    dnn_opr->param().pad_w = conv.pad_w;
    dnn_opr->param().stride_h = conv.stride_h;
    dnn_opr->param().stride_w = conv.stride_w;
    dnn_opr->param().dilate_h = conv.dilate_h;
    dnn_opr->param().dilate_w = conv.dilate_w;
    dnn_opr->param().sparse = conv.sparse;
    dnn_opr->param().compute_mode = conv.compute_mode;
    dnn_opr->param().format = conv.format;

    // shape infer
    TensorLayout shp({0}, inputs[0]->dtype());
    shp.ndim = 0;

    size_t sz = setup_algo<megdnn::ConvBiasForward>(
            {inp_shapes[0], inp_shapes[1], shp, shp, oup_shapes[0]}, dnn_opr.get(), 0,
            false, false, cn, conv.policy(), false);

    // alloc memory
    DeviceTensorND bias = BlobManager::inst()->alloc_workspace_with_defrag(cn, shp);

    auto wk = Blob::make(cn, sz);
    auto ptr = wk->storage().get();
    megdnn::Workspace dnn_wk(ptr, sz);

    // exeucte
    dnn_opr->exec(
            inp_tensornds[0], inp_tensornds[1], bias.as_megdnn(), bias.as_megdnn(),
            out.as_megdnn(), nullptr, dnn_wk);
    return {Tensor::make(out)};
}

203
OP_TRAIT_REG(Convolution, Convolution, opr::Convolution)
M
Megvii Engine Team 已提交
204 205
        .make_from_op_node(make_from_op_node)
        .apply_on_var_node(apply_on_var_node)
206 207
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
208 209 210
        .fallback();
}  // namespace convolution
}  // namespace
211

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
namespace {
namespace conv_bias {
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
    auto&& conv = static_cast<const ConvBias&>(def);
    cg::OperatorNodeConfig config{conv.dtype};
    config.name(conv.make_name());
    if (inputs.size() == 2) {
        return opr::ConvBias::make(
                inputs[0], inputs[1], conv.param(), conv.policy(), config);
    } else if (inputs.size() == 3) {
        return opr::ConvBias::make(
                inputs[0], inputs[1], inputs[2], conv.param(), conv.policy(), config);
    } else if (inputs.size() == 4) {
        return opr::ConvBias::make(
                inputs[0], inputs[1], inputs[2], inputs[3], conv.param(), conv.policy(),
                config);
    }
    mgb_assert(0);
}

OP_TRAIT_REG(ConvBias, ConvBias).apply_on_var_node(apply_on_var_node).fallback();
}  // namespace conv_bias
}  // namespace

M
Megvii Engine Team 已提交
236 237 238
namespace {
namespace convolution_backward_data {
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
239 240
    auto&& conv = static_cast<const ConvolutionBackwardData&>(def);
    OperatorNodeConfig config{conv.make_name()};
241 242 243 244 245
    DType output_dtype = conv.dtype;
    if (output_dtype.valid()) {
        config.output_dtype(output_dtype);
    }

246
    if (inputs.size() == 2) {
M
Megvii Engine Team 已提交
247 248
        return opr::ConvolutionBackwardData::make(
                inputs[0], inputs[1], conv.param(), conv.policy(), config);
249 250
    } else {
        mgb_assert(inputs.size() == 3);
M
Megvii Engine Team 已提交
251 252
        return opr::ConvolutionBackwardData::make(
                inputs[0], inputs[1], inputs[2], conv.param(), conv.policy(), config);
253 254 255 256
    }
}

OP_TRAIT_REG(ConvolutionBackwardData, ConvolutionBackwardData)
M
Megvii Engine Team 已提交
257 258 259 260
        .apply_on_var_node(apply_on_var_node)
        .fallback();
}  // namespace convolution_backward_data
}  // namespace
261

M
Megvii Engine Team 已提交
262 263
namespace {
namespace convolution3d {
264 265 266 267 268
std::shared_ptr<OpDef> make_from_op_node(cg::OperatorNodeBase* node_) {
    auto* node = &node_->cast_final_safe<opr::Convolution3D>();
    return Convolution3D::make(node->param(), node->execution_policy());
}

M
Megvii Engine Team 已提交
269
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
270 271 272 273
    auto&& conv = static_cast<const Convolution3D&>(def);
    return opr::Convolution3D::make(inputs[0], inputs[1], conv.param(), conv.policy());
}

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
TensorLayout do_shape_infer(
        const OpDef& def, size_t src_ndim, TensorLayout src, TensorLayout filter) {
    auto&& conv = static_cast<const Convolution3D&>(def);
    using Param = ::megdnn::param::Convolution3D;
    auto img_ndim = src_ndim - 2;
    mgb_assert(
            img_ndim == 3,
            "only 3D convolution is supported, and input should be 5-dim; "
            "got input dim = %zu",
            src_ndim);

    size_t group = 1;
    size_t flt_start, flt_spatial_start, ocpg_pos, icpg_pos;
    if (conv.sparse == Param::Sparse::DENSE) {
        mgb_assert(
                filter.ndim == img_ndim + 2 || filter.ndim == img_ndim + 4,
                "bad filter ndim for dense convolution: "
                "spatial_ndim=%zu filter_ndim=%zu",
                img_ndim, filter.ndim);
        group = 1;
        flt_start = 0;
    } else {  // Param::Sparse::GROUP
        mgb_assert(
                filter.ndim == img_ndim + 3 || filter.ndim == img_ndim + 5,
                "bad filter ndim for group convolution: "
                "spatial_ndim=%zu filter_ndim=%zu",
                img_ndim, filter.ndim);

        // grp, oc, ic, dims[]
        group = filter[0];
        flt_start = 1;
    }

    uint32_t ic_block_size = 1, oc_block_size = 1;
    size_t src_or_dst_c_pos = 0;
    size_t src_or_dst_spatial_start = 0;
    if (conv.format == Param::Format::NCDHW) {
        // filter should be (oc, ic, fd, fh, fw)
        flt_spatial_start = 2;
        ocpg_pos = 0;
        icpg_pos = 1;
        src_or_dst_c_pos = 1;
        src_or_dst_spatial_start = 2;
    } else {  // Param::Format::NDHWC
        // filter should be (oc, fd, fh, fw, ic)
        flt_spatial_start = 1;
        ocpg_pos = 0;
        icpg_pos = 4;
        src_or_dst_c_pos = 4;
        src_or_dst_spatial_start = 1;
    }
    size_t ocpg = filter[flt_start + ocpg_pos] * oc_block_size;
    size_t icpg = filter[flt_start + icpg_pos] * ic_block_size;
    uint32_t dilation[3], dilated_spatial[3], stride[3], padding[3];
    dilation[0] = conv.dilate_d;
    dilation[1] = conv.dilate_h;
    dilation[2] = conv.dilate_w;
    stride[0] = conv.stride_d;
    stride[1] = conv.stride_h;
    stride[2] = conv.stride_w;
    padding[0] = conv.pad_d;
    padding[1] = conv.pad_h;
    padding[2] = conv.pad_w;
    for (size_t i = 0; i < img_ndim; ++i) {
        mgb_assert(
                dilation[i] > 0, "invalid dilation on spatial dim %zu: %u", i,
                dilation[i]);
        dilated_spatial[i] =
                (filter[i + flt_start + flt_spatial_start] - 1) * dilation[i] + 1;
    }
    mgb_assert(icpg * group == src[src_or_dst_c_pos], "group conv invalid");

    TensorLayout dst{src.dtype};
    dst.ndim = src_ndim;
    dst[0] = src[0];
    dst[src_or_dst_c_pos] = ocpg * group;
    for (size_t i = 0; i < img_ndim; ++i) {
        dst[i + src_or_dst_spatial_start] = infer_conv_shape(
                src[i + src_or_dst_spatial_start], dilated_spatial[i], stride[i],
                padding[i]);
    }
    dst.init_contiguous_stride();

    return dst;
}

std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
        const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
    auto&& conv = static_cast<const Convolution3D&>(def);
    using Param = ::megdnn::param::Convolution3D;

    SmallVector<LogicalTensorDesc> dests(1);
    auto&& desc = dests[0];
    desc.comp_node = inputs[0].comp_node;

    TensorLayout src = inputs[0].layout;
    size_t src_ndim = src.ndim;
    if (src_ndim == 0) {
        return {dests, false};
    }

    TensorLayout filter = inputs[1].layout;
    desc.layout = do_shape_infer(def, src_ndim, src, filter);
    return {dests, true};
}

SmallVector<TensorPtr> apply_on_physical_tensor(
        const OpDef& def, const SmallVector<TensorPtr>& inputs,
        SmallVector<LogicalTensorDesc>& output_descs, const bool& validated) {
    // create megdnn opr
    auto&& conv = static_cast<const Convolution3D&>(def);

    TensorLayout out_layout = output_descs[0].layout;
    if (!validated)
        out_layout = do_shape_infer(
                def, inputs[0]->layout().ndim, inputs[0]->layout(),
                inputs[1]->layout());

    using TensorND = megdnn::TensorND;
    CompNode cn = inputs[0]->comp_node();
    SmallVector<TensorND> inp_tensornds(inputs.size());
    TensorLayoutArray inp_shapes(inputs.size()), oup_shapes(output_descs.size());
    for (unsigned i = 0; i < inputs.size(); ++i) {
        inp_tensornds[i] = inputs[i]->dnn_tensor();
        inp_shapes[i] = inputs[i]->layout();
    }
    oup_shapes[0] = out_layout;
    auto&& dnn_opr = opr::intl::create_megdnn_opr<megdnn::Convolution3D>(cn);
    dnn_opr->param() = conv.param();

    // shape infer
    size_t sz = setup_algo<megdnn::Convolution3D>(
            {inp_shapes[0], inp_shapes[1], oup_shapes[0]}, dnn_opr.get(), 0, false,
            false, cn, conv.policy(), false);

    // alloc memory
    DeviceTensorND out =
            BlobManager::inst()->alloc_workspace_with_defrag(cn, out_layout);

    auto wk = Blob::make(cn, sz);
    auto ptr = wk->storage().get();
    megdnn::Workspace dnn_wk(ptr, sz);

    // exeucte
    dnn_opr->exec(inp_tensornds[0], inp_tensornds[1], out.as_megdnn(), dnn_wk);
    return {Tensor::make(out)};
}

422
OP_TRAIT_REG(Convolution3D, Convolution3D, opr::Convolution3D)
M
Megvii Engine Team 已提交
423 424
        .make_from_op_node(make_from_op_node)
        .apply_on_var_node(apply_on_var_node)
425 426
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
427 428 429
        .fallback();
}  // namespace convolution3d
}  // namespace
430

M
Megvii Engine Team 已提交
431 432 433
namespace {
namespace convolution3d_backward_data {
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
434 435 436
    auto&& conv = static_cast<const Convolution3DBackwardData&>(def);
    OperatorNodeConfig config{conv.make_name()};
    mgb_assert(inputs.size() == 2);
M
Megvii Engine Team 已提交
437 438
    return opr::Convolution3DBackwardData::make(
            inputs[0], inputs[1], conv.param(), conv.policy(), config);
439 440 441
}

OP_TRAIT_REG(Convolution3DBackwardData, Convolution3DBackwardData)
M
Megvii Engine Team 已提交
442 443 444 445
        .apply_on_var_node(apply_on_var_node)
        .fallback();
}  // namespace convolution3d_backward_data
}  // namespace
446

M
Megvii Engine Team 已提交
447 448
}  // namespace imperative
}  // namespace mgb