convolution.cpp 22.8 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
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) {
    SmallVector<LogicalTensorDesc> dests(1);
    auto&& desc = dests[0];
    desc.comp_node = inputs[0].comp_node;

    TensorLayout src = inputs[0].layout;
120
    TensorLayout filter = inputs[1].layout;
121
    size_t src_ndim = src.ndim;
122 123
    if (src_ndim == 0 || filter.ndim == 0) {
        desc.layout = TensorLayout{{}, src.dtype};
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
        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;
145
    SmallVector<TensorND> inp_tensornds(inputs.size() + 2);
146 147 148 149 150 151
    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;
152
    DnnOprCaller<megdnn::ConvBiasForward> dnn_opr(cn);
153 154 155 156 157 158 159 160 161 162
    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;
163 164

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

168
    auto empty_bias = Tensor::make(empty_shp, cn);
169

170 171
    inp_tensornds[2] = empty_bias->dnn_tensor();
    inp_tensornds[3] = empty_bias->dnn_tensor();
172

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

    // alloc memory
179
    auto out = Tensor::make(out_layout, cn);
180

181
    auto dnn_wk = dnn_opr.create_workspace(sz);
182 183

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

190
OP_TRAIT_REG(Convolution, Convolution, opr::Convolution)
M
Megvii Engine Team 已提交
191 192
        .make_from_op_node(make_from_op_node)
        .apply_on_var_node(apply_on_var_node)
193 194
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
195 196 197
        .fallback();
}  // namespace convolution
}  // namespace
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
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 已提交
223 224 225
namespace {
namespace convolution_backward_data {
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
226 227
    auto&& conv = static_cast<const ConvolutionBackwardData&>(def);
    OperatorNodeConfig config{conv.make_name()};
228 229 230 231 232
    DType output_dtype = conv.dtype;
    if (output_dtype.valid()) {
        config.output_dtype(output_dtype);
    }

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

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 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
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;
    }
    mgb_assert(ocpg * group == diff[src_or_dst_c_pos], "group conv invalid");

    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;
345 346
    if (diff_ndim == 0 || filter.ndim == 0) {
        desc.layout = TensorLayout{{}, diff.dtype};
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
        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);

368 369
    auto out = Tensor::make(out_layout, cn);

370 371 372 373 374 375 376 377 378 379 380 381 382
    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,
383 384
            false, cn, convbwd.policy(), false, &inp_tensornds);

385
    auto dnn_wk = dnn_opr.create_workspace(sz);
386 387

    // exeucte
388 389
    dnn_opr.op->exec(inp_tensornds[0], inp_tensornds[1], out->dnn_tensor(), dnn_wk);
    return {out};
390 391
}

392
OP_TRAIT_REG(ConvolutionBackwardData, ConvolutionBackwardData)
M
Megvii Engine Team 已提交
393
        .apply_on_var_node(apply_on_var_node)
394 395
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
396 397 398
        .fallback();
}  // namespace convolution_backward_data
}  // namespace
399

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

412 413 414 415 416 417 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 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
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) {
    SmallVector<LogicalTensorDesc> dests(1);
    auto&& desc = dests[0];
    desc.comp_node = inputs[0].comp_node;

    TensorLayout src = inputs[0].layout;
505
    TensorLayout filter = inputs[1].layout;
506
    size_t src_ndim = src.ndim;
507 508
    if (src_ndim == 0 || filter.ndim == 0) {
        desc.layout = TensorLayout{{}, src.dtype};
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
        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;
537 538
    DnnOprCaller<megdnn::Convolution3D> dnn_opr(cn);
    dnn_opr.op->param() = conv.param();
539 540 541

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

    // alloc memory
546
    auto out = Tensor::make(out_layout, cn);
547

548
    auto dnn_wk = dnn_opr.create_workspace(sz);
549 550

    // exeucte
551 552
    dnn_opr.op->exec(inp_tensornds[0], inp_tensornds[1], out->dnn_tensor(), dnn_wk);
    return {out};
553 554
}

555
OP_TRAIT_REG(Convolution3D, Convolution3D, opr::Convolution3D)
M
Megvii Engine Team 已提交
556 557
        .make_from_op_node(make_from_op_node)
        .apply_on_var_node(apply_on_var_node)
558 559
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
560 561 562
        .fallback();
}  // namespace convolution3d
}  // namespace
563

M
Megvii Engine Team 已提交
564 565
namespace {
namespace convolution3d_backward_data {
566 567 568 569 570 571 572 573 574 575 576 577 578

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;

579
    if (weight.layout.ndim == 0 || diff.layout.ndim == 0) {
580 581 582 583 584 585 586 587 588 589 590 591 592 593
        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();
594 595 596

    auto&& wlayout = inputs[0]->layout();
    auto&& dlayout = inputs[1]->layout();
597 598 599 600 601 602 603 604

    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(
605
                wlayout, dlayout, op_def.param(), oup_layout);
606
    }
607
    auto oup = Tensor::make(oup_layout, cn);
608

609 610 611
    SmallVector<megdnn::TensorND> inp_tensornds(inputs.size());
    inp_tensornds[0] = inputs[0]->dnn_tensor();
    inp_tensornds[1] = inputs[1]->dnn_tensor();
612
    size_t wk_size = setup_algo<megdnn::Convolution3DBackwardData>(
613 614
            {wlayout, dlayout, oup_layout}, dnn_opr.get(), 0, false, false, cn,
            op_def.policy(), false, &inp_tensornds);
615
    auto dnn_wk = caller.create_workspace(wk_size);
616

617 618
    dnn_opr->exec(inp_tensornds[0], inp_tensornds[1], oup->dnn_tensor(), dnn_wk);
    return {oup};
619 620
}

M
Megvii Engine Team 已提交
621
auto apply_on_var_node(const OpDef& def, const VarNodeArray& inputs) {
622 623 624
    auto&& conv = static_cast<const Convolution3DBackwardData&>(def);
    OperatorNodeConfig config{conv.make_name()};
    mgb_assert(inputs.size() == 2);
M
Megvii Engine Team 已提交
625 626
    return opr::Convolution3DBackwardData::make(
            inputs[0], inputs[1], conv.param(), conv.policy(), config);
627 628 629
}

OP_TRAIT_REG(Convolution3DBackwardData, Convolution3DBackwardData)
M
Megvii Engine Team 已提交
630
        .apply_on_var_node(apply_on_var_node)
631 632
        .infer_output_attrs_fallible(infer_output_attrs_fallible)
        .apply_on_physical_tensor(apply_on_physical_tensor)
M
Megvii Engine Team 已提交
633 634 635
        .fallback();
}  // namespace convolution3d_backward_data
}  // namespace
636

M
Megvii Engine Team 已提交
637 638
}  // namespace imperative
}  // namespace mgb