basic_arith.cpp 63.1 KB
Newer Older
1 2 3 4
/**
 * \file src/opr/impl/basic_arith.cpp
 * 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 9 10 11 12
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

#include "megbrain/opr/basic_arith.h"
M
Megvii Engine Team 已提交
13 14 15
#include "megbrain/gopt/basic_arith.h"
#include "megbrain/gopt/gtrans.h"
#include "megbrain/graph/grad_impl.h"
16 17
#include "megbrain/opr/basic_arith_wrapper.h"
#include "megbrain/opr/cond.h"
M
Megvii Engine Team 已提交
18
#include "megbrain/opr/io.h"
19
#include "megbrain/opr/tensor_manip.h"
M
Megvii Engine Team 已提交
20
#include "megbrain/opr/utility.h"
21 22 23 24 25 26 27 28 29 30 31
#include "megbrain/utils/arith_helper.h"

#include "./internal/megdnn_opr_wrapper.inl"

#include <cmath>

using namespace mgb;
using namespace opr;

namespace {

M
Megvii Engine Team 已提交
32 33 34 35 36
//! global operator instance for static inference
template <class Opr>
class StaticInferOpr {
    intl::UniqPtrWithCN<Opr> m_opr;
    MGB_MUTEX m_mtx;
37

M
Megvii Engine Team 已提交
38 39 40 41
public:
    class Lock {
        friend class StaticInferOpr;
        StaticInferOpr* m_owner;
42

M
Megvii Engine Team 已提交
43
        explicit Lock(StaticInferOpr* owner) : m_owner{owner} {
44
#if !__DEPLOY_ON_XP_SP2__
M
Megvii Engine Team 已提交
45
            m_owner->m_mtx.lock();
46
#endif
M
Megvii Engine Team 已提交
47
        }
48

M
Megvii Engine Team 已提交
49 50
    public:
        Lock(Lock&& rhs) : m_owner{rhs.m_owner} { rhs.m_owner = nullptr; }
51

M
Megvii Engine Team 已提交
52
        ~Lock() {
53
#if !__DEPLOY_ON_XP_SP2__
M
Megvii Engine Team 已提交
54 55
            if (m_owner)
                m_owner->m_mtx.unlock();
56
#endif
M
Megvii Engine Team 已提交
57 58 59 60 61 62
        }

        Lock& operator=(const Lock&) = delete;
        Lock& operator=(Lock&&) = delete;

        intl::UniqPtrWithCN<Opr>& operator()() { return m_owner->m_opr; }
63
    };
M
Megvii Engine Team 已提交
64 65 66 67 68 69 70 71 72 73 74

    //! lock and acquire the operator
    Lock lock() {
        Lock ret{this};
        if (!m_opr) {
            m_opr = intl::create_megdnn_opr<Opr>(CompNode::default_cpu());
        }
        return ret;
    }
};
}  // anonymous namespace
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

/* ========================= BatchedDTypePromotion ========================= */
intl::BatchedDTypePromotion::BatchedDTypePromotion(const VarNodeArrayView& vars)
        : m_orig_vars{vars} {
    mgb_assert(!vars.empty());
    DType final_dtype;
    bool changed = false;
    for (size_t i = 0; i < vars.size(); ++i) {
        auto cur = vars[i]->dtype();
        if (!i) {
            final_dtype = cur;
        } else {
            auto promoted = dtype_promotion(final_dtype, cur);
            changed |= promoted != final_dtype || promoted != cur;
            final_dtype = promoted;
        }
    }
    m_changed = changed;
    m_final_dtype = final_dtype;
}

void intl::BatchedDTypePromotion::set_dtype(DType dtype) {
    mgb_assert(!m_finalized);
    if (m_final_dtype != dtype) {
        m_final_dtype = dtype;
        m_changed = true;
    }
}

const VarNodeArrayView& intl::BatchedDTypePromotion::get_vars() {
    m_finalized = true;
    if (!m_changed) {
        return m_orig_vars;
    }
    if (!m_cvt_vars_view.valid()) {
        m_cvt_vars.resize(m_orig_vars.size());
        auto dtype = m_final_dtype;
        for (size_t i = 0; i < m_cvt_vars.size(); ++i) {
            m_cvt_vars[i] = TypeCvt::make(m_orig_vars[i], dtype).node();
        }
        m_cvt_vars_view.emplace(m_cvt_vars);
    }
    return m_cvt_vars_view.val();
}

/* =========================== Elemwise =========================== */

MGB_DYN_TYPE_OBJ_FINAL_IMPL(Elemwise);
Elemwise::Elemwise(
M
Megvii Engine Team 已提交
124 125 126
        const ModeTrait& mode_trait, const VarNodeArrayView& inputs, Param param,
        const OperatorNodeConfig& config)
        : Super{inputs.at(0)->owner_graph(), config, mode_trait.name, inputs} {
127
    init_megdnn_opr(*this, param);
128
    output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    if (mode_trait.commutable) {
        mgb_assert(inputs.size() == 2);
        add_input({inputs[0], inputs[1]}, AddInputSortType::CUR_ADDED);
    } else {
        if (param.mode == Mode::FUSE_MUL_ADD3) {
            add_input({inputs[0], inputs[1]}, AddInputSortType::CUR_ADDED);
            add_input({inputs[2]});
        } else if (param.mode == Mode::FUSE_MUL_ADD4) {
            auto i0 = inputs[0], i1 = inputs[1], i2 = inputs[2], i3 = inputs[3];
            if (i0->id() > i1->id())
                std::swap(i0, i1);
            if (i2->id() > i3->id())
                std::swap(i2, i3);
            if (i0->id() > i2->id()) {
                std::swap(i0, i2);
                std::swap(i1, i3);
            }
            add_input({i0, i1, i2, i3});
        } else {
M
Megvii Engine Team 已提交
148
            for (auto i : inputs)
149 150 151 152 153
                add_input({i});
        }
    }

    mgb_assert(m_input_broadcastable.size() >= inputs.size());
M
Megvii Engine Team 已提交
154 155
    for (size_t i = 0; i < inputs.size(); ++i) {
        if (input()[i]->owner_opr()->same_type<opr::MarkNoBroadcastElemwise>()) {
156 157 158 159 160 161 162 163 164 165
            m_input_broadcastable[i] = false;
        } else {
            m_input_broadcastable[i] = true;
        }
    }
    if (inputs.size() == 1) {
        m_input_broadcastable[0] = false;
    } else {
        Maybe<size_t> non_scalar;
        using namespace cg::static_infer;
M
Megvii Engine Team 已提交
166 167
        auto&& mgr = owner_graph()->static_infer_manager();
        for (size_t i = 0; i < input().size(); ++i) {
168 169
            auto it = mgr.get_infer_type(input(i));
            if (!((it.shape & InferType::CONST) &&
M
Megvii Engine Team 已提交
170
                  mgr.infer_shape(input(i)).is_scalar())) {
171 172 173 174 175 176 177 178 179 180 181 182 183
                if (non_scalar.valid()) {
                    non_scalar.invalidate();
                    break;
                }
                non_scalar = i;
            }
        }
        if (non_scalar.valid()) {
            // exactly one input is non-scalar
            m_input_broadcastable[non_scalar.val()] = false;
        }
    }

M
Megvii Engine Team 已提交
184 185 186 187 188 189 190 191 192 193
    if (inputs.size() && inputs[0]->dtype().category() == DTypeCategory::QUANTIZED) {
        mgb_assert(
                param.mode == Param::Mode::ADD || param.mode == Param::Mode::SUB ||
                        param.mode == Param::Mode::NEGATE ||
                        param.mode == Param::Mode::RELU ||
                        param.mode == Param::Mode::MAX ||
                        param.mode == Param::Mode::MIN,
                "Only ADD, SUB, NEGATE, RELU, MAX and MIN is guaranteed "
                "to be supported on Elemwise for quantized DType, no support %d",
                (int)param.mode);
194 195 196
    }
}

M
Megvii Engine Team 已提交
197 198
SymbolVar Elemwise::make(
        const VarNodeArrayView& inputs, Param param, const OperatorNodeConfig& config) {
199
    auto trait = ModeTrait::from_mode(param.mode);
M
Megvii Engine Team 已提交
200 201 202
    mgb_assert(
            inputs.size() == trait.arity, "%s expects %u inputs; got %zu actually",
            trait.name, trait.arity, inputs.size());
203 204 205 206 207
    intl::BatchedDTypePromotion dtp{inputs};
    if (dtp.get_dtype().category() == DTypeCategory::INT && !trait.allow_int) {
        dtp.set_dtype(dtype::Float32());
    }

M
Megvii Engine Team 已提交
208 209 210 211 212 213
    mgb_throw_if(
            dtp.get_dtype().category() == DTypeCategory::FLOAT && !trait.allow_float,
            ConversionError,
            "elemwise mode %s does not allow float input; "
            "got inputs: %s",
            trait.name, cg::dump_var_info(inputs).c_str());
214 215

#if !MGB_BUILD_SLIM_SERVING
216 217
    auto&& options = inputs[0]->owner_graph()->options();
    if (options.graph_opt_level && !(options.disable_inplace_arith_opt)) {
M
Megvii Engine Team 已提交
218
        auto repl = gopt::optimize_elemwise_expr_inplace(dtp.get_vars(), param, config);
219 220 221 222 223 224 225 226 227 228
        if (repl)
            return repl;
    }
#endif

    return SymbolVar{inputs[0]}.insert_single_output_opr<Elemwise>(
            trait, dtp.get_vars(), param, config);
}

TensorShape Elemwise::get_output_var_shape(
M
Megvii Engine Team 已提交
229
        Mode mode, const TensorShapeArray& input_shapes) {
230 231 232 233 234 235 236
    mgb_assert(input_shapes.size() == ModeTrait::from_mode(mode).arity);
    TensorShape ret;
    megdnn::Elemwise::deduce_shape(input_shapes, ret);
    return ret;
}

void Elemwise::perform(
M
Megvii Engine Team 已提交
237 238
        Mode mode, DeviceTensorND& dest, const SmallVector<DeviceTensorND>& inputs,
        intl::UniqPtrWithCN<megdnn::Elemwise>& opr) {
239 240 241 242
    megdnn::TensorNDArray dnn_inputs(inputs.size());
    TensorShapeArray inp_shapes(inputs.size());
    DType out_dt;
    CompNode out_cn;
M
Megvii Engine Team 已提交
243 244
    for (size_t i = 0; i < inputs.size(); ++i) {
        auto&& t = inputs[i];
245 246 247 248 249 250 251
        if (!i) {
            out_cn = t.comp_node();
            out_dt = t.dtype();
        } else {
            mgb_assert(t.comp_node() == out_cn);
            mgb_assert(t.dtype() == out_dt);
        }
252 253 254 255
        if (t.shape().is_empty()) {
            mgb_assert(dest.empty());
            return;
        }
256 257 258 259 260 261 262 263
        inp_shapes[i] = t.shape();
    }
    if (!opr) {
        opr = intl::create_megdnn_opr<megdnn::Elemwise>(out_cn);
    } else {
        mgb_assert(out_cn == opr.comp_node());
    }
    out_cn.activate();
M
Megvii Engine Team 已提交
264
    for (size_t i = 0; i < inputs.size(); ++i)
265
        dnn_inputs[i] = inputs[i].as_megdnn();
M
Megvii Engine Team 已提交
266
    dest.comp_node(out_cn).dtype(out_dt).resize(get_output_var_shape(mode, inp_shapes));
267
    opr->param() = {mode};
M
Megvii Engine Team 已提交
268
    call_megdnn_opr_exec(out_cn, dnn_inputs, dest.as_megdnn(), opr.get(), nullptr);
269 270
}

M
Megvii Engine Team 已提交
271
TensorLayoutArray Elemwise::collective_collapse(const TensorLayoutArray& layouts) {
272 273
    TensorLayoutPtrArray inp(layouts.size());
    TensorLayoutArray result(inp.size());
M
Megvii Engine Team 已提交
274
    for (size_t i = 0; i < layouts.size(); ++i) {
275 276 277 278 279 280 281
        result[i] = layouts[i];
        inp[i] = &result[i];
    }
    collective_collapse_inplace(inp);
    return result;
}

M
Megvii Engine Team 已提交
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
void Elemwise::collective_collapse_inplace(const TensorLayoutPtrArray& layouts) {
    mgb_assert(layouts.size());
    size_t ndim = layouts[0]->ndim;
    for (auto i : layouts) {
        if (i->ndim != ndim)
            mgb_throw(MegBrainError, "ndims must be same");
    }

    auto update_all = [&layouts](size_t axis) {
        for (auto i : layouts) {
            i->shape[axis] *= i->shape[axis + 1];
            i->stride[axis] = i->stride[axis + 1];
            i->remove_axis_inplace(axis + 1);
        }
    };

    auto check = [&layouts](size_t axis) -> bool {
        auto std_p =
                std::make_pair(layouts[0]->shape[axis], layouts[0]->shape[axis + 1]);
        for (auto i : layouts) {
            auto cur_p = std::make_pair(i->shape[axis], i->shape[axis + 1]);
            if (std_p != cur_p)
                return false;
            if (i->stride[axis] !=
                i->stride[axis + 1] * static_cast<ptrdiff_t>(i->shape[axis + 1]))
                return false;
        }
        return true;
    };

    for (int i = static_cast<int>(ndim) - 2; i >= 0; i--) {
        if (check(i)) {
            update_all(i);
        }
    }
317 318 319
}

void Elemwise::broadcast_collective_collapse(
M
Megvii Engine Team 已提交
320 321
        const TensorLayoutPtrArray& inp_layouts, TensorLayout* target_layout) {
    for (auto&& p : inp_layouts) {
322 323 324 325 326
        *p = p->broadcast(*target_layout);
    }
    TensorLayoutPtrArray buf(inp_layouts.size() + 1);
    buf[0] = target_layout;
    for (size_t i = 0; i < inp_layouts.size(); i++) {
M
Megvii Engine Team 已提交
327
        buf[i + 1] = inp_layouts[i];
328 329 330 331 332
    }
    collective_collapse_inplace(buf);
}

void Elemwise::mem_plan_fwd_in2out_writable() {
333
    mixin_mem_plan_fwd_in2out_writable(*this);
334 335 336
}

void Elemwise::scn_do_execute() {
337 338
    auto&& inp = input();
    megdnn::TensorNDArray dnn_inp;
M
Megvii Engine Team 已提交
339
    mgb_assert(dnn_inp.capacity() >= inp.size(), "heap allocation in elemwise exec");
340 341
    dnn_inp.resize(inp.size());
    for (size_t i = 0; i < inp.size(); ++i) {
342 343 344 345
        if (inp[i]->dev_tensor().empty()) {
            mgb_assert(output(0)->dev_tensor().empty());
            return;
        }
346
        dnn_inp[i] = (inp[i]->dev_tensor().as_megdnn());
347 348
    }
    mgb_assert(!output(0)->dev_tensor().empty());
349 350

    megdnn_opr()->param() = param();
M
Megvii Engine Team 已提交
351 352 353
    call_megdnn_opr_exec(
            comp_node(), dnn_inp, output(0)->dev_tensor().as_megdnn(), megdnn_opr(),
            this);
354 355 356 357 358 359 360 361
}

void Elemwise::init_output_static_infer_desc() {
    Super::init_output_static_infer_desc();
    static StaticInferOpr<megdnn::Elemwise> static_infer_opr;

    using namespace cg::static_infer;

M
Megvii Engine Team 已提交
362
    auto infer_value = [this](DeviceTensorND& dest, const InpVal& inp) {
363
        SmallVector<DeviceTensorND> inp_vals(inp.val.size());
M
Megvii Engine Team 已提交
364
        for (size_t i = 0; i < inp_vals.size(); ++i)
365 366 367 368 369 370 371
            inp_vals[i] = inp.val[i].value();
        auto sopr = static_infer_opr.lock();
        perform(param().mode, dest, inp_vals, sopr());
        return true;
    };

    DepVal deps(input().size());
M
Megvii Engine Team 已提交
372
    for (size_t i = 0; i < input().size(); ++i)
373 374 375 376 377 378
        deps[i] = {input(i), DepType::VALUE};
    owner_graph()->static_infer_manager().register_value_infer(
            output(0), {SourceType::DEP, deps, infer_value});
}

void Elemwise::get_output_var_shape(
M
Megvii Engine Team 已提交
379
        const TensorShapeArray& inp_shape, TensorShapeArray& out_shape) const {
380
    out_shape.at(0) = get_output_var_shape(param().mode, inp_shape);
M
Megvii Engine Team 已提交
381 382 383 384
    for (size_t i = 0; i < input().size(); ++i) {
        mgb_throw_if(
                !m_input_broadcastable[i] && !out_shape[0].eq_shape(inp_shape[i]),
                GraphError,
385
                "input %zu declared to be non-broadcastable but broacast "
M
Megvii Engine Team 已提交
386 387
                "actually happened",
                i);
388 389 390 391
    }
}

void Elemwise::add_input_layout_constraint() {
M
Megvii Engine Team 已提交
392
    for (auto i : input()) {
393 394 395 396 397
        i->add_layout_constraint_monotone();
    }
}

void Elemwise::call_megdnn_opr_exec(
M
Megvii Engine Team 已提交
398 399
        CompNode comp_node, megdnn::TensorNDArray& inp, const megdnn::TensorND& out,
        megdnn::Elemwise* opr, Elemwise* caller) {
400
    if (opr->param().mode == Mode::FUSE_MUL_ADD3 &&
M
Megvii Engine Team 已提交
401 402
        !(inp[2].layout.eq_layout(inp[0].layout) ||
          inp[2].layout.eq_layout(inp[1].layout) || inp[2].layout.is_scalar())) {
403
        if (caller && !caller->fuse_badlayout_warn_printed()) {
M
Megvii Engine Team 已提交
404 405
            mgb_log_debug(
                    "%s: FUSE_MUL_ADD3 input layouts mismatch: %s %s %s; "
406
                    "fallback to normal computing",
M
Megvii Engine Team 已提交
407
                    caller->cname(), inp[0].layout.to_string().c_str(),
408
                    inp[1].layout.to_string().c_str(),
M
Megvii Engine Team 已提交
409
                    inp[2].layout.to_string().c_str());
410 411 412
            caller->m_fuse_badlayout_warn_printed = true;
        }

M
Megvii Engine Team 已提交
413
        for (auto&& i : inp) {
414 415 416 417
            i.layout = i.layout.broadcast(out.layout);
        }

        megdnn::TensorNDArray run_inp(2);
M
Megvii Engine Team 已提交
418 419
        auto run = [&](Mode mode, const megdnn::TensorND& i0,
                       const megdnn::TensorND& i1, const megdnn::TensorND& out) {
420 421 422 423 424 425
            run_inp[0] = i0;
            run_inp[1] = i1;
            opr->param() = {mode};
            opr->exec(run_inp, out);
        };

M
Megvii Engine Team 已提交
426 427
        auto tmp = intl::get_temp_tensor(
                caller ? caller->owner_graph() : nullptr, comp_node, out.layout);
428 429 430 431 432
        auto tmpv = tmp.as_megdnn();

        MGB_TRY {
            run(Mode::MUL, inp[0], inp[1], tmpv);
            run(Mode::ADD, inp[2], tmpv, out);
M
Megvii Engine Team 已提交
433 434
        }
        MGB_FINALLY(opr->param() = {Mode::FUSE_MUL_ADD3});
435 436 437 438
        return;
    }

    if (opr->param().mode == Mode::FUSE_MUL_ADD4 &&
M
Megvii Engine Team 已提交
439 440 441 442
        !(inp[0].layout.eq_layout(inp[2].layout) &&
          inp[1].layout.eq_layout(inp[3].layout)) &&
        !(inp[0].layout.eq_layout(inp[3].layout) &&
          inp[1].layout.eq_layout(inp[2].layout))) {
443 444 445 446
        if (caller && !caller->fuse_badlayout_warn_printed()) {
            mgb_log_debug(
                    "%s: FUSE_MUL_ADD4 input layouts mismatch: %s %s %s %s; "
                    "fallback to normal computing",
M
Megvii Engine Team 已提交
447
                    caller->cname(), inp[0].layout.to_string().c_str(),
448 449
                    inp[1].layout.to_string().c_str(),
                    inp[2].layout.to_string().c_str(),
M
Megvii Engine Team 已提交
450
                    inp[3].layout.to_string().c_str());
451 452 453
            caller->m_fuse_badlayout_warn_printed = true;
        }

M
Megvii Engine Team 已提交
454
        for (auto&& i : inp) {
455 456 457 458
            i.layout = i.layout.broadcast(out.layout);
        }

        megdnn::TensorNDArray run_inp(2);
M
Megvii Engine Team 已提交
459 460
        auto run = [&](Mode mode, const megdnn::TensorND& i0,
                       const megdnn::TensorND& i1, const megdnn::TensorND& out) {
461 462 463 464 465 466
            run_inp[0] = i0;
            run_inp[1] = i1;
            opr->param() = {mode};
            opr->exec(run_inp, out);
        };

M
Megvii Engine Team 已提交
467 468
        auto tmp = intl::get_temp_tensor(
                caller ? caller->owner_graph() : nullptr, comp_node, out.layout);
469 470 471 472 473 474
        auto tmpv = tmp.as_megdnn();

        MGB_TRY {
            run(Mode::MUL, inp[0], inp[1], tmpv);
            run(Mode::MUL, inp[2], inp[3], out);
            run(Mode::ADD, out, tmpv, out);
M
Megvii Engine Team 已提交
475 476
        }
        MGB_FINALLY(opr->param() = {Mode::FUSE_MUL_ADD4});
477 478 479 480 481 482 483
        return;
    }

    // All Elemwise operations on QuantizedS32/QuantizedS8 are not related to
    // scale. MegDNN does not support computing Elemwise for
    // QuantizedS32/QuantizedS8, we translate the data type to Int32/Int8 before
    // passing to MegDNN.
M
Megvii Engine Team 已提交
484
    if (inp.size() && inp[0].layout.dtype.category() == DTypeCategory::QUANTIZED) {
485 486 487 488 489 490 491
        auto inp_dtype = inp[0].layout.dtype;
        DType compute_dtype;
        if (inp_dtype.enumv() == DTypeEnum::QuantizedS32) {
            compute_dtype = dtype::Int32();
        } else if (inp_dtype.enumv() == DTypeEnum::QuantizedS8) {
            compute_dtype = dtype::Int8();
        } else {
M
Megvii Engine Team 已提交
492 493 494 495
            mgb_throw(
                    MegBrainError, "Unsupported Quantized Elemwise Mode %s: %d on %s",
                    inp[0].layout.dtype.name(), int(opr->param().mode),
                    comp_node.to_string().c_str());
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
        }

        megdnn::TensorNDArray run_inp(inp);
        for (size_t i = 0; i < inp.size(); i++) {
            run_inp[i].layout.dtype = compute_dtype;
        }
        megdnn::TensorND run_out = out;
        run_out.layout.dtype = compute_dtype;
        opr->exec(run_inp, run_out);
        return;
    }

    opr->exec(inp, out);
}

511
#if MGB_ENABLE_GRAD
512 513
MGB_IMPL_OPR_GRAD(Elemwise) {
    SymbolVar i[5];
M
Megvii Engine Team 已提交
514 515
    SymbolVar i0(opr.input(0)), i1, i2, out(opr.output(0)), og{out_grad.at(0)}, result;
    for (size_t t = 0; t < opr.input().size(); ++t)
516 517 518 519 520 521 522 523
        i[t] = opr.input()[t];
    if (opr.input().size() >= 2)
        i1 = opr.input(1);
    if (opr.input().size() >= 3)
        i2 = opr.input(2);

    // negate after reduce, for better performance
    bool negate_result = false;
M
Megvii Engine Team 已提交
524 525 526 527 528
#define RET(_v)    \
    result = (_v); \
    break
#define EL1(_mode, _a)         Elemwise::make({_a}, Mode::_mode)
#define EL2(_mode, _a, _b)     Elemwise::make({_a, _b}, Mode::_mode)
529
#define EL3(_mode, _a, _b, _c) Elemwise::make({_a, _b, _c}, Mode::_mode)
M
Megvii Engine Team 已提交
530
#define RET_INVALID()          return InvalidGrad::make(opr, wrt_idx)
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 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

    using Mode = Elemwise::Mode;

    switch (opr.param().mode) {
        // unary
        case Mode::RELU:
        case Mode::FUSE_ADD_RELU:
            RET(EL2(SWITCH_GT0, out, og));
        case Mode::ABS:
            RET(EL2(ABS_GRAD, i0, og));
        case Mode::ACOS:
            negate_result = true;
            RET(og / EL1(SIN, out));
        case Mode::ASIN:
            RET(og / EL1(COS, out));
        case Mode::ATAN2:
            if (wrt_idx) {
                negate_result = true;
            }
            RET(og * i[!wrt_idx] / (i0 * i0 + i1 * i1));
        case Mode::CEIL:
            return nullptr;
        case Mode::COS:
            negate_result = true;
            RET(EL1(SIN, i0) * og);
        case Mode::EXP:
            RET(og * out);
        case Mode::EXPM1:
            RET(og * EL1(EXP, i0));
        case Mode::FLOOR:
            return nullptr;
        case Mode::LOG:
            RET(og / i0);
        case Mode::LOG1P:
            RET(og / (i0 + 1));
        case Mode::NEGATE:
            negate_result = true;
            RET(og);
        case Mode::SIGMOID:
        case Mode::FUSE_ADD_SIGMOID:
            RET(EL2(SIGMOID_GRAD, out, og));
        case Mode::SIN:
            RET(EL1(COS, i0) * og);
        case Mode::TANH:
        case Mode::FUSE_ADD_TANH:
            RET(EL2(TANH_GRAD, out, og));
        case Mode::FAST_TANH:
            RET(EL2(FAST_TANH_GRAD, i0, og));
        case Mode::ROUND:
            return nullptr;
        case Mode::ERF:
M
Megvii Engine Team 已提交
582
            RET(EL1(EXP, -i0 * i0) * 2 / static_cast<float>(sqrt(M_PI)) * og);
583 584 585 586 587 588 589 590
        case Mode::ERFINV:
            RET(EL1(EXP, out * out) * static_cast<float>(sqrt(M_PI)) / 2 * og);
        case Mode::ERFC:
            RET(-EL1(EXP, -i0 * i0) * 2 / static_cast<float>(sqrt(M_PI)) * og);
        case Mode::H_SWISH:
            RET(EL2(H_SWISH_GRAD, i0, og));
        case Mode::FUSE_ADD_H_SWISH:
            RET(EL2(H_SWISH_GRAD, (i0 + i1), og));
M
Megvii Engine Team 已提交
591 592
        case Mode::NOT:
            return nullptr;
593 594 595 596
        case Mode::SILU:
            RET(EL2(SILU_GRAD, i0, og));
        case Mode::GELU:
            RET(EL2(GELU_GRAD, i0, og));
597 598 599 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 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

        // binary
        case Mode::ABS_GRAD:
            if (wrt_idx == 0) {
                return nullptr;
            }
            RET(EL2(ABS_GRAD, i0, og));
        case Mode::ADD:
            RET(og);
        case Mode::FLOOR_DIV:
            return nullptr;
        case Mode::MAX:
            RET(EL3(COND_LEQ_MOV, i[!wrt_idx], i[wrt_idx], og));
        case Mode::MIN:
            RET(EL3(COND_LEQ_MOV, i[wrt_idx], i[!wrt_idx], og));
        case Mode::MOD:
            if (wrt_idx == 0) {
                RET(og);
            }
            RET_INVALID();
        case Mode::MUL:
            RET(og * i[!wrt_idx]);
        case Mode::POW:
            if (wrt_idx) {
                RET(out * EL1(LOG, i0) * og);
            }
            RET(og * i1 * EL2(POW, i0, i1 - 1));
        case Mode::SIGMOID_GRAD:
            if (wrt_idx == 0) {
                auto one = i0.make_scalar_dt(1), two = i0.make_scalar_dt(2);
                RET((one - i0 * two) * i1 * og);
            }
            RET(EL2(SIGMOID_GRAD, i0, og));
        case Mode::SUB:
            negate_result = wrt_idx;
            RET(og);
        case Mode::SWITCH_GT0:
            if (!wrt_idx)
                return nullptr;
            RET(EL2(SWITCH_GT0, i0, og));
        case Mode::TANH_GRAD:
            if (wrt_idx == 0) {
                auto mtwo = i0.make_scalar_dt(-2);
                RET(mtwo * i0 * i1 * og);
            }
            RET(EL2(TANH_GRAD, i0, og));
        case Mode::TRUE_DIV:
            if (wrt_idx == 0) {
                RET(og / i1);
            }
            negate_result = true;
            RET((og * i0) * EL2(POW, i1, i1.make_scalar(-2)));
        case Mode::LOG_SUM_EXP:
            if (wrt_idx == 0) {
                RET(og * EL1(SIGMOID, i0 - i1));
            }
            RET(og * EL1(SIGMOID, i1 - i0));
        case Mode::LT:
        case Mode::LEQ:
            return nullptr;
        case Mode::EQ:
            RET_INVALID();
M
Megvii Engine Team 已提交
659 660 661 662
        case Mode::OR:
        case Mode::XOR:
        case Mode::AND:
            return nullptr;
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679

        // ternary
        case Mode::COND_LEQ_MOV:
            if (wrt_idx <= 1)
                return nullptr;
            RET(EL3(COND_LEQ_MOV, i0, i1, og));

        // fuse oprs
        case Mode::FUSE_MUL_ADD3:
            if (wrt_idx < 2) {
                RET(og * i[wrt_idx ^ 1]);
            } else {
                RET(og);
            }
        case Mode::FUSE_MUL_ADD4:
            RET(og * i[wrt_idx ^ 1]);
        default:
M
Megvii Engine Team 已提交
680 681 682
            mgb_throw(
                    GraphError, "grad for elemwise mode %s unimplemented",
                    megdnn::Elemwise::ModeTrait::from_mode(opr.param().mode).name);
683 684 685 686 687 688 689
    }
#undef EL3
#undef EL2
#undef EL1
#undef RET

    if (opr.input_broadcastable()[wrt_idx]) {
M
Megvii Engine Team 已提交
690
        result = reduce_sum(result, opr::GetVarShape::make(opr.input(wrt_idx)));
691 692
    } else if (result.node()->owner_opr()->same_type<Broadcast>()) {
        // forward broadcast for optimizer to work
M
Megvii Engine Team 已提交
693 694
        result = opr::Broadcast::make(
                result.node()->owner_opr()->input(0),
695 696 697 698 699 700
                opr::GetVarShape::make(i[wrt_idx]));
    }
    if (negate_result)
        result = -result;
    return result.node();
}
701
#endif
702

M
Megvii Engine Team 已提交
703
VarNode* Elemwise::sum_grad_list(VarNode* wrt, VarNodeArray& grads) {
704 705 706 707 708 709 710
    mgb_assert(!grads.empty());
    if (grads.size() == 1)
        return grads[0];
#if MGB_ENABLE_COND_EXEC
    CondExecMerge::modify_grad_sum_list(wrt, grads);
#endif
    VarNodeArray mid_results;
M
Megvii Engine Team 已提交
711
    VarNode* ret;
712 713 714
    if (wrt->owner_graph()->options().graph_opt_level) {
        ret = gopt::GradSumListOptimizer{wrt, grads, mid_results}.get_sum();
    } else {
M
Megvii Engine Team 已提交
715
        ret = gopt::elemwise_reduce_var_list(grads, Elemwise::Mode::ADD, &mid_results);
716 717 718 719 720 721 722 723 724
    }
    mid_results.swap(grads);
    return ret;
}

void Elemwise::record_execute_deps(ExecDependencyArray& deps) {
    record_megdnn_opr(deps);
}

725 726 727
Elemwise::NodeProp* Elemwise::do_make_node_prop() const {
    auto ret = Super::do_make_node_prop();
    for (auto& inp : input()) {
M
Megvii Engine Team 已提交
728
        ret->add_dep_type_existing_var(inp, NodeProp::DepType::VALUE_ALLOW_EMPTY);
729 730 731 732
    }
    return ret;
}

733 734 735 736
/* =========================== TypeCvt =========================== */

MGB_DYN_TYPE_OBJ_FINAL_IMPL(TypeCvt);

M
Megvii Engine Team 已提交
737 738 739 740 741
TypeCvt::TypeCvt(VarNode* inp, DType dest_type, const OperatorNodeConfig& config)
        : Super{inp->owner_graph(),
                config,
                std::string("as") + dest_type.name(),
                {inp}} {
742 743 744 745 746 747 748 749
    init_megdnn_opr(*this, {});
    mgb_assert(dest_type.valid());
    add_input({inp});
    add_equivalence_component<ScalarHash<const void*>>(dest_type.handle());
    output(0)->dtype(dest_type).add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
}

SymbolVar TypeCvt::make(
M
Megvii Engine Team 已提交
750
        SymbolVar input, DType dest_type, const OperatorNodeConfig& config) {
751 752
    if (input.dtype() == dest_type)
        return input;
M
Megvii Engine Team 已提交
753
    return input.insert_single_output_opr<TypeCvt>(input.node(), dest_type, config);
754 755
}

M
Megvii Engine Team 已提交
756 757 758
void TypeCvt::perform(
        DeviceTensorND& dest, DType dest_type, const DeviceTensorND& src,
        intl::UniqPtrWithCN<megdnn::TypeCvt>& opr) {
759 760
    mgb_assert(src.comp_node() == opr.comp_node());
    mgb_assert(dest_type.valid());
761 762 763 764
    if (src.empty()) {
        mgb_assert(dest.empty());
        return;
    }
765 766 767 768 769 770 771 772 773 774
    if (src.dtype() == dest_type) {
        dest.copy_from(src);
        return;
    }
    src.comp_node().activate();
    dest.comp_node(src.comp_node()).dtype(dest_type).resize(src.shape());
    opr->exec(src.as_megdnn(), dest.as_megdnn());
}

void TypeCvt::add_input_layout_constraint() {
M
Megvii Engine Team 已提交
775
    for (auto i : input()) {
776 777 778 779 780 781
        i->add_layout_constraint_contiguous();
    }
}

TypeCvt::NodeProp* TypeCvt::do_make_node_prop() const {
    auto ret = Super::do_make_node_prop();
M
Megvii Engine Team 已提交
782
    ret->add_dep_type_existing_var(input(0), NodeProp::DepType::VALUE_ALLOW_EMPTY);
783 784 785
    return ret;
}

786
#if MGB_ENABLE_GRAD
787 788 789 790 791 792 793 794 795 796 797 798
MGB_IMPL_OPR_GRAD(TypeCvt) {
    MGB_MARK_USED_VAR(wrt_idx);
    auto itype = opr.input(0)->dtype(), otype = opr.output(0)->dtype();
    if (itype.category() == DTypeCategory::FLOAT &&
        otype.category() == DTypeCategory::INT) {
        return nullptr;
    }
    if (itype.category() != DTypeCategory::FLOAT) {
        return InvalidGrad::make(opr, 0);
    }
    return TypeCvt::make(out_grad[0], opr.input(0)->dtype()).node();
}
799
#endif
800 801

void TypeCvt::mem_plan_fwd_in2out_writable() {
M
Megvii Engine Team 已提交
802 803 804
    bool cond_low_bit = input(0)->dtype().is_low_bit() &&
                        output(0)->dtype().is_low_bit() &&
                        input(0)->dtype().low_bit() == output(0)->dtype().low_bit();
805 806 807 808
    bool cond_normal = !input(0)->dtype().is_low_bit() &&
                       !output(0)->dtype().is_low_bit() &&
                       input(0)->dtype().size() == output(0)->dtype().size();
    if ((cond_low_bit || cond_normal) && input(0)->layout().is_contiguous()) {
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
        output(0)->set_fwd_in2out_writable(input(0));
    }
}

void TypeCvt::scn_do_execute() {
    auto ovar = output(0)->dev_tensor().as_megdnn();
    for (size_t i = 0; i < ovar.layout.ndim; ++i) {
        if (!ovar.layout[i]) {
            // skip execution for empty var
            return;
        }
    }
    megdnn_opr()->exec(input(0)->dev_tensor().as_megdnn(), ovar);
}

void TypeCvt::init_output_static_infer_desc() {
    static StaticInferOpr<megdnn::TypeCvt> static_infer_opr;
    Super::init_output_static_infer_desc();

    using namespace cg::static_infer;

M
Megvii Engine Team 已提交
830
    auto infer_value = [this](DeviceTensorND& dest, const InpVal& inp) {
831 832 833 834 835
        auto sopr = static_infer_opr.lock();
        perform(dest, output(0)->dtype(), inp.val.at(0).value(), sopr());
        return true;
    };
    owner_graph()->static_infer_manager().register_value_infer(
M
Megvii Engine Team 已提交
836
            output(0), {SourceType::DEP, {{input(0), DepType::VALUE}}, infer_value});
837 838 839 840 841 842 843 844 845 846
}

void TypeCvt::record_execute_deps(ExecDependencyArray& deps) {
    record_megdnn_opr(deps);
}

/* =========================== AddUpdate =========================== */

MGB_DYN_TYPE_OBJ_FINAL_IMPL(AddUpdate);

M
Megvii Engine Team 已提交
847 848 849 850 851
AddUpdate::AddUpdate(
        VarNode* dest, VarNode* delta, const Param& param,
        const OperatorNodeConfig& config)
        : Super{dest->owner_graph(), config, "inplace_add", {dest, delta}},
          m_param{param} {
852
    auto dest_opr = dest->owner_opr();
M
Megvii Engine Team 已提交
853 854
    mgb_throw_if(
            dest_opr->same_type<ImmutableTensor>(), GraphError,
855
            "AddUpdate cannot be applied on ImmutableTensor; ");
856 857 858 859 860 861 862
    add_input({dest, delta});

    /*
     * here we tell the system that output(0) would force-update input(0); the
     * topo-sorting system would ensure that all the readers finish before
     * executing this AddUpdate operation
     */
M
Megvii Engine Team 已提交
863 864
    add_output(None)->set_fwd_in2out_writable_force(input(0)).add_flag(
            VarNode::Flag::NO_MEM_RECLAIM);
865

M
Megvii Engine Team 已提交
866 867
    mgb_assert(
            m_param.disable->dtype() == dtype::Int32{},
868 869 870 871 872 873 874 875 876
            "dtype of disable flag on AddUpdate must be Int32, got %s actually.",
            m_param.disable->dtype().name());

    add_equivalence_component<ScalarHash<void*>>(m_param.alpha.get());
    add_equivalence_component<ScalarHash<void*>>(m_param.beta.get());
    add_equivalence_component<ScalarHash<void*>>(m_param.bias.get());
    add_equivalence_component<ScalarHash<void*>>(m_param.disable.get());
}

M
Megvii Engine Team 已提交
877 878 879
SymbolVar AddUpdate::make(
        SymbolVar dest, SymbolVar delta, const Param& param,
        const OperatorNodeConfig& config) {
880 881 882 883 884 885 886 887 888 889 890 891
    delta = opr::TypeCvt::make(delta, dest.dtype());
    return dest.insert_single_output_opr<AddUpdate>(
            dest.node(), delta.node(), param, config);
}

cg::OperatorNodeBase::NodeProp* AddUpdate::do_make_node_prop() const {
    auto ret = Super::do_make_node_prop();
    ret->add_flag(NodeProp::Flag::FORCE_UPDATE_INPUT_VAR);
    return ret;
}

void AddUpdate::create_megdnn_opr() {
M
Megvii Engine Team 已提交
892 893
    set_megdnn_opr(
            intl::get_megdnn_handle(comp_node())->create_operator<megdnn::AddUpdate>());
894 895 896
}

void AddUpdate::scn_do_execute() {
M
Megvii Engine Team 已提交
897 898
    mgb_assert(
            m_param.disable->dtype() == dtype::Int32{},
899 900 901
            "dtype of disable flag on AddUpdate must be Int32, got %s actually.",
            m_param.disable->dtype().name());
    auto disable = m_param.disable->get_cast<int>();
M
Megvii Engine Team 已提交
902 903 904 905 906 907 908 909 910 911
    if (disable == 1)
        return;
    mgb_assert(
            disable == 0,
            "disable flag on AddUpdate can only be 0 or 1,"
            " got %d actually.",
            disable);

    auto&& dest = output(0)->dev_tensor();
    auto&& delta_nobrd = input(1)->dev_tensor();
912 913 914 915 916
    auto delta = delta_nobrd.sub(SubTensorSpec::make_from_offset_elem(
            delta_nobrd.layout().broadcast(dest.shape()), 0));
    mgb_assert(input(0)->dev_tensor().raw_ptr() == dest.raw_ptr());
    auto beta = m_param.beta->get_cast<float>();
    if (!m_param.alpha->get_cast<bool>() && beta == 1 &&
M
Megvii Engine Team 已提交
917
        !m_param.bias->get_cast<bool>()) {
918 919 920 921
        dest.copy_from_fixlayout(delta);
    } else {
        auto opr = static_cast<megdnn::AddUpdate*>(megdnn_opr());
        opr->param() = {
M
Megvii Engine Team 已提交
922 923
                m_param.alpha->get_cast<float>(), beta,
                m_param.bias->get_cast<float>()};
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
        opr->exec(dest.as_megdnn(), delta.as_megdnn());
    }
}

void AddUpdate::init_output_static_infer_desc() {
    using namespace cg::static_infer;

    owner_graph()->static_infer_manager().register_shape_infer(
            output(0), ShapeInferDesc::make_identity(input(0)));
}

void AddUpdate::record_execute_deps(ExecDependencyArray& deps) {
    record_megdnn_opr(deps);
}

939
#if MGB_ENABLE_GRAD
940 941 942 943
MGB_IMPL_OPR_GRAD(AddUpdate) {
    // actually valid, just not implemented
    return InvalidGrad::make(opr, wrt_idx);
}
944
#endif
945

946 947 948 949 950
/* =========================== Reduce =========================== */

class Reduce::KernScheduler {
    class ValueDep final : public ExecDependency {
        DeviceTensorStorage m_val;
M
Megvii Engine Team 已提交
951

952 953 954 955
    public:
        explicit ValueDep(DeviceTensorStorage val) : m_val(std::move(val)) {}
    };

M
Megvii Engine Team 已提交
956 957 958 959 960
public:
    bool has_actual_computing() const {
        mgb_assert(m_shape_computed);
        return !m_kern_param.empty() || m_apply_side_effect;
    }
961

M
Megvii Engine Team 已提交
962
    size_t workspace_size() const { return m_workspace_spec[2].end(); }
963

M
Megvii Engine Team 已提交
964
    bool shape_computed() const { return m_shape_computed; }
965

M
Megvii Engine Team 已提交
966 967 968 969
    //! init shapes in kern param
    void init_shapes(
            megdnn::Reduce* opr, CompNode comp_node, DType dtype, Mode mode,
            TensorShape ishp, TensorShape oshp, const Param::DataType data_type);
970

M
Megvii Engine Team 已提交
971 972
    void setup_kern_params_layout_and_mode(
            Mode mode, DType inp_dtype, TensorShape& inp_shp, const Param::DataType);
973

M
Megvii Engine Team 已提交
974 975 976
    void check_shapes(const TensorShape& ishp, const TensorShape& oshp) {
        mgb_assert(m_prev_ishp.eq_shape(ishp) && m_prev_oshp.eq_shape(oshp));
    }
977

M
Megvii Engine Team 已提交
978 979 980 981
    //! update pointers in kern param; the tensors must have been allocated
    void update_ptr(
            const DeviceTensorND& input, const DeviceTensorND& dest,
            const DeviceTensorND& workspace);
982

M
Megvii Engine Team 已提交
983 984 985
    void execute(
            megdnn::Reduce* opr, const DeviceTensorND& input,
            const DeviceTensorND& dest);
986

M
Megvii Engine Team 已提交
987 988 989 990 991 992
    void record_execute_deps(ExecDependencyArray& deps) {
        if (m_elemwise_trans_opr) {
            deps.emplace_back(std::make_unique<intl::MegDNNGraphDep>(
                    std::move(m_elemwise_trans_opr)));
        }
        if (m_typecvt_opr) {
993
            deps.emplace_back(
M
Megvii Engine Team 已提交
994
                    std::make_unique<intl::MegDNNGraphDep>(std::move(m_typecvt_opr)));
995
        }
M
Megvii Engine Team 已提交
996 997
        deps.emplace_back(std::make_unique<ValueDep>(m_side_affect_wkspc.storage()));
    }
998

M
Megvii Engine Team 已提交
999 1000 1001
private:
    struct KernParam {
        megdnn::TensorND input, output;
1002

M
Megvii Engine Team 已提交
1003 1004
        //! param passed to megdnn
        megdnn::param::Reduce kparam;
1005

M
Megvii Engine Team 已提交
1006
        megdnn::Workspace workspace;
1007

M
Megvii Engine Team 已提交
1008 1009
        KernParam(Mode mode, int32_t ra) : kparam{mode, ra} {}
    };
1010

M
Megvii Engine Team 已提交
1011 1012 1013 1014
    struct SubWorkspace {
        size_t size, offset;
        size_t end() const { return size + offset; }
    };
1015

M
Megvii Engine Team 已提交
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
    void update_kparam_for_elemwise_side_effect(
            CompNode comp_node, Mode mode, const Param::DataType data_type);

    bool m_shape_computed = false;
    std::vector<KernParam> m_kern_param;
    TensorShape m_prev_ishp, m_prev_oshp;
    SubWorkspace m_workspace_spec[3];  //! tmp output[2], kern workspce

    /*!
     * some reduce mode (like SUM_SQR) has side effect of element-wise
     * trans. If this is the case and there is no kernel param,
     * m_apply_side_effect would be non-null
     */
    thin_function<void(const DeviceTensorND& in, const DeviceTensorND& out)>
1030
            m_apply_side_effect;
M
Megvii Engine Team 已提交
1031 1032 1033 1034
    std::unique_ptr<megdnn::Elemwise> m_elemwise_trans_opr;
    std::unique_ptr<megdnn::TypeCvt> m_typecvt_opr;
    std::unique_ptr<megdnn::Fill> m_fill_opr;
    DeviceTensorND m_side_affect_wkspc;
1035 1036
};

M
Megvii Engine Team 已提交
1037 1038
void Reduce::KernScheduler::setup_kern_params_layout_and_mode(
        Mode mode, DType inp_dtype, TensorShape& ishp,
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
        const Param::DataType data_type) {
    auto prev_dtype = inp_dtype;
    for (size_t idx = 0; idx < m_kern_param.size(); ++idx) {
        auto&& i = m_kern_param[idx];

#if !MEGDNN_DISABLE_FLOAT16
        if (idx == 0 && data_type == Param::DataType::FLOAT_O32xC32) {
            i.input.layout.dtype = inp_dtype;
            i.output.layout.dtype = dtype::Float32();
            i.kparam.data_type = data_type;
        } else if (data_type == Param::DataType::FLOAT_O16xC32) {
            i.input.layout.dtype = prev_dtype;
            if (idx + 1 == m_kern_param.size()) {
                i.output.layout.dtype = dtype::Float16();
                i.kparam.data_type = data_type;
M
Megvii Engine Team 已提交
1054
            } else {
1055 1056 1057 1058 1059 1060
                i.output.layout.dtype = dtype::Float32();
                i.kparam.data_type = Param::DataType::FLOAT_O32xC32;
            }
        } else
#endif
        {
M
Megvii Engine Team 已提交
1061 1062 1063
            mgb_assert(
                    data_type == Param::DataType::DEFAULT ||
                    (data_type == Param::DataType::FLOAT_O32xC32 && idx));
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
            i.input.layout.dtype = prev_dtype;
            i.output.layout.dtype = prev_dtype;
            i.kparam.data_type = Param::DataType::DEFAULT;
        }
        prev_dtype = i.output.layout.dtype;

        i.input.layout.init_contiguous_stride(ishp);
        ishp.shape[i.kparam.axis] = 1;
        i.output.layout.init_contiguous_stride(ishp);
    }
    if (mode == Mode::SUM_SQR) {
M
Megvii Engine Team 已提交
1075
        for (size_t i = 1; i < m_kern_param.size(); ++i)
1076 1077 1078 1079 1080
            m_kern_param[i].kparam.mode = Mode::SUM;
    }
}

void Reduce::KernScheduler::init_shapes(
M
Megvii Engine Team 已提交
1081
        megdnn::Reduce* opr, CompNode comp_node, DType inp_dtype, Mode mode,
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
        TensorShape ishp, TensorShape oshp, const Param::DataType data_type) {
    mgb_assert(ishp.ndim && oshp.ndim);

    if (ishp.eq_shape(m_prev_ishp) && oshp.eq_shape(m_prev_oshp))
        return;

    m_prev_ishp = ishp;
    m_prev_oshp = oshp;

    m_kern_param.clear();

    if (oshp.is_scalar()) {
        // if ishp is non-contiguous, add_layout_constraint_contiguous would be
        // added; so we do not have to worry about this
        ishp.shape[0] = ishp.total_nr_elems();
        ishp.ndim = 1;
    }

M
Megvii Engine Team 已提交
1100 1101
    mgb_assert(
            oshp.ndim == ishp.ndim,
1102 1103 1104
            "input and output ndim mismatch for reduction: ishp=%s oshp=%s",
            ishp.to_string().c_str(), oshp.to_string().c_str());

M
Megvii Engine Team 已提交
1105
    for (size_t i = 0; i < ishp.ndim; ++i) {
1106
        if (ishp.shape[i] != oshp.shape[i]) {
M
Megvii Engine Team 已提交
1107 1108
            mgb_assert(
                    oshp.shape[i] == 1,
1109 1110 1111 1112 1113 1114
                    "input and output shape mismatch for reduction: "
                    "ishp=%s oshp=%s",
                    ishp.to_string().c_str(), oshp.to_string().c_str());
        }
    }

M
Megvii Engine Team 已提交
1115
    auto remove_axis = [](TensorShape& shp, size_t ax) {
1116
        mgb_assert(shp.ndim > 1);
M
Megvii Engine Team 已提交
1117
        for (auto i = ax + 1; i < shp.ndim; ++i)
1118
            shp.shape[i - 1] = shp.shape[i];
M
Megvii Engine Team 已提交
1119
        --shp.ndim;
1120 1121 1122
    };

    // collapse consecutive shape-1 axes in oshp
M
Megvii Engine Team 已提交
1123
    for (size_t i = 0; i < oshp.ndim; ++i) {
1124 1125
        auto start = i;
        while (i < oshp.ndim && oshp.shape[i] == 1)
M
Megvii Engine Team 已提交
1126
            ++i;
1127 1128

        if (start + 1 < i) {
M
Megvii Engine Team 已提交
1129
            for (auto j = start + 1; j < i; ++j)
1130 1131
                ishp.shape[start] *= ishp.shape[j];

M
Megvii Engine Team 已提交
1132
            for (auto j = start + 1; j < i; ++j) {
1133 1134 1135 1136 1137 1138 1139 1140
                remove_axis(ishp, start + 1);
                remove_axis(oshp, start + 1);
            }

            i = start;
        }
    }

M
Megvii Engine Team 已提交
1141
    for (uint32_t i = 0; i < ishp.ndim; ++i) {
1142 1143 1144 1145 1146 1147
        if (ishp.shape[i] != oshp.shape[i]) {
            mgb_assert(oshp.shape[i] == 1);
            m_kern_param.push_back({mode, static_cast<int32_t>(i)});
        }
    }
    // sort according to reduction size, so workspace can be smaller
M
Megvii Engine Team 已提交
1148 1149 1150
    small_sort(
            m_kern_param.begin(), m_kern_param.end(),
            [&](const KernParam& a, const KernParam& b) {
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
                return ishp.shape[a.kparam.axis] > ishp.shape[b.kparam.axis];
            });

    // init kparam input/output layout
    setup_kern_params_layout_and_mode(mode, inp_dtype, ishp, data_type);

    // init workspace size
    memset(m_workspace_spec, 0, sizeof(m_workspace_spec));

    for (auto&& i : m_kern_param) {
        opr->param() = i.kparam;
M
Megvii Engine Team 已提交
1162
        i.workspace.size = opr->get_workspace_in_bytes(i.input.layout, i.output.layout);
1163 1164 1165 1166 1167 1168
        update_max(m_workspace_spec[2].size, i.workspace.size);
    }

    mgb_assert(ishp.eq_shape(oshp));

    if (m_kern_param.size() >= 2) {
M
Megvii Engine Team 已提交
1169
        m_workspace_spec[0].size = m_kern_param[1].input.layout.span().high_byte;
1170 1171
    }
    if (m_kern_param.size() >= 3) {
M
Megvii Engine Team 已提交
1172
        m_workspace_spec[1].size = m_kern_param[2].input.layout.span().high_byte;
1173 1174 1175
    }

    auto align = comp_node.get_mem_addr_alignment();
M
Megvii Engine Team 已提交
1176 1177 1178
    for (int i = 0; i < 2; ++i) {
        m_workspace_spec[i + 1].offset =
                get_aligned_power2(m_workspace_spec[i].end(), align);
1179 1180 1181 1182 1183 1184 1185 1186
    }

    update_kparam_for_elemwise_side_effect(comp_node, mode, data_type);

    m_shape_computed = true;
}

void Reduce::KernScheduler::update_kparam_for_elemwise_side_effect(
M
Megvii Engine Team 已提交
1187
        CompNode comp_node, Mode mode, const Param::DataType data_type) {
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    m_apply_side_effect = nullptr;
    m_elemwise_trans_opr.reset();
    m_typecvt_opr.reset();
    if (!m_kern_param.empty()) {
        // no need to set m_apply_side_effect
        return;
    } /* else */
    // case A: input.layout == output.layout
    // case B: input.total_nr_elems == 1 and output is a scalar

    if (mode == Mode::SUM_SQR) {
M
Megvii Engine Team 已提交
1199 1200
        m_elemwise_trans_opr =
                intl::get_megdnn_handle(comp_node)->create_operator<megdnn::Elemwise>();
1201 1202 1203 1204
        m_elemwise_trans_opr->param() = {Elemwise::Mode::MUL};
    }
    if (data_type != Param::DataType::DEFAULT) {
        m_side_affect_wkspc = DeviceTensorND{comp_node, dtype::Float32()};
M
Megvii Engine Team 已提交
1205 1206
        m_typecvt_opr =
                intl::get_megdnn_handle(comp_node)->create_operator<megdnn::TypeCvt>();
1207 1208 1209 1210
    }
    if (!m_typecvt_opr && !m_elemwise_trans_opr)
        return;

M
Megvii Engine Team 已提交
1211
    m_apply_side_effect = [this](const DeviceTensorND& in, const DeviceTensorND& out) {
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
        if (m_typecvt_opr) {
            m_side_affect_wkspc.resize(in.shape());
        }
        if (!m_elemwise_trans_opr) {
            mgb_assert(m_typecvt_opr);
            m_typecvt_opr->exec(in.as_megdnn(), out.as_megdnn());
            return;
        }
        auto im = in.as_megdnn();
        megdnn::TensorND wm;
        if (m_typecvt_opr && in.dtype() != m_side_affect_wkspc.dtype()) {
            m_side_affect_wkspc.resize(in.shape());
            wm = m_side_affect_wkspc.as_megdnn();
            m_typecvt_opr->exec(im, wm);
        } else {
            wm = im;
        }
        if (m_typecvt_opr && wm.layout.dtype != out.dtype()) {
            m_elemwise_trans_opr->exec({wm, wm}, wm);
            m_typecvt_opr->exec(wm, out.as_megdnn());
        } else {
M
Megvii Engine Team 已提交
1233
            auto&& wshp = wm.layout;
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
            if (wshp.ndim != out.layout().ndim) {
                // to ensure that wkspc.ndim equals out.ndim in the case:
                // wkspc.shape=(1, 1, ..., 1) and out.shape=(1), otherwise it
                // may lead the 'TensorShape Dimension' assertion failed in
                // the following broadcast operator
                mgb_assert(wshp.total_nr_elems() == 1 && out.layout().ndim == 1);
                wshp.ndim = 1;
            }
            m_elemwise_trans_opr->exec({wm, wm}, out.as_megdnn());
        }
    };
}

void Reduce::KernScheduler::update_ptr(
M
Megvii Engine Team 已提交
1248 1249
        const DeviceTensorND& input, const DeviceTensorND& dest,
        const DeviceTensorND& workspace) {
1250 1251 1252 1253 1254
    auto dtype = dest.layout().dtype;
    mgb_assert(dtype.valid());
    mgb_assert(m_shape_computed);

    if (workspace_size()) {
M
Megvii Engine Team 已提交
1255 1256
        mgb_assert(
                workspace.layout().dtype == dtype::Byte() &&
1257 1258 1259 1260 1261 1262 1263
                workspace.layout().ndim == 1 &&
                workspace.shape()[0] >= workspace_size());
    }

    if (m_kern_param.empty())
        return;

M
Megvii Engine Team 已提交
1264 1265
    mgb_assert(
            input.layout().total_nr_elems() ==
1266
            m_kern_param[0].input.layout.total_nr_elems());
M
Megvii Engine Team 已提交
1267 1268
    mgb_assert(
            dest.shape().total_nr_elems() ==
1269 1270 1271
            m_kern_param.back().output.layout.total_nr_elems());
    m_kern_param[0].input.raw_ptr = const_cast<dt_byte*>(input.raw_ptr());

M
Megvii Engine Team 已提交
1272 1273 1274 1275 1276 1277 1278 1279
    dt_byte *workspace_begin = workspace_size()
                                     ? const_cast<dt_byte*>(workspace.raw_ptr())
                                     : nullptr,
            *tmp_reduce_ptr[2] =
                    {workspace_begin + m_workspace_spec[0].offset,
                     workspace_begin + m_workspace_spec[1].offset},
            *kern_workspace = workspace_begin + m_workspace_spec[2].offset;
    for (size_t i = 0; i < m_kern_param.size() - 1; ++i) {
1280 1281 1282 1283
        auto optr = tmp_reduce_ptr[i % 2];
        m_kern_param[i].output.raw_ptr = optr;
        m_kern_param[i + 1].input.raw_ptr = optr;
    }
M
Megvii Engine Team 已提交
1284
    for (auto&& i : m_kern_param)
1285 1286 1287 1288 1289
        i.workspace.raw_ptr = kern_workspace;
    m_kern_param.back().output.raw_ptr = const_cast<dt_byte*>(dest.raw_ptr());
}

void Reduce::KernScheduler::execute(
M
Megvii Engine Team 已提交
1290
        megdnn::Reduce* opr, const DeviceTensorND& input, const DeviceTensorND& dest) {
1291 1292 1293 1294 1295 1296 1297
    if (m_apply_side_effect) {
        mgb_assert(m_kern_param.empty());
        m_apply_side_effect(input, dest);
        return;
    }

    mgb_assert(!m_kern_param.empty());
1298 1299 1300 1301 1302

    // empty input
    if (input.shape_valid() && input.empty()) {
        auto mode = m_kern_param[0].kparam.mode;
        if (!m_fill_opr) {
M
Megvii Engine Team 已提交
1303 1304
            m_fill_opr = intl::get_megdnn_handle(dest.comp_node())
                                 ->create_operator<megdnn::Fill>();
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
        }
        std::string err_msg;
        switch (mode) {
            case Reduce::Mode::SUM:
                if (!dest.empty()) {
                    m_fill_opr->param() = 0;
                    m_fill_opr->exec(dest.as_megdnn(), {});
                }
                break;
            case Reduce::Mode::PRODUCT:
                if (!dest.empty()) {
                    m_fill_opr->param() = 1;
                    m_fill_opr->exec(dest.as_megdnn(), {});
                }
                break;
            case Reduce::Mode::MEAN:
M
Megvii Engine Team 已提交
1321 1322
                err_msg = "mean";
                break;
1323
            case Reduce::Mode::MIN:
M
Megvii Engine Team 已提交
1324 1325
                err_msg = "min";
                break;
1326
            case Reduce::Mode::MAX:
M
Megvii Engine Team 已提交
1327 1328
                err_msg = "max";
                break;
1329
            case Reduce::Mode::SUM_SQR:
M
Megvii Engine Team 已提交
1330 1331
                err_msg = "sum_sqr";
                break;
1332 1333 1334 1335 1336
            default:
                mgb_throw(MegBrainError, "bad reduce mode");
        }
        if (!err_msg.empty()) {
            mgb_throw(
M
Megvii Engine Team 已提交
1337 1338
                    MegBrainError, "empty input is not allowed for reduce mode: %s",
                    err_msg.c_str());
1339 1340 1341
        }
        return;
    }
M
Megvii Engine Team 已提交
1342 1343
    mgb_assert(
            input.layout().is_contiguous() &&
1344 1345
            input.raw_ptr() == m_kern_param[0].input.raw_ptr &&
            dest.raw_ptr() == m_kern_param.back().output.raw_ptr);
M
Megvii Engine Team 已提交
1346
    for (auto&& i : m_kern_param) {
1347 1348 1349 1350 1351 1352 1353 1354 1355
        opr->param() = i.KernParam::kparam;
        opr->exec(i.input, i.output, i.workspace);
    }
}

class Reduce::OutTensorShapeExtender {
public:
    OutTensorShapeExtender(const TensorShape& ishp, const TensorShape& oshp)
            : m_oshp(oshp) {
M
Megvii Engine Team 已提交
1356 1357 1358 1359 1360 1361
        mgb_assert(
                oshp.ndim <= ishp.ndim,
                "output ndim should be less and equal than input ndim for "
                "reduction: "
                "ishp=%s oshp=%s",
                ishp.to_string().c_str(), oshp.to_string().c_str());
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
        // Ex. ishp = (a, b, c, d), oshp = (c, d)
        if (!oshp.is_scalar() && ishp.ndim != oshp.ndim) {
            size_t ndim_diff = ishp.ndim - oshp.ndim;
            auto&& canonized_oshp = m_canonized_oshp_storage.emplace(oshp);
            for (size_t i = 0; i < ishp.ndim; ++i)
                if (i < ndim_diff)
                    canonized_oshp[i] = 1;
                else
                    canonized_oshp[i] = oshp[i - ndim_diff];
            canonized_oshp.ndim = ishp.ndim;
        }
    }

    const TensorShape& get() const {
        return m_canonized_oshp_storage.valid() ? m_canonized_oshp_storage.val()
                                                : m_oshp;
    }

private:
    Maybe<TensorShape> m_canonized_oshp_storage;
    const TensorShape& m_oshp;
};

MGB_DYN_TYPE_OBJ_FINAL_IMPL(Reduce);
M
Megvii Engine Team 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394
Reduce::Reduce(
        VarNode* inp, VarNode* target_shape, const Param& param,
        const OperatorNodeConfig& config)
        : Super{inp->owner_graph(),
                config,
                ssprintf("reduce%d", static_cast<int>(param.mode)),
                {inp}},
          m_param{param},
          m_kern_scheduler{std::make_unique<KernScheduler>()} {
1395 1396 1397 1398
    add_input({inp});

    if (inp->dtype().enumv() == DTypeEnum::Quantized8Asymm &&
        inp->dtype().category() == DTypeCategory::QUANTIZED) {
M
Megvii Engine Team 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407
        mgb_assert(
                param.mode != Param::Mode::PRODUCT,
                "Reduce does not support PRODUCT mode on quantized input");
        mgb_assert(
                param.mode != Param::Mode::SUM_SQR,
                "Reduce does not support SUM_SQR mode on quantized input");
        mgb_assert(
                param.mode != Param::Mode::SUM,
                "Reduce does not support SUM mode on quantized input");
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
    }

    DType out_dtype;
    switch (param.data_type) {
        case Param::DataType::DEFAULT:
            out_dtype = inp->dtype();
            break;
#if !MEGDNN_DISABLE_FLOAT16
        case Param::DataType::FLOAT_O16xC32:
            out_dtype = dtype::Float16();
            break;
        case Param::DataType::FLOAT_IO16xC32:
            mgb_assert(false);
#endif
        case Param::DataType::FLOAT_O32xC32:
            out_dtype = dtype::Float32();
            break;
        case Param::DataType::QUINT_I8xO32:
            out_dtype = dtype::QuantizedS32(
                    inp->dtype().param<dtype::Quantized8Asymm>().scale);
            break;
        case Param::DataType::QINT_I8xO32:
M
Megvii Engine Team 已提交
1430 1431
            out_dtype =
                    dtype::QuantizedS32(inp->dtype().param<dtype::QuantizedS8>().scale);
1432 1433
            break;
        default:
M
Megvii Engine Team 已提交
1434
            mgb_throw(GraphError, "invalid param data_type: %d", int(param.data_type));
1435
    }
M
Megvii Engine Team 已提交
1436
    add_output(None)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE).dtype(out_dtype);
1437 1438 1439 1440 1441
    cg::add_workspace_output(this);

    add_equivalence_component<PODHash<Param>>(&m_param);

    if (param.axis >= -MEGDNN_MAX_NDIM && param.axis < MEGDNN_MAX_NDIM) {
M
Megvii Engine Team 已提交
1442 1443
        mgb_throw_if(
                target_shape, GraphError,
1444 1445 1446
                "could not specify both axis and target shape");
        m_is_symtshp = false;
    } else {
M
Megvii Engine Team 已提交
1447 1448
        mgb_throw_if(
                !target_shape, GraphError, "neither axis or target_shape specified");
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
        add_input({target_shape});
        m_is_symtshp = true;

        outshape_by_symvar_enable(0, 1);
    }
}

Reduce::~Reduce() = default;

SymbolVar Reduce::make(
        SymbolVar src, Param param, SymbolVar target_shape,
M
Megvii Engine Team 已提交
1460
        const OperatorNodeConfig& config) {
1461
    if (param.data_type == Param::DataType::FLOAT_IO16xC32) {
M
Megvii Engine Team 已提交
1462 1463
        mgb_log_warn(
                "DataType FLOAT_IO16xC32 has been deprecated "
1464 1465 1466 1467
                "use FLOAT_O16xC32 instead");
        param.data_type = Param::DataType::FLOAT_O16xC32;
    }

M
Megvii Engine Team 已提交
1468
    if (param.mode == Mode::SUM && src.node()->owner_opr()->same_type<Elemwise>()) {
1469
        // replace sum(x^2) by sum_sqr(x)
M
Megvii Engine Team 已提交
1470
        auto&& opr = src.node()->owner_opr()->cast_final<Elemwise>();
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
        if (opr.param().mode == Elemwise::Mode::POW) {
            mgb_assert(opr.input().size() == 2);
            auto pow = SymbolVar{opr.input(1)}.as_immutable_scalar();
            if (pow.valid() && pow->get_cast<float>() == 2) {
                src = opr.input(0);
                param.mode = Mode::SUM_SQR;
            }
        }
    }
    return src.insert_single_output_opr<Reduce>(
            src.node(), target_shape.node(), param, config);
}

void Reduce::outshape_by_symvar_do_get_output_shape(
M
Megvii Engine Team 已提交
1485
        TensorShape& dest, const ShapeInferInfo& shpinfo) {
1486 1487 1488 1489 1490
    cg::copy_tensor_value_to_shape(dest, *shpinfo.shpval_inp_val.at(0));
}

void Reduce::init_output_static_infer_desc() {
    using namespace cg::static_infer;
M
Megvii Engine Team 已提交
1491
    auto&& mgr = owner_graph()->static_infer_manager();
1492 1493 1494 1495 1496 1497 1498

    // infer output shape
    if (m_is_symtshp) {
        // reduce to target shape
        Super::init_output_static_infer_desc();
    } else {
        // reduce along axis
M
Megvii Engine Team 已提交
1499
        auto infer_shape = [this](TensorShape& dest, const InpVal& inp) {
1500
            dest = inp.val.at(0).shape();
M
Megvii Engine Team 已提交
1501 1502 1503 1504 1505
            mgb_assert(
                    m_param.axis < static_cast<int>(dest.ndim) &&
                            m_param.axis >= -static_cast<int>(dest.ndim),
                    "invalid axis for reduction: shape=%s axis=%d",
                    dest.to_string().c_str(), m_param.axis);
1506 1507 1508 1509 1510 1511 1512
            int real_axis = m_param.axis;
            if (real_axis < 0)
                real_axis += dest.ndim;
            dest.shape[real_axis] = 1;
            return true;
        };
        mgr.register_shape_infer(
M
Megvii Engine Team 已提交
1513 1514
                output(0),
                {SourceType::DEP, {{input(0), DepType::SHAPE}}, infer_shape});
1515 1516 1517
    }

    // infer workspace
M
Megvii Engine Team 已提交
1518
    auto infer_workspace = [this](TensorShape& dest, const InpVal& inp) {
1519 1520 1521 1522 1523
        init_kern_sched_shape(inp.val[0].shape(), inp.val[1].shape());
        dest.ndim = 1;
        dest.shape[0] = m_kern_scheduler->workspace_size();
        return true;
    };
M
Megvii Engine Team 已提交
1524 1525 1526 1527
    mgr.register_shape_infer(
            output(1), {SourceType::DEP,
                        {{input(0), DepType::SHAPE}, {output(0), DepType::SHAPE}},
                        infer_workspace});
1528 1529 1530 1531

    // infer value

    static StaticInferOpr<megdnn::Reduce> static_infer_opr;
M
Megvii Engine Team 已提交
1532
    auto infer_value = [this](DeviceTensorND& dest, const InpVal& inp) {
1533 1534
        DeviceTensorND workspace;
        auto sopr = static_infer_opr.lock();
M
Megvii Engine Team 已提交
1535 1536
        perform(m_param.mode, dest, workspace, inp.val[0].value(), output(0)->dtype(),
                inp.val.at(1).shape(), sopr(), m_param.data_type);
1537 1538 1539
        return true;
    };

M
Megvii Engine Team 已提交
1540 1541 1542 1543
    mgr.register_value_infer(
            output(0), {SourceType::DEP,
                        {{input(0), DepType::VALUE}, {output(0), DepType::SHAPE}},
                        infer_value});
1544 1545
}

M
Megvii Engine Team 已提交
1546
void Reduce::init_kern_sched_shape(const TensorShape& ishp, const TensorShape& oshp) {
1547 1548
    OutTensorShapeExtender extender(ishp, oshp);
    auto&& canonized_oshp = extender.get();
M
Megvii Engine Team 已提交
1549 1550 1551
    m_kern_scheduler->init_shapes(
            static_cast<megdnn::Reduce*>(megdnn_opr()), comp_node(), input(0)->dtype(),
            m_param.mode, ishp, canonized_oshp, m_param.data_type);
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
}

cg::OperatorNodeBase::OprEventCallback Reduce::get_opr_event_callback() {
    auto on_mem_status_changed = [this]() {
        auto&& ishp = input(0)->shape();
        auto&& oshp = output(0)->shape();
        OutTensorShapeExtender extender(ishp, oshp);
        auto&& canonized_oshp = extender.get();
        m_kern_scheduler->check_shapes(input(0)->shape(), canonized_oshp);
        m_kern_scheduler->update_ptr(
                input(0)->dev_tensor(), output(0)->dev_tensor(),
M
Megvii Engine Team 已提交
1563
                output(1)->shape()[0] ? output(1)->dev_tensor() : DeviceTensorND{});
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
    };
    return {on_mem_status_changed};
}

void Reduce::mem_plan_fwd_in2out_readonly() {
    init_kern_sched_shape(input(0)->shape(), output(0)->shape());

    if (!m_kern_scheduler->has_actual_computing()) {
        // forward memory if no actual computing needed

        if (!output(0)->mem_plan().valid()) {
            // output(0) is dynamic but current is staic alloc phase (for
            // workspace)
            return;
        }
        auto&& ily = input(0)->layout();
        auto&& oly = output(0)->layout();
        const TensorLayout* fwd_spec = nullptr;
        Maybe<TensorLayout> ily_modified_storage;

        if (!ily.eq_shape(oly)) {
            auto&& ily_modified = ily_modified_storage.emplace(ily);
            mgb_assert(ily.ndim > oly.ndim);
            for (size_t i = 0; i < ily.ndim - oly.ndim; ++i)
                mgb_assert(ily.shape[i] == 1);
            ily_modified = ily_modified.reshape(oly);
            fwd_spec = &ily_modified;
        } else {
            fwd_spec = &ily;
        }
        m_mem_fwd_success = output(0)->set_fwd_in2out_readonly(
                input(0), SubTensorSpec::make_from_layout(*fwd_spec));
    }
}

void Reduce::add_input_layout_constraint() {
    if (!cg::is_static_var_shape(output(0))) {
        // output shape can not be inferred; require contiguous to be safe
        input(0)->add_layout_constraint_contiguous();
    } else {
M
Megvii Engine Team 已提交
1604 1605
        auto check = [this](const TensorLayout& ily) {
            auto&& mgr = owner_graph()->static_infer_manager();
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
            auto oshp = mgr.infer_shape(output(0));
            init_kern_sched_shape(ily, oshp);
            if (m_kern_scheduler->has_actual_computing())
                return ily.is_contiguous();
            return true;
        };
        input(0)->add_layout_constraint(check);
    }
}

void Reduce::scn_do_execute() {
    auto&& inp = input(0)->dev_tensor();
    auto&& out = output(0)->dev_tensor();
    auto&& ishp = input(0)->shape();
    auto&& oshp = output(0)->shape();
    const DeviceTensorND* out_ptr;
    Maybe<DeviceTensorND> canonized_storage;
    OutTensorShapeExtender extender(ishp, oshp);
    auto&& canonized_oshp = extender.get();
    if (canonized_oshp.ndim != out.shape().ndim) {
        auto&& canonized_out = canonized_storage.emplace(out);
        canonized_out.reset(
                canonized_out.storage(),
                canonized_out.layout().reshape(canonized_oshp));
        out_ptr = &canonized_out;
    } else {
        out_ptr = &out;
    }
    // shape initialized either in deducing workspace,
    // mem_plan_fwd_in2out_readonly, or check input layout
    m_kern_scheduler->check_shapes(inp.shape(), out_ptr->shape());

    if (m_kern_scheduler->has_actual_computing()) {
M
Megvii Engine Team 已提交
1639 1640
        m_kern_scheduler->execute(
                static_cast<megdnn::Reduce*>(megdnn_opr()), inp, *out_ptr);
1641 1642 1643
    } else {
        // no reduction needed, just forward
        if (m_mem_fwd_success) {
M
Megvii Engine Team 已提交
1644 1645 1646 1647
            mgb_assert(
                    inp.raw_ptr() == out_ptr->raw_ptr() &&
                    out_ptr->layout().total_nr_elems() ==
                            inp.layout().total_nr_elems());
1648 1649
        } else {
            if (!out_ptr->shape().eq_shape(inp.shape())) {
M
Megvii Engine Team 已提交
1650 1651 1652
                mgb_assert(
                        out_ptr->shape().is_scalar() &&
                        inp.shape().total_nr_elems() == 1);
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
                out_ptr->sub(SubTensorSpec::make_from_layout(inp.layout()))
                        .copy_from_fixlayout(inp);
            } else {
                out_ptr->copy_from_fixlayout(inp);
            }
        }
    }
}

void Reduce::perform(
M
Megvii Engine Team 已提交
1663 1664 1665 1666 1667 1668
        Mode mode, DeviceTensorND& dest, DeviceTensorND& workspace,
        const DeviceTensorND& input, const DType& target_dtype,
        const TensorShape& target_shape, intl::UniqPtrWithCN<megdnn::Reduce>& opr,
        const Param::DataType data_type) {
    mgb_assert(
            !dest.storage().comp_node_valid() || opr.comp_node() == dest.comp_node());
1669
    KernScheduler ksched;
1670 1671
    OutTensorShapeExtender extender(input.shape(), target_shape);
    auto&& canonized_oshp = extender.get();
M
Megvii Engine Team 已提交
1672 1673 1674
    ksched.init_shapes(
            opr.get(), opr.comp_node(), input.layout().dtype, mode, input.shape(),
            canonized_oshp, data_type);
1675 1676

    if (!ksched.has_actual_computing()) {
M
Megvii Engine Team 已提交
1677
        mgb_assert(target_shape.total_nr_elems() == input.layout().total_nr_elems());
1678 1679 1680 1681 1682
        dest.copy_from(input);
        dest.reset(dest.storage(), {target_shape, dest.dtype()});
        return;
    }

M
Megvii Engine Team 已提交
1683
    workspace.comp_node(opr.comp_node()).dtype(dtype::Byte());
1684 1685
    size_t workspace_size = ksched.workspace_size();
    DeviceTensorND input_contig_storage;
M
Megvii Engine Team 已提交
1686
    const DeviceTensorND* input_contig = &input;
1687 1688 1689
    if (!input.layout().is_contiguous()) {
        auto offset = get_aligned_power2(
                workspace_size, opr.comp_node().get_mem_addr_alignment());
M
Megvii Engine Team 已提交
1690
        workspace_size = offset + input.dtype().size(input.shape().total_nr_elems());
1691 1692

        workspace.resize({workspace_size});
M
Megvii Engine Team 已提交
1693 1694 1695
        input_contig_storage
                .reset(workspace.storage().sub(offset), {input.shape(), input.dtype()})
                .copy_from(input);
1696 1697 1698 1699 1700 1701
        input_contig = &input_contig_storage;
    } else {
        workspace.resize({workspace_size});
    }

    opr.comp_node().activate();
1702
    dest.comp_node(opr.comp_node()).dtype(target_dtype).resize(target_shape);
1703 1704 1705 1706
    ksched.update_ptr(*input_contig, dest, workspace);
    ksched.execute(opr.get(), *input_contig, dest);
}

1707 1708
Reduce::NodeProp* Reduce::do_make_node_prop() const {
    auto ret = Super::do_make_node_prop();
M
Megvii Engine Team 已提交
1709
    ret->add_dep_type_existing_var(input(0), NodeProp::DepType::VALUE_ALLOW_EMPTY);
1710 1711 1712
    return ret;
}

1713
void Reduce::create_megdnn_opr() {
M
Megvii Engine Team 已提交
1714 1715
    set_megdnn_opr(
            intl::get_megdnn_handle(comp_node())->create_operator<megdnn::Reduce>());
1716 1717
}

1718
#if MGB_ENABLE_GRAD
1719
MGB_IMPL_OPR_GRAD(Reduce) {
M
Megvii Engine Team 已提交
1720
    for (size_t i = 1; i < opr.output().size(); ++i)
1721
        mgb_assert(!out_grad[i]);
1722
    if (wrt_idx || opr.input(0)->dtype().category() != DTypeCategory::FLOAT)
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
        return InvalidGrad::make(opr, wrt_idx);
    SymbolVar og{out_grad[0]}, iv{opr.input(0)}, ov{opr.output(0)};
    constexpr auto cmv = Elemwise::Mode::COND_LEQ_MOV;
    using Mode = Reduce::Mode;
    SymbolVar grad = [&]() {
        switch (opr.param().mode) {
            case Mode::SUM:
                return Broadcast::make(og, GetVarShape::make(iv));
            case Mode::SUM_SQR:
                return (og * og.make_scalar_dt(2) * iv);
            case Mode::PRODUCT:
                return ((og * ov) / iv);
            case Mode::MIN:
                return Elemwise::make({iv, ov, og}, cmv);
            case Mode::MAX:
                return Elemwise::make({ov, iv, og}, cmv);
            case Mode::MEAN: {
                auto og_shape = opr::GetVarShape::make(og),
M
Megvii Engine Team 已提交
1741 1742 1743 1744
                     iv_shape = opr::GetVarShape::make(iv),
                     scale =
                             div(opr::reduce_prod(og_shape, og_shape.make_scalar(1)),
                                 opr::reduce_prod(iv_shape, iv_shape.make_scalar(1)));
1745 1746 1747 1748 1749 1750 1751 1752 1753
                return scale * Broadcast::make(og, GetVarShape::make(iv));
            }
            default:
                mgb_throw(MegBrainError, "bad reduce mode");
        }
    }();
    grad = TypeCvt::make(grad, iv.dtype());
    return grad.node();
}
1754
#endif
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764

void Reduce::record_execute_deps(ExecDependencyArray& deps) {
    record_megdnn_opr(deps);
    m_kern_scheduler->record_execute_deps(deps);
}

/* =========================== PowC =========================== */

MGB_DYN_TYPE_OBJ_FINAL_IMPL(PowC);

M
Megvii Engine Team 已提交
1765 1766 1767
PowC::PowC(VarNode* i0, const Param& param, const OperatorNodeConfig& config)
        : Super(OperatorNodeBaseCtorParam{
                  i0->owner_graph(), config, ssprintf("powc_%g", param.exp), {i0}}) {
1768 1769 1770 1771 1772
    init_megdnn_opr(*this, param);
    add_input({i0});
    output(0)->add_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE);
    intl::MegDNNOprInitPostCtor<PowC>::apply(*this);
}
1773

M
Megvii Engine Team 已提交
1774 1775
SymbolVar PowC::make(
        SymbolVar x, const Param& param, const OperatorNodeConfig& config) {
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
    if (almost_equal(param.exp, 1.f)) {
        return x;
    }
    if (almost_equal(param.exp, 0.f)) {
        return x.make_scalar_dt(1).broadcast(x.symshape());
    }
    return x.insert_single_output_opr<PowC>(x.node(), param, config);
}

void PowC::add_input_layout_constraint() {
    input(0)->add_layout_constraint_monotone();
}

void PowC::mem_plan_fwd_in2out_writable() {
    output(0)->set_fwd_in2out_writable(input(0));
}

void PowC::init_output_static_infer_desc() {
    Super::init_output_static_infer_desc();
    static StaticInferOpr<megdnn::PowC> static_infer_opr;
    using namespace cg::static_infer;

    auto infer_value = [this](DeviceTensorND& dest, const InpVal& inp) {
        auto infer_opr_lock = static_infer_opr.lock();
        auto&& infer_opr = infer_opr_lock();
        infer_opr->param() = this->param();
        auto&& ival = inp.val[0].value().as_megdnn();
        infer_opr->exec(ival, dest.resize(ival.layout).as_megdnn());
        return true;
    };
    owner_graph()->static_infer_manager().register_value_infer(
M
Megvii Engine Team 已提交
1807
            output(0), {SourceType::DEP, {{input(0), DepType::VALUE}}, infer_value});
1808 1809
}

1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
void PowC::scn_do_execute() {
    if (input(0)->dev_tensor().empty()) {
        mgb_assert(output(0)->dev_tensor().empty());
        return;
    }
    mgb_assert(!output(0)->dev_tensor().empty());
    Super::scn_do_execute();
}

PowC::NodeProp* PowC::do_make_node_prop() const {
    auto ret = Super::do_make_node_prop();
M
Megvii Engine Team 已提交
1821
    ret->add_dep_type_existing_var(input(0), NodeProp::DepType::VALUE_ALLOW_EMPTY);
1822 1823 1824
    return ret;
}

1825
#if MGB_ENABLE_GRAD
1826 1827 1828 1829 1830 1831
MGB_IMPL_OPR_GRAD(PowC) {
    auto exp = opr.param().exp;
    return (exp * SymbolVar{out_grad[0]} *
            PowC::make(opr.input(0), exp - 1, opr.config()))
            .node();
}
1832
#endif
1833 1834

// vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}