convolution.cpp 23.4 KB
Newer Older
1
#include "megbrain/opr/dnn/convolution.h"
2 3 4
#include "../algo_chooser.h"
#include "../blob_manager_impl.h"
#include "../dnn_op_helper.h"
5
#include "../op_trait.h"
6 7
#include "megbrain/imperative/ops/autogen.h"
#include "megbrain/opr/internal/megdnn_opr_wrapper.h"
8 9 10 11

namespace mgb {
namespace imperative {

M
Megvii Engine Team 已提交
12
namespace {
13 14 15 16 17 18

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 已提交
19
namespace convolution {
20 21 22 23 24
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 已提交
25
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
26 27
    auto&& conv = static_cast<const Convolution&>(def);
    OperatorNodeConfig config{conv.make_name()};
M
Megvii Engine Team 已提交
28 29
    return opr::Convolution::make(
            inputs[0], inputs[1], conv.param(), conv.policy(), config);
30 31
}

32 33 34 35 36 37 38 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
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;
    }
98 99 100 101 102
    mgb_assert(
            icpg * group == src[src_or_dst_c_pos],
            "group conv invalid: input channel of Conv expect %zu, but got %zu\n"
            "hint: weight may be changed by mistake\n",
            icpg * group, src[src_or_dst_c_pos]);
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    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) {
    SmallVector<LogicalTensorDesc> dests(1);
    auto&& desc = dests[0];
    desc.comp_node = inputs[0].comp_node;

    TensorLayout src = inputs[0].layout;
123
    TensorLayout filter = inputs[1].layout;
124
    size_t src_ndim = src.ndim;
125 126
    if (src_ndim == 0 || filter.ndim == 0) {
        desc.layout = TensorLayout{{}, src.dtype};
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        return {dests, false};
    }

    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());

    using TensorND = megdnn::TensorND;
148
    SmallVector<TensorND> inp_tensornds(inputs.size() + 2);
149 150 151 152 153 154
    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;
155
    DnnOprCaller<megdnn::ConvBiasForward> dnn_opr(cn);
156 157 158 159 160 161 162 163 164 165
    auto&& param = dnn_opr.op->param();
    param.pad_h = conv.pad_h;
    param.pad_w = conv.pad_w;
    param.stride_h = conv.stride_h;
    param.stride_w = conv.stride_w;
    param.dilate_h = conv.dilate_h;
    param.dilate_w = conv.dilate_w;
    param.sparse = conv.sparse;
    param.compute_mode = conv.compute_mode;
    param.format = conv.format;
166 167

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

171
    auto empty_bias = Tensor::make(empty_shp, cn);
172

173 174
    inp_tensornds[2] = empty_bias->dnn_tensor();
    inp_tensornds[3] = empty_bias->dnn_tensor();
175

176
    size_t sz = setup_algo<megdnn::ConvBiasForward>(
177
            {inp_shapes[0], inp_shapes[1], empty_shp, empty_shp, oup_shapes[0]},
178 179
            dnn_opr.op.get(), 0, false, false, cn, conv.policy(), false,
            &inp_tensornds);
180 181

    // alloc memory
182
    auto out = Tensor::make(out_layout, cn);
183

184
    auto dnn_wk = dnn_opr.create_workspace(sz);
185 186

    // exeucte
187
    dnn_opr.op->exec(
188 189 190
            inp_tensornds[0], inp_tensornds[1], inp_tensornds[2], inp_tensornds[3],
            out->dnn_tensor(), nullptr, dnn_wk);
    return {out};
191 192
}

193
OP_TRAIT_REG(Convolution, Convolution, opr::Convolution)
M
Megvii Engine Team 已提交
194 195
        .make_from_op_node(make_from_op_node)
        .apply_on_var_node(apply_on_var_node)
196 197
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
198 199 200
        .fallback();
}  // namespace convolution
}  // namespace
201

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
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 已提交
226 227 228
namespace {
namespace convolution_backward_data {
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
229 230
    auto&& conv = static_cast<const ConvolutionBackwardData&>(def);
    OperatorNodeConfig config{conv.make_name()};
231 232 233 234 235
    DType output_dtype = conv.dtype;
    if (output_dtype.valid()) {
        config.output_dtype(output_dtype);
    }

236
    if (inputs.size() == 2) {
M
Megvii Engine Team 已提交
237 238
        return opr::ConvolutionBackwardData::make(
                inputs[0], inputs[1], conv.param(), conv.policy(), config);
239 240
    } else {
        mgb_assert(inputs.size() == 3);
M
Megvii Engine Team 已提交
241 242
        return opr::ConvolutionBackwardData::make(
                inputs[0], inputs[1], inputs[2], conv.param(), conv.policy(), config);
243 244 245
    }
}

246 247 248 249 250 251 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 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
TensorLayout convbwd_do_shape_infer(
        const OpDef& def, size_t diff_ndim, TensorLayout filter, TensorLayout diff,
        CompNode cn) {
    auto&& bwd_conv = static_cast<const ConvolutionBackwardData&>(def);
    DnnOprCaller<megdnn::ConvolutionBackwardData> caller(cn);
    auto&& dnn_opr = caller.op;
    using Param = ::megdnn::param::Convolution;
    // using Param1 = ::megdnn::param::ConvolutionBackwardData;

    auto img_ndim = diff_ndim - 2;
    mgb_assert(
            img_ndim == 2,
            "only 2D convolution is supported, and input should be 4-dim; "
            "got input dim = %zu",
            diff_ndim);
    size_t group = 1;
    size_t flt_start, flt_spatial_start, ocpg_pos, icpg_pos;
    if (bwd_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 (bwd_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] = bwd_conv.dilate_h;
    dilation[1] = bwd_conv.dilate_w;
    stride[0] = bwd_conv.stride_h;
    stride[1] = bwd_conv.stride_w;
    padding[0] = bwd_conv.pad_h;
    padding[1] = bwd_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;
    }
316 317 318 319 320
    mgb_assert(
            ocpg * group == diff[src_or_dst_c_pos],
            "group conv invalid: input channel of Conv expect %zu, but got %zu\n"
            "hint: weight may be changed by mistake\n",
            ocpg * group, diff[src_or_dst_c_pos]);
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
    auto deduce = [](size_t out, size_t filter, size_t stride, size_t pad) {
        auto i = (out - 1) * stride + filter;
        mgb_assert(i > pad * 2);
        return i - pad * 2;
    };

    DType dst_dtype = bwd_conv.dtype;
    dnn_opr->deduce_dtype(filter.dtype, diff.dtype, dst_dtype);
    TensorLayout dst{dst_dtype};
    dst.ndim = diff_ndim;
    dst[0] = diff[0];
    dst[src_or_dst_c_pos] = icpg * group;
    for (size_t i = 0; i < img_ndim; ++i) {
        dst[i + src_or_dst_spatial_start] =
                deduce(diff[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) {
    SmallVector<LogicalTensorDesc> dests(1);
    auto&& desc = dests[0];
    desc.comp_node = inputs[0].comp_node;

    TensorLayout filter = inputs[0].layout;
    TensorLayout diff = inputs[1].layout;
    size_t diff_ndim = diff.ndim;
351 352
    if (diff_ndim == 0 || filter.ndim == 0) {
        desc.layout = TensorLayout{{}, diff.dtype};
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
        return {dests, false};
    }

    desc.layout =
            convbwd_do_shape_infer(def, diff_ndim, filter, diff, inputs[0].comp_node);
    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&& convbwd = static_cast<const ConvolutionBackwardData&>(def);
    CompNode cn = inputs[0]->comp_node();

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

374 375
    auto out = Tensor::make(out_layout, cn);

376 377 378 379 380 381 382 383 384 385 386 387 388
    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;
    DnnOprCaller<megdnn::ConvolutionBackwardData> dnn_opr(cn);
    dnn_opr.op->param() = convbwd.param();

    size_t sz = setup_algo<megdnn::ConvolutionBackwardData>(
            {inp_shapes[0], inp_shapes[1], oup_shapes[0]}, dnn_opr.op.get(), 0, false,
389 390
            false, cn, convbwd.policy(), false, &inp_tensornds);

391
    auto dnn_wk = dnn_opr.create_workspace(sz);
392 393

    // exeucte
394 395
    dnn_opr.op->exec(inp_tensornds[0], inp_tensornds[1], out->dnn_tensor(), dnn_wk);
    return {out};
396 397
}

398
OP_TRAIT_REG(ConvolutionBackwardData, ConvolutionBackwardData)
M
Megvii Engine Team 已提交
399
        .apply_on_var_node(apply_on_var_node)
400 401
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
402 403 404
        .fallback();
}  // namespace convolution_backward_data
}  // namespace
405

M
Megvii Engine Team 已提交
406 407
namespace {
namespace convolution3d {
408 409 410 411 412
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 已提交
413
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
414 415 416 417
    auto&& conv = static_cast<const Convolution3D&>(def);
    return opr::Convolution3D::make(inputs[0], inputs[1], conv.param(), conv.policy());
}

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
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;
    }
488 489 490 491 492
    mgb_assert(
            icpg * group == src[src_or_dst_c_pos],
            "group conv invalid: input channel of Conv expect %zu, but got %zu\n"
            "hint: weight may be changed by mistake\n",
            icpg * group, src[src_or_dst_c_pos]);
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
    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) {
    SmallVector<LogicalTensorDesc> dests(1);
    auto&& desc = dests[0];
    desc.comp_node = inputs[0].comp_node;

    TensorLayout src = inputs[0].layout;
514
    TensorLayout filter = inputs[1].layout;
515
    size_t src_ndim = src.ndim;
516 517
    if (src_ndim == 0 || filter.ndim == 0) {
        desc.layout = TensorLayout{{}, src.dtype};
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
        return {dests, false};
    }

    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;
546 547
    DnnOprCaller<megdnn::Convolution3D> dnn_opr(cn);
    dnn_opr.op->param() = conv.param();
548 549 550

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

    // alloc memory
555
    auto out = Tensor::make(out_layout, cn);
556

557
    auto dnn_wk = dnn_opr.create_workspace(sz);
558 559

    // exeucte
560 561
    dnn_opr.op->exec(inp_tensornds[0], inp_tensornds[1], out->dnn_tensor(), dnn_wk);
    return {out};
562 563
}

564
OP_TRAIT_REG(Convolution3D, Convolution3D, opr::Convolution3D)
M
Megvii Engine Team 已提交
565 566
        .make_from_op_node(make_from_op_node)
        .apply_on_var_node(apply_on_var_node)
567 568
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
569 570 571
        .fallback();
}  // namespace convolution3d
}  // namespace
572

M
Megvii Engine Team 已提交
573 574
namespace {
namespace convolution3d_backward_data {
575 576 577 578 579 580 581 582 583 584 585 586 587

std::tuple<SmallVector<LogicalTensorDesc>, bool> infer_output_attrs_fallible(
        const OpDef& def, const SmallVector<LogicalTensorDesc>& inputs) {
    mgb_assert(
            inputs.size() == 2,
            "inputs num of conv_transpose3d should be 2 but you give %zu",
            inputs.size());

    auto&& op_def = def.cast_final_safe<Convolution3DBackwardData>();
    auto&& weight = inputs[0];
    auto&& diff = inputs[1];
    auto& cn = weight.comp_node;

588
    if (weight.layout.ndim == 0 || diff.layout.ndim == 0) {
589 590 591 592 593 594 595 596 597 598 599 600 601 602
        return {{{TensorLayout{weight.layout.dtype}, cn, {}}}, false};
    }

    TensorLayout oup_layout;
    megdnn::Convolution3DBackwardData::deduce_layout_impl(
            weight.layout, diff.layout, op_def.param(), oup_layout);
    return {{{oup_layout, cn, {}}}, true};
}

SmallVector<TensorPtr> apply_on_physical_tensor(
        const OpDef& def, const SmallVector<TensorPtr>& inputs,
        SmallVector<LogicalTensorDesc>& output_descs, const bool& validated) {
    auto&& op_def = def.cast_final_safe<Convolution3DBackwardData>();
    auto cn = inputs[0]->comp_node();
603 604 605

    auto&& wlayout = inputs[0]->layout();
    auto&& dlayout = inputs[1]->layout();
606 607 608 609 610 611 612 613

    DnnOprCaller<megdnn::Convolution3DBackwardData> caller(cn);
    auto&& dnn_opr = caller.op;
    dnn_opr->param() = op_def.param();

    TensorLayout& oup_layout = output_descs[0].layout;
    if (!validated) {
        megdnn::Convolution3DBackwardData::deduce_layout_impl(
614
                wlayout, dlayout, op_def.param(), oup_layout);
615
    }
616
    auto oup = Tensor::make(oup_layout, cn);
617

618 619 620
    SmallVector<megdnn::TensorND> inp_tensornds(inputs.size());
    inp_tensornds[0] = inputs[0]->dnn_tensor();
    inp_tensornds[1] = inputs[1]->dnn_tensor();
621
    size_t wk_size = setup_algo<megdnn::Convolution3DBackwardData>(
622 623
            {wlayout, dlayout, oup_layout}, dnn_opr.get(), 0, false, false, cn,
            op_def.policy(), false, &inp_tensornds);
624
    auto dnn_wk = caller.create_workspace(wk_size);
625

626 627
    dnn_opr->exec(inp_tensornds[0], inp_tensornds[1], oup->dnn_tensor(), dnn_wk);
    return {oup};
628 629
}

M
Megvii Engine Team 已提交
630
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
631 632 633
    auto&& conv = static_cast<const Convolution3DBackwardData&>(def);
    OperatorNodeConfig config{conv.make_name()};
    mgb_assert(inputs.size() == 2);
M
Megvii Engine Team 已提交
634 635
    return opr::Convolution3DBackwardData::make(
            inputs[0], inputs[1], conv.param(), conv.policy(), config);
636 637 638
}

OP_TRAIT_REG(Convolution3DBackwardData, Convolution3DBackwardData)
M
Megvii Engine Team 已提交
639
        .apply_on_var_node(apply_on_var_node)
640 641
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
642 643 644
        .fallback();
}  // namespace convolution3d_backward_data
}  // namespace
645

M
Megvii Engine Team 已提交
646 647
}  // namespace imperative
}  // namespace mgb