opr_proxy.h 23.4 KB
Newer Older
1 2 3 4
/**
 * \file dnn/test/common/opr_proxy.h
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6 7 8
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
9 10
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.
11 12 13
 */
#pragma once

14 15
#include "src/common/opr_trait.h"

16 17
#include "test/common/deduce_layout_proxy.h"
#include "test/common/exec_proxy.h"
18
#include "test/common/fast_run_cache.h"
19
#include "test/common/inspect_type.h"
20
#include "test/common/opr_algo_proxy.h"
21 22 23 24
#include "test/common/timer.h"
#include "test/common/workspace_wrapper.h"

#include <algorithm>
25
#include <limits>
26
#include <memory>
27
#include <unordered_map>
28

29 30 31
namespace megdnn {
namespace test {

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
template <Algorithm::OprType>
struct OprFromOprTypeTrait;

template <typename Opr>
struct OprTypeFromOprTrait;

#define cb(_opr_type, _opr)                                     \
    template <>                                                 \
    struct OprFromOprTypeTrait<Algorithm::OprType::_opr_type> { \
        using Opr = megdnn::_opr;                               \
    };                                                          \
    template <>                                                 \
    struct OprTypeFromOprTrait<megdnn::_opr> {                  \
        constexpr static Algorithm::OprType opr_type =          \
                Algorithm::OprType::_opr_type;                  \
    }

cb(MATRIX_MUL_FORWARD, MatrixMulForward);
50
cb(BATCHED_MATRIX_MUL_FORWARD, BatchedMatrixMulForward);
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
cb(CONVOLUTION_FORWARD, ConvolutionForward);
cb(CONVOLUTION_BACKWARD_DATA, ConvolutionBackwardData);
cb(CONVOLUTION_BACKWARD_FILTER, ConvolutionBackwardFilter);
cb(CONVOLUTION3D_FORWARD, Convolution3DForward);
cb(CONVOLUTION3D_BACKWARD_DATA, Convolution3DBackwardData);
cb(CONVOLUTION3D_BACKWARD_FILTER, Convolution3DBackwardFilter);
cb(LOCAL_SHARE_FORWARD, LocalShareForward);
cb(LOCAL_SHARE_BACKWARD_DATA, LocalShareBackwardData);
cb(LOCAL_SHARE_BACKWARD_FILTER, LocalShareBackwardFilter);
cb(DEFORMABLE_CONV_FORWARD, DeformableConvForward);
cb(DEFORMABLE_CONV_BACKWARD_DATA, DeformableConvBackwardData);
cb(DEFORMABLE_CONV_BACKWARD_FILTER, DeformableConvBackwardFilter);
cb(BATCH_CONV_FORWARD, BatchConvBiasForward);
cb(CONVBIAS_FORWARD, ConvBiasForward);

#undef cb

// clang-format off
#define FOREACH_OPR_TYPE(cb) \
    cb(MATRIX_MUL_FORWARD) \
71
    cb(BATCHED_MATRIX_MUL_FORWARD) \
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    cb(CONVOLUTION_FORWARD) \
    cb(CONVOLUTION_BACKWARD_DATA) \
    cb(CONVOLUTION_BACKWARD_FILTER) \
    cb(CONVOLUTION3D_FORWARD) \
    cb(CONVOLUTION3D_BACKWARD_DATA) \
    cb(CONVOLUTION3D_BACKWARD_FILTER) \
    cb(LOCAL_SHARE_FORWARD) \
    cb(LOCAL_SHARE_BACKWARD_DATA) \
    cb(LOCAL_SHARE_BACKWARD_FILTER) \
    cb(DEFORMABLE_CONV_FORWARD) \
    cb(DEFORMABLE_CONV_BACKWARD_DATA) \
    cb(DEFORMABLE_CONV_BACKWARD_FILTER) \
    cb(BATCH_CONV_FORWARD) \
    cb(CONVBIAS_FORWARD)

#define FOREACH_OPR_TYPE_WITH_STMT(cb, stmt) \
    cb(MATRIX_MUL_FORWARD, stmt) \
89
    cb(BATCHED_MATRIX_MUL_FORWARD, stmt) \
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
    cb(CONVOLUTION_FORWARD, stmt) \
    cb(CONVOLUTION_BACKWARD_DATA, stmt) \
    cb(CONVOLUTION_BACKWARD_FILTER, stmt) \
    cb(CONVOLUTION3D_FORWARD, stmt) \
    cb(CONVOLUTION3D_BACKWARD_DATA, stmt) \
    cb(CONVOLUTION3D_BACKWARD_FILTER, stmt) \
    cb(LOCAL_SHARE_FORWARD, stmt) \
    cb(LOCAL_SHARE_BACKWARD_DATA, stmt) \
    cb(LOCAL_SHARE_BACKWARD_FILTER, stmt) \
    cb(DEFORMABLE_CONV_FORWARD, stmt) \
    cb(DEFORMABLE_CONV_BACKWARD_DATA, stmt) \
    cb(DEFORMABLE_CONV_BACKWARD_FILTER, stmt) \
    cb(BATCH_CONV_FORWARD, stmt) \
    cb(CONVBIAS_FORWARD, stmt)

// clang-format on

#define _OPR_TYPE_CASE(_opr_type, _stmt)             \
    case Algorithm::OprType::_opr_type: {            \
        using _Opr = typename OprFromOprTypeTrait<   \
                Algorithm::OprType::_opr_type>::Opr; \
        _stmt;                                       \
        break;                                       \
    }

#define FOREACH_OPR_TYPE_DISPATCH(_search_items, _stmt)          \
    for (size_t _item_idx = 0; _item_idx < _search_items.size(); \
         _item_idx++) {                                          \
        auto&& _item = _search_items[_item_idx];                 \
        switch (_item.opr_type) {                                \
            FOREACH_OPR_TYPE_WITH_STMT(_OPR_TYPE_CASE, _stmt)    \
            default:                                             \
                megdnn_throw("unknown opr_type");                \
        }                                                        \
    }

126 127 128 129 130 131 132 133 134 135
template <typename Opr, size_t arity = OprTrait<Opr>::arity,
          bool has_workspace = OprTrait<Opr>::has_workspace,
          bool can_deduce_layout = OprTrait<Opr>::can_deduce_layout>
struct OprProxyDefaultImpl
        : public DeduceLayoutProxy<Opr, arity, can_deduce_layout>,
          public ExecProxy<Opr, arity, has_workspace> {};

template <typename Opr>
struct OprProxy : public OprProxyDefaultImpl<Opr> {};

136 137 138
template <typename Opr>
struct OprWeightPreprocessProxy : public OprProxyDefaultImpl<Opr> {};

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
template <typename Opr>
struct OprProxyVectorToSingle {};

template <>
struct OprProxy<ElemwiseForward> {
    static void deduce_layout(ElemwiseForward* opr,
                              TensorLayoutArray& layouts) {
        megdnn_assert(layouts.size() >= 2);
        auto inp = layouts;
        inp.pop_back();
        opr->deduce_layout(inp, layouts.back());
    }

    static void exec(ElemwiseForward* opr, const TensorNDArray& tensors) {
        megdnn_assert(tensors.size() >= 2);
        auto inp = tensors;
        inp.pop_back();
        opr->exec(inp, tensors.back());
    }
};

template <>
struct OprProxy<ElemwiseMultiType> {
    static void deduce_layout(ElemwiseMultiType* opr,
                              TensorLayoutArray& layouts) {
        megdnn_assert(layouts.size() >= 2);
        auto inp = layouts;
        inp.pop_back();
        opr->deduce_layout(inp, layouts.back());
    }

    static void exec(ElemwiseMultiType* opr, const TensorNDArray& tensors) {
        megdnn_assert(tensors.size() >= 2);
        auto inp = tensors;
        inp.pop_back();
        opr->exec(inp, tensors.back());
    }
};

template <>
struct OprProxy<ConcatForward> {
    static void deduce_layout(ConcatForward* opr, TensorLayoutArray& layouts) {
        megdnn_assert(layouts.size() >= 2);
        auto inp = layouts;
        inp.pop_back();
        opr->deduce_layout(inp, layouts.back());
    }

    static void exec(ConcatForward* opr, const TensorNDArray& tensors) {
        megdnn_assert(tensors.size() >= 2);
        auto inp = tensors;
        inp.pop_back();

        TensorLayoutArray layouts(tensors.size());
        std::transform(tensors.begin(), tensors.end(), layouts.begin(),
                       [](const TensorND& tensor) { return tensor.layout; });
        auto inp_layouts = layouts;
        inp_layouts.pop_back();

        WorkspaceWrapper W(opr->handle(), opr->get_workspace_in_bytes(
                                                  inp_layouts, layouts.back()));

        auto inp_tensors = tensors;
        inp_tensors.pop_back();
        opr->exec(inp_tensors, tensors.back(), W.workspace());
    }
};

template <>
struct OprProxy<SplitForward> : DeduceLayoutProxy<SplitForward, 0, false> {
    static void exec(SplitForward* opr, const TensorNDArray& tensors) {
        megdnn_assert(tensors.size() >= 2);
        auto out = tensors;
        out.erase(out.begin());

        TensorLayoutArray layouts(tensors.size());
        std::transform(tensors.begin(), tensors.end(), layouts.begin(),
                       [](const TensorND& tensor) { return tensor.layout; });
        auto out_layouts = layouts;
        out_layouts.erase(out_layouts.begin());

        WorkspaceWrapper W(
                opr->handle(),
                opr->get_workspace_in_bytes(layouts.front(), out_layouts));

        auto out_tensors = tensors;
        out_tensors.erase(out_tensors.begin());
        opr->exec(tensors.front(), out_tensors, W.workspace());
    }
};

//! OprProxy impl for tenary oprs with profiling support
231
template <class Opr>
232
struct OprProxyProfilingBase
233
        : public DeduceLayoutProxy<Opr, OprTrait<Opr>::arity,
234
                                   OprTrait<Opr>::can_deduce_layout> {
235
    static constexpr int arity = OprTrait<Opr>::arity;
236 237 238 239 240 241 242 243
    size_t warmup_times = 10, exec_times = 100;

    //! whether to enable profiling
    bool m_profiling;
    WorkspaceWrapper W;

    //! target algo setup by profiler; it can also be directly specified by the
    //! caller
244
    ExecutionPolicy target_execution_policy;
245 246

    OprProxyProfilingBase(bool profile = false) { m_profiling = profile; }
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

    //! used for alloc tensor for weight preprocess
    static std::shared_ptr<TensorNDArray> alloc_tensors(
            Handle* handle, const TensorLayoutArray& layouts) {
        auto deleter = [handle](TensorNDArray* ptr) {
            for (auto&& i : *ptr) {
                auto pdata = static_cast<dt_byte*>(i.raw_ptr) +
                             i.layout.span().low_byte;
                megdnn_free(handle, pdata);
            }
            delete ptr;
        };
        std::shared_ptr<TensorNDArray> ret{new TensorNDArray, deleter};
        for (size_t i = 0; i < layouts.size(); ++i) {
            auto span = layouts[i].span();
            ret->emplace_back(static_cast<dt_byte*>(
                                      megdnn_malloc(handle, span.dist_byte())) -
                                      span.low_byte,
                              layouts[i]);
        }
        return ret;
    }
269

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
    /**
     * flatten search space in postorder traversal
     * The subopr search construct a search tree
     *
     *           A
     *        /    \
     *       B1B2   C
     *      /     \
     *     D1D2D3   E
     * We use postorder traverse the search tree.
     * D1 -> D2 -> D3 -> E -> B1 -> B2 -> C -> A
     */
    static std::vector<Algorithm::SearchItem> flatten_search_space(
            const TensorLayoutArray layouts, const std::string& param,
            Handle* handle) {
        megdnn_assert(layouts.size() == arity);
        auto opr = handle->create_operator<Opr>();
        opr->param() =
                Algorithm::deserialize_read_pod<typename Opr::Param>(param);

        std::vector<Algorithm::SearchItem> ret;
291
        for (auto algo_info : AlgoProxy<Opr, arity>::get_all_algorithms_info_safe(
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
                     opr.get(), layouts)) {
            Algorithm* algo = opr->get_algorithm_from_desc(algo_info.desc);
            std::vector<Algorithm::SearchItem>&& sub_items =
                    algo->get_subopr_list(layouts, opr.get());

            FOREACH_OPR_TYPE_DISPATCH(sub_items, {
                auto space = OprProxyProfilingBase<_Opr>::flatten_search_space(
                        _item.layouts, _item.param, handle);
                ret.insert(ret.end(), space.begin(), space.end());
            });
        }
        ret.push_back({OprTypeFromOprTrait<Opr>::opr_type, param, layouts});
        return ret;
    }

    static void construct_execution_policy(
            const TensorLayoutArray& layouts, const std::string& param,
            Handle* handle, FastRunCache& cache,
            ExecutionPolicy& policy) {
        megdnn_assert(layouts.size() == arity);
        auto opr = handle->create_operator<Opr>();
        opr->param() =
                Algorithm::deserialize_read_pod<typename Opr::Param>(param);
        if (!policy.algo.valid()) {
            policy.algo = cache.get(Algorithm::SearchItem{
                    OprTypeFromOprTrait<Opr>::opr_type, param, layouts});
            megdnn_assert(policy.algo.valid(),
                          "No cache found, maybe some error occured in "
                          "flatten_search_space or get_subopr_list");
        }
        policy.sub_policy.clear();
        Algorithm* algo = opr->get_algorithm_from_desc(policy.algo);
        std::vector<Algorithm::SearchItem>&& sub_items =
                algo->get_subopr_list(layouts, opr.get());
        FOREACH_OPR_TYPE_DISPATCH(sub_items, {
            policy.sub_policy.push_back({});
            OprProxyProfilingBase<_Opr>::construct_execution_policy(
                    _item.layouts, _item.param, handle, cache,
                    policy.sub_policy.back());
        });
        return;
    }

    /**
     * \brief search and get the best execution_policy
     */
    static void search(const TensorLayoutArray& layouts,
                       const std::string& param,
                       WorkspaceWrapper& workspace_wrapper, Handle* handle,
                       size_t warmup_times, size_t exec_times,
                       FastRunCache& cache) {
        megdnn_assert(layouts.size() == arity);
        auto opr = handle->create_operator<Opr>();
345

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
        opr->param() =
                Algorithm::deserialize_read_pod<typename Opr::Param>(param);
        SmallVector<size_t> sizes_in_bytes;
        for (const auto& layout : layouts) {
            sizes_in_bytes.push_back(layout.span().dist_byte());
        }

        float min_time = std::numeric_limits<float>::max();
        Algorithm::Info::Desc best_algo;

        std::string log_info = "Profiling start: ";
        for (auto&& layout : layouts) {
            log_info += layout.to_string() + " ";
        }
        megdnn_log("%s", log_info.c_str());
        best_algo = cache.get(Algorithm::SearchItem{
                OprTypeFromOprTrait<Opr>::opr_type, param, layouts});

        if (best_algo.valid()) {
            auto&& algo = opr->get_algorithm_from_desc(best_algo);
            MEGDNN_MARK_USED_VAR(algo);
            megdnn_log("Find best algo %s in cache", algo->name());
            return;
        }
370
        for (auto algo : AlgoProxy<Opr, arity>::get_all_algorithms_info_safe(
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
                     opr.get(), layouts)) {
            //! construct execution_policy
            opr->execution_policy().algo = algo.desc;
            construct_execution_policy(layouts, param, handle, cache,
                                       opr->execution_policy());

            auto workspace_size = AlgoProxy<Opr, arity>::get_workspace_in_bytes(
                    opr.get(), layouts);
            sizes_in_bytes.push_back(workspace_size);

            WorkspaceBundle wb(nullptr, sizes_in_bytes);
            workspace_wrapper.update(wb.total_size_in_bytes());
            wb.set(workspace_wrapper.workspace().raw_ptr);
            TensorNDArray tensors;
            for (size_t i = 0; i < arity; i++) {
                tensors.push_back({wb.get(i), layouts[i]});
            }

            for (size_t times = 0; times < warmup_times; ++times) {
                AlgoProxy<Opr, arity>::exec(opr.get(), tensors,
                                            wb.get_workspace(arity));
            }
            megcoreSynchronize(opr->handle()->megcore_computing_handle());
            Timer timer;
            timer.start();
            for (size_t times = 0; times < exec_times; ++times) {
                AlgoProxy<Opr, arity>::exec(opr.get(), tensors,
                                            wb.get_workspace(arity));
            }
            megcoreSynchronize(opr->handle()->megcore_computing_handle());
            timer.stop();
            megdnn_log("%.3fms %s", timer.get_time_in_us() / 1e3,
403
                       algo.desc.name.c_str());
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
            if (min_time > timer.get_time_in_us()) {
                min_time = timer.get_time_in_us();
                best_algo = algo.desc;
            }

            sizes_in_bytes.pop_back();
        }
        auto&& algo = opr->get_algorithm_from_desc(best_algo);
        MEGDNN_MARK_USED_VAR(algo);
        megdnn_log("Profiling end, got best algo: %s", algo->name());
        cache.put(Algorithm::SearchItem{OprTypeFromOprTrait<Opr>::opr_type,
                                        param, layouts},
                  best_algo);
    }

419
    void exec(Opr* opr, const TensorNDArray& tensors) {
420 421 422
        megdnn_assert(tensors.size() == arity);
        if (!W.valid()) {
            W = WorkspaceWrapper(opr->handle(), 0);
423
        }
424 425 426
        TensorLayoutArray layouts;
        for (auto&& tensor : tensors) {
            layouts.push_back(tensor.layout);
427
        }
428 429 430 431 432 433 434
        if (m_profiling && !target_execution_policy.algo.valid()) {
            FastRunCache cache;
            std::string param_str;
            Algorithm::serialize_write_pod(opr->param(), param_str);
            auto&& search_items =
                    flatten_search_space(layouts, param_str, opr->handle());
            FOREACH_OPR_TYPE_DISPATCH(search_items, {
435 436 437
                OprProxyProfilingBase<_Opr>::search(
                        _item.layouts, _item.param, W, opr->handle(),
                        warmup_times, exec_times, cache);
438 439 440 441 442
            });

            construct_execution_policy(layouts, param_str, opr->handle(), cache,
                                       opr->execution_policy());
            target_execution_policy = opr->execution_policy();
443 444 445
            auto workspace_size =
                    AlgoProxy<Opr, arity>::get_workspace_in_bytes(opr, layouts);
            W.update(workspace_size);
446
        }
447
        if (!target_execution_policy.algo.valid()) {
448 449 450
            auto workspace_size =
                    AlgoProxy<Opr, arity>::get_workspace_in_bytes(opr, layouts);
            W.update(workspace_size);
451
        }
452
        AlgoProxy<Opr, arity>::exec(opr, tensors, W.workspace());
453 454 455
    }
};

456 457 458 459
#define DEF_PROF(c)                                            \
    template <>                                                \
    struct OprProxy<c> : public OprProxyProfilingBase<c> {     \
        using OprProxyProfilingBase<c>::OprProxyProfilingBase; \
460
    }
461

462 463 464 465 466 467 468
DEF_PROF(MatrixMulForward);
DEF_PROF(ConvolutionForward);
DEF_PROF(ConvolutionBackwardData);
DEF_PROF(ConvolutionBackwardFilter);
DEF_PROF(LocalShareForward);
DEF_PROF(LocalShareBackwardData);
DEF_PROF(LocalShareBackwardFilter);
469

470 471 472 473
DEF_PROF(DeformableConvForward);
DEF_PROF(DeformableConvBackwardFilter);
DEF_PROF(BatchConvBiasForward);
DEF_PROF(ConvBiasForward);
474

475
DEF_PROF(DeformableConvBackwardData);
476
#undef DEF_PROF
477

478 479 480 481
template <class Opr>
struct OprWeightPreprocessProxyImpl : public OprProxyProfilingBase<Opr> {
    using Base = OprProxyProfilingBase<Opr>;
    static constexpr int arity = OprTrait<Opr>::arity;
482
    void exec(Opr* opr, const TensorNDArray& tensors) {
483
        megdnn_assert(tensors.size() == arity);
484 485 486 487
        if (!Base::W.valid()) {
            Base::W = WorkspaceWrapper(opr->handle(), 0);
        }

488 489 490
        TensorLayoutArray layouts;
        for (auto&& tensor : tensors) {
            layouts.push_back(tensor.layout);
491
        }
492
        if (Base::m_profiling && !Base::target_execution_policy.algo.valid()) {
493
            size_t min_time = std::numeric_limits<size_t>::max();
494
            for (auto algo :
495
                 AlgoProxy<Opr, arity>::get_all_algorithms_info_safe(opr, layouts)) {
496
                opr->execution_policy().algo = algo.desc;
497

498 499
                auto preprocess_tensors =
                        weight_prerocess(opr, tensors, algo.desc);
500
                megcoreSynchronize(opr->handle()->megcore_computing_handle());
501
                typename Opr::PreprocessedFilter preprocessed_filter{
502
                        nullptr, *preprocess_tensors};
503

504 505 506
                auto workspace_size =
                        AlgoProxy<Opr, arity>::get_workspace_in_bytes(
                                opr, layouts, &preprocessed_filter);
507 508
                Base::W.update(workspace_size);

509 510 511 512 513
                for (size_t times = 0; times < Base::warmup_times; ++times) {
                    AlgoProxy<Opr, arity>::exec(opr, tensors,
                                                &preprocessed_filter,
                                                Base::W.workspace());
                }
514 515 516 517
                megcoreSynchronize(opr->handle()->megcore_computing_handle());
                Timer timer;
                timer.start();
                for (size_t times = 0; times < Base::exec_times; ++times) {
518 519 520
                    AlgoProxy<Opr, arity>::exec(opr, tensors,
                                                &preprocessed_filter,
                                                Base::W.workspace());
521 522 523 524
                }
                megcoreSynchronize(opr->handle()->megcore_computing_handle());
                timer.stop();
                printf("%.3fms %s\n", timer.get_time_in_us() / 1e3,
525
                       algo.desc.name.c_str());
526 527
                if (min_time > timer.get_time_in_us()) {
                    min_time = timer.get_time_in_us();
528
                    Base::target_execution_policy.algo = algo.desc;
529 530
                }
            }
531 532 533
            opr->execution_policy() = Base::target_execution_policy;
            auto preprocess_tensors = weight_prerocess(
                    opr, tensors, Base::target_execution_policy.algo);
534
            megcoreSynchronize(opr->handle()->megcore_computing_handle());
535
            typename Opr::PreprocessedFilter preprocessed_filter{
536
                    nullptr, *preprocess_tensors};
537 538
            auto workspace_size = AlgoProxy<Opr, arity>::get_workspace_in_bytes(
                    opr, layouts, &preprocessed_filter);
539 540
            Base::W.update(workspace_size);
        }
541 542
        auto preprocess_tensors = weight_prerocess(
                opr, tensors, Base::target_execution_policy.algo);
543
        megcoreSynchronize(opr->handle()->megcore_computing_handle());
544
        typename Opr::PreprocessedFilter preprocessed_filter{
545
                nullptr, *preprocess_tensors};
546
        if (!Base::target_execution_policy.algo.valid()) {
547 548
            auto workspace_size = AlgoProxy<Opr, arity>::get_workspace_in_bytes(
                    opr, layouts, &preprocessed_filter);
549 550
            Base::W.update(workspace_size);
        }
551 552
        AlgoProxy<Opr, arity>::exec(opr, tensors, &preprocessed_filter,
                                    Base::W.workspace());
553 554 555 556
    }

    //! handle weight preprocess
    std::shared_ptr<TensorNDArray> weight_prerocess(
557 558 559 560 561 562 563 564 565
            Opr* opr, const TensorNDArray& tensors,
            const typename Opr::AlgorithmDesc&) {
        TensorLayoutArray layouts;
        for (auto&& tensor : tensors) {
            layouts.push_back(tensor.layout);
        }
        auto weight_perprocess_layouts =
                AlgoProxy<Opr, arity>::deduce_preprocessed_filter_layout(
                        opr, layouts);
566
        auto preprocessed_filter_tensors_ptr =
567 568
                Base::alloc_tensors(opr->handle(), weight_perprocess_layouts);
        typename Opr::PreprocessedFilter preprocessed_filter{
569
                nullptr, *preprocessed_filter_tensors_ptr};
570
        size_t preprocess_workspace_size =
571 572
                AlgoProxy<Opr, arity>::get_preprocess_workspace_in_bytes(
                        opr, layouts);
573 574
        WorkspaceWrapper preprocess_workspace(opr->handle(),
                                              preprocess_workspace_size);
575 576 577
        AlgoProxy<Opr, arity>::exec_preprocess(
                opr, tensors, layouts, &preprocessed_filter,
                preprocess_workspace.workspace());
578 579 580 581
        return preprocessed_filter_tensors_ptr;
    }
};

582 583 584 585 586
#define DEF_PROF(c)                                                          \
    template <>                                                              \
    struct OprWeightPreprocessProxy<c>                                       \
            : public OprWeightPreprocessProxyImpl<c> {                       \
        using OprWeightPreprocessProxyImpl<c>::OprWeightPreprocessProxyImpl; \
587 588
    }

589 590
DEF_PROF(ConvolutionForward);
DEF_PROF(ConvBias);
591
#undef DEF_PROF
592 593 594 595 596

}  // namespace test
}  // namespace megdnn

// vim: syntax=cpp.doxygen