nn.h 106.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
#pragma once
#include "megdnn/internal/opr_header_prologue.h"

namespace megdnn {

class SeparableConvBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(SeparableConvBase, OperatorBase);
    DEF_OPR_PARAM(SeparableConv);

public:
    using Mode = Param::Mode;

protected:
M
Megvii Engine Team 已提交
14 15 16 17 18 19
    void deduce_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter_x,
            const TensorLayout& filter_y, TensorLayout& dst);
    void check_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter_x,
            const TensorLayout& filter_y, const TensorLayout& dst);
20 21 22 23 24 25
};

class SeparableConvForward : public SeparableConvBase {
    DEF_OPR_IMPL(SeparableConvForward, SeparableConvBase, 3, 1);

public:
M
Megvii Engine Team 已提交
26 27 28 29 30 31 32 33 34 35
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter_x,
            _megdnn_tensor_in filter_y, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& src, const TensorLayout& filter_x,
            const TensorLayout& filter_y, TensorLayout& dst);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter_x,
            const TensorLayout& filter_y, const TensorLayout& dst) = 0;
36 37

protected:
M
Megvii Engine Team 已提交
38 39 40 41
    void check_exec(
            const TensorLayout& src, const TensorLayout& filter_x,
            const TensorLayout& filter_y, const TensorLayout& dst,
            size_t workspace_in_bytes);
42 43 44
};
using SeparableConv = SeparableConvForward;

45 46 47 48 49 50 51 52 53
namespace detail {

struct PreprocessedFilter {
    //! user data; its lifetime should be bound to MegDNN Convolution
    //! operator
    void* algorithm_id;
    TensorNDArray tensors;
};

54
}  // namespace detail
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
/**
 * \brief base class for convolution operation
 *
 * This operator is supposed to perform convolution on arbitrary input
 * dimensions. The input/output format is N, C, dims..., and kernel format can
 * take two forms:
 *  1. OC, IC, dims..., for conventional dense convolution
 *  2. GROUP, OC_PER_GRP, IC_PER_GRP, dims... for sparse group convolution
 *
 * Currently, only 2D images are supported.
 */
template <typename Parameter>
class ConvolutionBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(ConvolutionBase, OperatorBase);
    using Param = Parameter;

public:
    Param& param() { return m_param; }
    const Param& param() const { return m_param; }

protected:
    Param m_param;

public:
    static constexpr size_t MAX_SPATIAL_DIM = 2;
    using Mode = typename Param::Mode;
    struct CanonizedFilterMeta {
        DType dtype;
        typename Param::Format format;

        uint32_t
                //! whether filter should be flipped (i.e. is CONVOLUTION)
                should_flip,
                group,  //!< number of groups
                icpg,   //!< input channels per group
                ocpg,   //!< output channels per group
                spatial_ndim, stride[MAX_SPATIAL_DIM], padding[MAX_SPATIAL_DIM],
                //! spatial dim
                spatial[MAX_SPATIAL_DIM], dilation[MAX_SPATIAL_DIM],
                //! spatial dim with dilation applied
                dilated_spatial[MAX_SPATIAL_DIM];

        //! T should be a ConvolutionBase<Z>::CanonizedFilterMeta
        template <typename T>
        void copy_from(const T& b) {
            dtype = b.dtype;
            format = b.format;
            should_flip = b.should_flip;
            group = b.group;
            icpg = b.icpg;
            ocpg = b.ocpg;
            spatial_ndim = b.spatial_ndim;
            memcpy(stride, b.stride, sizeof(stride));
            memcpy(padding, b.padding, sizeof(padding));
            memcpy(spatial, b.spatial, sizeof(spatial));
            memcpy(dilation, b.dilation, sizeof(dilation));
            memcpy(dilated_spatial, b.dilated_spatial, sizeof(dilated_spatial));
        }

        bool operator==(const CanonizedFilterMeta& b) const {
            bool flag = true;
            flag = flag && (format == b.format);
            flag = flag && (dtype == b.dtype);
            flag = flag && (should_flip == b.should_flip);
            flag = flag && (group == b.group);
            flag = flag && (icpg == b.icpg);
            flag = flag && (ocpg == b.ocpg);
            flag = flag && (spatial_ndim == b.spatial_ndim);
            if (flag) {
                for (uint32_t i = 0; i < spatial_ndim; ++i) {
                    flag = flag && (stride[i] == b.stride[i]);
                    flag = flag && (padding[i] == b.padding[i]);
                    flag = flag && (spatial[i] == b.spatial[i]);
                    flag = flag && (dilation[i] == b.dilation[i]);
                    flag = flag && (dilated_spatial[i] == b.dilated_spatial[i]);
                }
            }
            return flag;
        }
    };
136
    using PreprocessedFilter = detail::PreprocessedFilter;
137

138 139 140
protected:
    // Check or deduce output DType
    void check_or_deduce_dtype_fwd(DType src, DType filter, DType& dst) const;
M
Megvii Engine Team 已提交
141 142 143 144 145 146
    CanonizedFilterMeta deduce_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter,
            TensorLayout& dst) const;
    CanonizedFilterMeta check_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst) const;
147 148 149 150 151 152 153 154 155 156

    CanonizedFilterMeta make_canonized_filter_meta(
            size_t src_ndim, const TensorLayout& filter) const;
};

class MaskPropagate : public OperatorBase {
    DEF_OPR_IMPL(MaskPropagate, OperatorBase, 1, 1);
    DEF_OPR_PARAM(MaskPropagate);

public:
M
Megvii Engine Team 已提交
157 158 159 160 161
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& dst) = 0;
162 163 164 165 166 167 168 169 170 171 172

    void deduce_layout(const TensorLayout& src, TensorLayout& dst);
};

/**
 * \brief ConvolutionForward Operator with 0/1 Mask matrix
 */
class MaskConvForward : public ConvolutionBase<param::Convolution> {
    DEF_OPR_IMPL(MaskConvForward, ConvolutionBase, 3, 1);

public:
M
Megvii Engine Team 已提交
173 174 175 176 177 178
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_in mask,
            _megdnn_tensor_out dst, _megdnn_workspace worksapce) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& mask, const TensorLayout& dst) = 0;
179 180

    void deduce_dtype(DType src, DType filter, DType mask, DType& dst);
M
Megvii Engine Team 已提交
181 182 183
    void deduce_layout(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& mask, TensorLayout& dst);
184 185

protected:
M
Megvii Engine Team 已提交
186 187 188 189
    CanonizedFilterMeta check_exec(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& mask, const TensorLayout& dst,
            size_t workspace_in_bytes);
190 191 192 193 194 195 196 197 198 199 200 201 202 203
};
using MaskConvolution = MaskConvForward;

/**
 * \brief ConvolutionForward operator.
 */
class ConvolutionForward : public ConvolutionBase<param::Convolution>,
                           public detail::MultiAlgoOpr<ConvolutionForward, 3> {
    DEF_OPR_IMPL(ConvolutionForward, ConvolutionBase, 2, 1);

public:
    /**
     * \param[in] src (n, ic, ih, iw)
     * \param[in] filter (oc, ic, fh, fw)
204 205 206 207 208 209 210
     * \param[in] preprocessed_filter if weight no preprocessed it will be
     * nullptr, else the preprocessed weights store in the tensors of
     * preprocessed_filter.
     * \param[in] workspace if weight no preprocessed
     * (preprocessed_filter == nullptr), The size of the workspace satisfies the
     * situation that weights is not processed, other wise the size of workspace
     * satisfies the situation that weights is preprocessed
211 212
     * \param[out] dst (n, oc, oh, ow)
     */
M
Megvii Engine Team 已提交
213 214 215 216
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_out dst,
            const PreprocessedFilter* preprocessed_filter,
            _megdnn_workspace workspace) = 0;
217 218 219 220 221 222

    MGE_WIN_DECLSPEC_FUC void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) {
        exec(src, filter, dst, nullptr, workspace);
    }
223
    /**
M
Megvii Engine Team 已提交
224 225
     * \brief execute weight preprocessing, read weights form filter and write
     * to preprocessed_filter after preprocessed.
226 227 228
     *
     * \praram[in] workspace the needed tmp workspace when exec_preprocess
     */
M
Megvii Engine Team 已提交
229 230 231 232
    virtual void exec_preprocess(
            const TensorLayout& src_layout, _megdnn_tensor_in filter,
            const TensorLayout& dst_layout, PreprocessedFilter* preprocessed_filter,
            _megdnn_workspace workspace) = 0;
233
    MGE_WIN_DECLSPEC_FUC void deduce_dtype(DType src, DType filter, DType& dst);
234

235
    MGE_WIN_DECLSPEC_FUC void deduce_layout(
M
Megvii Engine Team 已提交
236
            const TensorLayout& src, const TensorLayout& filter, TensorLayout& dst);
237 238 239 240 241 242 243 244 245

    /**
     * \brief query the workspace needed when executing the opr, if the weights
     * are preprocessed the preprocessed_filter will not be nullptr, else it
     * will be nullptr, the workspace size maybe different whether weights are
     * preprocessed
     *
     * \return the size of workspace needed when executing
     */
246 247
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
M
Megvii Engine Team 已提交
248
            const TensorLayout& dst, const PreprocessedFilter* preprocessed_filter) = 0;
249

250 251 252 253 254 255 256 257
    /**
     * \brief deduce the preprocessed filter layouts according to the src,
     * filter and dst layout, the result may contain multi layouts when the
     * weights is not one
     *
     * \return SmallVector<TensorLayout> Derive the layouts of weight
     * preprocessing, return empty if preprocessing is not needed.
     */
258 259 260
    virtual SmallVector<TensorLayout> deduce_preprocessed_filter_layout(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst) = 0;
261

262 263 264 265 266 267 268
    /**
     * \brief query the workspace needed when preprocessing the weights,
     * according to the return size, a _megdnn_workspace will be created and
     * passed through exec_preprocess
     *
     * \return the size of workspace needed when preprocessing
     */
269 270 271
    virtual size_t get_preprocess_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst) = 0;
272

273 274 275 276
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::CONVOLUTION_FORWARD;
    }

277
protected:
278 279 280 281
    CanonizedFilterMeta check_exec(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst, size_t workspace_in_bytes,
            const PreprocessedFilter* preprocessed_filter);
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
};
using Convolution = ConvolutionForward;

/**
 * \brief ConvolutionBackwardData operator.
 *
 * Calculating the gradient wrt. convolution input data.
 */
class ConvolutionBackwardData
        : public ConvolutionBase<param::Convolution>,
          public detail::MultiAlgoOpr<ConvolutionBackwardData, 3> {
    DEF_OPR_IMPL(ConvolutionBackwardData, ConvolutionBase, 2, 1);

public:
    /**
     * \param[in] filter (oc, ic, fh, fw)
     * \param[in] diff (n, oc, oh, ow)
     * \param[out] grad (n, ic, ih, iw)
     */
M
Megvii Engine Team 已提交
301 302 303 304 305 306
    virtual void exec(
            _megdnn_tensor_in filter, _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
307

308
    MGE_WIN_DECLSPEC_FUC void deduce_dtype(DType filter, DType diff, DType& grad);
309
    MGE_WIN_DECLSPEC_FUC void deduce_layout(
M
Megvii Engine Team 已提交
310
            const TensorLayout& filter, const TensorLayout& diff, TensorLayout& grad);
311

312 313 314 315
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::CONVOLUTION_BACKWARD_DATA;
    }

316
protected:
M
Megvii Engine Team 已提交
317 318 319
    CanonizedFilterMeta check_exec(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& grad, size_t workspace_in_bytes);
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
};

/**
 * \brief ConvolutionBackwardFilter operator.
 *
 * Calculating the gradient wrt. convolution filter.
 */
class ConvolutionBackwardFilter
        : public ConvolutionBase<param::Convolution>,
          public detail::MultiAlgoOpr<ConvolutionBackwardFilter, 3> {
    DEF_OPR_IMPL(ConvolutionBackwardFilter, ConvolutionBase, 2, 1);

public:
    /**
     * \param[in] src (n, ic, ih, iw)
     * \param[in] diff (n, oc, oh, ow)
     * \param[out] grad (oc, ic, fh, fw)
     */
M
Megvii Engine Team 已提交
338 339 340 341 342 343
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
344

345 346 347 348
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::CONVOLUTION_BACKWARD_FILTER;
    }

349
protected:
M
Megvii Engine Team 已提交
350 351 352
    CanonizedFilterMeta check_exec(
            const TensorLayout& src, const TensorLayout& diff, const TensorLayout& grad,
            size_t workspace_in_bytes);
353 354 355 356 357 358 359 360 361 362 363 364 365
};

/**
 * \brief ConvolutionBias operator
 */
class ConvBiasForward : public ConvolutionBase<param::ConvBias>,
                        public detail::MultiAlgoOpr<ConvBiasForward, 5> {
    DEF_OPR_IMPL(ConvBiasForward, ConvolutionBase, 4, 1);

public:
    /**
     * \param[in] src (n, ic, ih, iw) or (n, ih, iw, ic)
     * \param[in] filter (oc, ic, fh, fw) or (oc, fh, fw, ic) or (oc/4, fh, fw,
366 367 368
     * 4 * ic)
     * \param[in] bias (1, oc, 1, 1)
     * \param[in] z same as dst
369 370 371 372 373 374 375
     * \param[in] preprocessed_filter if weight no preprocessed it will be
     * nullptr, else the preprocessed weights store in the tensors of
     * preprocessed_filter.
     * \param[in] workspace if weight no preprocessed
     * (preprocessed_filter == nullptr), The size of the workspace satisfies the
     * situation that weights is not processed, other wise the size of workspace
     * satisfies the situation that weights is preprocessed
376
     * \param[out] dst (n, oc, oh, ow) or (n, oh, ow, oc)
377 378 379 380
     *
     * \note if the format is NCHW_WINOGRAD, the filter layout is (alphah,
     * alphaw, oc, ic)
     */
M
Megvii Engine Team 已提交
381 382 383 384 385
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_in bias,
            _megdnn_tensor_in z, _megdnn_tensor_out dst,
            const PreprocessedFilter* preprocessed_filter,
            _megdnn_workspace workspace) = 0;
386

387 388 389 390 391 392
    MGE_WIN_DECLSPEC_FUC void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_in bias,
            _megdnn_tensor_in z, _megdnn_tensor_out dst, _megdnn_workspace workspace) {
        exec(src, filter, bias, z, dst, nullptr, workspace);
    }

393
    /**
394 395
     * \brief execute weight preprocessing, read weights form filter and bias,
     * write to preprocessed_filter after preprocessed.
396 397 398 399
     *
     * \praram[in] workspace the needed tmp workspace when exec_preprocess
     * running, the size is got by get_preprocess_workspace_in_bytes
     */
M
Megvii Engine Team 已提交
400 401 402 403 404
    virtual void exec_preprocess(
            const TensorLayout& src_layout, _megdnn_tensor_in filter,
            _megdnn_tensor_in bias, const TensorLayout& z_layout,
            const TensorLayout& dst_layout, PreprocessedFilter* preprocessed_filter,
            _megdnn_workspace workspace) = 0;
405 406 407
    MGE_WIN_DECLSPEC_FUC void deduce_dtype(
            DType src, DType filter, DType bias, DType z, DType& dst);
    MGE_WIN_DECLSPEC_FUC void deduce_layout(
M
Megvii Engine Team 已提交
408 409
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& bias, const TensorLayout& z, TensorLayout& dst);
410

411 412 413 414 415 416 417 418
    /**
     * \brief query the workspace needed when executing the opr, if the weights
     * are preprocessed the preprocessed_filter will not be nullptr, else it
     * will be nullptr, the workspace size maybe different whether weights are
     * preprocessed
     *
     * \return the size of workspace needed when executing
     */
419 420
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
M
Megvii Engine Team 已提交
421
            const TensorLayout& bias, const TensorLayout& z, const TensorLayout& dst,
422
            const PreprocessedFilter* preprocessed_filter) = 0;
423 424 425 426 427 428 429 430

    /**
     * \brief query the workspace needed when pre-processing the weights,
     * according to the return size, a _megdnn_workspace will be created and
     * passed through exec_preprocess
     *
     * \return the size of workspace needed when pre-processing
     */
431 432 433 434
    virtual size_t get_preprocess_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& bias, const TensorLayout& z,
            const TensorLayout& dst) = 0;
435 436 437 438 439 440 441 442 443

    /**
     * \brief deduce the pre-processed filter layouts according to the src,
     * filter and dst layout, which may contain multi layouts when the weights
     * is not one
     *
     * \return SmallVector<TensorLayout> Derive the layouts of weight
     * preprocessing, return empty if preprocessing is not needed.
     */
444 445 446 447 448
    virtual SmallVector<TensorLayout> deduce_preprocessed_filter_layout(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& bias, const TensorLayout& z,
            const TensorLayout& dst) = 0;

449 450 451 452 453 454 455
    enum class BiasMode : uint32_t {
        NO_BIAS = 0,             //!< no bias
        BROADCAST_CHANNEL_BIAS,  //!< broadcast channel bias, [1, c, 1, 1]
        BIAS                     //!< [N, C, H, W]
    };

    //! param for winograd algos.
456

457 458 459 460
    struct WinogradParam {
        uint32_t channel_block_size;
        uint32_t output_block_size;
        uint32_t tile_size;
461
        uint32_t filter_size;
462 463 464
        bool operator==(const WinogradParam& rhs) const {
            return channel_block_size == rhs.channel_block_size &&
                   output_block_size == rhs.output_block_size &&
465
                   tile_size == rhs.tile_size && filter_size == rhs.filter_size;
466 467 468 469
        }

        std::string to_string() const;
    };
470
    static constexpr WinogradParam INVALID_WINOGRAD_PARAM = {0, 0, 0, 0};
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486

    struct DirectParam {
        std::string to_string() const { return ""; }
    };

    struct MatmulParam {
        std::string to_string() const { return ""; }
    };

    struct DefaultParam {
        std::string to_string() const { return ""; }
    };

    //! get algo name, the format is ParamTrait<T>::category:base:p.to_string()
    //! \warning: base must not contain :.
    template <typename T>
487 488 489
    static std::string algo_name(
            const std::string& base, const T& p,
            param::ConvBias::Format format = param::ConvBias::Format::NCHW);
490 491 492 493 494 495 496 497 498 499 500
    /*!
     * \brief parse algo_name and get WinogradParam from algo name.
     *
     * \param algo name string
     * \return WinogradParam parsed from algo name, use pattern
     * winograd:base:m:tile_size.
     *
     * \warning: INVALID_WINOGRAD_PARAM returns if the algo_name is not matched.
     */
    static WinogradParam parse_winograd_name(const std::string& algo_name);

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    /**
     * @brief find if there is nchw_nchwxx conv kernel optimized for argment,
     * nchw44 used for arm, nchw88 used for x86
     *
     * @param src_dtype  conv feature map data type
     * @param filter_dtype  conv filter or weight data type
     * @param dst_dtype output data type
     * @param fm filter meta param
     * @param bias_mode bias mode, no_bias or broadcast or bias
     * @param nonline_mode identity or relu or h_swish or sigmoid
     * @return true, found a kernel
     * @return false, can`t found any kernel
     */
    static bool is_nchw_nchwxx_optimized(
            const DTypeEnum src_dtype, const DTypeEnum filter_dtype,
            const DTypeEnum dst_dtype,
            const ConvolutionBase<param::Convolution>::CanonizedFilterMeta& fm,
            const ConvBiasForward::BiasMode bias_mode,
            const param::ConvBias::NonlineMode nonline_mode);

521 522 523 524
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::CONVBIAS_FORWARD;
    }

525
protected:
526 527
    CanonizedFilterMeta check_exec(
            const TensorLayout& src, const TensorLayout& filter,
M
Megvii Engine Team 已提交
528 529
            const TensorLayout& bias, const TensorLayout& z, const TensorLayout& dst,
            size_t workspace_in_bytes, const PreprocessedFilter* preprocessed_filter);
530 531 532

    CanonizedFilterMeta check_exec_allow_noncontiguous(
            const TensorLayout& src, const TensorLayout& filter,
M
Megvii Engine Team 已提交
533 534
            const TensorLayout& bias, const TensorLayout& z, const TensorLayout& dst,
            size_t workspace_in_bytes, const PreprocessedFilter* preprocessed_filter);
535 536 537
};
using ConvBias = ConvBiasForward;

538 539 540 541 542 543 544 545
/**
 * \brief RegionRestrictedConvolutionForward operator.
 */
class RegionRestrictedConvolutionForward : public ConvolutionBase<param::Convolution> {
    DEF_OPR_IMPL(RegionRestrictedConvolutionForward, ConvolutionBase, 4, 1);

public:
    /**
546 547
     * \param[in] src (n, ic, ih, iw) or (n, g*icpg, ih, iw)
     * \param[in] filter (oc, ic, fh, fw) or (g, ocpg, icpg, fh, fw)
548 549
     * \param[in] rin (n, ih, iw)
     * \param[in] rout (n, oh, ow)
550
     * \param[out] dst (n, oc, oh, ow) or (n, g*ocpg, oh, ow)
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
     */
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_in rin,
            _megdnn_tensor_in rout, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;

    void deduce_dtype(DType src, DType filter, DType rin, DType rout, DType& dst);

    MGE_WIN_DECLSPEC_FUC void deduce_layout(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& rin, const TensorLayout& rout, TensorLayout& dst);

    /**
     * \brief query the workspace needed when executing the opr
     * \return the size of workspace needed when executing
     */
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& rin, const TensorLayout& rout,
            const TensorLayout& dst) = 0;

    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::REGIONRESTRICTEDCONVOLUTION_FORWARD;
    }

protected:
    CanonizedFilterMeta check_exec(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& rin, const TensorLayout& rout, const TensorLayout& dst,
            size_t workspace_in_bytes);
};
using RegionRestrictedConvolution = RegionRestrictedConvolutionForward;

/**
 * \brief RegionRestrictedConvolutionBackwardData operator.
 *
 * Calculating the gradient wrt. convolution input data.
 */
class RegionRestrictedConvolutionBackwardData
        : public ConvolutionBase<param::Convolution> {
    DEF_OPR_IMPL(RegionRestrictedConvolutionBackwardData, ConvolutionBase, 4, 1);

public:
    /**
595 596
     * \param[in] filter (oc, ic, fh, fw) or (g, ocpg, icpg, fh, fw)
     * \param[in] diff (n, oc, oh, ow) or (n, g*ocpg, oh, ow)
597 598
     * \param[in] rin (n, ih, iw)
     * \param[in] rout (n, oh, ow)
599
     * \param[out] grad (n, ic, ih, iw) or (n, g*icpg, ih, iw)
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
     */
    virtual void exec(
            _megdnn_tensor_in filter, _megdnn_tensor_in diff, _megdnn_tensor_in rin,
            _megdnn_tensor_in rout, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& rin, const TensorLayout& rout,
            const TensorLayout& grad) = 0;

    MGE_WIN_DECLSPEC_FUC void deduce_dtype(
            DType filter, DType diff, DType rin, DType rout, DType& grad);
    MGE_WIN_DECLSPEC_FUC void deduce_layout(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& rin, const TensorLayout& rout, TensorLayout& grad);

    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::REGIONRESTRICTEDCONVOLUTION_BACKWARD_DATA;
    }

protected:
    CanonizedFilterMeta check_exec(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& rin, const TensorLayout& rout, const TensorLayout& grad,
            size_t workspace_in_bytes);
};

/**
 * \brief RegionRestrictedConvolutionBackwardFilter operator.
 *
 * Calculating the gradient wrt. convolution filter.
 */
class RegionRestrictedConvolutionBackwardFilter
        : public ConvolutionBase<param::Convolution> {
    DEF_OPR_IMPL(RegionRestrictedConvolutionBackwardFilter, ConvolutionBase, 4, 1);

public:
    /**
638 639
     * \param[in] src (n, ic, ih, iw) or (n, g*icpg, ih, iw)
     * \param[in] diff (n, oc, oh, ow) or (n, g*ocpg, oh, ow)
640 641
     * \param[in] rin (n, ih, iw)
     * \param[in] rout (n, oh, ow)
642
     * \param[out] grad (oc, ic, fh, fw) or (g, ocpg, icpg, fh, fw)
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
     */
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in diff, _megdnn_tensor_in rin,
            _megdnn_tensor_in rout, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& diff, const TensorLayout& rin,
            const TensorLayout& rout, const TensorLayout& grad) = 0;

    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::REGIONRESTRICTEDCONVOLUTION_BACKWARD_FILTER;
    }

protected:
    CanonizedFilterMeta check_exec(
            const TensorLayout& src, const TensorLayout& diff, const TensorLayout& rin,
            const TensorLayout& rout, const TensorLayout& grad,
            size_t workspace_in_bytes);
};

663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
/**
 * \brief base class for Conv - Nonline - Pooling
 */
class ConvPoolingBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(ConvPoolingBase, OperatorBase);

    /**
     *  \ Param::Method: Two methods to fetch the input data.
     *  Default methods is WITH_TEXTURE_OBJ.
     *  If you want to use WITH_SHARED_MEM mode,
     *  please make sure that the size of
     *   [ all of the fliter kernels + a channel
     *  of input data + a channel of output data]
     *  should be no large than 38KB.
     *  And the pooling mode should not be "MAX".
     */
    DEF_OPR_PARAM(ConvPooling);

protected:
M
Megvii Engine Team 已提交
682 683 684 685 686 687 688
    virtual void deduce_layout(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& bias, TensorLayout& dst) = 0;
    virtual void check_layout(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& bias, TensorLayout& dst,
            size_t workspace_limit_in_bytes) = 0;
689 690 691 692 693 694 695 696 697 698
};

class ConvPoolingForward : public ConvPoolingBase {
    DEF_OPR_IMPL(ConvPoolingForward, ConvPoolingBase, 2, 1);

public:
    /**
     * \param[in] src input tensor
     * \param[out] dst output tensor
     */
M
Megvii Engine Team 已提交
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
    virtual void exec(
            const _megdnn_in TensorND src, const _megdnn_in TensorND filter,
            const _megdnn_in TensorND bias, _megdnn_out TensorND dst,
            _megdnn_out Workspace workspace) = 0;
    virtual void deduce_layout(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& bias, TensorLayout& dst) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& bias, const TensorLayout& dst) = 0;

protected:
    virtual void check_layout(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& bias, TensorLayout& dst,
            size_t workspace_limit_in_bytes) = 0;
715 716 717 718 719 720 721 722 723 724 725
};
using ConvPooling = ConvPoolingForward;

class GroupLocalBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(GroupLocalBase, OperatorBase);
    DEF_OPR_PARAM(Convolution);

public:
    using Mode = Param::Mode;

protected:
M
Megvii Engine Team 已提交
726 727 728 729 730
    void deduce_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter, TensorLayout& dst);
    void check_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst);
731 732 733 734 735 736 737 738 739 740 741
};

class GroupLocalForward : public GroupLocalBase {
    DEF_OPR_IMPL(GroupLocalForward, GroupLocalBase, 2, 1);

public:
    /**
     * \param[in] src (N, IC, IH, IW)
     * \param[in] filter (G, OH, OW, IC/G, FH, FW, OC/G)
     * \param[out] dst (N, OC, OH, OW)
     **/
M
Megvii Engine Team 已提交
742 743 744 745 746
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& src, const TensorLayout& filter, TensorLayout& dst) {
747 748
        deduce_layout_fwd(src, filter, dst);
    }
M
Megvii Engine Team 已提交
749 750 751
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst) = 0;
752 753

protected:
M
Megvii Engine Team 已提交
754 755 756
    void check_exec(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst, size_t workspace_in_bytes);
757 758 759 760 761 762 763
};
using GroupLocal = GroupLocalForward;

class GroupLocalBackwardData : public GroupLocalBase {
    DEF_OPR_IMPL(GroupLocalBackwardData, GroupLocalBase, 2, 1);

public:
M
Megvii Engine Team 已提交
764 765 766 767 768 769
    virtual void exec(
            _megdnn_tensor_in filter, _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
770 771

protected:
M
Megvii Engine Team 已提交
772 773 774
    void check_exec(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& grad, size_t workspace_in_bytes);
775 776 777 778 779 780
};

class GroupLocalBackwardFilter : public GroupLocalBase {
    DEF_OPR_IMPL(GroupLocalBackwardFilter, GroupLocalBase, 2, 1);

public:
M
Megvii Engine Team 已提交
781 782 783 784 785 786
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
787 788

protected:
M
Megvii Engine Team 已提交
789 790 791
    void check_exec(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& grad, size_t workspace_in_bytes);
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
};

class Images2NeibsBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(Images2NeibsBase, OperatorBase);
    DEF_OPR_PARAM(Images2Neibs);

protected:
    void deduce_layout_fwd(const TensorLayout& src, TensorLayout& dst);
    void check_layout_fwd(const TensorLayout& filter, const TensorLayout& dst);
};

class Images2NeibsForward : public Images2NeibsBase {
    DEF_OPR_IMPL(Images2NeibsForward, Images2NeibsBase, 1, 1);

public:
    /**
     * \param[in] src (N, C, IH, IW)
     * \param[out] dst (N, C, OH, OW, window_h, window_w)
     *
     * \see
     * http://deeplearning.net/software/theano/library/tensor/nnet/neighbours.html
     *
     * \f$ dst_{n, c, oh, ow, wh, ww} = src_{n, c, ih+wh, iw+fw}\f$,
815 816
     * where \f$ ih=-pad_h+oh*stride_h+(wh-1)*(dilation_h-1),
     * iw=-pad_w+ow*stride_w+(ww-1)*(dilation_w-1)\f$.
817
     */
M
Megvii Engine Team 已提交
818 819 820 821 822
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& dst) = 0;
823 824 825
    void deduce_layout(const TensorLayout& src, TensorLayout& dst);

protected:
M
Megvii Engine Team 已提交
826 827 828
    void check_exec(
            const TensorLayout& src, const TensorLayout& dst,
            size_t workspace_in_bytes);
829 830 831 832 833 834 835 836 837 838 839
};
using Images2Neibs = Images2NeibsForward;

class Images2NeibsBackward : public Images2NeibsBase {
    DEF_OPR_IMPL(Images2NeibsBackward, Images2NeibsBase, 1, 1);

public:
    /**
     * \param[in] diff the backpropagated gradient wrt. dst
     * \param[out] grad the backpropagated gradient wrt. src
     */
M
Megvii Engine Team 已提交
840 841 842 843 844
    virtual void exec(
            _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& diff, const TensorLayout& grad) = 0;
845

846
protected:
M
Megvii Engine Team 已提交
847 848 849
    void check_exec(
            const TensorLayout& diff, const TensorLayout& grad,
            size_t workspace_in_bytes);
850 851 852 853 854 855 856 857 858 859 860 861
};

class SlidingWindowTransposeBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(SlidingWindowTransposeBase, OperatorBase);
    DEF_OPR_PARAM(SlidingWindowTranspose);

protected:
    void deduce_layout_fwd(const TensorLayout& src, TensorLayout& dst);
    void check_layout_fwd(const TensorLayout& filter, const TensorLayout& dst);
};

class SlidingWindowTransposeForward : public SlidingWindowTransposeBase {
M
Megvii Engine Team 已提交
862
    DEF_OPR_IMPL(SlidingWindowTransposeForward, SlidingWindowTransposeBase, 1, 1);
863 864 865 866 867 868

public:
    /**
     * \param[in] src (N, C, IH, IW, window_h, window_w)
     * \param[out] dst (N, C, OH, OW)
     */
M
Megvii Engine Team 已提交
869 870 871 872 873
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& dst) = 0;
874 875 876
    void deduce_layout(const TensorLayout& src, TensorLayout& dst);

protected:
M
Megvii Engine Team 已提交
877 878 879
    void check_exec(
            const TensorLayout& src, const TensorLayout& dst,
            size_t workspace_in_bytes);
880 881 882 883
};
using SlidingWindowTranspose = SlidingWindowTransposeForward;

class SlidingWindowTransposeBackward : public SlidingWindowTransposeBase {
M
Megvii Engine Team 已提交
884
    DEF_OPR_IMPL(SlidingWindowTransposeBackward, SlidingWindowTransposeBase, 1, 1);
885 886 887 888 889 890

public:
    /**
     * \param[in] diff the backpropagated gradient wrt. dst
     * \param[out] grad the backpropagated gradient wrt. src
     */
M
Megvii Engine Team 已提交
891 892 893 894 895
    virtual void exec(
            _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& diff, const TensorLayout& grad) = 0;
896

897
protected:
M
Megvii Engine Team 已提交
898 899 900
    void check_exec(
            const TensorLayout& diff, const TensorLayout& grad,
            size_t workspace_in_bytes);
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
};

/**
 * \brief base class for Pooling
 */
class PoolingBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(PoolingBase, OperatorBase);
    DEF_OPR_PARAM(Pooling);

public:
    using Mode = Param::Mode;

protected:
    void deduce_layout_fwd(const TensorLayout& src, TensorLayout& dst);
    void check_layout_fwd(const TensorLayout& src, const TensorLayout& dst);
916 917

public:
918
    static void deduce_layout_impl(
919
            const TensorLayout& src, const Param& param, TensorLayout& dst);
920 921
};

922 923
class PoolingForward : public PoolingBase,
                       public detail::MultiAlgoOpr<PoolingForward, 2> {
924 925 926 927 928 929 930
    DEF_OPR_IMPL(PoolingForward, PoolingBase, 1, 1);

public:
    /**
     * \param[in] src input tensor
     * \param[out] dst output tensor
     */
M
Megvii Engine Team 已提交
931 932 933
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
934
    MGE_WIN_DECLSPEC_FUC void deduce_layout(const TensorLayout& src, TensorLayout& dst);
M
Megvii Engine Team 已提交
935 936
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& dst) = 0;
937

938 939 940 941
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::POOLING_FORWARD;
    }

942
protected:
M
Megvii Engine Team 已提交
943 944 945
    void check_exec(
            const TensorLayout& src, const TensorLayout& dst,
            size_t workspace_in_bytes);
946 947 948 949
};

using Pooling = PoolingForward;

950 951
class PoolingBackward : public PoolingBase,
                        public detail::MultiAlgoOpr<PoolingBackward, 4> {
952 953 954 955 956 957 958 959 960
    DEF_OPR_IMPL(PoolingBackward, PoolingBase, 3, 1);

public:
    /**
     * \param[in] src the `src' parameter in PoolingForward::exec
     * \param[in] dst the `dst' parameter in PoolingForward::exec
     * \param[in] diff the backpropagated gradient wrt. dst
     * \param[out] grad the backpropagated gradient wrt. src
     */
M
Megvii Engine Team 已提交
961 962 963 964 965 966
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in dst, _megdnn_tensor_in diff,
            _megdnn_tensor_out grad, _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& dst, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
967

968 969 970 971
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::POOLING_BACKWARD;
    }

972
protected:
M
Megvii Engine Team 已提交
973 974 975
    void check_exec(
            const TensorLayout& src, const TensorLayout& dst, const TensorLayout& diff,
            const TensorLayout& grad, size_t workspace_in_bytes);
976 977
};

978 979 980 981 982 983 984 985
/**
 * \brief base class for AdaptivePooling
 */
class AdaptivePoolingBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(AdaptivePoolingBase, OperatorBase);
    DEF_OPR_PARAM(AdaptivePooling);

protected:
M
Megvii Engine Team 已提交
986 987
    param::Pooling deduce_pooling_param(
            const TensorLayout& src, const TensorLayout& dst);
988 989 990 991 992 993 994 995 996 997
};

class AdaptivePoolingForward : public AdaptivePoolingBase {
    DEF_OPR_IMPL(AdaptivePoolingForward, AdaptivePoolingBase, 1, 1);

public:
    /**
     * \param[in] src input tensor
     * \param[out] dst output tensor
     */
M
Megvii Engine Team 已提交
998 999 1000 1001 1002
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& dst) = 0;
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
};

using AdaptivePooling = AdaptivePoolingForward;

class AdaptivePoolingBackward : public AdaptivePoolingBase {
    DEF_OPR_IMPL(AdaptivePoolingBackward, AdaptivePoolingBase, 3, 1);

public:
    /**
     * \param[in] src the `src' parameter in AdaptivePoolingForward::exec
     * \param[in] dst the `dst' parameter in AdaptivePoolingForward::exec
     * \param[in] diff the backpropagated gradient wrt. dst
     * \param[out] grad the backpropagated gradient wrt. src
     */
M
Megvii Engine Team 已提交
1017 1018 1019 1020 1021 1022
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in dst, _megdnn_tensor_in diff,
            _megdnn_tensor_out grad, _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& dst, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
1023 1024
};

1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
/**
 * \brief base class for Local
 */
class LocalBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(LocalBase, OperatorBase);
    DEF_OPR_PARAM(Convolution);

public:
    using Mode = Param::Mode;

protected:
M
Megvii Engine Team 已提交
1036 1037 1038 1039 1040
    void deduce_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter, TensorLayout& dst);
    void check_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst);
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
};

class LocalForward : public LocalBase {
    DEF_OPR_IMPL(LocalForward, LocalBase, 2, 1);

public:
    /**
     * \param[in] src (n, ic, ih, iw)
     * \param[in] filter (oh, ow, ic, fh, fw, oc)
     * \param[out] dst (n, oc, oh, ow)
     */
M
Megvii Engine Team 已提交
1052 1053 1054
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
1055 1056 1057 1058 1059 1060
    /**
     * \brief Deducing output tensor layouts from input tensor layouts.
     *
     * Be aware that the first and second dimension of `filter' are ignored
     * when deducing `dst' layout.
     */
M
Megvii Engine Team 已提交
1061 1062 1063 1064 1065
    void deduce_layout(
            const TensorLayout& src, const TensorLayout& filter, TensorLayout& dst);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst) = 0;
1066 1067

protected:
M
Megvii Engine Team 已提交
1068 1069 1070
    void check_exec(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst, size_t workspace_in_bytes);
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
};
using Local = LocalForward;

class LocalBackwardData : public LocalBase {
    DEF_OPR_IMPL(LocalBackwardData, LocalBase, 2, 1);

public:
    /**
     * \param[in] filter (oh, ow, ic, fh, fw, oc)
     * \param[in] diff (n, oc, oh, ow)
     * \param[out] grad (n, ic, ih, iw)
     */
M
Megvii Engine Team 已提交
1083 1084 1085
    virtual void exec(
            _megdnn_tensor_in filter, _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
1086

M
Megvii Engine Team 已提交
1087 1088 1089
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
1090 1091

protected:
M
Megvii Engine Team 已提交
1092 1093 1094
    void check_exec(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& grad, size_t workspace_in_bytes);
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
};

class LocalBackwardFilter : public LocalBase {
    DEF_OPR_IMPL(LocalBackwardFilter, LocalBase, 2, 1);

public:
    /**
     * \param[in] src (n, ic, ih, iw)
     * \param[in] diff (n, oc, oh, ow)
     * \param[out] grad (oh, ow, ic, fh, fw, oc)
     */
M
Megvii Engine Team 已提交
1106 1107 1108
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
1109

M
Megvii Engine Team 已提交
1110 1111 1112
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
1113 1114

protected:
M
Megvii Engine Team 已提交
1115 1116 1117
    void check_exec(
            const TensorLayout& src, const TensorLayout& diff, const TensorLayout& grad,
            size_t workspace_in_bytes);
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
};

class BNBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(BNBase, OperatorBase);
    DEF_OPR_PARAM(BN);

protected:
    void check_param();
};

class BNForward : public BNBase {
1129
    DEF_OPR_IMPL(BNForward, BNBase, 6, 6);
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

public:
    /**
     * \dst[i] = gemma
     * *(x[i]-estimatedMean[k])/sqrt(epsilon+estimatedVariance[k]) + beta \where
     * epsilon is a very small value to avoid a "divide by zero" error.
     * \param[in] src (n, c, h, w)
     * \param[out] dst (n, c, h, w)
     * \param[out] mean (see m_param.ParamDim) Global mean.
     * \param[out] variance (see m_param.ParamDim) Global variance.
1140
     * \param[out] batch_mean (see m_param.ParamDim)
1141
     *   Optionally cached intermediate mean from forward pass
1142
     * \param[out] batch_inv_variance (see m_param.ParamDim)
1143
     *   Optionally cached intermediate variance from forward pass
1144
     * \param[out] reserve (see cudnnBatchNormalizationForwardTrainingEx)
1145 1146 1147
     * src and dst must have the same shape.
     * src and dst must be contiguous.
     */
M
Megvii Engine Team 已提交
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in bn_scale,
            _megdnn_tensor_in bn_bias, _megdnn_tensor_inout mean,
            _megdnn_tensor_inout variance, _megdnn_tensor_out batch_mean,
            _megdnn_tensor_out batch_inv_variance, _megdnn_tensor_out reserve,
            _megdnn_tensor_out dst, _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& src, const TensorLayout& bn_scale,
            const TensorLayout& bn_bias, TensorLayout& mean, TensorLayout& variance,
            TensorLayout& batch_mean, TensorLayout& batch_inv_variance,
            TensorLayout& reserve, TensorLayout& dst);
1159 1160 1161 1162
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& bn_scale,
            const TensorLayout& bn_bias, const TensorLayout& mean,
            const TensorLayout& variance, const TensorLayout& batch_mean,
1163
            const TensorLayout& batch_inv_variance, const TensorLayout& reserve,
1164
            const TensorLayout& dst) = 0;
1165
    virtual size_t get_reserve_in_bytes(const TensorLayout& src) = 0;
1166 1167

protected:
M
Megvii Engine Team 已提交
1168 1169 1170 1171 1172 1173
    void check_exec(
            const TensorLayout& src, const TensorLayout& bn_scale,
            const TensorLayout& bn_bias, const TensorLayout& mean,
            const TensorLayout& variance, const TensorLayout& batch_mean,
            const TensorLayout& batch_inv_variance, const TensorLayout& dst,
            size_t workspace_in_bytes, size_t reserve_in_bytes = 0);
1174 1175 1176 1177
};
using BN = BNForward;

class BNBackward : public BNBase {
1178
    DEF_OPR_IMPL(BNBackward, BNBase, 6, 3);
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191

public:
    /**
     * \param[in] input data of forwarding propagate.
     * \param[in] dy the backpropagated gradient of y.
     * \param[out] dx the backpropagated gradient of x.
     * \param[out] d_bn_scale, the backpropagated gradient of bn_scale.
     * \param[out] d_bn_bias, the backpropagated gradient of bn_bias.
     * Optionally cached intermediate results from forward pass
     * \param[in] saved_batch_mean mean of the input batch.
        Calculated in the forwardpropagation.
     * \param[in] saved_batch_variance of the input batch.
        Calculated in the forwardpropagation.
1192
     * \param[in] reserve (see cudnnBatchNormalizationBackwardEx)
1193
     */
M
Megvii Engine Team 已提交
1194 1195 1196 1197 1198 1199
    virtual void exec(
            _megdnn_tensor_in x, _megdnn_tensor_in dy,
            _megdnn_tensor_in saved_batch_mean, _megdnn_tensor_in saved_batch_variance,
            _megdnn_tensor_in bn_scale, _megdnn_tensor_in reserve,
            _megdnn_tensor_out d_bn_scale, _megdnn_tensor_out d_bn_bias,
            _megdnn_tensor_out dx, _megdnn_workspace workspace) = 0;
1200 1201 1202
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& x, const TensorLayout& dy,
            const TensorLayout& saved_batch_mean,
M
Megvii Engine Team 已提交
1203 1204 1205
            const TensorLayout& saved_batch_variance, const TensorLayout& bn_scale,
            const TensorLayout& reserve, const TensorLayout& d_bn_scale,
            const TensorLayout& d_bn_bias, const TensorLayout& dx) = 0;
1206
    virtual size_t get_reserve_in_bytes(const TensorLayout& src) = 0;
1207 1208

protected:
M
Megvii Engine Team 已提交
1209 1210 1211 1212 1213 1214 1215
    void check_exec(
            const TensorLayout& x, const TensorLayout& dy,
            const TensorLayout& saved_batch_mean,
            const TensorLayout& saved_batch_variance, const TensorLayout& bn_scale,
            const TensorLayout& d_bn_scale, const TensorLayout& d_bn_bias,
            const TensorLayout& dx, size_t workspace_in_bytes,
            size_t reserve_in_bytes = 0);
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
};

class LRNBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(LRNBase, OperatorBase);
    DEF_OPR_PARAM(LRN);

protected:
    void check_param();
};

class LRNForward : public LRNBase {
    DEF_OPR_IMPL(LRNForward, LRNBase, 1, 1);

public:
    /**
     * \see ImageNet Classification with Deep Convolutional Neural Networks
     * \param[in] src (n, c, h, w)
     * \param[out] dst (n, c, h, w)
     *
     * src and dst must have the same shape.
     * src and dst must be contiguous.
     */
M
Megvii Engine Team 已提交
1238 1239 1240
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
1241
    void deduce_layout(const TensorLayout& src, TensorLayout& dst);
M
Megvii Engine Team 已提交
1242 1243
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& dst) = 0;
1244 1245

protected:
M
Megvii Engine Team 已提交
1246 1247 1248
    void check_exec(
            const TensorLayout& src, const TensorLayout& dst,
            size_t workspace_in_bytes);
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
};
using LRN = LRNForward;

class LRNBackward : public LRNBase {
    DEF_OPR_IMPL(LRNBackward, LRNBase, 3, 1);

public:
    /**
     * \param[in] src the `src' parameter in LRNForward::exec
     * \param[in] dst the `dst' parameter in LRNForward::exec
     * \param[in] diff the backpropagated gradient wrt. dst
     * \param[out] grad the backpropagated gradient wrt. src
     *
     * All tensors should be contiguous and of the same shape.
     */
M
Megvii Engine Team 已提交
1264 1265 1266 1267 1268 1269
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in dst, _megdnn_tensor_in diff,
            _megdnn_tensor_out grad, _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& dst, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
1270 1271

protected:
M
Megvii Engine Team 已提交
1272 1273 1274
    void check_exec(
            const TensorLayout& src, const TensorLayout& dst, const TensorLayout& diff,
            const TensorLayout& grad, size_t workspace_in_bytes);
1275 1276 1277 1278 1279 1280 1281
};

class ROIPoolingBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(ROIPoolingBase, OperatorBase);
    DEF_OPR_PARAM(ROIPooling);

protected:
M
Megvii Engine Team 已提交
1282 1283 1284
    void check_layout_fwd(
            const TensorLayout& src, const TensorLayout& rois, const TensorLayout& dst,
            const TensorLayout& index);
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
};

class ROIPoolingForward : public ROIPoolingBase {
    DEF_OPR_IMPL(ROIPoolingForward, ROIPoolingBase, 2, 2);

public:
    /**
     * \param[in] src (n, c, ih, iw)
     * \param[in] rois (m, 5)
     * \param[out] dst (m, c, oh, ow)
     * \param[out] index (m, c, oh, ow) if mode is MAX, (0) if mode is AVERAGE
     *
     * The internal implementation is akin to
     * https://github.com/rbgirshick/caffe-fast-rcnn .d
     * Note that rois(, 0) denotes the input image index. We store it as
     * a float, but it should be an integer instead.
     *
     * index is a temporary tensor to facilitate its backward operator.
     * It is used to store argmax indicex in MAX mode, and it is not used
     * in AVERAGE mode.
     */
M
Megvii Engine Team 已提交
1306 1307 1308 1309 1310 1311
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in rois, _megdnn_tensor_out dst,
            _megdnn_tensor_out index, _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& rois, const TensorLayout& dst,
            const TensorLayout& index) = 0;
1312 1313

protected:
M
Megvii Engine Team 已提交
1314 1315 1316
    void check_exec(
            const TensorLayout& src, const TensorLayout& rois, const TensorLayout& dst,
            const TensorLayout& index, size_t workspace_in_bytes);
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
};
using ROIPooling = ROIPoolingForward;

class ROIPoolingBackward : public ROIPoolingBase {
    DEF_OPR_IMPL(ROIPoolingBackward, ROIPoolingBase, 4, 1);

public:
    /**
     * \param[in] diff the backpropagated gradient wrt. dst
     * \param[in] src the `src' parameter in ROIPoolingForward::exec
     * \param[in] rois the `rois' parameter in ROIPoolingForward::exec
     * \param[in] index the `index' parameter in ROIPoolingForward::exec
     * \param[out] grad the backpropagated gradient wrt. src
     */
M
Megvii Engine Team 已提交
1331 1332 1333 1334 1335 1336 1337
    virtual void exec(
            _megdnn_tensor_in diff, _megdnn_tensor_in src, _megdnn_tensor_in rois,
            _megdnn_tensor_in index, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& diff, const TensorLayout& src, const TensorLayout& rois,
            const TensorLayout& index, const TensorLayout& grad) = 0;
1338 1339

protected:
M
Megvii Engine Team 已提交
1340 1341 1342 1343
    void check_exec(
            const TensorLayout& diff, const TensorLayout& src, const TensorLayout& rois,
            const TensorLayout& index, const TensorLayout& grad,
            size_t workspace_in_bytes);
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
};

class Convolution3DBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(Convolution3DBase, OperatorBase);
    DEF_OPR_PARAM(Convolution3D);

public:
    static constexpr size_t MAX_SPATIAL_DIM = 3;
    using Mode = Param::Mode;
    struct CanonizedFilterMeta {
        DTypeEnum dtype_enum;
        Param::Format format;
        uint32_t
                //! whether filter should be flipped (i.e. is CONVOLUTION)
                should_flip,
                group,  //!< number of groups
                icpg,   //!< input channels per group
                ocpg,   //!< output channels per group
                spatial_ndim, stride[MAX_SPATIAL_DIM], padding[MAX_SPATIAL_DIM],
                //! spatial dim
                spatial[MAX_SPATIAL_DIM], dilation[MAX_SPATIAL_DIM],
                //! spatial dim with dilation applied
                dilated_spatial[MAX_SPATIAL_DIM];
    } MEGDNN_PACKED;

protected:
M
Megvii Engine Team 已提交
1370 1371 1372 1373 1374 1375
    CanonizedFilterMeta deduce_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter,
            TensorLayout& dst) const;
    CanonizedFilterMeta check_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst) const;
1376

1377 1378
    static CanonizedFilterMeta make_canonized_filter_meta_impl(
            size_t src_ndim, const TensorLayout& filter, const Param& param);
1379 1380 1381 1382
    CanonizedFilterMeta make_canonized_filter_meta(
            size_t src_ndim, const TensorLayout& filter) const;
};

M
Megvii Engine Team 已提交
1383 1384
class Convolution3DForward : public Convolution3DBase,
                             public detail::MultiAlgoOpr<Convolution3DForward, 3> {
1385 1386 1387 1388 1389 1390 1391 1392
    DEF_OPR_IMPL(Convolution3DForward, Convolution3DBase, 2, 1);

public:
    /**
     * \param[in] src (n, ic, id, ih, iw)
     * \param[in] filter (oc, ic, fd, fh, fw)
     * \param[out] dst (n, oc, od, oh, ow)
     */
M
Megvii Engine Team 已提交
1393 1394 1395
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
1396
    MGE_WIN_DECLSPEC_FUC void deduce_layout(
M
Megvii Engine Team 已提交
1397 1398 1399 1400
            const TensorLayout& src, const TensorLayout& filter, TensorLayout& dst);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst) = 0;
1401

1402 1403 1404 1405
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::CONVOLUTION3D_FORWARD;
    }

1406
protected:
M
Megvii Engine Team 已提交
1407 1408 1409
    CanonizedFilterMeta check_exec(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst, size_t workspace_in_bytes);
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
};
using Convolution3D = Convolution3DForward;

class Convolution3DBackwardData
        : public Convolution3DBase,
          public detail::MultiAlgoOpr<Convolution3DBackwardData, 3> {
    DEF_OPR_IMPL(Convolution3DBackwardData, Convolution3DBase, 2, 1);

public:
    /**
     * \param[in] filter (oc, ic, fd, fh, fw)
     * \param[in] diff (n, oc, od, oh, ow)
     * \param[out] grad (n, ic, id, ih, iw)
     */
1424
    static void deduce_layout_impl(
1425 1426
            const TensorLayout& filter, const TensorLayout& diff, const Param& param,
            TensorLayout& grad);
M
Megvii Engine Team 已提交
1427 1428 1429 1430 1431 1432
    virtual void exec(
            _megdnn_tensor_in filter, _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
1433
    MGE_WIN_DECLSPEC_FUC void deduce_layout(
M
Megvii Engine Team 已提交
1434
            const TensorLayout& filter, const TensorLayout& diff, TensorLayout& grad);
1435

1436 1437 1438 1439
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::CONVOLUTION3D_BACKWARD_DATA;
    }

1440
protected:
M
Megvii Engine Team 已提交
1441 1442 1443
    CanonizedFilterMeta check_exec(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& grad, size_t workspace_in_bytes);
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
};

class Convolution3DBackwardFilter
        : public Convolution3DBase,
          public detail::MultiAlgoOpr<Convolution3DBackwardFilter, 3> {
    DEF_OPR_IMPL(Convolution3DBackwardFilter, Convolution3DBase, 2, 1);

public:
    /**
     * \param[in] src (n, ic, id, ih, iw)
     * \param[in] diff (n, oc, od, oh, ow)
     * \param[out] grad (oc, ic, fd, fh, fw)
     */
M
Megvii Engine Team 已提交
1457 1458 1459 1460 1461 1462
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
1463

1464 1465 1466 1467
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::CONVOLUTION3D_BACKWARD_FILTER;
    }

1468
protected:
M
Megvii Engine Team 已提交
1469 1470 1471
    CanonizedFilterMeta check_exec(
            const TensorLayout& src, const TensorLayout& diff, const TensorLayout& grad,
            size_t workspace_in_bytes);
1472 1473 1474 1475 1476 1477 1478
};

class LocalShareBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(LocalShareBase, OperatorBase);
    DEF_OPR_PARAM(LocalShare);

protected:
M
Megvii Engine Team 已提交
1479 1480 1481 1482 1483
    void deduce_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter, TensorLayout& dst);
    void check_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst);
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
};

class LocalShareForward : public LocalShareBase,
                          public detail::MultiAlgoOpr<LocalShareForward, 3> {
    DEF_OPR_IMPL(LocalShareForward, LocalShareBase, 2, 1);

public:
    /**
     * \param[in] src (N, IC, IH, IW)
     * \param[in] filter (G, spatial_groups_h, spatial_groups_w, IC / G,
     * FH, FW, OC / G)
     * \param[out] dst (N, OC, OH, OW)
     */
M
Megvii Engine Team 已提交
1497 1498 1499
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
1500 1501 1502
    /**
     * \brief deduce layout of the ouput tensor
     */
M
Megvii Engine Team 已提交
1503 1504 1505 1506 1507
    void deduce_layout(
            const TensorLayout& src, const TensorLayout& filter, TensorLayout& dst);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst) = 0;
1508

1509 1510 1511 1512
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::LOCAL_SHARE_FORWARD;
    }

1513
protected:
M
Megvii Engine Team 已提交
1514 1515 1516
    void check_exec(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& dst, size_t workspace_in_bytes);
1517 1518 1519
};
using LocalShare = LocalShareForward;

M
Megvii Engine Team 已提交
1520 1521
class LocalShareBackwardData : public LocalShareBase,
                               public detail::MultiAlgoOpr<LocalShareBackwardData, 3> {
1522 1523 1524 1525 1526 1527 1528 1529 1530
    DEF_OPR_IMPL(LocalShareBackwardData, LocalShareBase, 2, 1);

public:
    /**
     * \param[in] filter (G, spatial_groups_h, spatial_groups_w, IC / G,
     * FH, FW, OC / G)
     * \param[in] diff (N, OC, OH, OW)
     * \param[out] grad (N, IC, IH, IW)
     */
M
Megvii Engine Team 已提交
1531 1532 1533 1534 1535 1536 1537 1538
    virtual void exec(
            _megdnn_tensor_in filter, _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
    void deduce_layout(
            const TensorLayout& filter, const TensorLayout& diff, TensorLayout& grad);
1539

1540 1541 1542 1543
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::LOCAL_SHARE_BACKWARD_DATA;
    }

1544
protected:
M
Megvii Engine Team 已提交
1545 1546 1547
    void check_exec(
            const TensorLayout& filter, const TensorLayout& diff,
            const TensorLayout& grad, size_t workspace_in_bytes);
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
};

class LocalShareBackwardFilter
        : public LocalShareBase,
          public detail::MultiAlgoOpr<LocalShareBackwardFilter, 3> {
    DEF_OPR_IMPL(LocalShareBackwardFilter, LocalShareBase, 2, 1);

public:
    /**
     * \param[in] src (N, IC, IH, IW)
     * \param[in] diff (N, OC, OH, OW)
     * \param[out] grad (G, spatial_groups_h, spatial_groups_w, IC / G,
     * FH, FW, OC / G)
     */
M
Megvii Engine Team 已提交
1562 1563 1564
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in diff, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
1565

M
Megvii Engine Team 已提交
1566 1567 1568
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& diff,
            const TensorLayout& grad) = 0;
1569

1570 1571 1572 1573
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::LOCAL_SHARE_BACKWARD_FILTER;
    }

1574
protected:
M
Megvii Engine Team 已提交
1575 1576 1577
    void check_exec(
            const TensorLayout& src, const TensorLayout& diff, const TensorLayout& grad,
            size_t workspace_in_bytes);
1578 1579 1580 1581 1582 1583 1584
};

class ROIAlignBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(ROIAlignBase, OperatorBase);
    DEF_OPR_PARAM(ROIAlign);

protected:
M
Megvii Engine Team 已提交
1585 1586 1587 1588 1589 1590
    void deduce_layout_fwd(
            const TensorLayout& src, const TensorLayout& rois, TensorLayout& dst,
            TensorLayout& index);
    void check_layout_fwd(
            const TensorLayout& src, const TensorLayout& rois, const TensorLayout& dst,
            const TensorLayout& index);
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
};

class ROIAlignForward : public ROIAlignBase {
    DEF_OPR_IMPL(ROIAlignForward, ROIAlignBase, 2, 2);

public:
    /**
     * \param[in] src (n, c, ih, iw)
     * \param[in] rois (m, 5)
     * \param[out] dst (m, c, oh, ow)
     * \param[out] index (m, c, oh, ow) if mode is MAX, (0) if mode is AVERAGE
     *
     * Note that rois(, 0) denotes the input image index. We store it as
     * a float, but it should be an integer instead.
     *
     * index is a temporary tensor to facilitate its backward operator.
     * It is used to store argmax indicex in MAX mode, and it is not used
     * in AVERAGE mode.
     */
M
Megvii Engine Team 已提交
1610 1611 1612
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in rois, _megdnn_tensor_out dst,
            _megdnn_tensor_out index, _megdnn_workspace workspace) = 0;
1613
    MGE_WIN_DECLSPEC_FUC void deduce_layout(
M
Megvii Engine Team 已提交
1614 1615 1616 1617 1618
            const TensorLayout& src, const TensorLayout& rois, TensorLayout& dst,
            TensorLayout& index);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& rois, const TensorLayout& dst,
            const TensorLayout& index) = 0;
1619 1620

protected:
M
Megvii Engine Team 已提交
1621 1622 1623
    void check_exec(
            const TensorLayout& src, const TensorLayout& rois, const TensorLayout& dst,
            const TensorLayout& index, size_t workspace_in_bytes);
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
};
using ROIAlign = ROIAlignForward;

class ROIAlignBackward : public ROIAlignBase {
    DEF_OPR_IMPL(ROIAlignBackward, ROIAlignBase, 3, 1);

public:
    /**
     * \param[in] diff the backpropagated gradient wrt. dst
     * \param[in] rois the `rois' parameter in ROIAlignForward::exec
     * \param[in] index the `index' parameter in ROIAlignForward::exec
     * \param[out] grad the backpropagated gradient wrt. src
     */
M
Megvii Engine Team 已提交
1637 1638 1639 1640 1641 1642
    virtual void exec(
            _megdnn_tensor_in diff, _megdnn_tensor_in rois, _megdnn_tensor_in index,
            _megdnn_tensor_out grad, _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& diff, const TensorLayout& rois,
            const TensorLayout& index, const TensorLayout& grad) = 0;
1643 1644

protected:
M
Megvii Engine Team 已提交
1645 1646 1647 1648
    void check_exec(
            const TensorLayout& diff, const TensorLayout& rois,
            const TensorLayout& index, const TensorLayout& grad,
            size_t workspace_in_bytes);
1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
};

class DeformableConvBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(DeformableConvBase, OperatorBase);
    DEF_OPR_PARAM(Convolution);

public:
    static constexpr size_t MAX_SPATIAL_DIM = 2;
    struct CanonizedFilterMeta : Convolution::CanonizedFilterMeta {
        uint32_t deformable_group;
    };

protected:
    CanonizedFilterMeta make_canonized_filter_meta(
            size_t src_ndim, const TensorLayout& filter,
            const TensorLayout& offset) const;
M
Megvii Engine Team 已提交
1665 1666 1667 1668 1669 1670 1671
    void deduce_layout_fwd(
            const TensorLayout& im, const TensorLayout& filter,
            const TensorLayout& mask, const TensorLayout& offset, TensorLayout& dst);
    void check_layout_fwd(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& mask, const TensorLayout& offset,
            const TensorLayout& dst);
1672 1673
};

M
Megvii Engine Team 已提交
1674 1675
class DeformableConvForward : public DeformableConvBase,
                              public detail::MultiAlgoOpr<DeformableConvForward, 5> {
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
    DEF_OPR_IMPL(DeformableConvForward, DeformableConvBase, 4, 1);

public:
    /**
     * \param[in] im (n, ic, ih, iw)
     * \param[in] filter (oc, ic, fh, fw)
     * \param[in] offset (dg, 2, fh, fw, oh, ow)
     * \param[in] mask (dg, fh, fw, oh, ow)
     * \param[out] dst (n, oc, oh, ow)
     */
M
Megvii Engine Team 已提交
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
    virtual void exec(
            _megdnn_tensor_in im, _megdnn_tensor_in filter, _megdnn_tensor_in offset,
            _megdnn_tensor_in mask, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& im, const TensorLayout& filter,
            const TensorLayout& offset, const TensorLayout& mask, TensorLayout& dst);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& im, const TensorLayout& filter,
            const TensorLayout& offset, const TensorLayout& mask,
            const TensorLayout& dst) = 0;
1697

1698 1699 1700 1701
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::DEFORMABLE_CONV_FORWARD;
    }

1702
protected:
M
Megvii Engine Team 已提交
1703 1704 1705 1706
    CanonizedFilterMeta check_exec(
            const TensorLayout& im, const TensorLayout& filter,
            const TensorLayout& offset, const TensorLayout& mask,
            const TensorLayout& dst, size_t workspace_in_bytes);
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
};
using DeformableConv = DeformableConvForward;

/**
 * \brief DeformableConvBackwardFilter operator.
 *
 * Calculating the gradient wrt. convolution filter.
 */
class DeformableConvBackwardFilter
        : public DeformableConvBase,
          public detail::MultiAlgoOpr<DeformableConvBackwardFilter, 5> {
    DEF_OPR_IMPL(DeformableConvBackwardFilter, DeformableConvBase, 4, 1);

public:
    /**
     * \param[in] im (oc, ic, fh, fw)
     * \param[in] offset (dg, 2, fh, fw, oh, ow)
     * \param[in] mask (dg, fh, fw, oh, ow)
     * \param[in] out_grad (n, oc, oh, ow)
     * \param[out] filter_grad (oc, ic, ih, iw)
     */
M
Megvii Engine Team 已提交
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
    virtual void exec(
            _megdnn_tensor_in im, _megdnn_tensor_in offset, _megdnn_tensor_in mask,
            _megdnn_tensor_in out_grad, _megdnn_tensor_out filter_grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& im, const TensorLayout& offset,
            const TensorLayout& mask, const TensorLayout& out_grad,
            const TensorLayout& filter_grad) = 0;
    void deduce_layout(
            const TensorLayout& im, const TensorLayout& offset,
            const TensorLayout& mask, const TensorLayout& out_grad,
            TensorLayout& filter_grad);
1740

1741 1742 1743 1744
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::DEFORMABLE_CONV_BACKWARD_FILTER;
    }

1745
protected:
M
Megvii Engine Team 已提交
1746 1747 1748 1749
    CanonizedFilterMeta check_exec(
            const TensorLayout& im, const TensorLayout& offset,
            const TensorLayout& mask, const TensorLayout& out_grad,
            const TensorLayout& filter_grad, size_t workspace_in_bytes);
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
};

/**
 * \brief DeformableConvBackwardData operator.
 *
 * Calculating the gradient wrt. convolution input data, offset and mask.
 */
class DeformableConvBackwardData
        : public DeformableConvBase,
          public detail::MultiAlgoOpr<DeformableConvBackwardData, 8> {
    DEF_OPR_IMPL(DeformableConvBackwardData, DeformableConvBase, 5, 3);

public:
    /**
     * \param[in] im (oc, ic, fh, fw)
     * \param[in] filter (oc, ic, fh, fw)
     * \param[in] offset (dg, 2, fh, fw, oh, ow)
     * \param[in] mask (dg, fh, fw, oh, ow)
     * \param[in] out_grad (n, oc, oh, ow)
     * \param[out] im_grad (n, ic, ih, iw)
     * \param[out] offset_grad (dg, 2, fh, fw, oh, ow)
     * \param[out] mask_grad (dg, fh, fw, oh, ow)
     */
M
Megvii Engine Team 已提交
1773 1774 1775 1776 1777
    virtual void exec(
            _megdnn_tensor_in im, _megdnn_tensor_in filter, _megdnn_tensor_in offset,
            _megdnn_tensor_in mask, _megdnn_tensor_in out_grad,
            _megdnn_tensor_out im_grad, _megdnn_tensor_out offset_grad,
            _megdnn_tensor_out mask_grad, _megdnn_workspace workspace) = 0;
1778 1779 1780 1781 1782
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& im, const TensorLayout& filter,
            const TensorLayout& offset, const TensorLayout& mask,
            const TensorLayout& out_grad, const TensorLayout& im_grad,
            const TensorLayout& offset_grad, const TensorLayout& mask_grad) = 0;
M
Megvii Engine Team 已提交
1783 1784 1785 1786 1787
    void deduce_layout(
            const TensorLayout& im, const TensorLayout& filter,
            const TensorLayout& offset, const TensorLayout& mask,
            const TensorLayout& out_grad, TensorLayout& im_grad,
            TensorLayout& offset_grad, TensorLayout& mask_grad);
1788

1789 1790 1791 1792
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::DEFORMABLE_CONV_BACKWARD_DATA;
    }

1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
protected:
    CanonizedFilterMeta check_exec(
            const TensorLayout& im, const TensorLayout& filter,
            const TensorLayout& offset, const TensorLayout& mask,
            const TensorLayout& out_grad, const TensorLayout& im_grad,
            const TensorLayout& offset_grad, const TensorLayout& mask_grad,
            size_t workspace_in_bytes);
};

class DeformablePSROIPoolingBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(DeformablePSROIPoolingBase, OperatorBase);
    DEF_OPR_PARAM(DeformablePSROIPooling);

protected:
M
Megvii Engine Team 已提交
1807 1808 1809
    void deduce_layout_fwd(
            const TensorLayout& data, const TensorLayout& trans,
            const TensorLayout& rois, TensorLayout& out_data, TensorLayout& out_count);
1810

M
Megvii Engine Team 已提交
1811 1812 1813 1814
    void check_layout_fwd(
            const TensorLayout& data, const TensorLayout& trans,
            const TensorLayout& rois, const TensorLayout& out_data,
            const TensorLayout& out_count, size_t workspace_in_bytes);
1815 1816 1817
};

class DeformablePSROIPoolingForward : public DeformablePSROIPoolingBase {
M
Megvii Engine Team 已提交
1818
    DEF_OPR_IMPL(DeformablePSROIPoolingForward, DeformablePSROIPoolingBase, 3, 2);
1819 1820 1821 1822 1823 1824 1825 1826 1827

public:
    /**
     * \param[in]  data       (oc, ic, ih, iw)
     * \param[in]  rois       (xx, xx, xx, xx)
     * \param[in]  trans      (oc, ic, fh, fw)
     * \param[out] out_data   ( n, ic, ih, iw)
     * \param[out] out_count  ( n, ic, ih, iw)
     */
M
Megvii Engine Team 已提交
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& data, const TensorLayout& rois,
            const TensorLayout& trans, const TensorLayout& out_data,
            const TensorLayout& out_count) = 0;
    virtual void exec(
            _megdnn_tensor_in data, _megdnn_tensor_in rois, _megdnn_tensor_in trans,
            _megdnn_tensor_out out_data, _megdnn_tensor_out out_count,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& data, const TensorLayout& rois,
            const TensorLayout& trans, TensorLayout& out_data, TensorLayout& out_count);
    void check_exec(
            const TensorLayout& data, const TensorLayout& rois,
            const TensorLayout& trans, const TensorLayout& out_data,
            const TensorLayout& out_count, size_t workspace_in_bytes);
1843 1844 1845 1846 1847
};

using DeformablePSROIPooling = DeformablePSROIPoolingForward;

class DeformablePSROIPoolingBackward : public DeformablePSROIPoolingBase {
M
Megvii Engine Team 已提交
1848
    DEF_OPR_IMPL(DeformablePSROIPoolingBackward, DeformablePSROIPoolingBase, 5, 2);
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859

public:
    /**
     * \param[in]  data        (oc, ic, ih, iw)
     * \param[in]  rois        (xx, xx, xx, xx)
     * \param[in]  trans       (oc, ic, fh, fw)
     * \param[in]  out_diff    (xx, xx, xx, xx)
     * \param[in]  out_count   (xx, xx, xx, xx)
     * \param[out] data_diff   ( n, ic, ih, iw)
     * \param[out] trans_diff  ( n, ic, ih, iw)
     */
M
Megvii Engine Team 已提交
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
    virtual void exec(
            _megdnn_tensor_in data, _megdnn_tensor_in rois, _megdnn_tensor_in trans,
            _megdnn_tensor_in out_diff, _megdnn_tensor_in out_count,
            _megdnn_tensor_out data_diff, _megdnn_tensor_out trans_diff,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& data, const TensorLayout& rois,
            const TensorLayout& trans, const TensorLayout& out_diff,
            const TensorLayout& out_count, const TensorLayout& data_diff,
            const TensorLayout& trans_diff) = 0;

    void check_exec(
            const TensorLayout& data, const TensorLayout& rois,
            const TensorLayout& trans, const TensorLayout& out_diff,
            const TensorLayout& out_count, const TensorLayout& data_diff,
            const TensorLayout& trans_diff, size_t workspace_in_bytes);
};

class BatchConvBiasForward : public ConvolutionBase<param::BatchConvBias>,
                             public detail::MultiAlgoOpr<BatchConvBiasForward, 5> {
1880 1881 1882
    DEF_OPR_IMPL(BatchConvBiasForward, ConvolutionBase, 4, 1);

public:
M
Megvii Engine Team 已提交
1883 1884 1885 1886
    virtual void exec(
            _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_in bias,
            _megdnn_tensor_in z, _megdnn_tensor_out dst,
            _megdnn_workspace workspace) = 0;
1887 1888

    void deduce_dtype(DType src, DType filter, DType bias, DType z, DType& dst);
M
Megvii Engine Team 已提交
1889 1890 1891
    void deduce_layout(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& bias, const TensorLayout& z, TensorLayout& dst);
1892

M
Megvii Engine Team 已提交
1893 1894 1895 1896
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& bias, const TensorLayout& z,
            const TensorLayout& dst) = 0;
1897

1898 1899 1900 1901
    static Algorithm::OprType get_opr_type() {
        return Algorithm::OprType::BATCH_CONV_FORWARD;
    }

1902
protected:
M
Megvii Engine Team 已提交
1903 1904 1905 1906
    CanonizedFilterMeta check_exec(
            const TensorLayout& src, const TensorLayout& filter,
            const TensorLayout& bias, const TensorLayout& z, const TensorLayout& dst,
            size_t workspace_in_bytes);
1907 1908 1909
};
using BatchConvBias = BatchConvBiasForward;

1910 1911 1912 1913 1914 1915
class FakeQuantBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(FakeQuantBase, OperatorBase);
    DEF_OPR_PARAM(FakeQuant);

protected:
    void deduce_layout_fwd(const TensorLayout& input, TensorLayout& output);
M
Megvii Engine Team 已提交
1916 1917 1918
    void check_layout_fwd(
            const TensorLayout& input, const TensorLayout& scale,
            const TensorLayout& zero_point, const TensorLayout& output);
1919 1920 1921 1922 1923 1924
};

class FakeQuantForward : public FakeQuantBase {
    DEF_OPR_IMPL(FakeQuantForward, FakeQuantBase, 3, 1);

public:
M
Megvii Engine Team 已提交
1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
    virtual void exec(
            _megdnn_tensor_in input, _megdnn_tensor_in scale,
            _megdnn_tensor_in zero_point, _megdnn_tensor_out output,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& input, const TensorLayout& scale,
            const TensorLayout& zero_point, TensorLayout& output);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& input, const TensorLayout& scale,
            const TensorLayout& zero_point, const TensorLayout& output) = 0;
1935 1936

protected:
M
Megvii Engine Team 已提交
1937 1938 1939 1940
    void check_exec(
            const TensorLayout& input, const TensorLayout& scale,
            const TensorLayout& zero_point, const TensorLayout& output,
            size_t workspace_in_bytes);
1941 1942 1943 1944 1945 1946 1947 1948
};

using FakeQuant = FakeQuantForward;

class FakeQuantBackward : public FakeQuantBase {
    DEF_OPR_IMPL(FakeQuantBackward, FakeQuantBase, 4, 1);

public:
M
Megvii Engine Team 已提交
1949 1950 1951 1952 1953 1954 1955 1956
    virtual void exec(
            _megdnn_tensor_in diff, _megdnn_tensor_in input, _megdnn_tensor_in scale,
            _megdnn_tensor_in zero_point, _megdnn_tensor_out grad,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& diff, const TensorLayout& input,
            const TensorLayout& scale, const TensorLayout& zero_point,
            const TensorLayout& grad) = 0;
1957 1958

protected:
M
Megvii Engine Team 已提交
1959 1960 1961 1962
    void check_exec(
            const TensorLayout& diff, const TensorLayout& input,
            const TensorLayout& scale, const TensorLayout& zero_point,
            const TensorLayout& grad, size_t workspace_in_bytes);
1963 1964
};

M
Megvii Engine Team 已提交
1965 1966 1967 1968 1969 1970
class TQTBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(TQTBase, OperatorBase);
    DEF_OPR_PARAM(TQT);

protected:
    void deduce_layout_fwd(const TensorLayout& input, TensorLayout& output);
M
Megvii Engine Team 已提交
1971 1972 1973
    void check_layout_fwd(
            const TensorLayout& input, const TensorLayout& scale,
            const TensorLayout& output);
M
Megvii Engine Team 已提交
1974 1975 1976 1977 1978 1979
};

class TQTForward : public TQTBase {
    DEF_OPR_IMPL(TQTForward, TQTBase, 2, 1);

public:
M
Megvii Engine Team 已提交
1980 1981 1982 1983 1984 1985 1986 1987
    virtual void exec(
            _megdnn_tensor_in input, _megdnn_tensor_in scale, _megdnn_tensor_out output,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& input, const TensorLayout& scale, TensorLayout& output);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& input, const TensorLayout& scale,
            const TensorLayout& output) = 0;
M
Megvii Engine Team 已提交
1988 1989

protected:
M
Megvii Engine Team 已提交
1990 1991 1992
    void check_exec(
            const TensorLayout& input, const TensorLayout& scale,
            const TensorLayout& output, size_t workspace_in_bytes);
M
Megvii Engine Team 已提交
1993 1994 1995 1996 1997 1998 1999
};
using TQT = TQTForward;

class TQTBackward : public TQTBase {
    DEF_OPR_IMPL(TQTBackward, TQTBase, 3, 2);

public:
M
Megvii Engine Team 已提交
2000 2001 2002 2003 2004 2005 2006 2007
    virtual void exec(
            _megdnn_tensor_in diff, _megdnn_tensor_in input, _megdnn_tensor_in scale,
            _megdnn_tensor_out grad_x, _megdnn_tensor_out grad_s,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& diff, const TensorLayout& input,
            const TensorLayout& scale, const TensorLayout& grad_x,
            const TensorLayout& grad_s) = 0;
M
Megvii Engine Team 已提交
2008 2009

protected:
M
Megvii Engine Team 已提交
2010 2011 2012 2013
    void check_exec(
            const TensorLayout& diff, const TensorLayout& input,
            const TensorLayout& scale, const TensorLayout& grad_x,
            const TensorLayout& grad_s, size_t workspace_in_bytes);
M
Megvii Engine Team 已提交
2014 2015
};

M
Megvii Engine Team 已提交
2016 2017 2018 2019 2020 2021
class LSQBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(LSQBase, OperatorBase);
    DEF_OPR_PARAM(LSQ);

protected:
    void deduce_layout_fwd(const TensorLayout& input, TensorLayout& output);
M
Megvii Engine Team 已提交
2022 2023 2024 2025
    void check_layout_fwd(
            const TensorLayout& input, const TensorLayout& scale,
            const TensorLayout& zero_point, const TensorLayout& grad_scale,
            const TensorLayout& output);
M
Megvii Engine Team 已提交
2026 2027 2028 2029 2030 2031
};

class LSQForward : public LSQBase {
    DEF_OPR_IMPL(LSQForward, LSQBase, 4, 1);

public:
M
Megvii Engine Team 已提交
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
    virtual void exec(
            _megdnn_tensor_in input, _megdnn_tensor_in scale,
            _megdnn_tensor_in zero_point, _megdnn_tensor_in grad_scale,
            _megdnn_tensor_out output, _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& input, const TensorLayout& scale,
            const TensorLayout& zero_point, const TensorLayout& grad_scale,
            TensorLayout& output);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& input, const TensorLayout& scale,
            const TensorLayout& zero_point, const TensorLayout& grad_scale,
            const TensorLayout& output) = 0;

protected:
    void check_exec(
            const TensorLayout& input, const TensorLayout& scale,
            const TensorLayout& zero_point, const TensorLayout& grad_scale,
            const TensorLayout& output, size_t workspace_in_bytes);
M
Megvii Engine Team 已提交
2050 2051 2052 2053 2054 2055 2056
};
using LSQ = LSQForward;

class LSQBackward : public LSQBase {
    DEF_OPR_IMPL(LSQBackward, LSQBase, 5, 2);

public:
M
Megvii Engine Team 已提交
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073
    virtual void exec(
            _megdnn_tensor_in diff, _megdnn_tensor_in input, _megdnn_tensor_in scale,
            _megdnn_tensor_in zero_point, _megdnn_tensor_in grad_scale,
            _megdnn_tensor_out grad_x, _megdnn_tensor_out grad_s,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& diff, const TensorLayout& input,
            const TensorLayout& scale, const TensorLayout& zero_point,
            const TensorLayout& grad_scale, const TensorLayout& grad_x,
            const TensorLayout& grad_s) = 0;

protected:
    void check_exec(
            const TensorLayout& diff, const TensorLayout& input,
            const TensorLayout& scale, const TensorLayout& zero_point,
            const TensorLayout& grad_scale, const TensorLayout& grad_x,
            const TensorLayout& grad_s, size_t workspace_in_bytes);
M
Megvii Engine Team 已提交
2074 2075
};

2076 2077 2078 2079
class LayerNormBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(LayerNormBase, OperatorBase);
    DEF_OPR_PARAM(LayerNorm);

2080 2081 2082 2083 2084
public:
    MGE_WIN_DECLSPEC_FUC static void deduce_layout_fwd_impl(
            const TensorLayout& data, const Param& p, TensorLayout& dst,
            TensorLayout& mean, TensorLayout& rstd);

2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
protected:
    void deduce_layout_fwd(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, TensorLayout& dst, TensorLayout& mean,
            TensorLayout& rstd);
    void check_layout_fwd(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, const TensorLayout& dst, const TensorLayout& mean,
            const TensorLayout& rstd);
};

class LayerNormForward : public LayerNormBase {
    DEF_OPR_IMPL(LayerNormForward, LayerNormBase, 3, 3);

public:
    virtual void exec(
            _megdnn_tensor_in data, _megdnn_tensor_in weight, _megdnn_tensor_in bias,
            _megdnn_tensor_out dst, _megdnn_tensor_out mean, _megdnn_tensor_out rstd,
            _megdnn_workspace workspace) = 0;
2104
    MGE_WIN_DECLSPEC_FUC void deduce_layout(
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, TensorLayout& dst, TensorLayout& mean,
            TensorLayout& rstd);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, const TensorLayout& dst, const TensorLayout& mean,
            const TensorLayout& rstd) = 0;

protected:
    void check_exec(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, const TensorLayout& dst, const TensorLayout& mean,
            const TensorLayout& rstd, size_t workspace_in_bytes);
};
using LayerNorm = LayerNormForward;

class LayerNormBackward : public LayerNormBase {
    DEF_OPR_IMPL(LayerNormBackward, LayerNormBase, 5, 3);

2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
public:
    virtual void exec(
            _megdnn_tensor_in diff, _megdnn_tensor_in data, _megdnn_tensor_in weight,
            _megdnn_tensor_in mean, _megdnn_tensor_in rstd, _megdnn_tensor_out ddata,
            _megdnn_tensor_out dweight, _megdnn_tensor_out dbias,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& diff, const TensorLayout& data,
            const TensorLayout& weight, const TensorLayout& mean,
            const TensorLayout& rstd, TensorLayout& ddata, TensorLayout& dweight,
            TensorLayout& dbias);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& diff, const TensorLayout& data,
            const TensorLayout& weight, const TensorLayout& mean,
            const TensorLayout& rstd, const TensorLayout& ddata,
            const TensorLayout& dweight, const TensorLayout& dbias) = 0;

protected:
    void check_exec(
            const TensorLayout& diff, const TensorLayout& data,
            const TensorLayout& weight, const TensorLayout& mean,
            const TensorLayout& rstd, const TensorLayout& ddata,
            const TensorLayout& dweight, const TensorLayout& dbias,
            size_t workspace_in_bytes);
};

class GeneralNormBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(GeneralNormBase, OperatorBase);
    DEF_OPR_PARAM(GeneralNorm);

public:
    MGE_WIN_DECLSPEC_FUC static void deduce_layout_fwd_impl(
            const TensorLayout& data, const Param& p, TensorLayout& dst,
            TensorLayout& mean, TensorLayout& rstd);

protected:
    void deduce_layout_fwd(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, TensorLayout& dst, TensorLayout& mean,
            TensorLayout& rstd);
    void check_layout_fwd(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, const TensorLayout& dst, const TensorLayout& mean,
            const TensorLayout& rstd);
};

class GeneralNormForward : public GeneralNormBase {
    DEF_OPR_IMPL(GeneralNormForward, GeneralNormBase, 3, 3);

public:
    virtual void exec(
            _megdnn_tensor_in data, _megdnn_tensor_in weight, _megdnn_tensor_in bias,
            _megdnn_tensor_out dst, _megdnn_tensor_out mean, _megdnn_tensor_out rstd,
            _megdnn_workspace workspace) = 0;
    MGE_WIN_DECLSPEC_FUC void deduce_layout(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, TensorLayout& dst, TensorLayout& mean,
            TensorLayout& rstd);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, const TensorLayout& dst, const TensorLayout& mean,
            const TensorLayout& rstd) = 0;

protected:
    void check_exec(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, const TensorLayout& dst, const TensorLayout& mean,
            const TensorLayout& rstd, size_t workspace_in_bytes);
};
using GeneralNorm = GeneralNormForward;

class GeneralNormBackward : public GeneralNormBase {
    DEF_OPR_IMPL(GeneralNormBackward, GeneralNormBase, 5, 3);

2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
public:
    virtual void exec(
            _megdnn_tensor_in diff, _megdnn_tensor_in data, _megdnn_tensor_in weight,
            _megdnn_tensor_in mean, _megdnn_tensor_in rstd, _megdnn_tensor_out ddata,
            _megdnn_tensor_out dweight, _megdnn_tensor_out dbias,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& diff, const TensorLayout& data,
            const TensorLayout& weight, const TensorLayout& mean,
            const TensorLayout& rstd, TensorLayout& ddata, TensorLayout& dweight,
            TensorLayout& dbias);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& diff, const TensorLayout& data,
            const TensorLayout& weight, const TensorLayout& mean,
            const TensorLayout& rstd, const TensorLayout& ddata,
            const TensorLayout& dweight, const TensorLayout& dbias) = 0;

protected:
    void check_exec(
            const TensorLayout& diff, const TensorLayout& data,
            const TensorLayout& weight, const TensorLayout& mean,
            const TensorLayout& rstd, const TensorLayout& ddata,
            const TensorLayout& dweight, const TensorLayout& dbias,
            size_t workspace_in_bytes);
};

2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
class DropoutBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(DropoutBase, OperatorBase);
    DEF_OPR_PARAM(Dropout);
};

class DropoutForward : public DropoutBase {
    DEF_OPR_IMPL(DropoutForward, DropoutBase, 1, 2);

public:
    void deduce_layout(const TensorLayout& inp, TensorLayout& oup, TensorLayout& mask);
    virtual void exec(
            _megdnn_tensor_in inp, _megdnn_tensor_out oup, _megdnn_tensor_out mask,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& inp, const TensorLayout& oup,
            const TensorLayout& mask) = 0;
    virtual size_t get_mask_size_in_bytes(const TensorLayout& inp) = 0;

protected:
    void check_exec(
            const TensorLayout& inp, const TensorLayout& oup, const TensorLayout& mask,
            size_t workspace_in_bytes);
};
using Dropout = DropoutForward;

class DropoutBackward : public DropoutBase {
    DEF_OPR_IMPL(DropoutBackward, DropoutBase, 2, 1);

public:
    void deduce_layout(
            const TensorLayout& doup, const TensorLayout& mask, TensorLayout& dinp);
    virtual void exec(
            _megdnn_tensor_in doup, _megdnn_tensor_in mask, _megdnn_tensor_out dinp,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& doup, const TensorLayout& mask,
            const TensorLayout& dinp) = 0;

protected:
    void check_exec(
            const TensorLayout& doup, const TensorLayout& mask,
            const TensorLayout& dinp, size_t workspace_in_bytes);
};
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
class SoftmaxBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(SoftmaxBase, OperatorBase);
    DEF_OPR_PARAM(Softmax);

protected:
    void deduce_layout_fwd(const TensorLayout& input, TensorLayout& output);
    void check_layout_fwd(const TensorLayout& input, const TensorLayout& output);
};

class SoftmaxForward : public SoftmaxBase {
    DEF_OPR_IMPL(SoftmaxForward, SoftmaxBase, 1, 1);

public:
    /**
     * \param[in] input input tensor
     * \param[out] output output tensor
     */
    virtual void exec(
            _megdnn_tensor_in input, _megdnn_tensor_out output,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(const TensorLayout& input, TensorLayout& output);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& input, const TensorLayout& output) = 0;

protected:
    void check_exec(
            const TensorLayout& input, const TensorLayout& output,
            size_t workspace_in_bytes);
};
using Softmax = SoftmaxForward;

class SoftmaxBackward : public SoftmaxBase {
    DEF_OPR_IMPL(SoftmaxBackward, SoftmaxBase, 2, 1);

public:
    virtual void exec(
            _megdnn_tensor_in input, _megdnn_tensor_in diff, _megdnn_tensor_out grad_x,
            _megdnn_workspace workspace) = 0;
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& input, const TensorLayout& diff,
            const TensorLayout& grad_x) = 0;

protected:
    void check_exec(
            const TensorLayout& input, const TensorLayout& diff,
            const TensorLayout& grad_x, size_t workspace_in_bytes);
};
2314

2315 2316 2317 2318 2319 2320 2321 2322 2323 2324
class RNNCellForward : public OperatorBase {
    DEF_OPR_PARAM(RNNCell);
    DEF_OPR_IMPL(RNNCellForward, OperatorBase, 6, 1);

public:
    virtual void exec(
            _megdnn_tensor_in input, _megdnn_tensor_in weight_ih,
            _megdnn_tensor_in bias_ih, _megdnn_tensor_in hx,
            _megdnn_tensor_in weight_hh, _megdnn_tensor_in bias_hh,
            _megdnn_tensor_out dst, _megdnn_workspace workspace) = 0;
2325
    void deduce_layout(
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
            const TensorLayout& input, const TensorLayout& weight_ih,
            const TensorLayout& bias_ih, const TensorLayout& hx,
            const TensorLayout& weight_hh, const TensorLayout& bias_hh,
            TensorLayout& dst);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& input, const TensorLayout& weight_ih,
            const TensorLayout& bias_ih, const TensorLayout& hx,
            const TensorLayout& weight_hh, const TensorLayout& bias_hh,
            const TensorLayout& dst) = 0;

protected:
    void check_exec(
            const TensorLayout& input, const TensorLayout& weight_ih,
            const TensorLayout& bias_ih, const TensorLayout& hx,
            const TensorLayout& weight_hh, const TensorLayout& bias_hh,
            const TensorLayout& dst, size_t workspace_in_bytes);
};
using RNNCell = RNNCellForward;

class LSTMCellForward : public OperatorBase {
    // DEF_OPR_PARAM(LSTMCell);
    DEF_OPR_PARAM(Empty);
    DEF_OPR_IMPL(LSTMCellForward, OperatorBase, 7, 3);

public:
    virtual void exec(
            _megdnn_tensor_in input, _megdnn_tensor_in weight_ih,
            _megdnn_tensor_in bias_ih, _megdnn_tensor_in hx,
            _megdnn_tensor_in weight_hh, _megdnn_tensor_in bias_hh,
            _megdnn_tensor_in cx, _megdnn_tensor_out h_new, _megdnn_tensor_out c_new,
            _megdnn_tensor_out gates, _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& input, const TensorLayout& weight_ih,
            const TensorLayout& bias_ih, const TensorLayout& hx,
            const TensorLayout& weight_hh, const TensorLayout& bias_hh,
            const TensorLayout& cx, TensorLayout& h_new, TensorLayout& c_new,
            TensorLayout& gates);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& input, const TensorLayout& weight_ih,
            const TensorLayout& bias_ih, const TensorLayout& hx,
            const TensorLayout& weight_hh, const TensorLayout& bias_hh,
            const TensorLayout& cx, const TensorLayout& h_new,
            const TensorLayout& c_new, const TensorLayout& gates) = 0;

protected:
    void check_exec(
            const TensorLayout& input, const TensorLayout& weight_ih,
            const TensorLayout& bias_ih, const TensorLayout& hx,
            const TensorLayout& weight_hh, const TensorLayout& bias_hh,
            const TensorLayout& cx, const TensorLayout& h_new,
            const TensorLayout& c_new, const TensorLayout& gates,
            size_t workspace_in_bytes);
};
using LSTMCell = LSTMCellForward;

class RNNForward : public OperatorBase {
    DEF_OPR_PARAM(RNN);
    DEF_OPR_IMPL(RNNForward, OperatorBase, 3, 3);

public:
    virtual void exec(
            _megdnn_tensor_in input, _megdnn_tensor_in hx,
            _megdnn_tensor_in flatten_weights, _megdnn_tensor_out output,
            _megdnn_tensor_out hy, _megdnn_tensor_out reserve_space,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& input, const TensorLayout& hx,
            const TensorLayout& flatten_weights, TensorLayout& output, TensorLayout& hy,
            TensorLayout& reserve_space);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& input, const TensorLayout& hx,
            const TensorLayout& flatten_weights, const TensorLayout& output,
            const TensorLayout& hy, const TensorLayout& reserve_space) = 0;
    virtual size_t get_reserve_size_in_bytes(const TensorLayout& input) = 0;

protected:
    void check_exec(
            const TensorLayout& input, const TensorLayout& hx,
            const TensorLayout& flatten_weights, const TensorLayout& output,
            const TensorLayout& hy, const TensorLayout& reserve_space,
            size_t workspace_in_bytes);
};
using RNN = RNNForward;

class RNNBackward : public OperatorBase {
    DEF_OPR_PARAM(RNN);
    DEF_OPR_IMPL(RNNBackward, OperatorBase, 7, 3);

public:
    virtual void exec(
            _megdnn_tensor_in x, _megdnn_tensor_in y, _megdnn_tensor_in hx,
            _megdnn_tensor_in dy, _megdnn_tensor_in dhy,
            _megdnn_tensor_in flatten_weights, _megdnn_tensor_in reserve_space,
            _megdnn_tensor_out dx, _megdnn_tensor_out dhx, _megdnn_tensor_out dw,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& x, const TensorLayout& y, const TensorLayout& hx,
            const TensorLayout& dy, const TensorLayout& dhy,
            const TensorLayout& flatten_weights, const TensorLayout& reserve_space,
            TensorLayout& dx, TensorLayout& dhx, TensorLayout& dw);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& x, const TensorLayout& y, const TensorLayout& hx,
            const TensorLayout& dy, const TensorLayout& dhy,
            const TensorLayout& flatten_weights, const TensorLayout& reserve_space,
            const TensorLayout& dx, const TensorLayout& dhx,
            const TensorLayout& dw) = 0;

protected:
    void check_exec(
            const TensorLayout& x, const TensorLayout& y, const TensorLayout& hx,
            const TensorLayout& dy, const TensorLayout& dhy,
            const TensorLayout& flatten_weights, const TensorLayout& reserve_space,
            const TensorLayout& dx, const TensorLayout& dhx, const TensorLayout& dw,
            size_t workspace_in_bytes);
};

class LSTMForward : public OperatorBase {
    DEF_OPR_PARAM(LSTM);
    DEF_OPR_IMPL(LSTMForward, OperatorBase, 4, 4);

public:
    virtual void exec(
            _megdnn_tensor_in input, _megdnn_tensor_in hx, _megdnn_tensor_in cx,
            _megdnn_tensor_in flatten_weights, _megdnn_tensor_out output,
            _megdnn_tensor_out hy, _megdnn_tensor_out cy,
            _megdnn_tensor_out reserve_space, _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& input, const TensorLayout& hx, const TensorLayout& cx,
            const TensorLayout& flatten_weights, TensorLayout& output, TensorLayout& hy,
            TensorLayout& cy, TensorLayout& reserve_space);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& input, const TensorLayout& hx, const TensorLayout& cx,
            const TensorLayout& flatten_weights, const TensorLayout& output,
            const TensorLayout& hy, const TensorLayout& cy,
            const TensorLayout& reserve_space) = 0;
    virtual size_t get_reserve_size_in_bytes(const TensorLayout& input) = 0;

protected:
    void check_exec(
            const TensorLayout& input, const TensorLayout& hx, const TensorLayout& cx,
            const TensorLayout& flatten_weights, const TensorLayout& output,
            const TensorLayout& hy, const TensorLayout& cy,
            const TensorLayout& reserve_space, size_t workspace_in_bytes);
};
using LSTM = LSTMForward;

class LSTMBackward : public OperatorBase {
    DEF_OPR_PARAM(LSTM);
    DEF_OPR_IMPL(LSTMBackward, OperatorBase, 9, 4);

public:
    virtual void exec(
            _megdnn_tensor_in x, _megdnn_tensor_in y, _megdnn_tensor_in hx,
            _megdnn_tensor_in cx, _megdnn_tensor_in dy, _megdnn_tensor_in dhy,
            _megdnn_tensor_in dcy, _megdnn_tensor_in flatten_weights,
            _megdnn_tensor_in reserve_space, _megdnn_tensor_out dx,
            _megdnn_tensor_out dhx, _megdnn_tensor_out dcx, _megdnn_tensor_out dw,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& x, const TensorLayout& y, const TensorLayout& hx,
            const TensorLayout& cx, const TensorLayout& dy, const TensorLayout& dhy,
            const TensorLayout& dcy, const TensorLayout& flatten_weights,
            const TensorLayout& reserve_space, TensorLayout& dx, TensorLayout& dhx,
            TensorLayout& dcx, TensorLayout& dw);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& x, const TensorLayout& y, const TensorLayout& hx,
            const TensorLayout& cx, const TensorLayout& dy, const TensorLayout& dhy,
            const TensorLayout& dcy, const TensorLayout& flatten_weights,
            const TensorLayout& reserve_space, const TensorLayout& dx,
            const TensorLayout& dhx, const TensorLayout& dcx,
            const TensorLayout& dw) = 0;

protected:
    void check_exec(
            const TensorLayout& x, const TensorLayout& y, const TensorLayout& hx,
            const TensorLayout& cx, const TensorLayout& dy, const TensorLayout& dhy,
            const TensorLayout& dcy, const TensorLayout& flatten_weights,
            const TensorLayout& reserve_space, const TensorLayout& dx,
            const TensorLayout& dhx, const TensorLayout& dcx, const TensorLayout& dw,
            size_t workspace_in_bytes);
};
2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576

class GroupNormBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(GroupNormBase, OperatorBase);
    DEF_OPR_PARAM(GroupNorm);

protected:
    void deduce_layout_fwd(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, TensorLayout& dst, TensorLayout& mean,
            TensorLayout& rstd);
    void check_layout_fwd(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, const TensorLayout& dst, const TensorLayout& mean,
            const TensorLayout& rstd);
};

class GroupNormForward : public GroupNormBase {
    DEF_OPR_IMPL(GroupNormForward, GroupNormBase, 3, 3);

public:
    virtual void exec(
            _megdnn_tensor_in data, _megdnn_tensor_in weight, _megdnn_tensor_in bias,
            _megdnn_tensor_out dst, _megdnn_tensor_out mean, _megdnn_tensor_out rstd,
            _megdnn_workspace workspace) = 0;
    MGE_WIN_DECLSPEC_FUC void deduce_layout(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, TensorLayout& dst, TensorLayout& mean,
            TensorLayout& rstd);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, const TensorLayout& dst, const TensorLayout& mean,
            const TensorLayout& rstd) = 0;

protected:
    void check_exec(
            const TensorLayout& data, const TensorLayout& weight,
            const TensorLayout& bias, const TensorLayout& dst, const TensorLayout& mean,
            const TensorLayout& rstd, size_t workspace_in_bytes);
};
using GroupNorm = GroupNormForward;

class GroupNormBackward : public GroupNormBase {
    DEF_OPR_IMPL(GroupNormBackward, GroupNormBase, 5, 3);

public:
    virtual void exec(
            _megdnn_tensor_in diff, _megdnn_tensor_in data, _megdnn_tensor_in weight,
            _megdnn_tensor_in mean, _megdnn_tensor_in rstd, _megdnn_tensor_out ddata,
            _megdnn_tensor_out dweight, _megdnn_tensor_out dbias,
            _megdnn_workspace workspace) = 0;
    void deduce_layout(
            const TensorLayout& diff, const TensorLayout& data,
            const TensorLayout& weight, const TensorLayout& mean,
            const TensorLayout& rstd, TensorLayout& ddata, TensorLayout& dweight,
            TensorLayout& dbias);
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& diff, const TensorLayout& data,
            const TensorLayout& weight, const TensorLayout& mean,
            const TensorLayout& rstd, const TensorLayout& ddata,
            const TensorLayout& dweight, const TensorLayout& dbias) = 0;

protected:
    void check_exec(
            const TensorLayout& diff, const TensorLayout& data,
            const TensorLayout& weight, const TensorLayout& mean,
            const TensorLayout& rstd, const TensorLayout& ddata,
            const TensorLayout& dweight, const TensorLayout& dbias,
            size_t workspace_in_bytes);
};

2577 2578 2579 2580 2581 2582
class MultiHeadAttnBase : public OperatorBase {
    DEF_OPR_IMPL_CTOR(MultiHeadAttnBase, OperatorBase);
    DEF_OPR_PARAM(MultiHeadAttn);
};

class MultiHeadAttnForward : public MultiHeadAttnBase {
2583
    DEF_OPR_IMPL(MultiHeadAttnForward, MultiHeadAttnBase, 7, 4);
2584 2585

public:
2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629
    /**
     * \param[in] queries (N, L, E_q), where N is the batch size, L is the target
     * sequence length, and E_q is the query embedding dimension embed_dim.
     * \param[in] keys (N, S, E_k), where N is the batch size, S is the source
     * sequence length, and E_k is the key embedding dimension k_dim.
     * \param[in] values (N, S, E_v), where N is the batch size, S is the source
     * sequence length, and E_v is the value embedding dimension v_dim.
     * \param[in] qkvo_weight_bias, input/output projection weight/bias all in one.
     * The order of arrangement is: query weight, key weight, value weight,
     * out weight, query bias, key bias, value bias, out bias, the following parameters
     * in param will be used to indicate whether these items exist: qproj_size,
     * kproj_size, vproj_size, oproj_size, qbias, kbias, vbias, obias.
     * Note: Y=X@W+B is used here instead of Y=X@W^T+B in pytorch.
     * \param[in] attn_mask, (N*num_heads, L, S) or (L, S), where N is the batch size,
     * num_heads is the number of parallel attention heads, L is the target sequence
     * length, and S is the source sequence length. attention mask is obtained by
     * combining attn_mask, key_padding_mask, is_causal and maybe_cudnn_style_mask by
     * mge.functional._merge_masks.
     * \param[in] bias_k, (1, 1, kproj_size), where kproj_size is the projected
     * dimension of key weight, if kproj_size == 0, will be the key embedding dimension
     * k_dim.
     * Note: bias_k and bias_v are the bias of the K and V sequences to be added at
     * sequence dim, distinguished from kbias and vbias, bias_kv here is not kbias and
     * vbias in the linear layer, and bias_kv here will be added to the K and V at
     * sequence dimensions, where K and V are the matrices of key and value after
     * projection, and K and V will be used to calculate the attention matrix.
     * \param[in] bias_v, (1, 1, vproj_size), where vproj_size is the projected
     * dimension of value weight, if vproj_size == 0, will be the value embedding
     * dimension v_dim.
     * Note: see bias_k.
     * \param[out] out, (N, S, oproj_size), where N is
     * the batch size, S is the source sequence length, and oproj_size is the projected
     * dimension of output weight, if oproj_size == 0, will be the projected
     * dimension of value weight vproj_size, but if vproj_size == 0, will be the value
     * embedding dimension v_dim.
     * \param[out] attn_weight, (N * num_heads, L, S), where N is the batch size,
     * num_heads is the number of parallel attention heads, L is the target sequence
     * length, and S is the source sequence length.
     * Note: attn_weight is the output of softmax.
     * \param[out] mask_reservespace, when param.training=true, we need this output to
     * save the mask of attention dropout and output dropout.
     * \param[out] othr_reservespace, when param.training=true, we need this output to
     * save the intermediate calculation results.
     */
2630 2631
    virtual void exec(
            _megdnn_tensor_in queries, _megdnn_tensor_in keys, _megdnn_tensor_in values,
2632 2633 2634 2635 2636
            _megdnn_tensor_in qkvo_weight_bias, _megdnn_tensor_in attn_mask,
            _megdnn_tensor_in bias_k, _megdnn_tensor_in bias_v, _megdnn_tensor_out out,
            _megdnn_tensor_out attn_weight, _megdnn_tensor_out mask_reservespace,
            _megdnn_tensor_out othr_reservespace, _megdnn_workspace workspace) = 0;
    virtual void deduce_layout(
2637
            const TensorLayout& queries, const TensorLayout& keys,
2638 2639 2640 2641
            const TensorLayout& values, const TensorLayout& qkvo_weight_bias,
            const TensorLayout& attn_mask, const TensorLayout& bias_k,
            const TensorLayout& bias_v, TensorLayout& out, TensorLayout& attn_weight,
            TensorLayout& mask_reservespace, TensorLayout& othr_reservespace) = 0;
2642 2643
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& queries, const TensorLayout& keys,
2644 2645 2646 2647 2648 2649
            const TensorLayout& values, const TensorLayout& qkvo_weight_bias,
            const TensorLayout& attn_mask, const TensorLayout& bias_k,
            const TensorLayout& bias_v, const TensorLayout& out,
            const TensorLayout& attn_weight, const TensorLayout& mask_reservespace,
            const TensorLayout& othr_reservespace) = 0;
    virtual size_t get_mask_reservespace_in_bytes(
2650
            const TensorLayout& queries, const TensorLayout& keys,
2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
            const TensorLayout& values, const TensorLayout& qkvo_weight_bias,
            const TensorLayout& attn_mask, const TensorLayout& bias_k,
            const TensorLayout& bias_v, const TensorLayout& out,
            const TensorLayout& attn_weight, const TensorLayout& mask_reservespace,
            const TensorLayout& othr_reservespace) = 0;
    virtual size_t get_othr_reservespace_in_bytes(
            const TensorLayout& queries, const TensorLayout& keys,
            const TensorLayout& values, const TensorLayout& qkvo_weight_bias,
            const TensorLayout& attn_mask, const TensorLayout& bias_k,
            const TensorLayout& bias_v, const TensorLayout& out,
            const TensorLayout& attn_weight, const TensorLayout& mask_reservespace,
            const TensorLayout& othr_reservespace) = 0;
2663 2664 2665 2666

protected:
    void check_exec(
            const TensorLayout& queries, const TensorLayout& keys,
2667 2668 2669 2670 2671
            const TensorLayout& values, const TensorLayout& qkvo_weight_bias,
            const TensorLayout& attn_mask, const TensorLayout& bias_k,
            const TensorLayout& bias_v, const TensorLayout& out,
            const TensorLayout& attn_weight, const TensorLayout& mask_reservespace,
            const TensorLayout& othr_reservespace, size_t workspace_in_bytes);
2672 2673 2674 2675
};
using MultiHeadAttn = MultiHeadAttnForward;

class MultiHeadAttnBackward : public MultiHeadAttnBase {
2676
    DEF_OPR_IMPL(MultiHeadAttnBackward, MultiHeadAttnBase, 9, 6);
2677 2678 2679 2680

public:
    virtual void exec(
            _megdnn_tensor_in diff, _megdnn_tensor_in queries, _megdnn_tensor_in keys,
2681 2682 2683 2684 2685 2686 2687
            _megdnn_tensor_in values, _megdnn_tensor_in qkvo_weight_bias,
            _megdnn_tensor_in attn_mask, _megdnn_tensor_in attn_weight,
            _megdnn_tensor_in mask_reservespace, _megdnn_tensor_in othr_reservespace,
            _megdnn_tensor_out dqueries, _megdnn_tensor_out dkeys,
            _megdnn_tensor_out dvalues, _megdnn_tensor_out dqkvo_weight_bias,
            _megdnn_tensor_out dbias_k, _megdnn_tensor_out dbias_v,
            _megdnn_workspace workspace) = 0;
2688 2689 2690
    MGE_WIN_DECLSPEC_FUC void deduce_layout(
            const TensorLayout& diff, const TensorLayout& queries,
            const TensorLayout& keys, const TensorLayout& values,
2691 2692 2693 2694 2695
            const TensorLayout& qkvo_weight_bias, const TensorLayout& attn_mask,
            const TensorLayout& attn_weight, const TensorLayout& mask_reservespace,
            const TensorLayout& othr_reservespace, TensorLayout& dqueries,
            TensorLayout& dkeys, TensorLayout& dvalues, TensorLayout& dqkvo_weight_bias,
            TensorLayout& dbias_k, TensorLayout& dbias_v);
2696 2697 2698
    virtual size_t get_workspace_in_bytes(
            const TensorLayout& diff, const TensorLayout& queries,
            const TensorLayout& keys, const TensorLayout& values,
2699 2700 2701 2702 2703 2704
            const TensorLayout& qkvo_weight_bias, const TensorLayout& attn_mask,
            const TensorLayout& attn_weight, const TensorLayout& mask_reservespace,
            const TensorLayout& othr_reservespace, const TensorLayout& dqueries,
            const TensorLayout& dkeys, const TensorLayout& dvalues,
            const TensorLayout& dqkvo_weight_bias, const TensorLayout& dbias_k,
            const TensorLayout& dbias_v) = 0;
2705 2706 2707 2708 2709

protected:
    void check_exec(
            const TensorLayout& diff, const TensorLayout& queries,
            const TensorLayout& keys, const TensorLayout& values,
2710 2711 2712 2713 2714 2715
            const TensorLayout& qkvo_weight_bias, const TensorLayout& attn_mask,
            const TensorLayout& attn_weight, const TensorLayout& mask_reservespace,
            const TensorLayout& othr_reservespace, const TensorLayout& dqueries,
            const TensorLayout& dkeys, const TensorLayout& dvalues,
            const TensorLayout& dqkvo_weight_bias, const TensorLayout& dbias_k,
            const TensorLayout& dbias_v, size_t workspace_in_bytes);
2716
};
2717 2718 2719 2720
}  // namespace megdnn
#include "megdnn/internal/opr_header_epilogue.h"

// vim: syntax=cpp.doxygen